import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import sys
from bs4 import BeautifulSoup
sys.path.append('../')
import pandas as pd
import re
import collections
from nltk.corpus import stopwords
import random
import pickle
import argparse
import math

def clean(review, remove_freq = True):
    """Given a review, cleans it by removing html tags and punctation.
    Also filters out very common words if the remove_freq flag is given.
    Params:
    review - a single review from the dataset
    remove_freq: True if we remove frequent words (enabled by default)
    """
    # remove html
    text = BeautifulSoup(review, "html5lib").get_text()
    # regexp matching to extract letters only
    letters_only = re.sub("[^a-zA-Z]", " ", text)
    words = letters_only.lower().split()
    stops = set(stopwords.words("english"))
    meaningful_words = [w for w in words if not w in stops] if remove_freq else words
    return (" ".join(meaningful_words))

def extract_and_clean_data(path_to_file, get_labels = True):
    """Takes in a path to the reviews dataset and returns cleaned reviews along
    with their sentiments (binary labels)
    Params:
    path_to_file: the path to the data file
    Returns:
    clean_reviews: The cleaned reviews (punctation and common words stripped)
    y: the labels (sentiments for each review)
    """
    data = pd.read_csv(path_to_file, header = 0, delimiter='\t', quoting=3)
    clean_reviews = [clean(data['review'][i])
                     for i in range(len(data['review']))]
    if not get_labels:
        return clean_reviews
    y = data['sentiment']
    return clean_reviews, y

def build_vocab(cleaned_reviews, keep_dups = False):
    """Takes in a bunch of reviews and returns a list V of all the words
    (no dups)
    Params: cleaned_reviews
    Returns: vocab: a list of all of the words
    """
    li = []
    for review in cleaned_reviews:
        a = review.split()
        for item in a:
            li.append(item)
    return list(set(li)) if not keep_dups else li

def word_one_hot(word, vocab):
    idx = vocab.index(word)
    if(idx < 0):
        raise ValueError("vocab must contain word")
    v = np.zeros(len(vocab))
    v[idx] = 1
    return np.array(v)

def create_training_examples_one_hot(review, vocab, window_size = 1):
    """Creates the word pairs for the skip-gram model.
    Params: review - a single (cleaned) review
    window_size: how many context words to use.
    Default = 1 - ie, use the word to the left and to the right as the context
    Returns:
    data - a bunch of training data
    """
    words = review.split()
    data, labels = [], []
    for i in range(len(words)):
        left = [words[i-j] for j in range(1, window_size + 1) if i-j >= 0]
        right = [words[i+j] for j in range(1, window_size + 1) if i+j < len(words)]
        neighbors = left + right
        for item in neighbors:
            data.append(word_one_hot(words[i], vocab))
            labels.append(word_one_hot(item, vocab))
    return data, labels

def build_dataset(words, vocabulary_size):
    # create a counter for the msot common words
  count = [['UNK', -1]]
  count.extend(collections.Counter(words).most_common(vocabulary_size - 1))
  dictionary = dict()
  for word, _ in count:
    dictionary[word] = len(dictionary)
  data = list()
  unk_count = 0
  # get word indices
  for word in words:
    if word in dictionary:
      index = dictionary[word]
    else:
      index = 0  # dictionary['UNK']
      unk_count += 1
    data.append(index)
  count[0][1] = unk_count

  reverse_dictionary = dict(zip(dictionary.values(), dictionary.keys()))
  return data, count, dictionary, reverse_dictionary

# Step 3: Function to generate a training batch for the skip-gram model.
def generate_batch(batch_size, num_skips, skip_window):
  global data_index
  assert batch_size % num_skips == 0
  assert num_skips <= 2 * skip_window
  batch = np.ndarray(shape=(batch_size), dtype=np.int32)
  labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)
  span = 2 * skip_window + 1  # [ skip_window target skip_window ]
  buffer = collections.deque(maxlen=span)
  for _ in range(span):
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  for i in range(batch_size // num_skips):
    target = skip_window  # target label at the center of the buffer
    targets_to_avoid = [skip_window]
    for j in range(num_skips):
      while target in targets_to_avoid:
        target = random.randint(0, span - 1)
      targets_to_avoid.append(target)
      batch[i * num_skips + j] = buffer[skip_window]
      labels[i * num_skips + j, 0] = buffer[target]
    buffer.append(data[data_index])
    data_index = (data_index + 1) % len(data)
  # Backtrack a little bit to avoid skipping words in the end of a batch
  data_index = (data_index + len(data) - span) % len(data)
  return batch, labels

    # Visualize
def plot_with_labels(low_dim_embs, labels, filename='tsne.png'):
    assert low_dim_embs.shape[0] >= len(labels), "More labels than embeddings"
    plt.figure(figsize=(18, 18))  # in inches
    for i, label in enumerate(labels):
        x, y = low_dim_embs[i, :]
        plt.scatter(x, y)
        plt.annotate(label,
                    xy=(x, y),
                    xytext=(5, 2),
                    textcoords='offset points',
                    ha='right',
                    va='bottom')

    plt.savefig(filename)
    return 1
     # plt.show()

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("-l", "--load", help="load data structures from a file",
                        action = "store_true")
    args = parser.parse_args()
    if args.load:
        print("loading data from file data/data.pik")
        with open('data/data.pik', 'rb') as f:
            test_clean_reviews, clean_reviews, y, data, count, dictionary, reverse_dictionary, vocabulary_size = pickle.load(f)
            vocab = build_vocab(clean_reviews, keep_dups = False)
    else:
        clean_reviews, y = extract_and_clean_data('../data/labeledTrainData.tsv')
        test_clean_reviews = extract_and_clean_data('../data/unlabeledTrainData.tsv',
                                                    get_labels = False)
        vocab = build_vocab(clean_reviews, keep_dups = False)
        words, vocabulary_size = vocab, len(vocab)
        data, count, dictionary, reverse_dictionary = build_dataset(words, vocabulary_size)

        del words # hint to Python to reduce memory
        with open('data/data.pik', 'wb') as f:
            pickle.dump([test_clean_reviews, clean_reviews, y, data, count, dictionary,
                         reverse_dictionary, vocabulary_size], f, -1)

    print("cleaned reviews len: {}".format(len(clean_reviews)))
    print('Most common words (+UNK)', count[:5])
    print('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])
    data_index = 0
    batch_size = 8
    batch, labels = generate_batch(batch_size=batch_size, num_skips=2, skip_window=1)
    print(batch.shape)
    print(labels.shape)
    train_inputs = tf.placeholder(tf.int32, shape=[batch_size])
    train_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])
    valid_window = 100  # Only pick dev samples in the head of the distribution.
    valid_size = 16
    embedding_size = 128
    valid_examples = np.random.choice(valid_window, valid_size, replace=False)
    valid_dataset = tf.constant(valid_examples, dtype=tf.int32)
        # creates a vocab_size * embedding_size matrix. For the ith word in the vocab,
    # the vector embeddings[i] is the corresponding embedding.
    print(vocabulary_size)
    print(embedding_size)
    embeddings = tf.Variable(
        tf.random_uniform([vocabulary_size, embedding_size], -1.0, 1.0))
    embed = tf.nn.embedding_lookup(embeddings, train_inputs)

    # treats the embedding matrix as a lookup table so we can get the embeddings

    # "Xavier" init
    nce_weights = tf.Variable(tf.truncated_normal(
        [vocabulary_size, embedding_size],
        stddev=1.0/math.sqrt(embedding_size)))
    nce_biases = tf.Variable(tf.zeros([vocabulary_size]))
    num_sampled = 64
    # Compute the average NCE loss for the batch.
    # tf.nce_loss automatically draws a new sample of the negative labels each
    # time we evaluate the loss.
    losses = ['nce', 'sampled', ]
    loss_fun = tf.reduce_mean(
        tf.nn.nce_loss(weights=nce_weights,
                       biases=nce_biases,
                       labels=train_labels,
                       inputs=embed,
                       num_sampled=num_sampled,
                       num_classes=vocabulary_size))

    # Construct the SGD optimizer using a learning rate of 1.0.
    optimizer = tf.train.GradientDescentOptimizer(1.0).minimize(loss_fun)

    # Compute the cosine similarity between minibatch examples and all embeddings.
    norm = tf.sqrt(tf.reduce_sum(tf.square(embeddings), 1, keep_dims=True))
    normalized_embeddings = embeddings / norm
    valid_embeddings = tf.nn.embedding_lookup(
        normalized_embeddings, valid_dataset)
    similarity = tf.matmul(
        valid_embeddings, normalized_embeddings, transpose_b=True)

    init = tf.global_variables_initializer()
    skip_window = 1       # How many words to consider left and right.
    num_skips = 2         # How many times to reuse an input to generate a label.
    nsteps = 500000
    with tf.Session() as sess:
        sess.run(init)
        avg_loss = 0.
        for step in range(nsteps):
            batch_inputs, batch_labels = generate_batch(batch_size,
                                                        num_skips, skip_window) # 2 = num skips, 1 = skip window
            feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}
            _, loss = sess.run([optimizer, loss_fun], feed_dict = feed_dict)
            avg_loss+=loss
            if step % 10000 == 0:
                if step != 0: avg_loss /= 10000
                print("Average loss at epoch {}: {}".format(step, avg_loss))
                avg_loss = 0.
        final_embeddings = normalized_embeddings.eval()
    try:
         from sklearn.manifold import TSNE
         tsne = TSNE(perplexity=30, n_components=2, init='pca', n_iter=5000)
         plot_only = 500
         low_dim_embs = tsne.fit_transform(final_embeddings[:plot_only, :])
         labels = [reverse_dictionary[i] for i in range(plot_only)]
         plot_with_labels(low_dim_embs, labels)
    except ImportError:
        print("please install sklearn, matplotlib, and scipy for tsne embeddings")
    print(final_embeddings.shape)
    print(len(reverse_dictionary.values()))
    with open('data/embeddings.txt', 'wb') as f:
        print("dumping embeddings")
        pickle.dump([final_embeddings, reverse_dictionary], f, -1)
    with open('data/data.txt', 'wb') as f:
        print("dumping reviews, vocab, and labels")
        train_cleaned_reviews = clean_reviews
        pickle.dump([train_cleaned_reviews, test_clean_reviews, vocab, y], f, -1)


from dash import Dash, dcc, html, Input, Output
import plotly.express as px
import pandas as pd
import datetime
import numpy as np
import datetime
from dateutil.relativedelta import relativedelta
monthDiff = 2
today = datetime.date.today()
monthsAgo = today - relativedelta(months=monthDiff)
slopeID = 0
sensorID = 0

df = pd.read_csv('pivotFlexBarrier.csv')
a,b,c,d,e = df.iloc[0], df.iloc[1], df.iloc[2], df.iloc[3], df.iloc[4]
df2 = df
df2.iloc[0] = d
df2.iloc[1] = a
df2.iloc[2] = c
df2.iloc[3] = e
df2.iloc[4] = b
SensorIDs = df['deviceID'].tolist()
for i in range(0, len(SensorIDs)):
    SensorIDs[i] = int(SensorIDs[i])
SensorIDs = [str(i) for i in SensorIDs]
df = df.drop('Unnamed: 0', 1)
df = df.drop('Unnamed: 0.1', 1)
df = df.drop('deviceID', 1)
z = df.to_numpy()

dates = list(df)
for i, date in enumerate(dates):
    #dates[i] = datetime.datetime.strptime(date, '%d/%m/%Y').date()
    dates[i] = datetime.datetime.strptime(date, '%Y-%m-%d').date()
dates = np.array(dates)

def reloadData():
    df = pd.read_csv('pivotFlexBarrier.csv')
    a, b, c, d, e = df.iloc[0], df.iloc[1], df.iloc[2], df.iloc[3], df.iloc[4]
    df2 = df
    df2.iloc[0] = d
    df2.iloc[1] = a
    df2.iloc[2] = c
    df2.iloc[3] = e
    df2.iloc[4] = b
    SensorIDs = df['deviceID'].tolist()
    for i in range(0, len(SensorIDs)):
        SensorIDs[i] = int(SensorIDs[i])
    SensorIDs = [str(i) for i in SensorIDs]
    df = df.drop('Unnamed: 0', 1)
    df = df.drop('Unnamed: 0.1', 1)
    df = df.drop('deviceID', 1)
    z = df.to_numpy()

    dates = list(df)
    for i, date in enumerate(dates):
        #dates[i] = datetime.datetime.strptime(date, '%d/%m/%Y').date()
        dates[i] = datetime.datetime.strptime(date, '%Y-%m-%d').date()
    dates = np.array(dates)
    return SensorIDs, dates, z

# base = datetime.datetime.today()
# dates = base - np.arange(90) * datetime.timedelta(days=1)
# for i in range(0, len(dates)):
#      dates[i] = dates[i].date()
#
# dfWork = pd.DataFrame([
#     dict(Task="Job A", Start=dates[len(dates)-2], Finish=dates[len(dates)-1],Description='JobA'),
#     dict(Task="Job B", Start=dates[len(dates)-10], Finish=dates[len(dates)-8],Description='JobB'),
#     dict(Task="Job C", Start=dates[0], Finish=dates[1],Description='JobC')
# ])
dfWork = pd.read_csv('Task_Info_Flex.csv')
for i in range(0, len(dfWork)):
    dfWork['Start'][i] = datetime.datetime.strptime(dfWork['Start'][i], '%d/%m/%Y').date()
for i in range(0, len(dfWork)):
    dfWork['Finish'][i] = datetime.datetime.strptime(dfWork['Finish'][i], '%d/%m/%Y').date()
dfWork['SlopeID'] = dfWork['SlopeID'].fillna(slopeID)
dfWork['SensorID'] = dfWork['SensorID'].fillna(sensorID)
dfWork = dfWork.loc[(dfWork['SlopeID'] == slopeID) | (dfWork['SlopeID'] == 'ALL'), :]
dfWork = dfWork.loc[(dfWork['SensorID'] == sensorID) | (dfWork['SensorID'] == 'ALL'), :]
dfWork = dfWork[~(dfWork['Start'] < monthsAgo)].reset_index(drop=True)
if len(dfWork) == 0:
    today = datetime.date.today()
    yesterday = today - relativedelta(days=1)
    task = 'Place Holder'
    description = 'None'
    slopeID = 'None'
    sensorID = 'None'
    data = [{'Task': task,
             'Start': yesterday,
             'Finish': today,
             'Description': description,
             'SlopeID': slopeID,
             'SensorID': sensorID
             }]
    dfWork = pd.DataFrame(data)
def reloadWork(slopeID, sensorID):
    dfWork = pd.read_csv('Task_Info_Flex.csv')
    today = datetime.date.today()
    monthsAgo = today - relativedelta(months=monthDiff)
    for i in range(0, len(dfWork)):
        dfWork['Start'][i] = datetime.datetime.strptime(dfWork['Start'][i], '%d/%m/%Y').date()
    for i in range(0, len(dfWork)):
        dfWork['Finish'][i] = datetime.datetime.strptime(dfWork['Finish'][i], '%d/%m/%Y').date()
    toDrop = list()
    for i in range(0, len(dfWork)):
        if dfWork.iloc[i]['Start'] < monthsAgo:
            toDrop.append(i)
    dfWork = dfWork.drop(toDrop, axis=0).reset_index(drop=True)
    dfWork['SlopeID'] = dfWork['SlopeID'].fillna(slopeID)
    dfWork['SensorID'] = dfWork['SensorID'].fillna(sensorID)
    dfWork = dfWork.loc[(dfWork['SlopeID'] == slopeID) | (dfWork['SlopeID'] == 'ALL'), :]
    dfWork = dfWork.loc[(dfWork['SensorID'] == sensorID) | (dfWork['SensorID'] == 'ALL'), :]
    if len(dfWork) == 0:
        today = datetime.date.today()
        yesterday = today - relativedelta(days=1)
        task = 'Place Holder'
        description = 'None'
        slopeID = 'None'
        sensorID = 'None'
        data = [{'Task': task,
                'Start': yesterday,
                'Finish': today,
                'Description': description,
                'SlopeID': slopeID,
                'SensorID': sensorID
                }]
        dfWork = pd.DataFrame(data)
    return dfWork
# Color = ['rgb(0, 0, 0)','rgb(0, 0, 0)','rgb(0, 0, 0)']
# Jobs = ['JobA','JobB','JobC']
app = Dash(__name__)

app.layout = html.Div([
        html.H4('TCK928 - Monitoring Slope No.: 11SE-D/ND9', style={'font-size': '40px', 'textAlign': 'center'}),
        dcc.Graph(id="graph", responsive=True),
        dcc.Interval(id="trigger", interval=1000),
        html.H4('Location of the Slope', style={'font-size': '40px', 'textAlign': 'center'}),
        html.Div(html.Img(src=app.get_asset_url('slope.jpg')),style={'width': '70%',  'textAlign': 'center', 'display': 'inline-block'}),
        html.Div([
            html.P("Sensor A SN: 890771058921"),
            html.P("Sensor B SN: 890771058913"),
            html.P("Sensor C SN: 890771058918"),
            html.P("Sensor D SN: 890771059014"),
            html.P("Sensor E SN: 890771058915"),
        ],style={'width': '30%', 'display': 'inline-block'})
])

# html.Img(src=app.get_asset_url('slope.jpg'))
@app.callback(Output("graph", "figure"), Input('trigger', 'interval'))
def filter_heatmap(cols):
    import plotly.graph_objects as go
    import numpy as np
    import plotly.figure_factory as ff
    from plotly.subplots import make_subplots
    import pandas as pd
    # df = pd.read_csv('pivotFlexBarrier.csv')
    # SensorIDs = df['deviceID'].tolist()
    # df = df.drop('Unnamed: 0', 1)
    # df = df.drop('deviceID', 1)
    # z = df.to_numpy()
    slopeID = 0
    sensorID = 0
    SensorIDs, dates, z = reloadData()
    dfWork = reloadWork(slopeID, sensorID)
    labels = SensorIDs
    hovertext = list()
    for yi, yy in enumerate(labels):
        hovertext.append(list())
        for xi, xx in enumerate(dates):
            hovertext[-1].append('Date: {}
Sensor ID: {}
Maximum Reading: {}'.format(xx, yy, z[yi][xi]))
    hovertextWork = list()
    for i in range(0, len(dfWork)):
        hovertextWork.append(list())
        hovertextWork[-1].append('Date: {}
Event: {}
'.format(dfWork['Start'][i], dfWork['Description'][i]))
    # for i in range(0, len(z)):
    #     if i == 0 or i == 13 or i == 29:
    #         labels.append('Post -' + str(i))
    #     else:
    #         labels.append('Barrier -' + str(i))
    fig = make_subplots(rows=3, cols=1, shared_xaxes=True,specs=[
        [{'rowspan':2}], [None],
        [{}],
    ])
    fig.add_trace(go.Heatmap(
        colorbar={"title": 'Unit of Measure: m/s
(approximated)
(assuming stationary)'},
        z=z,
        x=dates,
        y=labels,
        colorscale='Viridis', colorbar_y=0.7,colorbar_len=0.6, hoverinfo='text', text=hovertext))
    figg = ff.create_gantt(dfWork, group_tasks=True, index_col='Description', reverse_colors=False, show_colorbar=False)
    #figg.update_traces(hoverinfo='text', text=hovertextWork)
    for trace in figg.data:
        fig.add_trace(trace, row=3, col=1)
    fig.update_layout(title={"text": "Motion Over Time and Works scheduled", "xanchor": "center", "x": 0.53},
                           yaxis={"title": "Barrier Posts", "autorange": "reversed"},
                           width=1800,
                           height=1000,
                           xaxis={"title": 'Time', "tickangle": 45})
    fig.update_layout(xaxis_showgrid=False, yaxis_showgrid=False, autosize=False)
    fig.update_yaxes(showticklabels=False, row=3, col=1, tickson='boundaries')
    fig.update_xaxes(tickson='boundaries')
    fig['layout'].update(margin=dict(l=0, r=0, b=0, t=0))
    fig['layout']['yaxis2']['title'] = 'Weather & Work Records'
    fig.update_xaxes(dtick=86400000.0)
    fig.update_layout(font={"size": 13})
    return fig

PORT = 8055
ADDRESS = "0.0.0.0"
if __name__ == '__main__':
    app.run_server(host=ADDRESS,port=PORT, debug=True, threaded=True)

# http://127.0.0.1:8055/


# -*- coding: utf-8 -*-
"""
Task from
https://www.codewars.com/kata/delete-occurrences-of-an
-element-if-it-occurs-more-than-n-times/train/python
"""

def delete_if_occurs_more_than_n(order: list, max_element: int) -> list:
    """
    Given a list lst and a number N, create a new list that contains each number
    of lst at most N times without reordering.
    For example:
        order = [1,2,3,1,2,1,2,3], max_element = 2 -> [1,2,3,1,2],
    drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times,
    and then take 3, which leads to [1,2,3,1,2,3].
    """
    order.reverse()
    while True:
        iterable = 0
        for item in order:
            if order.count(item) > max_element:
                order.remove(item)
                break
            iterable += 1
        if iterable == len(order):
            break
    order.reverse()
    return order


# This file is part of sner4 project governed by MIT license, see the LICENSE.txt file.
"""
scheduler.views.queue tests
"""

import json
from http import HTTPStatus
from pathlib import Path

from flask import url_for

from sner.server.scheduler.models import Job, Queue

def test_queue_list_route(cl_operator):
    """queue list route test"""

    response = cl_operator.get(url_for('scheduler.queue_list_route'))
    assert response.status_code == HTTPStatus.OK

def test_queue_list_json_route(cl_operator, queue):
    """queue list_json route test"""

    response = cl_operator.post(
        url_for('scheduler.queue_list_json_route'),
        {'draw': 1, 'start': 0, 'length': 1, 'search[value]': queue.name}
    )
    assert response.status_code == HTTPStatus.OK
    response_data = json.loads(response.body.decode('utf-8'))
    assert response_data['data'][0]['name'] == queue.name

    response = cl_operator.post(
        url_for('scheduler.queue_list_json_route', filter=f'Queue.name=="{queue.name}"'),
        {'draw': 1, 'start': 0, 'length': 1}
    )
    assert response.status_code == HTTPStatus.OK
    response_data = json.loads(response.body.decode('utf-8'))
    assert response_data['data'][0]['name'] == queue.name

    response = cl_operator.post(url_for('scheduler.queue_list_json_route', filter='invalid'), {'draw': 1, 'start': 0, 'length': 1}, status='*')
    assert response.status_code == HTTPStatus.BAD_REQUEST

def test_queue_add_route(cl_operator, queue_factory):
    """queue add route test"""

    aqueue = queue_factory.build()

    form = cl_operator.get(url_for('scheduler.queue_add_route')).forms['queue_form']
    form['name'] = aqueue.name
    form['config'] = aqueue.config
    form['group_size'] = aqueue.group_size
    form['priority'] = aqueue.priority
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    tqueue = Queue.query.filter(Queue.name == aqueue.name).one()
    assert tqueue.name == aqueue.name

def test_queue_add_route_config_validation(cl_operator, queue_factory):
    """queue add route test"""

    aqueue = queue_factory.build()

    form = cl_operator.get(url_for('scheduler.queue_add_route')).forms['queue_form']
    form['name'] = aqueue.name
    form['config'] = ''
    form['group_size'] = aqueue.group_size
    form['priority'] = aqueue.priority
    response = form.submit()
    assert response.status_code == HTTPStatus.OK
    assert response.lxml.xpath('//div[@class="invalid-feedback" and contains(text(), "Invalid YAML")]')

    form = response.forms['queue_form']
    form['config'] = "module: 'notexist'"
    response = form.submit()
    assert response.status_code == HTTPStatus.OK
    assert response.lxml.xpath('//div[@class="invalid-feedback" and text()="Invalid module specified"]')

    form = response.forms['queue_form']
    form['config'] = "module: 'dummy'\nadditionalKey: 'value'\n"
    response = form.submit()
    assert response.status_code == HTTPStatus.OK
    assert response.lxml.xpath('//div[@class="invalid-feedback" and contains(text(), "Invalid config")]')

def test_queue_edit_route(cl_operator, queue):
    """queue edit route test"""

    form = cl_operator.get(url_for('scheduler.queue_edit_route', queue_id=queue.id)).forms['queue_form']
    form['name'] = f'{form["name"].value} edited'
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    assert Queue.query.get(queue.id).name == form['name'].value

def test_queue_enqueue_route(cl_operator, queue, target_factory):
    """queue enqueue route test"""

    atarget = target_factory.build(queue=queue)

    form = cl_operator.get(url_for('scheduler.queue_enqueue_route', queue_id=queue.id)).forms['queue_enqueue_form']
    form['targets'] = f'{atarget.target}\n \n '
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    tqueue = Queue.query.get(queue.id)
    assert len(tqueue.targets) == 1
    assert tqueue.targets[0].target == atarget.target

def test_queue_flush_route(cl_operator, target):
    """queue flush route test"""

    queue_id = target.queue_id

    form = cl_operator.get(url_for('scheduler.queue_flush_route', queue_id=target.queue_id)).form
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    assert not Queue.query.get(queue_id).targets

def test_queue_prune_route(cl_operator, job_completed):
    """queue flush route test"""

    form = cl_operator.get(url_for('scheduler.queue_prune_route', queue_id=job_completed.queue_id)).form
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    assert not Job.query.filter(Job.queue_id == job_completed.queue_id).all()
    assert not Path(job_completed.output_abspath).exists()

def test_queue_prune_route_runningjob(cl_operator, job):
    """queue flush route test with running job; should fail, delete running job would corrupt heatmap"""

    form = cl_operator.get(url_for('scheduler.queue_prune_route', queue_id=job.queue_id)).form
    response = form.submit(expect_errors=True)
    assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR

    assert len(Job.query.filter(Job.queue_id == job.queue_id).all()) == 1

def test_queue_delete_route(cl_operator, job_completed):
    """queue delete route test"""

    tqueue = Queue.query.get(job_completed.queue_id)
    assert Path(tqueue.data_abspath)

    form = cl_operator.get(url_for('scheduler.queue_delete_route', queue_id=tqueue.id)).form
    response = form.submit()
    assert response.status_code == HTTPStatus.FOUND

    assert not Queue.query.get(tqueue.id)
    assert not Path(tqueue.data_abspath).exists()

def test_queue_delete_route_runningjob(cl_operator, job):
    """queue delete route test with running job; should fail as deleting queue with running job would corrupt heatmap"""

    form = cl_operator.get(url_for('scheduler.queue_delete_route', queue_id=job.queue_id)).form
    response = form.submit(expect_errors=True)
    assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR

    assert len(Job.query.filter(Job.queue_id == job.queue_id).all()) == 1


import sqlite3
import nextcord
from nextcord import PartialInteractionMessage, WebhookMessage
from nextcord.ext import commands

class Konto(commands.Cog):
    def __init__(self, bot: commands.Bot):
        self.bot = bot

    @nextcord.slash_command(
        name="geldbeutel",
        description="Zeigt dir dein Guthaben",
        force_global=True

    )
    async def geld_beutel(
            self,
            ctx: nextcord.Interaction,
            user: nextcord.Member = nextcord.SlashOption(required=False)
    ) -> PartialInteractionMessage | WebhookMessage:

        if user is None:
            # Use own user
            db = sqlite3.connect("ressourcen/bank.db")
            cursor = db.cursor()
            data = cursor.execute(f"SELECT money FROM bank WHERE userId={ctx.user.id}")

            money = data.fetchall()

            if not money:
                return await ctx.send("Du besitzt noch kein Geld.")

            embed_money = nextcord.Embed(
                title="Dein Geld",
                color=nextcord.Color.orange()
            )
            embed_money.set_thumbnail(url=self.bot.user.avatar)
            embed_money.add_field(name="Betrag: ", value=money[0][0])
            return await ctx.send(embed=embed_money)

        db = sqlite3.connect("ressourcen/bank.db")
        cursor = db.cursor()
        data = cursor.execute(f"SELECT money FROM bank WHERE userId={user.id}")

        money = data.fetchall()

        if not money:
            return await ctx.send("Dieser User besitzt noch kein Geld.", ephemeral=True)

        embed_money = nextcord.Embed(
            title="Dein Geld",
            color=nextcord.Color.orange()
        )
        embed_money.add_field(name="Betrag: ", value=money[0][0])
        embed_money.set_thumbnail(url=self.bot.user.avatar)
        await ctx.send(embed=embed_money)

def setup(bot):
    bot.add_cog(Konto(bot))


# -*- coding: utf-8 -*-
from .lib import *

class MerchantAccount(Safe2PayEntity):

	def __init__(cls, **kw):

		cls.__metadata__ = {}

		# FIELDS
		cls.id = String(max=26)
		cls.Identity = String(max=20)
		cls.Name = String(max=150)
		cls.MerchantType = Obj(context=cls, key='MerchantType', name='MerchantType')
		cls.BankData = Obj(context=cls, key='BankData', name='BankData')
		cls.metadata = Dict()

		super().__init__(**kw)


import timeit
import sys, os
import importlib
import shutil

class TestHandler:

    def __init__(self, filename):
        self.originalFilname = filename
        if "/" in filename or "\\" in filename:
            shutil.copy(filename, os.path.join(os.path.dirname(__file__), "testFile.py"))
            filename = os.path.join(os.path.dirname(__file__), "testFile.py")
        self.filename = filename
        self.fileHandler = open(filename, "r")
        self.executable = importlib.import_module(filename.split("/")[-1].split("\\")[-1][:-3])

    def processFile(self):
        if self.originalFilname != self.filename:
            try:
                shutil.copy(self.originalFilname, "testFile.py")
            except shutil.SameFileError:
                pass
        importlib.reload(self.executable)
        self.fileHandler = open(self.filename, "r")
        #__import__(self.filename)
        self.testCases = {}
        inTest = False
        currentTestCategory = ""
        currentTestName = ""
        for line in self.fileHandler:
            line = line.rstrip()
            if line.startswith("endTest'''"):
                inTest = False
            if inTest:
                if line.startswith("testCategory"):
                    currentTestCategory = line.split("testCategory ")[1]
                    if currentTestCategory not in self.testCases:
                        self.testCases[currentTestCategory] = {}

                if line.startswith("testName"):
                    currentTestName = line.split("testName ")[1]
                    if currentTestName not in self.testCases[currentTestCategory]:
                        self.testCases[currentTestCategory][currentTestName] = {}

                if line.startswith("maxtime"):
                    maxtime = int(line.split("maxtime ")[1])
                    self.testCases[currentTestCategory][currentTestName]["maxtime"] = maxtime

                if line.startswith("expectedResult"):
                    expectedResult = eval(line.split("expectedResult ")[1])
                    self.testCases[currentTestCategory][currentTestName]["expectedResult"] = expectedResult

                if line.startswith("call"):
                    call = line.split("call ")[1]
                    self.testCases[currentTestCategory][currentTestName]["call"] = "self.executable." + call

            if line.startswith("'''testStart"):
                inTest = True

    def executeTests(self):
        allok = True
        for category in self.testCases:
            catok = True
            for test in self.testCases[category]:
                try:
                    expected = self.testCases[category][test]["expectedResult"]
                    start_time = timeit.default_timer()
                    result = eval(self.testCases[category][test]["call"])
                    elapsed = timeit.default_timer() - start_time
                    if result != expected or elapsed > self.testCases[category][test]["maxtime"]:
                        allok = False
                        catok = False
                        self.testCases[category][test]["testOK"] = False
                        errorstring = "   " + " ERROR " + test
                        rstring = self.testCases[category][test]["call"].split("self.executable.")[1]
                        if len(rstring) > 70:
                            rstring = rstring[:70] + "..."
                        if (result != expected):
                            errorstring = errorstring + "\n      " + "Falsches Ergebnis"
                        else:
                            errorstring = errorstring + "\n      " + "Zu langsam"
                        errorstring = errorstring + "\n      " + rstring
                        errorstring = errorstring + "\n      " + "expected: " + str(expected) + ", got: " + str(result)
                        errorstring = errorstring + "\n      " + "runtime: " + str(elapsed) + " seconds "
                        errorstring = errorstring + "\n"
                        self.testCases[category][test]["resultOutput"] = errorstring
                    else:
                        self.testCases[category][test]["testOK"] = True
                        self.testCases[category][test]["resultOutput"] = "   " + test + " OK"
                except Exception as inst:
                    allok = False
                    catok = False
                    self.testCases[category][test]["testOK"] = False
                    errorstring = "   " + " ERROR " + test
                    errorstring = errorstring + "\n      " + "Programmierfehler"
                    rstring = self.testCases[category][test]["call"].split("self.executable.")[1]
                    if len(rstring) > 70:
                        rstring = rstring[:70] + "..."
                    errorstring = errorstring + "\n      " + rstring
                    errorstring = errorstring + "\n      " + inst
                    exc_type, exc_obj, exc_tb = sys.exc_info()
                    fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
                    errorstring = errorstring + "\n      " + str(exc_type) + " " + str(fname) + " " + str(exc_tb.tb_lineno)
                    errorstring = errorstring + "\n"
                    self.testCases[category][test]["resultOutput"] = errorstring
            if catok:
                print("OK " + category)
            else:
                print("ERROR " + category)
            for test in self.testCases[category]:
                print(self.testCases[category][test]["resultOutput"])
        return allok


# https://numericalrecipes.wordpress.com/2009/05/25/signature-preserving-function-decorators/

from __future__ import division

import inspect
import time
from os import name as OP_SYS

def performance_timer_2(_func_):
    """
    A decorator function to time execution of a function.

    Timing is activated by setting the verbose keyword to True.
    """

    stopwatch = time.time
    if OP_SYS in ('nt', 'dos'):
        stopwatch = time.clock

    def _wrap_(*args, **kwargs):
        """
        This is a function wrapper.
        """

        verbose = kwargs.pop('verbose', False)
        t = stopwatch()
        ret = _func_(*args, **kwargs)
        t = stopwatch() - t
        if verbose:
            print("Call to", _func_.__name__, "took", t, "sec.")
        return ret

    _wrap_.__name__ = _func_.__name__
    _wrap_.__doc__ = _func_.__doc__
    return _wrap_

def performance_timer_3(_func_):
    """
    A decorator function to time execution of a function.

    Timing is activated by setting the verbose keyword to True.
    """

    stopwatch = time.time
    if OP_SYS in ('nt', 'dos'):
        stopwatch = time.clock

    def _wrap_(*args, **kwargs):
        """
        This is a function wrapper.
        """

        verbose = kwargs.pop('verbose', False)
        t = stopwatch()
        ret = _func_(*args, **kwargs)
        t = stopwatch() - t
        if verbose:
            print("Call to", _func_.__name__, "took", t, "sec.")
        return ret

    sig = list(inspect.getargspec(_func_))
    wrap_sig = list(inspect.getargspec(_wrap_))
    if not sig[2]:
        sig[2] = wrap_sig[2]
    src = 'def %s%s :\n' % (_func_.__name__, inspect.formatargspec(*sig))
    src += '    return _wrap_%s\n' % (inspect.formatargspec(*sig))
    evaldict = {'_wrap_': _wrap_}
    exec(src in evaldict)
    ret = evaldict[_func_.__name__]
    ret.__doc__ = _func_.__doc__
    return ret

def signature_decorator(_wrap_, has_kwargs=False):
    """
    A decorator to create signature preserving wrappers.

    _wrap_     : the wrapper function, which must take a function as first
                 argument, can then take several optional arguments, which
                 must have defaults, plus the *args and **kwargs to pass to
                 the wrapped function.
    has_kwargs : should be set to True if the wrapper also accepts keyword
                 arguments to alter operation.
    """

    def decorator(func):
        """
        An intermediate decorator function
        """
        sig = list(inspect.getargspec(func))
        wrap_sig = list(inspect.getargspec(_wrap_))
        sig[0], wrap_sig[0] = sig[0] + wrap_sig[0][1:], wrap_sig[0] + sig[0]
        wrap_sig[0][0] = '_func_'
        sig[3] = list(sig[3]) if sig[3] is not None else []
        sig[3] += list(wrap_sig[3]) if wrap_sig[3] is not None else []
        sig[3] = tuple(sig[3]) if sig[3] else None
        wrap_sig[3] = None
        if sig[2] is None and has_kwargs:
            sig[2] = wrap_sig[2]
        wrap_sig[1:3] = sig[1:3]
        src = 'def %s%s :\n' % (func.__name__, inspect.formatargspec(*sig))
        src += '    return _wrap_%s\n' % (inspect.formatargspec(*wrap_sig))
        evaldict = {'_func_': func, '_wrap_': _wrap_}
        exec(src in evaldict)
        ret = evaldict[func.__name__]
        ret.__doc__ = func.__doc__
        return ret

    return decorator

def timer_wrapper_1(_func_, verbose=False, *args, **kwargs):
    """
    A wrapper to time functions, activated by the last argument.

    For use with signature_decorator
    """
    stopwatch = time.time
    if OP_SYS in ('nt', 'dos'):
        stopwatch = time.clock
    t = stopwatch()
    ret = _func_(*args, **kwargs)
    t = stopwatch() - t
    if verbose:
        print("Call to", _func_.__name__, "took", t, "sec.")
    return ret

def timer_wrapper_2(_func_, *args, **kwargs):
    """
    A wrapper to time functions, activated by a keyword argument..

    For use with signature_decorator
    """
    stopwatch = time.time
    if OP_SYS in ('nt', 'dos'):
        stopwatch = time.clock
    verbose = kwargs.pop('verbose', False)
    t = stopwatch()
    ret = func(*args, **kwargs)
    t = stopwatch() - t
    if verbose:
        print("Call to", _func_.__name__, "took", t, "sec.")
    return ret

def basic_stats(data):
    """
    Given a list of numbers, returns a dicitonary with the minimum, maximum,
    average and standard deviation, computed using Welford's method.

    """

    n = len(data)
    ret = {}
    if not n:
        ret['min'] = ret['max'] = ret['avg'] = ret['st_dev'] = None
    else:
        ret['min'] = min(data)
        ret['max'] = max(data)
        avg = data[0]
        var = 0
        for k, x in enumerate(data[1:], 2):
            delta = x - avg
            avg += delta / k
            var += delta * (x - avg)
        ret['avg'] = avg
        ret['st_dev'] = var ** (1 / 2) if n > 1 else None
    return ret

def performance_timer(_func_):
    """
    Decorator function to time execution of a function.

    Activated using the decorated function's **kwargs:

      verbose=1     --> Activates timing and printout
             =2     --> Increases output information
      timer_loops=1 --> Sets the number of times to run the function,
                        if gretaer than 1, output has detailed statistics

    """

    stopwatch = time.time
    if OP_SYS in ('nt', 'dos'):
        stopwatch = time.clock

    def _wrap_(*args, **kwargs):
        verbose = kwargs.pop('verbose', False)
        timer_loops = int(kwargs.pop('timer_loops', 1))
        if not verbose or timer_loops < 1:
            timer_loops = 1
        times = []
        ret = None
        for loop in range(timer_loops):
            times += [stopwatch()]
            ret = _func_(*args, **kwargs)
            times[-1] = stopwatch() - times[-1]
        if verbose:
            print("Call to", _func_.__name__,)
            if verbose > 1 and (args or kwargs):
                print("with arguments",)
                if args:
                    print(args,)
                if kwargs:
                    print(kwargs,)
            if timer_loops == 1:
                print("took %g sec." % (times[0]))
            else:
                print("took:")
                stats = basic_stats(times)
                for item in ('min', 'max', 'avg', 'st_dev'):
                    print("%g sec. (%s)" % (stats[item], item))
        return ret

    sig = list(inspect.getargspec(_func_))
    wrap_sig = list(inspect.getargspec(_wrap_))
    if not sig[2]:
        sig[2] = wrap_sig[2]
    src = 'def %s%s :\n' % (_func_.__name__, inspect.formatargspec(*sig))
    sig[3] = None  # if not, all vars with defaults are set to default value
    src += '    return _wrap_%s\n' % (inspect.formatargspec(*sig))
    evaldict = {'_wrap_': _wrap_}
    code = compile(src, '<string>', 'single')
    for code in evaldict:
        exec(code)
        ret = evaldict[_func_.__name__]
        ret.__doc__ = _func_.__doc__
    return ret

@performance_timer(timer_wrapper_1)
def decorated_sum(a,b=2) :
    """
    This is a function.
    """
    return a+b

if __name__ == '__main__':
    decorated_sum(1, 2)


import word_maker

# This is a riff on the old game "hangman", but with a melting snowman instead
#
#     _|@|_
#      (")
#  '--( : )--'
#    (  :  )

# Set some important variables
allowed_letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
                   "u", "v", "w", "x", "y", "z"]
guessed_letters = []
word = word_maker.hard_word()
word_array = list(word)
mistake_count = 0
allowed_mistakes = 5
revealed_letters = []
word_revealed = False
for letter in word_array:
    revealed_letters.append("_")

# A beautiful melting snowman
ascii_art = []
ascii_art.append('     _|@|_\n      (")\n  >--( : )--<\n    (  :  )')
ascii_art.append('          \n      (")\n  >--( : )--<\n    (  :  )')
ascii_art.append('          \n      (")\n     ( : )--<\n    (  :  )')
ascii_art.append('          \n      (")\n     ( : )   \n    (  :  )')
ascii_art.append('          \n         \n     ( : )   \n    (  :  )')
ascii_art.append('          \n         \n             \n    (  :  )')
ascii_art.append('          \n         \n             \n           ')

def print_revealed_word(revealed_so_far):
    print("Your mystery word: ", end="")
    for letter in revealed_so_far:
        print(letter, end="")
    print("\n")

# Start the main thread for the game
print("Guess the word before the snowman melts!")

while mistake_count <= allowed_mistakes and word_revealed is False:
    print(ascii_art[mistake_count])
    print_revealed_word(revealed_letters)
    player_response = input("Guess a letter\n")
    print(f"You entered {player_response}")
    if len(player_response) == 1 and player_response in allowed_letters:
        if player_response in guessed_letters:
            print(f"I'm sorry, but you already guessed the letter {player_response}.")
            print(f"In case you forgot, you've guessed the following letters: {sorted(guessed_letters)}\n")
        else:
            guessed_letters.append(player_response)
            if player_response in word_array:
                print(f"Congratulations! The letter {player_response} is in the secret word.")
                x = 0
                for letter in word_array:
                    if player_response == word_array[x]:
                        revealed_letters[x] = player_response
                    x += 1
            else:
                mistake_count += 1
                print(f"I'm sorry, but the letter {player_response} is not in the secret word. That's {mistake_count}"
                      f" mistakes.")
                print(f"You need to solve the problem before {allowed_mistakes + 1} mistakes.")
        if "_" not in revealed_letters:
            word_revealed = True
    else:
        print("Sorry, please pick just one letter from the English alphabet")

if word_revealed:
    print("Congratulations, you win!")
elif mistake_count > allowed_mistakes:
    print(f"You let the snowman melt! All you had to do was figure out the word {word}...")


# import files for servo motion and distance sensor
# import libraries
import numpy as np
import random
import pandas as pd
from itertools import product

class QLearning_advanced:

    def __init__(self, servos):
    ### init matrices and parameters ###
        self.servos = servos

        # Q-matrix
        self.q_matrix = np.zeros((81,6))
        self.actions = ['0_','1_','2_','_0','_1','_2']
        self.states = np.array(['00','01','11',
                        '10','02','22',
                        '20','12','21'])

        self.statesWithLastState = list(product(self.states, repeat=2))
        self.q_matrixDF = pd.DataFrame(self.q_matrix, columns=self.actions, index=self.statesWithLastState)
        self.q_matrixDF

        self.possibleStates = []

        for i in range(len(self.statesWithLastState)):
            if self.statesWithLastState[i][0][0] == self.statesWithLastState[i][1][0] or self.statesWithLastState[i][0][1] == self.statesWithLastState[i][1][1]:
                self.possibleStates.append(self.statesWithLastState[i])

        # removing impossible states from q matrix -> 45 possible states left
        self.q_matrix = np.zeros((45,6))
        self.q_matrixDF = pd.DataFrame(self.q_matrix, columns=self.actions, index=self.possibleStates)

        # discount rate
        self.gamma = 0.9

        # learning rate
        self.alpha = 0.1

        # decides if Q-value is used todetermine the action or take a random sample of the action space
        self.epsilon = 1.0
        self.epsilon_min = 0.01
        self.epsilon_decay = 0.95 #0.9

    ### methods for Q-Learning algorithm ###

    # get reward for movement
    def getDistanceReward(self, dist1, dist2):
        distanceReward = 0
        if dist2 < dist1:
            if dist1 - dist2 > 3:
                distanceReward = 10
            else:
                distanceReward = 5
        elif dist2 == dist1:
            distanceReward = -2
        elif dist1 - dist2 < -1:
            distanceReward = -10
        else:
            distanceReward = -5
        return distanceReward

    # get random action
    def getValidRandomAction(self, state):
        randomAction = state.sample(n=1, axis=1)
        print(f"random action:{randomAction.columns.values[0]}")
        return randomAction.columns.values[0]

    # get the next state for taken action
    def getNextState(self, state, action):
        if action.startswith('_'):
            temp = list(state.index[0])
            temp[1] = temp[0]
            temp[0] = temp[0][0] + action[1]
            nextState = tuple(temp)
        else:
            temp = list(state.index[0])
            temp[1] = temp[0]
            temp[0] = action[0] + temp[0][1]
            nextState = tuple(temp)
        return nextState

    # method to get all possible actions (not None) from a state row
    def getAllPossibleActions(self,stateRow):
        allPossibleActions = []
        for i in range(len(stateRow.columns)):
          allPossibleActions.append(stateRow.columns.values[i])
        return allPossibleActions

    def setStartingState(self,state,leg):
        if state == '00':
            print('00')
            self.servos.moveUpperLegDown(leg)
            self.servos.moveLowerLegDown(leg)
        elif state == '01':
            print('01')
            self.servos.moveUpperLegDown(leg)
            self.servos.moveLowerLegMid(leg)
        elif state == '02':
            print('02')
            self.servos.moveUpperLegDown(leg)
            self.servos.moveLowerLegUp(leg)
        elif state =='10':
            print('10')
            self.servos.moveUpperLegMid(leg)
            self.servos.moveLowerLegDown(leg)
        elif state =='11':
            print('11')
            self.servos.moveUpperLegMid(leg)
            self.servos.moveLowerLegMid(leg)
        elif state =='12':
            print('12')
            self.servos.moveUpperLegMid(leg)
            self.servos.moveLowerLegUp(leg)
        elif state =='20':
            print('20')
            self.servos.moveUpperLegUp(leg)
            self.servos.moveLowerLegDown(leg)
        elif state =='21':
            print('21')
            self.servos.moveUpperLegUp(leg)
            self.servos.moveLowerLegMid(leg)
        elif state =='22':
            print('22')
            self.servos.moveUpperLegUp(leg)
            self.servos.moveLowerLegUp(leg)

    def doAction(self, action, leg):
        if action == "2_":
            self.servos.moveUpperLegUp(leg)
        elif action == "0_":
            self.servos.moveUpperLegDown(leg)
        elif action == "_2":
            self.servos.moveLowerLegUp(leg)
        elif action == "_0":
            self.servos.moveLowerLegDown(leg)
        elif action == "1_":
            self.servos.moveUpperLegMid(leg)
        elif action == "_1":
            self.servos.moveLowerLegMid(leg)

    # function to find best action for current state
    def getBestActionFromQTable(self, state):
        maxValue = state.values[0][0]
        maxAction = state.columns.values[0]
        for i in range(len(state.columns)):
            if state.values[0][i] >= maxValue:
                maxAction = state.columns.values[i]
                maxValue = state.values[0][i]
            else:
                continue
        return maxAction

    def getBestNextValueFromQTable(self, state):
        maxValue = state.values[0][0]
        for i in range(len(state.columns)):
            if state.values[0][i] >= maxValue:
                maxValue = state.values[0][i]
            else:
                continue
        return maxValue


import globals
import utils
import math
import json

def draw_box(drawing_settings, width, padding):
    remain = width - 2 - (padding * 2)

    if json.loads(utils.read_file('config/setup.json'))["decode_settings"]['use_rotator'] is True:
        radio = f"ROTATOR: ⟳ {str(globals.ROTATOR_AZIMUTH).zfill(2)}°  ∠ {str(globals.ROTATOR_ELEVATION).zfill(2)}°".ljust(40)
    else:
        radio = utils.add_col("ROTATOR: disabled", math.floor(remain/4))

    if json.loads(utils.read_file('config/setup.json'))["api_settings"]['use_api'] is True:
        target = f"http://{globals.API_HOST}:{globals.API_PORT}"
        if drawing_settings.render == 'ansi':
            server = f"API: \u001b]8;;{target}\u001b\\{target}\u001b]8;;\u001b\\"
        elif drawing_settings.render == 'html':
            server = f"API: {target}"
        else:
            raise Exception(f"unsupported render type: {drawing_settings.render}")
    else:
        server = "SERVER: disabled"

    if width < 120:
        last_action = utils.add_col(f"LAST ACTION: {globals.LAST_ACTION}", math.floor(remain))
        text_buffer = (' ' * padding) + last_action
    elif width < 140:
        last_action = utils.add_col(f"LAST ACTION: {globals.LAST_ACTION}", math.floor(remain / 1.3))
        text_buffer = (' ' * padding) + last_action + radio
    else:
        last_action = utils.add_col(f"LAST ACTION: {globals.LAST_ACTION}", math.floor(remain / 2))
        text_buffer = (' ' * padding) + last_action + radio + server

    if drawing_settings.render == 'ansi':
        return text_buffer, 3
    elif drawing_settings.render == 'html':
        table = "<pre>" + text_buffer + "</pre>"
        return table, 3
    else:
        raise Exception("unsupported render type")


# adapted from https://github.com/SoloChe/ddib/blob/main/scripts/synthetic_sample.py

import argparse
import os
import sys
sys.path.append(os.path.realpath('./'))

import pathlib

import numpy as np
import torch as th
import torch.distributed as dist

from common import read_model_and_diffusion
from guided_diffusion import dist_util, logger
from guided_diffusion.script_util import  model_and_diffusion_defaults, add_dict_to_argparser

from torchvision.utils import make_grid, save_image

def sample(model, diffusion, num_classes=None,
           w=None, sample_shape=None, name=None):
    samples_for_each_cls = 5 # default
    if num_classes is not None: # for clf-free
        samples_for_each_cls = sample_shape[0] // num_classes
        y = th.ones(samples_for_each_cls, dtype=th.long) *\
            th.arange(start = 0, end = num_classes).reshape(-1, 1)
        y = y.reshape(-1,1).squeeze().to(dist_util.dev())
        model_kwargs = {'y': y}
    else:
        model_kwargs = {}

    samples = diffusion.ddim_sample_loop(model,
                                         sample_shape,
                                         clip_denoised=False,
                                         w=w,
                                         model_kwargs=model_kwargs,
                                         device=dist_util.dev())

    if name == 'cifar10':
        samples = (samples + 1) / 2 # normalize it back
    return samples, samples_for_each_cls

def main():
    args = create_argparser().parse_args()

    dist_util.setup_dist()
    logger.configure()
    logger.log(f"args: {args}")
    logger.log("starting to sample.")

    args.num_classes = int(args.num_classes) if args.num_classes is not None else None

    image_folder = args.image_dir
    pathlib.Path(image_folder).mkdir(parents=True, exist_ok=True)

    logger.log(f"reading models ...")
    model, diffusion = read_model_and_diffusion(args, args.model_path)

    all_samples = []

    for n in range(args.n_batches):
        logger.log("sampling in progress.")
        logger.log(f"on batch {n}, device: {dist_util.dev()}")

        # save samples

        samples, samples_for_each_cls = sample(model, diffusion, num_classes=args.num_classes,
                         w=args.w, sample_shape=args.sample_shape, name=args.name)

        if args.save_image:
            grid = make_grid(samples, nrow=samples_for_each_cls)
            path = os.path.join(image_folder, f'batch_{n}_rank_{dist.get_rank()}.png')
            save_image(grid, path)

        if args.save_data_numpy:
            gathered_samples = [th.zeros_like(samples) for _ in range(dist.get_world_size())]
            dist.all_gather(gathered_samples, samples)
            all_samples.extend([sample.cpu().numpy() for sample in gathered_samples])

    if args.save_data_numpy:
        samples = np.concatenate(all_samples, axis=0)
        points_path = os.path.join(image_folder, f"all_samples.npy")
        np.save(points_path, samples)

    dist.barrier()
    logger.log(f"sampling synthetic data complete\n\n")

def create_argparser():
    defaults = dict(
        n_batches=4,
        model_path="",
        image_dir="",
        name="",
        save_data_numpy=True, # save data in numpy format
        save_image=True # save image as in png format
    )
    defaults.update(model_and_diffusion_defaults())
    parser = argparse.ArgumentParser()

    parser.add_argument(
        "--sample_shape",
        type=int,
        nargs="+",
        help="sample shape for a batch"
    )
    parser.add_argument(
        "--w",
        type=float,
        help="weight for clf-free samples",
        default=-1. # disabled in default
    )
    add_dict_to_argparser(parser, defaults)
    return parser

if __name__ == "__main__":
    main()


from pysnmp.hlapi import *
from pysnmp.smi import builder

# Create a MIB builder with custom OIDs
mibBuilder = builder.MibBuilder()
mibBuilder.addMibSources(builder.DirMibSource('file://custom-mib.mib'))

# Add custom OIDs to the MIB tree (use invalid or custom OIDs)
mibBuilder.loadModules('NEW-MIB')

# Define your custom or invalid OID
custom_oid = '3.3.4.5.4.1.2.2'

# Define the SNMP trap parameters
community = 'public'
trap_host = '192.168.1.2'
trap_port = 162

snmp_trap = NotificationType(
    ObjectIdentity(custom_oid)
)

iterator = sendNotification(
    SnmpEngine(),                               # Initilise snmp engine
    CommunityData(community),         # specify the community (user group) that the message is part of
    UdpTransportTarget((trap_host, trap_port)), ## specify target address and port
    ContextData(),                              # any addition context (send as extra text)
    'trap',                                     # indicates we are sending a trap
    snmp_trap
)

errorIndication, errorStatus, errorIndex, varBinds = next(iterator)

if errorIndication:
    print(errorIndication)
else:
    print("SNMP Trap Sent")
    print(snmp_trap)


from flask import Blueprint, request, jsonify
from sqlalchemy import text
from ..utils import db

bp = Blueprint("records", __name__, url_prefix="/records")

@bp.route("/")
def records():
    conn = db.get_db()
    page = request.args["page"] if "page" in request.args else 0
    number = request.args["number"] if "number" in request.args else 10
    field = request.args["sortField"] if "sortField" in request.args else "disease"
    order = request.args["sortOrder"] if "sortOrder" in request.args else "asc"
    author = request.args["author"] if "author" in request.args else None

    if field == "country":
        field = "R.cname"
    elif field == "disease":
        field = "D.description"
    elif field == "discover_country":
        field = "DS.cname"
    elif field == "deaths":
        field = "total_deaths"
    elif field == "cured":
        field = "total_patients"

    query = f"""SELECT
                    R.cname as country,
                    R.email,
                    R.disease_code,
                    D.description as disease,
                    first_enc_date,
                    DS.cname as discover_country,
                    pathogen,
                    population,
                    total_deaths as deaths,
                    total_patients as cured,
                    name,
                    surname
                FROM Record R
                JOIN Country C ON R.cname = C.cname
                JOIN Disease D ON R.disease_code = D.disease_code
                JOIN DiseaseType DT ON D.id = DT.id
                JOIN Discover DS ON R.disease_code = DS.disease_code
                JOIN Users U ON R.email = U.email """
    filter = f"WHERE R.email = '{author}' " if author is not None else " "
    sorting = f"""ORDER BY {field} {order}
                  OFFSET {number} * {page}
                  LIMIT {number}"""

    rows = conn.execute(text(query + filter + sorting)).all()

    query = f"""SELECT COUNT(*)
                FROM Record R """
    count = conn.execute(text(query + filter)).one()[0]

    records = []
    for r in rows:
        records.append(r._asdict())

    res = { "count": count, "records": records }
    return jsonify(res)


#Exercício Python 081: Crie um programa que vai ler vários números e colocar em uma lista.
#A) Quantos números foram digitados.
# B) A lista de valores, ordenada de forma decrescente.
# C) Se o valor 5 foi digitado e está ou não na lista.
import sys

op = 'S'
while(op =='S'):
    numeros = []
    digitado = 'Sim'
    for i in range(1,7):
        n = int(input('Informe um valor: '))
        #Tratando para que um número não se repita na lista
        if n not in numeros:
            numeros.append(n)
        else:
            print(f'O número {n} já se encontra na lista.')

    #Verificando se o número 5 se encontra na lista
    if 5 in numeros:
        digitado = 'Sim'
    else:
        digitado = 'Não'

    print(f'Total de números digitados:{i}')
    numeros.sort(reverse=True)
    desc = '-'.join(map(str, numeros))
    print(f'Lista em ordem descrescente:{desc}')
    print(f'O número 5 foi digitado e está na lista? {digitado}')

    op = input('Deseja continuar? ').upper()[0]
else:
    print('Saindo...')
    sys.exit()


import re
import os
import shutil
import logging
import subprocess
from wave_train.graphics.helper import movie
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

class Animation:
    """
    Class for handling creation of animated output and eventually saving the
    animation as a .mp4 file. The motivation to develop this class has been to
    solve the underlying problem of the FuncAnimation class, namely that creation
    of animation output and visualization are executed in order and not in parallel.

    1) If image_file is not None, last snaphot is saved, but previous snapshots are removed.
    2) If image_file is not None and snapshot is True, all snapshots are saved.
       If image_file == None and snapshot == True, a default snapshot name will be assigned
    3) If image_file is not None, movie_file is not None, and snapshot is True,
       a movie is created from the snapshot and snapshots are not removed
    """
    __slots__ = [
        "dynamics",     # dynamics object used to update plot
        "movie_file",   # output name of movie
        "movie_suffix", # file suffix of output movie
        "image_file",   # name of the image file for output of last figure state
        "image_suffix", # suffix of the image file
        "snapshots",    # avoid cleanup of files created
        "save",         # variable holding the logical state if output movie is generated
        "fig",          # figure object holding the plot
        "update",       # update function called in FuncAnimation loop
        "init",         # init function called in FuncAnimation setup
        "frames",       # frames in the animation
        "pause",        # pause between frames
        "frame_rate",   # number of frames per second
        "frame_count"   # counter of frames/snaphots in animation
    ]

    movie_formats = ['mp4']
    image_formats = ['png']

    def __init__(self, dynamics, movie_file, image_file, snapshots, figure, update,
                            init=None, frames=None, blit=False, pause=200, frame_rate=10):
        """
        Parameters
        ------------
        dynamics: Instance of Dyanmics class
            The instance holding the dynamics object, which is provided
            via the fargs option to the update function
        movieFile: str
            Name of the movie file saving the animation output
        imageFile: str
            Name of the image file snapshotting the last frame
        figure: Figure object
            Figure instance for animated output
        update: Callable
            Update function for new frame
        init: Callable
            Initializer function for defining plot parameters
        frames: Iterable
            Number of frames to display
        blit: bool
            Use of blitting
        pause: uint
            Pause between each frame in visualization
        frame_rate:  uint
            Number of frames in animation output
        """
        self.dynamics       = dynamics
        self.movie_file     = movie_file
        self.image_file     = image_file
        self.snapshots      = snapshots
        self.fig            = figure
        self.update         = update
        self.init           = init
        self.frames         = frames
        self.pause          = pause
        self.frame_rate     = frame_rate
        self.frame_count    = 0
        self.save           = True

        if not (isinstance(movie_file, str) or movie_file is None):
            raise TypeError("Movie file argument must be an instance of 'str' or 'NoneType'")
        if not (isinstance(image_file, str) or image_file is None):
            raise TypeError("Image file argument must be an instance of 'str' or 'NoneType'")

        if self.image_file is None:
            if snapshots and self.movie_file is not None:
                self.image_file = "snaphot.png"
                logging.warning("Name for snapshots was not provided. Defaulting to 'snapshot.png'")
            elif self.movie_file is not None:
                # indicate that all snaphots must be removed
                self.image_file = "snapshot_removable.png"
            else:
                self.image_file = ""

        if self.movie_file is None:
            self.movie_file = ""

        self.image_file, self.image_suffix = os.path.splitext(self.image_file)
        self.movie_file, self.movie_suffix = os.path.splitext(self.movie_file)

    def start(self):
        try:
            animation = FuncAnimation(self.fig, self.update, init_func=lambda: None, frames=self.frames,
                                      fargs=(self.fig, self.dynamics, self, self.save),
                                      repeat=False)
            plt.show()
        except Exception as AnimationError:
            print(AnimationError)
        finally:
            movie_files = self._get_temp_files()

            if len(movie_files) == 0:
                return

            if self.movie_file != "":
                self._export_as_mp4(movie_files)

            if not self.snapshots and self.image_file != "":
                # if the snapshot is removable, remove all snapshots
                if not self.image_file == "snapshot_removable":
                    movie_files.pop(-1)

                self._cleanup(movie_files)

            if self.image_file == "" and self.snapshots == False:
                self._cleanup(movie_files)

    def _export_as_mp4(self, movie_files):
        print("""
------------------------
Saving animation to file
------------------------

Filename : {}
Frames   : {} per second
        """.format(self.movie_file, str(self.frame_rate)))

        subprocess.call(["ffmpeg", "-loglevel", "quiet", "-y", "-r", str(self.frame_rate - 9), "-i",
                         f"{self.image_file}_%06d{self.image_suffix}", f"output{self.movie_suffix}"])

        subprocess.call(["ffmpeg", "-loglevel", "quiet", "-y", "-i", f"output{self.movie_suffix}", "-c:v", "libx264", "-preset",
                         "slow", "-crf", "22", "-pix_fmt", "yuv420p", "-c:a",
                         "libvo_aacenc", "-b:a", "128k", f"{self.movie_file}{self.movie_suffix}"])

        os.remove(f"output{self.movie_suffix}")

    def _get_temp_files(self):
        tmp_files = re.compile("%s_\d{6}%s" % (self.image_file, self.image_suffix))
        movie_files = []

        for root, dir, files in os.walk("."):
            for tmp in files:
                if re.match(tmp_files, tmp):
                    movie_files.append(tmp)

        return sorted(movie_files)

    def _cleanup(self, movie_files):
        """
        Delete all temporary files that were created during the
        animation run. Ideally, the movie_files argument should
        be provided as the return of the _get_temp_files function.
        """
        for movie_file in movie_files:
            os.remove(movie_file)

    def save_as_image(self):
        if self.image_file != "":
            file_name = f"{self.image_file}_{str(self.frame_count).zfill(6)}{self.image_suffix}"
            self.fig.savefig(file_name)
            self.frame_count += 1


from collections import deque

class PieceInfo :
    def __init__(self, num, locaArr):
        self.num = num
        self.loca = locaArr

class PuzzleGame :
    def __init__(self, gameBoard, table):
        self.answer = 0
        self.gameBoard = gameBoard
        self.table = table
        self.N = len(gameBoard)

        self.gmaeDict = dict()
        self.tableDict = dict()

        self.gameVisted = set()
        self.tableVisted = set()

        self.dx = [-1,0,1,0]
        self.dy = [0,1,0,-1]

    def findPiece(self, target, board, x, y, visted) :
        visted.add((x,y))
        que = deque([(x,y)])
        arr = [(x,y)]
        while que :
            qx, qy = que.popleft()
            for i in range(4) :
                nx = qx + self.dx[i]
                ny = qy + self.dy[i]
                if nx < 0 or nx >= self.N or ny < 0 or ny >= self.N :
                    continue
                if board[nx][ny] != target :
                    continue
                if (nx,ny) in visted :
                    continue
                visted.add((nx, ny))
                que.append((nx, ny))
                arr.append((nx,ny))
        return arr

    def getTablePiece(self) :
        for i in range(self.N) :
            for j in range(self.N) :
                if (i,j) in self.tableVisted or self.table[i][j] == 0:
                    continue
                arr = self.findPiece(1, self.table, i,j, self.tableVisted)
                newPiece = PieceInfo(len(arr), arr)
                if len(arr) not in self.tableDict:
                    self.tableDict[len(arr)] = deque([])
                self.tableDict[len(arr)].append(newPiece)

    def getBoardPiece(self) :
        for i in range(self.N) :
            for j in range(self.N) :
                if (i,j) in self.gameVisted or self.gameBoard[i][j] == 1:
                    continue
                arr = self.findPiece(0, self.gameBoard, i,j, self.gameVisted)
                newPiece = PieceInfo(len(arr), arr)
                if len(arr) not in self.gmaeDict:
                    self.gmaeDict[len(arr)] = deque([])
                self.gmaeDict[len(arr)].append(newPiece)

    def moveToZero(self, arr) :
        result = []
        leftArr = sorted(arr, key = lambda x : x[0])
        topArr = sorted(arr, key = lambda x: x[1])

        left = leftArr[0][0]
        top = topArr[0][1]
        for x,y in arr :
            result.append((x-left, y - top))
        return sorted(result)

    def rotate90(self, arr) :
        retsut = []
        for x ,y in arr :
            nx = y + self.N -1
            ny = -x + self.N -1
            retsut.append((nx,ny))
        return self.moveToZero(retsut)

    def getAnswer(self) :
        self.getBoardPiece()
        self.getTablePiece()
        for k in self.gmaeDict.keys() :
            if k not in self.tableDict :
                continue
            if k == 2 :
                self.answer += min(len(self.gmaeDict[k]), len(self.tableDict[k]))*2
                continue
            elif k == 1 :
                self.answer += min(len(self.gmaeDict[k]), len(self.tableDict[k]))
                continue

            while self.gmaeDict[k] :
                piece = self.gmaeDict[k].pop()
                piece.loca = self.moveToZero(piece.loca)
                bf = False
                for tp in self.tableDict[k] :
                    target = self.moveToZero(tp.loca)
                    for _ in range(4) :
                        if target == piece.loca :
                            self.answer += k
                            bf = True
                            break
                        else :
                            target = self.rotate90(target)
                    if bf :
                        self.tableDict[k].remove(tp)
                        break
        return self.answer

def solution(game_board, table):
    answer = -1
    g = PuzzleGame(game_board, table)
    answer = g.getAnswer()
    return answer

gameBoard = [[1,1,0,0,1,0],[0,0,1,0,1,0],[0,1,1,0,0,1],[1,1,0,1,1,1],[1,0,0,0,1,0],[0,1,1,1,0,0]]
table = [[1,0,0,1,1,0],[1,0,1,0,1,0],[0,1,1,0,1,1],[0,0,1,0,0,0],[1,1,0,1,1,0],[0,1,0,0,0,0]]
print(solution(gameBoard, table))


from django.conf.urls import patterns, include, url
from web.views import *
#from django.contrib import admin
from django.conf import settings

urlpatterns = patterns('',
    # Examples:
    url(r'^$',login),
    url(r'^login/', login),
    url(r'^person/$',person),
    url(r'^mission/$',mission),
    url(r'^report/$',daily_report),
    url(r'^load/$',load),
    (r'^static/(?P<path>.*)$','django.views.static.serve',{'document_root':settings.STATIC_URL}),
    #url(r'^admin/', include(admin.site.urls)),
)


output_dir = './'
model_to_save = model.module if hasattr(model, 'module') else model
model_to_save.save_pretrained(output_dir)
tokenizer.save_pretrained(output_dir)

from transformers import BertTokenizer,BertForSequenceClassification
import torch
# Load the BERT tokenizer.
print('Loading BERT tokenizer...')
output_dir = './'
tokenizer = BertTokenizer.from_pretrained(output_dir)
model_loaded = BertForSequenceClassification.from_pretrained(output_dir)

test_text = test.tweet.values
input_ids = []
attention_mask = []
for i in tqdm(test_text):
    encoded_data = tokenizer.encode_plus(
    str(i),
    add_special_tokens=True,
    max_length= 64,
    pad_to_max_length = True,
    return_attention_mask= True,
    return_tensors='pt')
    input_ids.append(encoded_data['input_ids'])
    attention_mask.append(encoded_data['attention_mask'])
input_ids = torch.cat(input_ids,dim=0)
attention_mask = torch.cat(attention_mask,dim=0)

testset = TensorDataset(input_ids,attention_mask)
test_dl = DataLoader(testset, batch_size=1)

def evaluate2(dataloader_test):
    model_loaded =  BertForSequenceClassification.from_pretrained(output_dir)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    model_loaded = model_loaded.to(device)
    predictions = []

    for batch in dataloader_test:
        batch = tuple(b.to(device) for b in batch)
        inputs = {
            'input_ids':batch[0],
            'attention_mask': batch[1]
        }
        with torch.no_grad():
            outputs = model_loaded(**inputs)
        logits = outputs[0]
        logits = logits.detach().cpu().numpy()
        predictions.append(logits)
    predictions = np.concatenate(predictions,axis=0)
    result = np.argmax(predictions, axis=1).flatten()

    return result

test_result = evaluate2(test_dl)

measure_accuracy = test
measure_accuracy['bert'] = test_result
from sklearn.metrics import confusion_matrix
from sklearn.metrics import f1_score
from sklearn.metrics import precision_recall_fscore_support
from sklearn.metrics import accuracy_score
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split

print('f1 score', f1_score(measure_accuracy.sentiment, measure_accuracy.bert, average=None))
print(confusion_matrix(measure_accuracy.sentiment, measure_accuracy.bert))
print(precision_recall_fscore_support(measure_accuracy.sentiment, measure_accuracy.bert, average='weighted'))
print('accuarcy', accuracy_score(measure_accuracy.sentiment, measure_accuracy.bert))


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

i = 0
positive = 0
total = 0
while i < 6:
	a = float(input())
	if a > 0:
		positive += 1
		total += a
	i += 1

print(f'{positive} valores positivos')
print(f'{total / positive:.1f}')


from __future__ import absolute_import

from abc import ABCMeta, abstractmethod
from redis.exceptions import RedisError
from time import time
import collections
import pickle
import logging
import re

from tornado import gen
from tornado import concurrent

from reactorcore.dao.redis import RedisSource
from reactorcore.services.base import BaseService

logger = logging.getLogger(__name__)

class AbstractCache:
    __metaclass__ = ABCMeta

    @abstractmethod
    def set(self, *args, **kwargs):
        pass

    @abstractmethod
    def unique_add(self, *args, **kwargs):
        pass

    @abstractmethod
    def get_unique_set(self, *args, **kwargs):
        pass

    @abstractmethod
    def get(self, *args, **kwargs):
        pass

    @abstractmethod
    def get_int(self, *args, **kwargs):
        pass

    @abstractmethod
    def get_array(self, *args, **kwargs):
        pass

    @abstractmethod
    def get_multi(self, *keys):
        pass

    @gen.coroutine
    def incr(self, key, ticks=1):
        logger.debug('Incrementing  "%s" by %s', key, ticks)
        return

    @gen.coroutine
    def decr(self, key, ticks=1):
        logger.debug('Decrementing  "%s" by %s', key, ticks)
        yield self.incr(key, ticks * -1)

    @abstractmethod
    def prepend(self, *args, **kwargs):
        pass

    @abstractmethod
    def append(self, *args, **kwargs):
        pass

    @abstractmethod
    def remove(self, *args, **kwargs):
        pass

    @abstractmethod
    def flush(self, *args, **kwargs):
        pass

    @abstractmethod
    def flush_all(self):
        pass

class VoidCache(BaseService, AbstractCache):
    """
    Pass-through cache
    """

    @gen.coroutine
    def set(self, *args, **kwargs):
        return

    @gen.coroutine
    def unique_add(self, *args, **kwargs):
        return

    @gen.coroutine
    def get_unique_set(self, *args, **kwargs):
        pass

    @gen.coroutine
    def get(self, *args, **kwargs):
        return

    @gen.coroutine
    def get_int(self, *args, **kwargs):
        return 0

    @gen.coroutine
    def get_array(self, *args, **kwargs):
        return []

    @gen.coroutine
    def incr(self, key, ticks=1):
        pass

    @gen.coroutine
    def decr(self, key, ticks=1):
        pass

    @gen.coroutine
    def delete(self, *args, **kwargs):
        pass

    @gen.coroutine
    def flush(self, *args, **kwargs):
        pass

    @gen.coroutine
    def flush_all(self):
        pass

    @gen.coroutine
    def get_multi(self, *keys_in):
        raise gen.Return(dict.fromkeys(keys_in))

class RedisCache(RedisSource, BaseService, AbstractCache):
    """
    Redis-based cache
    """

    FLUSH_STEP = 1000

    def __init__(self):
        super(RedisCache, self).__init__(name="CACHE", cls=self.__class__)
        self.prefix = "cache:"

    @concurrent.run_on_executor
    def set(self, key, value, expire=None):
        logger.debug('Setting cache key "%s" with TTL %s', key, expire)

        key = self.prefix + key
        pickled_val = pickle.dumps(value)

        try:
            if expire is not None:
                # Add key and define an expire in a pipeline for atomicity
                with self.client.pipeline() as pipe:
                    pipe.set(key, pickled_val)
                    pipe.expire(key, expire)
                    pipe.execute()
            else:
                self.client.set(key, pickled_val)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache SET: %s", ex.message, exc_info=True
            )

    @concurrent.run_on_executor
    def get(self, key):
        logger.debug('Getting  key "%s"', key)

        key = self.prefix + key
        data = None

        value = None

        try:
            data = self.client.get(key)
            # unpickle
            value = pickle.loads(data) if data else None

            logger.debug('Value for "%s": %s', key, value)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET: %s", ex.message, exc_info=True
            )

        return value

    @gen.coroutine
    def unique_add(self, set_name, value):
        logger.debug('Adding "%s" to set "%s"', value, set_name)

        try:
            self.client.sadd(set_name, value)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET: %s", ex.message, exc_info=True
            )

    @gen.coroutine
    def get_unique_set(self, set_name):
        logger.debug('Getting set "%s"', set_name)
        try:
            members = self.client.smembers(set_name)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET: %s", ex.message, exc_info=True
            )

        members = members or set()
        logger.debug('%s items in "%s"', len(members), set_name)
        return members

    @concurrent.run_on_executor
    def get_int(self, key):
        logger.debug('Getting  key "%s"', key)

        key = self.prefix + key
        value = None

        try:
            value = self.client.get(key)
            logger.debug('Value for "%s": %s', key, value)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET: %s", ex.message, exc_info=True
            )

        return value or 0

    @concurrent.run_on_executor
    def get_array(self, key, count=None):
        assert count
        logger.debug('Getting array for key "%s" with %s items', key, count)

        key = self.prefix + key
        arr = []
        try:
            data = self.client.lrange(key, 0, count - 1)

            # unpickle elements
            if data:
                arr = map(lambda x: pickle.loads(x), data)

            logger.debug('Value for "%s": %s', key, arr)

        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET: %s", ex.message, exc_info=True
            )

        return arr

    @concurrent.run_on_executor
    def get_multi(self, *keys_in):
        if not keys_in:
            return None

        logger.debug('Getting keys "%s"', keys_in)
        keys = [self.prefix + key for key in keys_in]

        lookup = None

        try:
            data = self.client.mget(keys)

            # unpickle values
            values = [(val and pickle.loads(str(val))) or None for val in data]

            # remove the cache prefix from keys
            keys = [key[len(self.prefix) :] for key in keys]

            # pack into key/val dictionary so it's more usable for the client
            lookup = dict(zip(keys, values))

            logger.debug("Cache data: %s", lookup)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache MGET: %s",
                ex.message,
                exc_info=True,
            )
            return dict.fromkeys(keys_in)
        except pickle.UnpicklingError as ex:
            logger.critical(
                "[EXCEPTION] Unpickle error: %s", ex.message, exc_info=True
            )
            return dict.fromkeys(keys_in)

        return lookup

    @concurrent.run_on_executor
    def incr(self, key, ticks=1):
        assert key
        logger.debug('Incrementing "%s" by %s', key, ticks)
        key = self.prefix + key
        try:
            self.client.incr(key, ticks)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache INCR: %s",
                ex.message,
                exc_info=True,
            )

    @gen.coroutine
    def prepend(self, key, value, size=1000):
        assert key
        assert size > 1
        logger.debug('Prepending "%s" to %s', value, key)
        key = self.prefix + key
        pickled_val = pickle.dumps(value)

        try:
            with self.client.pipeline() as pipe:
                pipe.lpush(key, pickled_val)
                pipe.ltrim(key, 0, size - 1)
                pipe.execute()
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache PREPEND: %s",
                ex.message,
                exc_info=True,
            )

    @gen.coroutine
    def append(self, key, value, size=1000):
        assert key
        assert size > 1
        logger.debug('Appending "%s" to %s', value, key)
        key = self.prefix + key
        pickled_val = pickle.dumps(value)

        try:
            with self.client.pipeline() as pipe:
                pipe.rpush(key, pickled_val)
                pipe.ltrim(key, 0, size - 1)
                pipe.execute()
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache APPEND: %s",
                ex.message,
                exc_info=True,
            )

    @concurrent.run_on_executor
    def remove(self, *keys_in):
        if not keys_in:
            return None

        logger.debug("Deleting keys %s", keys_in)

        # add prefix
        keys = [self.prefix + key for key in keys_in]

        try:
            with self.client.pipeline() as pipe:
                pipe.delete(*keys)
                pipe.execute()
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache DELETE: %s",
                ex.message,
                exc_info=True,
            )

    @concurrent.run_on_executor
    def flush(self, pattern=None):
        if not pattern:
            return
        logger.debug('Flushing pattern "%s"', pattern)

        try:
            """Flush all cache (by group of step keys for efficiency),
            or only keys matching an optional pattern"""
            keys = self.client.keys(self.prefix + pattern)
            for i in xrange(0, len(keys), self.FLUSH_STEP):
                keys_to_flush = keys[i : i + self.FLUSH_STEP]
                logger.debug("Flushing cache keys %s", keys_to_flush)
                self.client.delete(*keys_to_flush)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache FLUSH: %s",
                ex.message,
                exc_info=True,
            )

    @concurrent.run_on_executor
    def flush_all(self):
        logger.debug("FLUSH ALL")
        # flush all keys for this environment
        return self.flush(self.prefix + "*")

    """
    Add hashing functionality
    """

    @gen.coroutine
    def set_hash(self, key, val):
        key = self.prefix + key
        try:
            self.client.hmset(key, val)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache HASH SET: %s",
                ex.message,
                exc_info=True,
            )

    @gen.coroutine
    def delete_hash_key(self, r_hash, *keys):
        r_hash = self.prefix + r_hash
        try:
            return self.client.hdel(r_hash, *keys)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache HASH DEL: %s",
                ex.message,
                exc_info=True,
            )

    @gen.coroutine
    def get_hash(self, key, hash_key):
        key = self.prefix + key
        try:
            return self.client.hget(key, hash_key)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache HASH GET: %s",
                ex.message,
                exc_info=True,
            )

    @gen.coroutine
    def get_all_hashes(self, key):
        key = self.prefix + key
        try:
            return self.client.hgetall(key)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET ALL HASHES: %s",
                ex.message,
                exec_info=True,
            )

    @gen.coroutine
    def get_hash_size(self, key):
        key = self.prefix + key
        try:
            return self.client.hlen(key)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET HASH LENGTH: %s",
                ex.message,
                exec_info=True,
            )

    @gen.coroutine
    def get_keys(self, pattern):
        try:
            return self.client.keys(pattern)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET KEYS: %s",
                ex.message,
                exec_info=True,
            )

    @gen.coroutine
    def trim_array(self, key, start, end):
        key = self.prefix + key
        try:
            return self.client.ltrim(key, start, end)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache TRIM ARRAY: %s",
                ex.message,
                exec_info=True,
            )

    @gen.coroutine
    def set_zset(self, key, **sets):
        key = self.prefix + key
        try:
            return self.client.zadd(key, **sets)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache SET ZSET: %s",
                ex.message,
                exec_info=True,
            )

    @gen.coroutine
    def get_zrangebyscore(
        self, key, min_score, max_score, start=None, num=None, withscores=False
    ):
        key = self.prefix + key
        try:
            return self.client.zrangebyscore(
                key,
                min_score,
                max_score,
                start=start,
                num=num,
                withscores=withscores,
            )
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache GET ZRANGEBYSCORE: %s",
                ex.message,
                exec_info=True,
            )

    @gen.coroutine
    def del_zrangebyscore(self, key, min_score, max_score):
        key = self.prefix + key
        try:
            return self.client.zremrangebyscore(key, min_score, max_score)
        except RedisError as ex:
            logger.critical(
                "[EXCEPTION] Error on cache ZREMRANGEBYSCORE: %s",
                ex.message,
                exec_info=True,
            )

class MemoryCache(AbstractCache):
    """
    A very simple implementation of memory-based caching,
    to test the interface and decorators.
    """

    def __init__(self):
        self._cache = dict()
        self.hits = 0
        self.misses = 0

    @gen.coroutine
    def set(self, key, value, expire=None):
        logger.debug('Setting cache key "%s" with TTL %s', key, expire)

        self._cache[key] = {"ttl": expire, "created": time(), "val": value}

    @gen.coroutine
    def unique_add(self, set_name, value):
        logger.debug('Adding "%s" to set "%s"', value, set_name)

        if set_name not in self._cache:
            self._cache[set_name] = set()

        self._cache[set_name].add(value)

    @gen.coroutine
    def get_unique_set(self, set_name):
        assert set_name
        members = self._cache.get(set_name, set())
        raise gen.Return(members)

    @gen.coroutine
    def get(self, key):
        if key not in self._cache:
            self.misses += 1
            logger.debug('Cache miss for "%s"', key)
            raise gen.Return(None)

        value = self._cache.get(key)

        # expire if needed
        ttl = value["ttl"]
        logger.debug('TTL for "%s": %s', key, ttl)

        key_life = int(time() - value["created"])
        logger.debug('Key life for "%s": %s', key, key_life)

        if ttl is not None and key_life >= ttl:
            logger.debug('Expiring "%s"', key)
            logger.debug('Cache miss for "%s"', key)
            self.misses += 1
            self._cache.pop(key)
            raise gen.Return(None)

        logger.debug('Cache hit for "%s": %s', key, value["val"])
        self.hits += 1
        raise gen.Return(value["val"])

    @gen.coroutine
    def get_int(self, key):
        val = yield self.get(key)
        raise gen.Return(val or 0)

    @gen.coroutine
    def get_array(self, key, count=None):
        assert count
        arr = yield self.get(key)
        arr = arr or []
        raise gen.Return(arr[:count])

    @gen.coroutine
    def get_multi(self, *keys):
        logger.debug('Getting keys "%s"', keys)

        values = yield [self.get(key) for key in keys]

        lookup = dict(zip(keys, values))

        logger.debug("Cache data: %s", lookup)
        raise gen.Return(lookup)

    @gen.coroutine
    def incr(self, key, ticks=1):
        counter = yield self.get(key)
        if not counter:
            counter = 0
        assert isinstance(counter, int)
        yield self.set(key, counter + ticks)

    @gen.coroutine
    def prepend(self, key, value, size=1000):
        assert size > 1
        assert key
        val = yield self.get(key)
        if val:
            arr = collections.deque(val, maxlen=size)
        else:
            arr = collections.deque(maxlen=size)

        arr.appendleft(value)
        yield self.set(key, list(arr))

    @gen.coroutine
    def append(self, key, value, size=1000):
        assert key
        assert size > 1
        val = yield self.get(key)
        if val:
            arr = collections.deque(val, maxlen=size)
        else:
            arr = collections.deque(maxlen=size)

        arr.append(value)
        yield self.set(key, list(arr))

    @gen.coroutine
    def remove(self, *keys_in):
        if not keys_in:
            pass

        for key in keys_in:
            try:
                del self._cache[key]
            except KeyError:
                pass

    @gen.coroutine
    def flush(self, pattern=None):
        if not pattern:
            raise gen.Return(None)

        logger.debug("Deleting pattern: %s", pattern)

        # turn the simple "star" pattern into a real regex
        pattern = pattern.replace("*", ".*")
        pattern = "%s%s%s" % ("^", pattern, "$")
        matcher = re.compile(pattern)

        keys_to_flush = [
            key for key in self._cache.keys() if re.match(matcher, key)
        ]
        logger.debug("Flushing cache keys %s", keys_to_flush)
        for key_to_flush in keys_to_flush:
            del self._cache[key_to_flush]

        raise gen.Return(None)

    @gen.coroutine
    def flush_all(self):
        self._cache = dict()
        raise gen.Return(None)


import asyncio
from fastapi import APIRouter, Depends, HTTPException
from fastapi_cache.decorator import cache
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from database import get_async_session
from operations.models import Operation
from operations.schemas import OperationCreate, OperationRead, OperationUpdate
from schemas import ErrorDetails

OPERATIONS_PER_PAGE = 3

router = APIRouter()

# Get operations with specific type
@router.get("/")
@cache(expire=5)
async def get_specific_operations(
    operation_type: str, page: int = 1, session: AsyncSession = Depends(get_async_session)
) -> list[OperationRead]:
    query = select(Operation).where(Operation.type == operation_type) \
                .limit(OPERATIONS_PER_PAGE).offset(OPERATIONS_PER_PAGE * (page - 1))
    result = await session.scalars(query)
    return result.all()

# Long operation
@router.get("/long-operation")
@cache(expire=30)
async def process_long_operations() -> str:
    await asyncio.sleep(5)
    return "results"

# Create operation
@router.post(
    "/",
    status_code=201
)
async def add_specific_operation(
    new_operation: OperationCreate,
    session: AsyncSession = Depends(get_async_session)
) -> OperationRead:
    op = Operation(**new_operation.model_dump())
    session.add(op)
    await session.commit()
    return op

# Create or replace operation
@router.put(
    "/{operation_id}",
    responses={
        440: {
            "description": "Error. An operation with this id doesn't exists",
            "model": ErrorDetails
        }
    }
)
async def replace_specific_operation(
    operation_id: int,
    operation_data: OperationCreate,
    session: AsyncSession = Depends(get_async_session)
) -> OperationRead:
    op = await session.get(Operation, operation_id)
    if op:
        op.update_from_dict(operation_data.model_dump())
    else:
        raise HTTPException(
            status_code=440,
            detail=f"Error occurred. An operation with id={operation_id} " \
                    "doesn't exists"
        )

    await session.commit()
    return op

# Edit operation
@router.patch(
    "/{operation_id}",
    responses={
        440: {
            "description": "Error. An operation with this id doesn't exists",
            "model": ErrorDetails
        }
    }
)
async def update_specific_operation(
    operation_id: int,
    operation_data: OperationUpdate,
    session: AsyncSession = Depends(get_async_session)
) -> OperationRead:
    op = await session.get(Operation, operation_id)
    if op:
        op.update_from_dict(operation_data.model_dump())
        await session.commit()
        return op
    else:
        raise HTTPException(
            status_code=440,
            detail=f"Error occurred. An operation with id={operation_id} " \
                    "doesn't exists"
        )


from kivy.lang import Builder
from kivymd.app import MDApp
from kivymd.uix.picker import MDTimePicker

class MainApp(MDApp):
	def build(self):
		self.theme_cls.theme_style = "Light"
		self.theme_cls.primary_palette = "BlueGray"
		return Builder.load_file('time.kv')

	# Get Time
	def get_time(self, instance, time):
		self.root.ids.time_label.text = str(time)

	# Cancel
	def on_cancel(self, instance, time):
		self.root.ids.time_label.text = "You Clicked Cancel!"

	def show_time_picker(self):
		from datetime import datetime

		# Define default time
		default_time = datetime.strptime("4:20:00", '%H:%M:%S').time()

		time_dialog = MDTimePicker()
		# Set default Time
		time_dialog.set_time(default_time)
		time_dialog.bind(on_cancel=self.on_cancel, time=self.get_time)
		time_dialog.open()

MainApp().run()


from django.shortcuts import render
from django.views import generic

from ml.models import UserProfile, Publication, Resource

class GroupView(generic.ListView):
    template_name = 'group.html'
    context_object_name = 'users'

    def get_queryset(self):
        users = dict()
        try:
            users['leader'] = UserProfile.objects.get(membership='L')
        except UserProfile.DoesNotExist:
            pass
        users['members'] = list(UserProfile.objects.filter(
            membership='M'))
        users['exmembers'] = list(UserProfile.objects.filter(
            membership='X'))
        return users

def get_profile(request, username):
    context = {'user': UserProfile.objects.get(user__username=username)}
    return render(request, 'user.html', context)

class PublicationDetailView(generic.DetailView):
    template_name = 'publ_detail.html'
    model = Publication

class PublicationListView(generic.ListView):
    template_name = 'publ_list.html'
    context_object_name = 'publications'

    def get_queryset(self):
        return Publication.objects.order_by('-year')

class ResourceDetailView(generic.DetailView):
    template_name = 'res_detail.html'
    model = Resource

class ResourcesView(generic.ListView):
    template_name = 'res_list.html'
    context_object_name = 'resources'

    def get_queryset(self):
        return Resource.objects.order_by('name')

class IndexView(generic.TemplateView):
    template_name = 'ml_home.html'