import pytest
from fixtures.constants import Links
from fixtures.edit.api import edit_file
import allure
from fixtures.response import Response
from com.jsonschema.file import FileResponse
from com.jsonschema.error import ResponseError404

@allure.feature("Проверка изменения содержимого файла")
@allure.story("Проверка функции изменения содержимого файла")
@pytest.mark.positive
def test_edit_file(update_refresh_token):
    with allure.step("Изменение содержимого файла на Google Drive"):
        value = edit_file(Links.EDIT_FILE_ID)
    with allure.step("Запрос отправлен, проверим тело ответа"):
        Response.validate(value, FileResponse.schema)
    with allure.step("Запрос отправлен, посмотрим код ответа"):
        Response.log_assert(value.status_code == 200, "Check your file ID")
    with allure.step("Проверим имя файла, который изменяли"):
        Response.log_assert(value.json().get('name') == "test_edit_file.txt", "Check your file ID")

@allure.feature("Проверка изменения содержимого файла")
@allure.story("Проверка функции изменения содержимого файла с неверным ID")
@pytest.mark.negative
def test_edit_unknown_file(update_refresh_token):
    with allure.step("Изменение содержимого файла с неверным ID на Google Drive"):
        value = edit_file(Links.FILE_ID)
    with allure.step("Запрос отправлен, проверим тело ответа"):
        Response.validate(value, ResponseError404.schema)
    with allure.step("Запрос отправлен, посмотрим код ответа"):
        Response.log_assert(value.status_code == 404, "Check your file ID")


# Uses python3
from random import randint

period = (0, 1, 1, 2, 3, 5, 8, 3, 1, 4, 5, 9, 4, 3, 7, 0, 7, 7, 4, 1, 5, 6, 1, 7, 8, 5, 3, 8, 1, 9, 0, 9, 9, 8, 7,
          5, 2, 7, 9, 6, 5, 1, 6, 7, 3, 0, 3, 3, 6, 9, 5, 4, 9, 3, 2, 5, 7, 2, 9, 1)

def fibonacci_partial_sum_naive(from_, to):
    sum_ = 0

    current = 0
    next_ = 1

    for i in range(to + 1):
        if i >= from_:
            sum_ += current

        current, next_ = next_, current + next_

    return sum_ % 10

def fibonacci_partial_sum_optimized(from_, to):
    return sum(period[i % len(period)] for i in range(from_, to + 1)) % 10

def test_one(a, b, expected):
    actual = fibonacci_partial_sum_optimized(a, b)
    if actual != expected:
        print('WRONG!')
        raise Exception('expected {} got {}'.format(expected, actual))
    else:
        print('OK')

def stress_test():
    while True:
        a = randint(2, 10)
        b = randint(11, 20)
        print(a, b)
        expected = fibonacci_partial_sum_naive(a, b)
        test_one(a, b, expected)

if __name__ == '__main__':
    # stress_test()
    from__, to__ = map(int, input().split())
    print(fibonacci_partial_sum_optimized(from__, to__))


#1012
data = (input().split(" "))
a,b,c = float(data[0]),float(data[1]),float(data[2])

rect = 0.5*a*c
cir = 3.14159*c*c

trp = c*(a+b)/2
quad = b*b
rectan = a*b

print("TRIANGULO: {:0.3f}\nCIRCULO: {:0.3f}\nTRAPEZIO: {:0.3f}\nQUADRADO: {:0.3f}\nRETANGULO: {:0.3f}" .format(rect,cir,trp,quad,rectan))


from hashlib import sha256
from datetime import datetime

class Blockchain:

    def __init__(self):
        self.blocks = []
        self.set_genesis_block()

    def set_genesis_block(self):
        data = 'Olá, mundo!'
        timesamp = datetime.utcnow().timestamp()
        prev_hash = 0
        index = 0
        self.hash_block(
            data, timesamp, prev_hash, index
        )

    def hash_block(self, data, timestamp, prev_hash, index):
        hash = ''
        nonce = 1
        while not self.is_hash_valid(hash):
            block = f'{data}:{timestamp}:{prev_hash}:{index}:{nonce}'
            hash = sha256(block.encode()).hexdigest()
            nonce += 1
        print('[nonce]', nonce)
        self.blocks.append(hash)

    def get_last_hash(self):
        return self.blocks[-1]

    def is_hash_valid(self, hash):
        return hash.startswith('0000')

    def add_new_block(self, data):
        index = len(self.blocks)
        prev_hash = self.get_last_hash()
        timestamp = datetime.utcnow().timestamp()
        self.hash_block(
            data,timestamp, prev_hash, index
        )

    def get_all(self):
        return self.blocks[:]


import numpy as np
import pandas as pd

# from .exceptions import *

name = "PermanentPriceImpact"
description = """
"""
vars_needed = {"Price", "Volume", "Mid Point", "Direction"}

def estimate(data: pd.DataFrame) -> np.ndarray:
    if not vars_needed.issubset(data.columns):
        raise MissingVariableError(name, vars_needed.difference(data.columns))

    price = data["Price"].to_numpy()
    volume = data["Volume"].to_numpy()
    direction = data["Direction"].to_numpy()
    dollar_volume = np.multiply(price, volume)
    signed_dollar_volume = np.multiply(direction, dollar_volume)

    # Find the total signed dollar volume and return per 1 second.
    timestamps = np.array(data.index, dtype="datetime64")
    last_ts, last_price = timestamps[0], price[0]
    bracket_sdv = 0
    bracket = last_ts + np.timedelta64(1, "s")
    rets, sdvs = [], []
    for idx, ts in enumerate(timestamps):
        if ts <= bracket:
            bracket_sdv += signed_dollar_volume[idx]
        else:
            ret = np.log(price[idx - 1]) - np.log(last_price)
            if not np.isnan(ret) and not np.isnan(bracket_sdv):
                rets.append(ret)
                sdvs.append(bracket_sdv)
            # Reset bracket
            bracket = ts + np.timedelta64(1, "s")
            last_price = price[idx]
            bracket_sdv = signed_dollar_volume[idx]

    # rets and sdvs store the returns and signed dollar volume per 1 second
    return rets, sdvs

if __name__ == "__main__":
    import pandas as pd
    from statsmodels.tsa.api import VAR

    df = pd.read_csv("./data/ABT.N/2021-02-16.signed.csv")

    rets, sdvs = estimate(df)

    df = pd.DataFrame({"returns": rets, "sdv": sdvs})
    model = VAR(df)
    results = model.fit(60)
    irf = results.irf(60)

    print(irf.cum_effects[-1][0][1] * 10_000)
    f = irf.plot_cum_effects(impulse="sdv", response="returns")

    from matplotlib import pyplot as plt

    plt.savefig("a.png")

    f = irf.plot_cum_effects(impulse="sdv", response="returns", orth=True)
    plt.savefig("b.png")
    print(irf.cum_effects[-1][0][1] * 10_000)


# -*- coding: utf-8 -*-
import unittest
from run import check_dt, check_zip, check_validity, check_other_id, check_amt, DataStream, DonationAnalytics, keepcols, preprocess_map
from datetime import datetime
import os

input_data = [('123','BOB SMITH','50512-1234','01012017','1',''),\
        ('123','JERRY PICKER','50512-1235','01012017','500',''),\
        ('123','BOB SMITH','50512-1234','01012018','2','')]

test_data = {check_dt:('02192019',datetime(2019,2,19,0,0)),\
                         check_dt:('021920191',False),\
                         check_zip:("123456","12345"),\
                         check_validity:("",False),\
                         check_other_id:("",True),\
                         check_amt:("335",335.0)}

data_file = "itcont.txt"
percentile_file = "percentile.txt"
output_file = "duplicate_donors.txt"
inputroot = "../input/unit_test/"
outputroot = "../output/unit_test/"

def set_up(fnd,fnp,output_file, inputroot,outputroot ):
    os.makedirs(inputroot, exist_ok = True)
    os.makedirs(outputroot, exist_ok = True)
    fnd = inputroot + fnd
    fnp = inputroot + fnp
    output_file = outputroot + output_file

    with open(fnd ,"w") as f:
        #['CMTE_ID', 'NAME', 'ZIP_CODE', 'TRANSACTION_DT', 'TRANSACTION_AMT', 'OTHER_ID']

        out = "\n".join(["|".join(x) for x in input_data])
        f.write(out)

    with open(fnp,"w") as f:
        data = "30\n"
        f.write(data)

    datafile = os.path.abspath(fnd)
    percentilefile = os.path.abspath(fnp)
    outputfile = os.path.abspath(output_file)
    return datafile, percentilefile, outputfile

def tear_down(files,inputroot,outputroot ):
    for file in files:
        os.remove(file)
    os.rmdir(inputroot)
    os.rmdir(outputroot)

class TestFunctions(unittest.TestCase):
    def testFunctions(self):
        for func, data in test_data.items():
            testdata = data[0]
            testcompare = data[1]
            result = func(testdata)
#            print("comparing {} to {} for func {}".format(result,testcompare, func))
            self.assertEqual(result,testcompare)
            self.assertEqual(type(result),type(testcompare))

    def testDonationAnalytics(self):
        """
        This could probably be broken down here, but the manual engineering
        of the test data and calculation of the output means that this test
        validates every piece of the class
        """
        files = set_up(data_file,percentile_file,output_file, inputroot,outputroot)

        self.ds = DonationAnalytics(keepcols, keepcols, preprocess_map, files)
        results = self.ds.process_data()
        self.assertEqual(results,['123|50512|2018|2|2|1\n'])

        tear_down(files,inputroot,outputroot)

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


from webapp.config import intervals
from webapp.plotter import candle_chart
from flask import Blueprint, render_template, request
from webapp.chart.forms import ChartForm

blueprint = Blueprint('chart', __name__)

@blueprint.route('/api', methods=["GET"])
def api():
    pair = request.args.get("pair", "BTCUSD")
    interval = int(request.args.get("interval", 1))
    depth = int(request.args.get("depth", 40))
    chart = candle_chart(pair, interval, depth)
    title = "API"
    return render_template('chart/api.html', page_title=title, chart=chart)

@blueprint.route('/chart', methods=["GET", "POST"])
def chart():
    title = "Chart"
    chart_menu = ChartForm()
    if request.method == "POST":
        if chart_menu.is_submitted():
            interval = intervals[chart_menu.interval.data]
            pair = str(chart_menu.pair.data)
            depth = int(chart_menu.depth.data)
    else:
        interval = intervals[chart_menu.interval.default]
        pair = str(chart_menu.pair.default)
        depth = int(chart_menu.depth.default)

    chart = candle_chart(pair, interval, depth)
    if chart:
        return render_template(
            'chart/chart.html',
            page_title=title,
            chart=chart,
            form=chart_menu)
    else:
        error_msg = "Что-то сломалось, но мы скоро починим"
        return render_template(
            'index/error_page.html',
            page_title=title,
            error_msg=error_msg)

@blueprint.route('/demo')
def demo():
    title = "Demo"
    chart = candle_chart("BTCUSD", 30, 50)
    if chart:
        return render_template(
            'chart/demo.html',
            page_title=title,
            chart=chart)
    else:
        error_msg = "Что-то сломалось, но мы скоро починим"
        return render_template(
            'index/error_page.html',
            page_title=title,
            error_msg=error_msg)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isCompleteTree(self, root: Optional[TreeNode]) -> bool:
        if not root:
            return True

        q = deque([root])
        complete = True

        while q:
            root = q.popleft()
            if not root:
                complete = False
            else:
                if not complete:
                    return False
                q.append(root.left)
                q.append(root.right)

        return True

Python3/958. Check Completeness of a Binary Tree.py


from databases.paths import SecuritiesPath
from tools.misc.database_misc import get_from_db, find_str_in_df
from tools.misc.dates_misc import to_datetime

class Security:
    """
    Finds in the db, with whatever identifier
    Fills up the object
    """

    def __init__(self, identifier):
        infos_dict = {}

        # ------------------
        # Database intent to fetch
        infos_df = get_from_db(SecuritiesPath, 'ticker')
        # looks for the identifier and if located, returns the index
        infos_df_filtered = find_str_in_df(infos_df, identifier)
        if not infos_df_filtered.empty:
            infos_dict = infos_df_filtered.T.to_dict()
            infos_dict = infos_dict[list(infos_dict.keys())[0]]

            # ------------------
            # fills our object
            self.__dict__.update(infos_dict)

            # light date rework
            if not str(self.active_since_ws) == 'nan' and self.active_since_ws is not None:
                self.active_since_ws = to_datetime(self.active_since_ws, 'WealthSimple')
            if not str(self.inactive_since_ws) == 'nan' and self.inactive_since_ws is not None:
                self.inactive_since_ws = to_datetime(self.inactive_since_ws, 'WealthSimple')

        else:
            print(f'Please load the security {identifier} in the db.')
            quit()

if __name__ == '__main__':
    Security('^BCBCLI')
    Security('UCO')
    Security('SCO')


import discord
from discord.ext import commands

# Get owner ID
BOT_OWNER_ID = 302967111980941312

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

    @commands.command(help='Responds with bot latency.')
    async def ping(self, ctx):
        # Pings bot and returns latency in ms
        await ctx.send(f"pong! {round(self.bot.latency * 1000)}ms")

    @commands.command(help='Sets status of bot.')
    async def setstatus(self, ctx, *, text=None):
        # sets status message of bot. Only owner can use.
        if (str(ctx.message.author.id) != BOT_OWNER_ID):
            return await ctx.send("You must be the owner to set the status.")

        if text is None:
            return await ctx.send("You must specify an argument.")

        await ctx.send(f"Setting status to {str(text)}")
        await self.bot.change_presence(activity=discord.Game(name=str(text)))

    # Miscellaneous
    @commands.command(name="amogus", hidden=True)
    async def amogus(self, ctx):
        await ctx.send("https://c.tenor.com/fWICUw1py9UAAAAd/among-us-meme.gif")

    @commands.command(name='moyai', hidden=True)
    async def rules(self, ctx):
        await ctx.send("https://c.tenor.com/Yu6oaGFXFVAAAAAC/ratio-moyai.gif")

    @commands.command(name="danbooru", hidden=True)
    async def danbooru(self, ctx):
        await ctx.send("This feature has been disabled. Sorry.", delete_after=5)
        await ctx.message.delete(delay=5)


# Import all the things needed for the program to funtion
import random
import utils

# Define the scores so they wont be overwriten
playerScore = 0
computerScore = 0

# Main menu function for game this is where most things happen.
def menu(playerScore, computerScore):
    # Interface so the user knows whats going on.
    print("Welcome to the king of the Jungle:")
    print("Please select an animal or exit.")
    print("""Your Choices are:
        1) Lion
        2) Elephant
        3) Mouse
        0) Exit and view the score
        S) View the score without quiting
        """)

    # Reset the varibles for the players animals so it wont cause issues.
    playerAnimalNumb = ""
    playerAnimal = ""

    # Get the users imput and make sure its vaild.
    while playerAnimalNumb not in ['0', '1', '2', '3', 'S']:
        playerAnimalNumb = str.upper(input("Your selection: "))
    # Handle if the user wants to quit the program
    if playerAnimalNumb == "0":
        quitting = True
        if playerScore == 0 and computerScore == 0:
            utils.screenClear()
            print("Thanks for playing and goodbye")
            print("There is no need to see the score since no one has scored")
            exit()
        else:
            print("Thanks for playing")
            print("This is the scoreboard")
            scoreBoard(playerScore, computerScore, quitting)
    if playerAnimalNumb == "S":
        quitting = False
        print("Thanks for playing")
        print("This is the scoreboard")
        scoreBoard(playerScore, computerScore, quitting)
    # Convert the number imput into a word so it is easier to understand
    elif playerAnimalNumb == "1":
        playerAnimal = "lion"
    elif playerAnimalNumb == "2":
        playerAnimal = "elephant"
    elif playerAnimalNumb == "3":
        playerAnimal = "mouse"

    # Run the function to get the computers animal choice
    computerAnimal = computerAnimalGenerator()

    return playerAnimal, computerAnimal

# Generate the computers animal choice from a list.
def computerAnimalGenerator():
    computerAnimalChoices = ["lion", "elephant", "mouse"]
    computerAnimal = random.choice(computerAnimalChoices)
    return computerAnimal

# Check wether or not the player or the computer won.
# Also keep track of there scores
def mainGame(playerAnimal, computerAnimal, playerScore, computerScore):
    if playerAnimal == computerAnimal:
        print("Argh, there was no battle you both chose",
              "{} it was a draw.".format(playerAnimal))
    elif playerAnimal == "lion":
        if computerAnimal == "mouse":
            print("Argh, you won lion beats mouse!",
                  "you are the king this time!")
            playerScore += 1
        else:
            print("Argh, you lost this one elephant beats lion!")
            computerScore += 1
    elif playerAnimal == "mouse":
        if computerAnimal == "elephant":
            print("Argh, you won this time mouse beats elephant,"
                  "this time your the king! but not for long!")
            playerScore += 1
        else:
            print("Argh, you lost this time lion beats up poor mouse!.")
            computerScore += 1
    elif playerAnimal == "elephant":
        if computerAnimal == "lion":
            print("Argh, you win this one elephant beats lion",
                  "you are the king! but not for long")
            playerScore += 1
        else:
            print("You loose computer chose mouse and mouse beats elephant")
            computerScore += 1

    # Let the user go back to the main menu
    input("Argh press enter to enter the main menu: ")
    utils.screenClear()
    playerAnimal, computerAnimal = "", ""
    return playerAnimal, computerAnimal, playerScore, computerScore

# This is the scoreboard that tells the players if they won or lost.
def scoreBoard(playerScore, computerScore, quitting):
    print(
        "Welcome to the scoreboard currently the score currently is: "
    )
    if playerScore > computerScore:
        print("The player is beating the computer.")
        print("The score is {} for the player and {} for the computer".format(
            playerScore, computerScore))
    elif playerScore == computerScore:
        print("The score is tied with both the computer and the player tied")
        print("The score is {} for both players".format(playerScore))
    elif playerScore < computerScore:
        print("The computer is winning and the players is loosing")
        print("The score is {} for the computer and {} for the player".format(
            computerScore, playerScore))
        if quitting == True:
            exit()

# Displays the messages you first see when you start the program.
utils.welcomeMessage()
utils.rulesScreen()

# Loop so they player can play again if they want to.
# This runs the game infintly unless the user stops it.
while True:
    # Runs the main menu
    playerAnimal, computerAnimal = menu(playerScore, computerScore)
    # Runs the main game and keeps track of scores.
    playerAnimal, computerAnimal, playerScore, computerScore = mainGame(
        playerAnimal, computerAnimal, playerScore, computerScore)


import os
import torch
from torch import nn
from torch import distributions

# FrEIA (https://github.com/VLL-HD/FrEIA/)
import FrEIA.framework as Ff
import FrEIA.modules as Fm

from flow_model.subnet import *
from config import WEIGHT_DIR

def get_flow_model(c):
    dims_in = [c.channels, int(c.img_size[0] / c.scales), int(c.img_size[1] / c.scales)]
    nodes = Ff.SequenceINN(*dims_in)
    for i in range(c.coupling * 2):
        nodes.append(
            Fm.AllInOneBlock,
            subnet_constructor=get_subnet(c=c),
            affine_clamping=c.clamp,
            permute_soft=False,
        )
    return nodes

class RessubFlow(nn.Module):

    def __init__(self, c):
        super(RessubFlow, self).__init__()
        self.flow_model = get_flow_model(c)

        # isotropic standard normal distribution
        self.prior = distributions.Normal(torch.tensor(0.).to(c.device), torch.tensor(1.).to(c.device))
        self.negative_val = c.negative_val
        self.neg_loss_weight = c.neg_loss_weight

    def forward(self, images):
        z, log_jac_dets = self.flow_model(images)

        return z, log_jac_dets

    def get_loss(self, B, z, log_jac_dets):
        loss_positive, loss_negative = self.get_neg_log_likelihood(B, z, log_jac_dets)
        max_loss_positive = loss_positive.max()

        loss_negative = loss_negative[loss_negative < self.negative_val]
        loss_negative = loss_negative[loss_negative < max_loss_positive]

        if loss_negative.shape[0] > 0:
            loss_negative *= (-1)
            loss_negative = loss_negative.mean()
            loss_positive = loss_positive.mean()
            loss = (1 - self.neg_loss_weight) * loss_positive + self.neg_loss_weight * loss_negative
        else:
            loss_negative = torch.tensor(0.)
            loss_positive = loss_positive.mean()
            loss = loss_positive
        return loss, loss_positive, loss_negative

    def get_neg_log_likelihood(self, B, z, log_jac_dets):
        log_prior_prob = torch.sum(self.prior.log_prob(z), dim=(1, 2, 3))
        log_likelihood = log_prior_prob + log_jac_dets
        neg_log_likelihood = -log_likelihood
        return neg_log_likelihood[:B], neg_log_likelihood[B:]

def save_model(model, filename, type):
    if not os.path.exists(WEIGHT_DIR):
        os.makedirs(WEIGHT_DIR)

    torch.save(model.state_dict(), os.path.join(WEIGHT_DIR, f'{filename}_{type}'))

def load_model(model, filename):
    state = torch.load(filename)
    model.load_state_dict(state, strict=True)
    return model


# 1

# print(not(True))
# print(not(False))

# hasil1 = not((5 > 2 or 4 == 5) and 5 != 5)
# hasil2 = not('hello' == 'hello')
# hasil3 = not(4 > 3 and 'apa' == 'Apa')
# hasil4 = not(3 > 5 or (7 != 8 and 'kari' != 'kuri'))
# hasil5 = not(5 != 5 and 7 > 2)

# print('Hasil1 =', hasil1, type(hasil1))
# print('Hasil2 =', hasil2, type(hasil2))
# print('Hasil3 =', hasil3, type(hasil3))
# print('Hasil4 =', hasil4, type(hasil4))
# print('Hasil5 =', hasil5, type(hasil5))

# ============================================================================#

# 2

# print('Selamat datang!')

# umur = int(input('Masukkan Umurmu : '))

# if(umur >= 17) :
#     print('Anda sudah boleh bikin SIM')
#     nama = input('Masukkan Namamu : ')
#     if(len(nama) > 1) :
#         print('Terima Kasih {}'.format(nama))

# print('Sampai Jumpa!')

# =============================================================================== #

# 3

# print('Selamat datang!')
# umur = int(input('Masukkan Umurmu : '))
# if(umur >= 17) :
#     print('Anda sudah boleh bikin SIM')
#     nama = input('Masukkan Namamu : ')
#     if(len(nama) >1 ) :
#         print('Terima Kasih {}'.format(nama))
#     else :
#         print('Nama harus diatas 1 huruf')
# else :
#     print('Anda belum boleh bikin SIM karena Umur harus 17 tahun atau lebih')

# print('Sampai Jumpa!')

# ================================================================================ #

# 4.

print('Pengecheckan Ujian')

nilai = int(input('Masukkan Nilai : '))
grade = ''

if(nilai >= 90 and nilai <=100) :
    grade = 'A'
elif(nilai >= 80 and nilai <= 89) :
    grade = 'B'
elif(nilai >= 70 and nilai <= 79) :
    grade = 'C'
elif(nilai >= 60 and nilai <= 69) :
    grade = 'D'
elif(nilai >= 0 and nilai <= 59) :
    grade = 'F'
else :
    grade = 'Nilai harus diinput dari jarak 0 - 100'

print('Grade = {}'.format(grade))


from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User

from artigo.models import TipoDeProduto, Modalidade, Produto
from usuarios.models import Usuario
from carrinho.models import Order, OrderItem
from aluguel.models import Aluguel

def get_user_pending_order(request):
    user_profile = get_object_or_404(Usuario, email=request.user)
    order = Order.objects.filter(owner=user_profile, is_ordered=False)
    if order:
        return order[0]
    return 0

def check_time():
    '''
    Verifica o tempo dos aluguéis criados pra ver se já expirou.
    '''

    users = Usuario.objects.all()
    for user in users:
        my_user_profile = Usuario.objects.filter(email=user).first()
        user_rents = Aluguel.objects.filter(usuario=my_user_profile)
        for ordeer in user_rents:
            Aluguel.delete_after_one_or_five_hours(ordeer)
            if ordeer.rent_in_process == False:
                aluguel = get_object_or_404(Aluguel, id=ordeer.id)
                aluguel.delete()

def home(request):
    '''
    View da página inicial, nada demais.
    '''

    check_time()
    context = {}
    return render(request, 'core/menu.html', context)

def modalidades(request):
    '''
    View que entrega à página os nomes das modalidades nas quais
    o sistema possui produtos.
    '''

    check_time()
    modalidades = Modalidade.objects.all()
    context = {'modalidades': modalidades}

    return render(request, 'core/modalidades.html', context)

def produtos_de_modalidade(request, id):
    '''
    View que entrega à página os tipos de produto associados à modalidade
    selecionada pelo usuário. Parâmetro id necessário para gerar a
    url dinâmica.
    '''

    check_time()
    produtos_de_modalidade = TipoDeProduto.objects.filter(modalidade=id)
    context = {'produtos_de_modalidade': produtos_de_modalidade,
               'id_antigo': id}

    return render(request, 'core/produtos_de_modalidade.html', context)

def produtos(request, id_antigo, id):
    '''
    View que entrega à pagina os produtos associados ao tipo de produto
    selecionado pelo usuário. Parâmetros id e id_antigo necessários para
    gerar a url dinâmica.
    '''

    check_time()
    produtos = Produto.objects.filter(tipo=id)
    context = {'produtos': produtos,
               'id_antigo2': id_antigo,
               'id_antigo1': id}

    return render(request, 'core/produtos.html', context)

def produto(request, id_antigo2, id_antigo1, item_id):
    '''
    View que entrega à página tanto as informações do produto quanto as informações
    necessárias para decidir se o usuário pode ou não fazer reservas, e avisá-lo
    conforme o requisito que ele não cumpre. Parâmetros id e id_antigo necessários
    para gerar a url dinâmica.
    '''

    check_time()
    pode_alugar = True
    tem_aluguel = False
    my_user_profile = Usuario.objects.filter(email=request.user).first()
    banido = True
    if my_user_profile.is_able_to_rent:
        banido = False
    user_rents = Aluguel.objects.filter(usuario=my_user_profile)
    id_produtos = list(user_rents.values_list('prod'))

    # Necessário tratar a QuerySet para entregar a lista com os ids dos produtos alugados pelo usuário
    # para a página.
    lista_id_produtos = []
    for i in id_produtos:
        for j in i:
            num = ""
            if type(j) == int:
                num += str(j)
        lista_id_produtos.append(int(num))

    existing_order = get_user_pending_order(request)
    lista_de_produtos = existing_order.get_cart_total() if existing_order != 0 else 0
    li_user_rents = list(user_rents)
    if (len(li_user_rents) > 0):
        tem_aluguel = True
    if (len(li_user_rents)+lista_de_produtos) >= 3 and not my_user_profile.is_professor and len(li_user_rents) != 0:
        pode_alugar = False

    # Entrega a quantidade de produtos e a lista de produtos que
    # constam no carrinho do usuário no momento.
    current_order_products = []
    filtered_orders = Order.objects.filter(owner=request.user.id, is_ordered=False)
    tamanho = 0
    if filtered_orders.exists():
        user_order = filtered_orders[0]
        user_order_items = user_order.items.all()
        current_order_products = [product.product for product in user_order_items]
        tamanho = len(current_order_products)

    # Por fim, obviamente, entrega o próprio objeto do tipo Produto em questão.
    obj = Produto.objects.get(id=item_id)

    context = {
    'obj': obj,
    'current_order_products': current_order_products,
    'tamanho':tamanho,
    'professor':my_user_profile.is_professor,
    'pode_alugar': pode_alugar,
    'lista_id_produtos':lista_id_produtos,
    'banido':banido,
    'tem_aluguel':tem_aluguel,
    }

    return render(request, 'core/produto.html', context)

def cestadeprodutos(request):
    '''
    View da cesta de produtos.
    '''

    check_time()
    obj=TipoDeProduto.objects.all()
    context = {'obj': obj}

    return render(request, 'carrinho/cestadeprodutos.html', context)

def reservados(request):
    '''
    View da página "Reservados". Entrega ao layout a lista de produtos reservados
    pelo usuário e também a reserva mais antiga, para que o tempo da sua primeira
    reserva seja contabilizado no reloginho da página.
    '''

    check_time()
    list_alug = []
    my_user_profile = Usuario.objects.filter(email=request.user).first()
    alugueis = Aluguel.objects.filter(usuario=my_user_profile)
    for aluguel in alugueis:
        if aluguel.prod.rese == True:
            list_alug.append(aluguel)
    reserva1=[]
    if list_alug:
        reserva1 = list_alug[0]
    context = {
        'reserva':list_alug,
        'reserva1':reserva1,
    }
    return render(request,'core/reservados.html', context)


from odoo import models, fields, api, _

class EmployeePayrollReport(models.TransientModel):
    _inherit = "account.common.partner.report"
    _name = 'emp.pay.report'

    emp_ids = fields.Many2many('hr.employee', string="Employees", domain="[('company_id', '=', company_id)]")
    payroll_type = fields.Selection([('date', 'Date'), ('batch', 'Batch')], default='date', string='Payroll by')
    batch_id = fields.Many2one('hr.payslip.run', 'Batch')

    @api.onchange('batch_id')
    def _get_batch_company(self):
        if self.batch_id:
            self.company_id = self.batch_id.journal_id.sudo().company_id.id

    def _print_report(self, data):
        data = self.pre_print_report(data)
        return self.env.ref('employee_payroll.action_report_employee_payroll').report_action(self, data=data)

    @api.multi
    def pre_print_report(self, data):
        data = super(EmployeePayrollReport, self).pre_print_report(data)
        data['form'].update(self.read(['emp_ids'])[0])
        data['form'].update(self.read(['payroll_type'])[0])
        data['form'].update(self.read(['batch_id'])[0])
        return data

    @api.multi
    def export_xls(self):
        context = self._context
        datas = {'ids': context.get('active_ids', [])}
        datas['form'] = self.read()[0]
        for field in datas['form'].keys():
            if isinstance(datas['form'][field], tuple):
                datas['form'][field] = datas['form'][field][0]
        if context.get('xls_export'):
                return self.env.ref('employee_payroll.report_employee_payroll_xlsx').report_action(self, data=datas)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from rest_framework import status
from datetime import datetime

from .models import Order, Orderitem, ShippingAddress
from .serializers import OrderSerializer
from products.models import Product

@api_view(['GET'])
@permission_classes([IsAdminUser])
def get_orders(request):
    orders = Order.objects.all()
    serializer = OrderSerializer(orders, many=True)
    return Response(serializer.data)

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_order(request):
    user = request.user
    data = request.data
    orderItems = data['order_items']
    order = Order.objects.create(
            user=user,
            total_price=data['total_price']
            )
    ShippingAddress.objects.create(
            order=order,
            address=data['address'],
            city=data['city'],
            country=data['country'],
            postal_code=data['postal_code'],
            shipping_price=data['shipping_price'],
            )
    for i in orderItems:
        product = Product.objects.get(id=i['id'])

        item = Orderitem.objects.create(
                    product=product,
                    order=order,
                    name=product.name,
                    quantity=i['quantity'],
                    price=i['price'],
                    )

        product.count_in_stock -= item.quantity
        product.save()

        serializer = OrderSerializer(order, many=False)
        return Response(serializer.data)

'''
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def create_order(request):
    user = request.user
    data = request.data
    orderItems = data['order_items']
    total_price = data['total_price']

    # Calcular la suma de los precios de los productos
    sum_of_prices = sum(item['price'] for item in orderItems)

    if total_price == sum_of_prices:
        # Crear la orden
        order = Order.objects.create(
            user=user,
            total_price=total_price
        )

        ShippingAddress.objects.create(
            order=order,
            address=data['address'],
            city=data['city'],
            country=data['country'],
            postal_code=data['postal_code'],
            shipping_price=data['shipping_price']
        )

        for i in orderItems:
            product = Product.objects.get(id=i['id'])
            item = Orderitem.objects.create(
                product=product,
                order=order,
                name=product.name,
                quantity=i['quantity'],
                price=i['price']
            )

            product.count_in_stock -= item.quantity
            product.save()

        serializer = OrderSerializer(order, many=False)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    else:
        return Response({'mensaje': 'El precio total no coincide con la suma de los precios de los productos'}, status=status.HTTP_400_BAD_REQUEST)
'''

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def solo_order(request, pk):
    user = request.user
    try:
        order = Order.objects.get(pk=pk)
        if user.is_staff or order.user == user:
            serializer = OrderSerializer(order, many=False)
            return Response(serializer.data)
        else:
            Response({'detail': 'No access to view orders'},
                     status=status.HTTP_401_UNAUTHORIZED)
    except:
        return Response({'detail': 'Order does not exist'}, status=status.HTTP_400_BAD_REQUEST)

@api_view(['GET'])
@permission_classes([IsAuthenticated])
def my_orders(request):
    user = request.user
    orders = user.order_set.all()
    serializer = OrderSerializer(orders, many=True)
    return Response(serializer.data)

@api_view(['PUT'])
@permission_classes([IsAdminUser])
def delivered(request, pk):
    order = Order.objects.get(pk=pk)
    order.is_delivered = True
    order.delivered_at = datetime.now()
    order.save()
    return Response('Order was delivered')


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

"""
@Time    : 2021/3/2 4:53 下午
@Author  : mc
@File    : solution.py
@Software: PyCharm
"""

class Solution:
    def permutation(self, s: str) -> list:
        c, res = list(s), []

        def dfs(x):
            if x == len(s) - 1:
                res.append(''.join(c))
                return
            ss = set()
            for i in range(x, len(c)):
                # 用set记录当前固定位置已经设置的值
                if c[i] in ss:
                    continue
                ss.add(c[i])
                # 将c[i] 固定在x位置
                c[x], c[i] = c[i], c[x]
                dfs(x + 1)
                # 结束递归后，恢复位置
                c[x], c[i] = c[i], c[x]

        dfs(0)
        return res

print(Solution().permutation('abac'))


import turtle
import pandas
import create_turtle

states = pandas.read_csv('50_states.csv')

screen = turtle.Screen()
screen.title("U.S. States Game")

image = 'blank_states_img.gif'

screen.addshape(image)

turtle.shape(image)

correct = 0

while correct < 50:
    answer_state = screen.textinput(title="Guess the state", prompt="What's another state's name?")
    answer_state = answer_state.title()
    for state in states.state:
        if answer_state == state:
            xcor = states[states['state'] == answer_state].x.item()
            ycor = states[states['state'] == answer_state].y.item()
            create_turtle.NewState(answer_state, xcor, ycor)
    correct += 1

turtle.mainloop()


"""The challenge is to write a program that adds to a travel_log, which is a list that contains 4 Dictionaries.
    Basically, we're gonna write a function to add the entry for a country to the travel_log."""

travel_log = [
    {
        "country": "France",
        "visits": 12,
        "cities_visited": ["Paris", "Lille", "Dijon"]
    },
    {
        "country": "Germany",
        "visits": 3,
        "cities_visited": ["Berlin", "Hamburg", "Stuttgart"]

    },
    {
        "country": "Uganda",
        "visits": 6,
        "cities_visited": ["Kampala", "Jinja", "Kasese", "Bwera", "Mbarara", "Masaka"]

    },
    {
        "country": "DRC",
        "visits": 8,
        "cities_visited": ["Kinshasa", "Goma", "Butembo", "Beni", "Kisangani", "Lubumbashi"]
    }
]

# Function to add a country to the travel_log list
def add_new_country(country_visited, times_visited, cities_visited):
    new_country = {"country": country_visited, "visits": times_visited, "cities_visited": cities_visited}
    travel_log.append(new_country)

# Call the function to populate the country to the travel_log list
add_new_country("Rwanda", 2, ["Kigali", "Gisenyi"])

# Print the travel_log list
print(travel_log)


from bitarray import *

def addprefixos(xs, p):
    return dict((k, bitarray(p) + v) for (k,v) in xs.items())

def huffmann(lista):
	while(len(lista) > 1):
		lista.sort()
		a = lista.pop()
		b = lista.pop()
		#print(str(a) + " " + str(b))
		c = a.join(b)
		lista.append(c)
	d = lista.pop().coding()
	return d

class N:
    def __init__(self, x, f):
        self.x = x
        self.f = f
        self.l = None
        self.r = None

    def join(self, o):
        n = N(None, self.f + o.f)
        n.l = self
        n.r = o
        return n

    def coding(self):

        l = {}
        r = {}
        if self.x:
            return {self.x: bitarray()}
        if self.l:
            l = self.l.coding()
        if self.r:
            r = self.r.coding()
        ret = {}
        ret.update(addprefixos(l, '0'))
        ret.update(addprefixos(r, '1'))
        #if(self.x == 0):
        #    print(str(self.x) + " " + str(self.f) + str(len(ret)))

        return ret

    def __lt__(self, o):
        return self.f > o.f

    def __repr__(self):
        return "N(%s,%f)" % (self.x, self.f)


import logging

# Zynthian specific modules
from zyngui import zynthian_gui_config
from zyngui.zynthian_ctrldev_manager import zynthian_ctrldev_base
from zyncoder.zyncore import lib_zyncore

# --------------------------------------------------------------------------
# Akai MIDI-Mix Integration
# --------------------------------------------------------------------------

class zynthian_ctrldev_akai_midimix(zynthian_ctrldev_base):

	dev_ids = ["MIDI_Mix_MIDI_1"]
	dev_zynmixer = True  # Can act as an audio mixer controller device
	rec_mode = 0

	bank_left_note = 25
	bank_right_note = 26
	solo_note = 27
	mute_notes = [1, 4, 7, 10, 13, 16, 19, 22]
	solo_notes = [2, 5, 8, 11, 14, 17, 20, 23]
	rec_notes = [3, 6, 9, 12, 15, 18, 21, 24]

	# knobs1_ccnum = [16, 20, 24, 28, 46, 50, 54, 58]
	# knobs2_ccnum = [17, 21, 25, 29, 47, 51, 55, 59]
	knobs3_ccnum = [18, 22, 26, 30, 48, 52, 56, 60]
	faders_ccnum = [19, 23, 27, 31, 49, 53, 57, 61]
	master_ccnum = 62

	# Function to initialise class
	def __init__(self):
		super().__init__()
		self.midimix_bank = 0
		self.zynmixer = self.zyngui.zynmixer
		self.zyngui_mixer = self.zyngui.screens["audio_mixer"]

	def init(self):
		self.midimix_bank = 0
		self.light_off()

	def end(self):
		self.light_off()

	# Update LED status
	def refresh(self, force = False):
		# Bank selection LED
		if self.midimix_bank:
			index0 = 8
			lib_zyncore.dev_send_note_on(self.idev, 0, self.bank_left_note, 0)
			lib_zyncore.dev_send_note_on(self.idev, 0, self.bank_right_note, 1)
		else:
			index0 = 0
			lib_zyncore.dev_send_note_on(self.idev, 0, self.bank_left_note, 1)
			lib_zyncore.dev_send_note_on(self.idev, 0, self.bank_right_note, 0)

		# Strips Leds
		layers = self.zyngui.screens['layer'].get_root_layers()
		for i in range(0, 8):
			index = index0 + i
			if index < len(self.zyngui.zynmixer.zctrls):
				mute = self.zyngui.zynmixer.get_mute(index)
				solo = self.zyngui.zynmixer.get_solo(index)
			else:
				mute = 0
				solo = 0

			if not self.rec_mode:
				if index < len(layers) and self.zyngui.curlayer and layers[index] == self.zyngui.curlayer:
					rec = 1
				else:
					rec = 0
			else:
				if index < len(layers):
					rec = self.zyngui.audio_recorder.is_armed(layers[index].midi_chan)
				else:
					rec = 0

			lib_zyncore.dev_send_note_on(self.idev, 0, self.mute_notes[i], mute)
			lib_zyncore.dev_send_note_on(self.idev, 0, self.solo_notes[i], solo)
			lib_zyncore.dev_send_note_on(self.idev, 0, self.rec_notes[i], rec)

	def midi_event(self, ev):
		evtype = (ev & 0xF00000) >> 20
		if evtype == 0x9:
			note = (ev >> 8) & 0x7F
			if note == self.solo_note:
				return True
			elif note == self.bank_left_note:
				self.midimix_bank = 0
				self.refresh()
				return True
			elif note == self.bank_right_note:
				self.midimix_bank = 1
				self.refresh()
				return True
			elif note in self.mute_notes:
				index = self.mute_notes.index(note)
				if self.midimix_bank:
					index += 8
				if self.zynmixer.get_mute(index):
					val = 0
				else:
					val = 1
				self.zynmixer.set_mute(index, val, True)
				# Send LED feedback
				lib_zyncore.dev_send_note_on(self.idev, 0, note, val)
				return True
			elif note in self.solo_notes:
				index = self.solo_notes.index(note)
				if self.midimix_bank:
					index += 8
				if self.zynmixer.get_solo(index):
					val = 0
				else:
					val = 1
				self.zynmixer.set_solo(index, val, True)
				# Update Main "solo" control
				self.zyngui_mixer.pending_refresh_queue.add((self.zyngui_mixer.main_mixbus_strip, 'solo'))
				# Send LED feedback
				lib_zyncore.dev_send_note_on(self.idev, 0, note, val)
				return True
			elif note in self.rec_notes:
				index = self.rec_notes.index(note)
				if self.midimix_bank:
					index += 8
				if index < len(self.zynmixer.zctrls):
					if not self.rec_mode:
						self.zyngui_mixer.select_chain_by_index(index)
					else:
						layer = self.zyngui.screens['layer'].get_root_layers()[index]
						self.zyngui.audio_recorder.toggle_arm(layer.midi_chan)
						# Send LED feedback
						val = self.zyngui.audio_recorder.is_armed(layer.midi_chan)
						lib_zyncore.dev_send_note_on(self.idev, 0, note, val)
				return True
		elif evtype == 0xB:
			ccnum = (ev & 0x7F00) >> 8
			ccval = (ev & 0x007F)
			if ccnum == self.master_ccnum:
				self.zyngui_mixer.main_mixbus_strip.zctrls['level'].set_value(ccval/127.0)
				return True
			elif ccnum in self.faders_ccnum:
				index = self.faders_ccnum.index(ccnum)
				if self.midimix_bank:
					index += 8
				self.zynmixer.set_level(index, ccval/127.0, True)
				return True
			elif ccnum in self.knobs3_ccnum:
				index = self.knobs3_ccnum.index(ccnum)
				if self.midimix_bank:
					index += 8
				self.zynmixer.set_balance(index, 2.0 * ccval/127.0 - 1.0)
				return True

	# Light-Off all LEDs
	def light_off(self):
		for note in range(1, 28):
			lib_zyncore.dev_send_note_on(self.idev, 0, note, 0)

#------------------------------------------------------------------------------


import sys
import os
sys.path.append(os.path.join(os.getcwd(),'lib'))

import instruments as inst
import experiments as expr

import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
import seaborn as sns
sns.set()
#sns.axes_style("darkgrid")
#sns.axes_style("ticks")
sns.set_context("notebook", font_scale=1.5, rc={"lines.linewidth": 2.5})
sns.set_style("ticks", {"xtick.major.size": 8, "ytick.major.size": 8,'axes.facecolor': '#EAEAF2'})
dataLocation = r"D:\Swapnil\OneDrive - Indian Institute of Science\001_Project_Data\003_PhD_Presentations\07_Thesis_Chapters\07_DRGN\DRGN_03\24_Annealing_in_atmosphere"
#r"D:\Swapnil\OneDrive - Indian Institute of Science\001_Project_Data\003_PhD_Presentations\07_Thesis_Chapters\07_DRGN\DRGN_03\22_RVG_InAir_Varying_Pressure\alpha_1.00bar"
paramDict = {'instClass':'KT2461',
             'address':'169.254.0.1',
             'source_channel':'a',
             'sourceVolt':0.05,
             'gate_channel':'b',
             'gateVolt':5,
             'dataPoints':100,
             'dataLocation':dataLocation,
             'experintName':'CurrentAnneal'}

rvg = expr.CurrentAnneal(paramDict,verbose = False)
rvg.setExperiment()
# try:
for i in range(1):
    (df,fileName) = rvg.startExperiment(saveData=True)
    print(df)
    print(df.columns)
    f, ax = plt.subplots(figsize=(10, 8))
    ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))
    df.plot(x="timeStamp",y="Rsd_Ohm",ax=ax,colormap='gist_rainbow')
    if not os.path.exists(os.path.join(rvg.dataLocation,"Plots")):
        os.makedirs(os.path.join(rvg.dataLocation,"Plots"))

    figPath = os.path.join( os.path.join(rvg.dataLocation,"Plots"),
                            '{}.svg'.format(fileName.split('csv')[0][:-1]))
    plt.savefig(figPath)
    plt.close("all")
# except:
#     rvg.closeExperiment()

rvg.closeExperiment()

## Ploting reference
#https://pandas.pydata.org/pandas-docs/version/0.12/cookbook.html#cookbook-plotting


import numpy as np
import mnist

def init(self,num_filters):
    self.num_filters = num_filters
    self.filters = np.random.randn
def iterate_regions(self, image):
    h, w = image.shape

    for i in range(h - 2):
      for j in range(w - 2):
        im_region = image[i:(i + 3), j:(j + 3)]
        yield im_region, i, j

def forward(self, input):
    h,w=input.shape
    output = np.zeros((h - 2, w - 2, self.num_filters))

    for im_region, i, j in self.iterate_regions(input):
        output[i, j] = np.sum(im_region * self.filters, axis=(1, 2))

    return output


import torch

class PowLogModel(torch.nn.Module):

    def __init__(self):
        super(PowLogModel, self).__init__()

    def forward(self, x, q):
        y = x ** q
        z = torch.log(y)
        return z

powLogModel = PowLogModel()

x = torch.tensor(5.0, requires_grad=True)
q = torch.tensor(3.0, requires_grad=True)
z = powLogModel(x, q)
z.backward()

print('x', x)
print('x.grad', x.grad)
print('q', q)
print('q.grad', q.grad)
print('z', z)


import resource
import typing as t
import unittest
import gc
import bblfsh
import docker

from bblfsh import (BblfshClient, iterator, TreeOrder,
                    Modes, role_id, role_name)
from bblfsh.launcher import ensure_bblfsh_is_running
from bblfsh.client import NonUTF8ContentException
from bblfsh.node import NodeTypedGetException
from bblfsh.result_context import (Node, NodeIterator, ResultContext)
from bblfsh.pyuast import uast, decode
from functools import cmp_to_key

class BblfshTests(unittest.TestCase):
    BBLFSH_SERVER_EXISTED = None
    fixtures_pyfile = "fixtures/test.py"
    fixtures_cfile = "fixtures/test.c"

    @classmethod
    def setUpClass(cls: t.Any) -> None:
        cls.BBLFSH_SERVER_EXISTED = ensure_bblfsh_is_running()

    @classmethod
    def tearDownClass(cls: t.Any) -> None:
        if not cls.BBLFSH_SERVER_EXISTED:
            client = docker.from_env(version="auto")
            client.containers.get("bblfshd").remove(force=True)
            client.api.close()

    def setUp(self) -> None:
        self.client = BblfshClient("localhost:9432")

    def _parse_fixture(self) -> ResultContext:
        ctx = self.client.parse(self.fixtures_pyfile)
        self._validate_ctx(ctx)
        return ctx

    def testVersion(self) -> None:
        version = self.client.version()

        self.assertTrue(hasattr(version, "version"))
        self.assertTrue(version.version)
        self.assertTrue(hasattr(version, "build"))
        self.assertTrue(version.build)

    def testServerVersion(self) -> None:
        version = self.client.server_version().version

        self.assertTrue(hasattr(version, "version"))
        self.assertTrue(version.version)
        self.assertTrue(hasattr(version, "build"))

    def testNativeParse(self) -> None:
        ctx = self.client.parse(self.fixtures_pyfile, mode=Modes.NATIVE)
        self._validate_ctx(ctx)
        self.assertIsNotNone(ctx)

        it = ctx.filter("//*[@ast_type='NoopLine']")
        self.assertIsNotNone(it)
        self.assertIsInstance(it, NodeIterator)
        res = list(it)
        self.assertGreater(len(res), 1)
        for i in res:
            t = i.get_dict().get("ast_type")
            self.assertIsNotNone(t)
            self.assertEqual(t, "NoopLine")

    def testNonUTF8ParseError(self) -> None:
        self.assertRaises(NonUTF8ContentException,
                          self.client.parse, "", "Python", b"a = '\x80abc'")

    def testUASTDefaultLanguage(self) -> None:
        ctx = self._parse_fixture()
        self.assertEqual(ctx.language, "python")

    def testUASTWithLanguage(self) -> None:
        ctx = self.client.parse(self.fixtures_pyfile, language="Python")
        self._validate_ctx(ctx)
        self.assertEqual(ctx.language, "python")

    def testUASTWithLanguageAlias(self) -> None:
        ctx = self.client.parse(self.fixtures_cfile)
        self._validate_ctx(ctx)
        self.assertEqual(ctx.language, "c")

        it = ctx.filter("//uast:FunctionGroup/Nodes/uast:Alias/Name/uast:Identifier/Name")
        self.assertIsInstance(it, NodeIterator)

        self.assertEqual(next(it).get(), "main")
        self.assertEqual(next(it).get(), "fib")

    def testUASTFileContents(self) -> None:
        with open(self.fixtures_pyfile, "r") as fin:
            contents = fin.read()

        ctx = self.client.parse("file.py", contents=contents)
        self._validate_ctx(ctx)

        def assert_strnode(n: Node, expected: str) -> None:
            self.assertEqual(n.get(), expected)
            self.assertIsInstance(n.get_str(), str)
            self.assertEqual(n.get_str(), expected)

        it = ctx.filter("//uast:RuntimeImport/Path/uast:Identifier/Name")
        self.assertIsInstance(it, NodeIterator)

        assert_strnode(next(it), "os")
        assert_strnode(next(it), "resource")
        assert_strnode(next(it), "unittest")
        assert_strnode(next(it), "docker")
        assert_strnode(next(it), "bblfsh")
        assert_strnode(next(it), "bblfsh")
        self.assertRaises(StopIteration, next, it)

    def testBrokenFilter(self) -> None:
        ctx = self._parse_fixture()

        self.assertRaises(RuntimeError, ctx.filter, "dsdfkj32423#$@#$")

    def testFilterToken(self):
        ctx = self._parse_fixture()
        it = ctx.filter("//*[@token='else']/text()")
        first = next(it).get_str()
        self.assertEqual(first, "else")

    def testFilterRoles(self) -> None:
        ctx = self._parse_fixture()
        it = ctx.filter("//*[@role='Identifier']")
        self.assertIsInstance(it, NodeIterator)

        l = list(it)
        self.assertGreater(len(l), 0)

        it = ctx.filter("//*[@role='Friend']")
        self.assertIsInstance(it, NodeIterator)
        l = list(it)
        self.assertEqual(len(l), 0)

    def testFilterProperties(self) -> None:
        ctx = uast()
        obj = {"k1": "v1", "k2": "v2"}
        self.assertTrue(any(ctx.filter("/*[@k1='v1']", obj)))
        self.assertTrue(any(ctx.filter("/*[@k2='v2']", obj)))
        self.assertFalse(any(ctx.filter("/*[@k2='v1']", obj)))
        self.assertFalse(any(ctx.filter("/*[@k1='v2']", obj)))

    def testFilterStartOffset(self) -> None:
        ctx = self._parse_fixture()
        self.assertTrue(any(ctx.filter("//uast:Positions/start/uast:Position[@offset=11749]")))
        self.assertFalse(any(ctx.filter("//uast:Positions/start/uast:Position[@offset=99999]")))

    def testFilterStartLine(self) -> None:
        ctx = self._parse_fixture()
        self.assertTrue(any(ctx.filter("//uast:Positions/start/uast:Position[@line=295]")))
        self.assertFalse(any(ctx.filter("//uast:Positions/start/uast:Position[@line=99999]")))

    def testFilterStartCol(self) -> None:
        ctx = self._parse_fixture()
        self.assertTrue(any(ctx.filter("//uast:Positions/start/uast:Position[@col=42]")))
        self.assertFalse(any(ctx.filter("//uast:Positions/start/uast:Position[@col=99999]")))

    def testFilterEndOffset(self) -> None:
        ctx = self._parse_fixture()
        self.assertTrue(any(ctx.filter("//uast:Positions/end/uast:Position[@offset=11757]")))
        self.assertFalse(any(ctx.filter("//uast:Positions/end/uast:Position[@offset=99999]")))

    def testFilterEndLine(self) -> None:
        ctx = self._parse_fixture()
        self.assertTrue(any(ctx.filter("//uast:Positions/end/uast:Position[@line=321]")))
        self.assertFalse(any(ctx.filter("//uast:Positions/end/uast:Position[@line=99999]")))

    def testFilterEndCol(self) -> None:
        ctx = self._parse_fixture()
        self.assertTrue(any(ctx.filter("//uast:Positions/end/uast:Position[@col=49]")))
        self.assertFalse(any(ctx.filter("//uast:Positions/end/uast:Position[@col=99999]")))

    def testFilterBool(self) -> None:
        ctx = self._parse_fixture()
        self.assertTrue(ctx.filter("boolean(//uast:Positions/end/uast:Position[@col=49])"))
        self.assertTrue(next(ctx.filter("boolean(//uast:Positions/end/uast:Position[@col=49])")).get())
        self.assertTrue(next(ctx.filter("boolean(//uast:Positions/end/uast:Position[@col=49])")).get_bool())

        self.assertFalse(next(ctx.filter("boolean(//uast:Positions/end/uast:Position[@col=9999])")).get())
        self.assertFalse(next(ctx.filter("boolean(//uast:Positions/end/uast:Position[@col=9999])")).get_bool())

    def testFilterNumber(self) -> None:
        ctx = self._parse_fixture()
        self.assertEqual(next(ctx.filter("count(//uast:Positions/end/uast:Position[@col=49])")).get(), 2)
        self.assertEqual(next(ctx.filter("count(//uast:Positions/end/uast:Position[@col=49])")).get_int(), 2)
        self.assertEqual(next(ctx.filter("count(//uast:Positions/end/uast:Position[@col=49])")).get_float(), 2.0)

    def testFilterString(self) -> None:
        ctx = self._parse_fixture()
        self.assertEqual(next(ctx.filter("name(//uast:Positions)")).get(), "uast:Positions")
        self.assertEqual(next(ctx.filter("name(//uast:Positions)")).get_str(), "uast:Positions")

    def testFilterBadQuery(self) -> None:
        ctx = uast()
        self.assertRaises(RuntimeError, ctx.filter, "//[@roleModule]", {})

    def testFilterBadType(self) -> None:
        ctx = self._parse_fixture()
        res = next(ctx.filter("count(//uast:Positions/end/uast:Position[@col=49])"))
        self.assertRaises(NodeTypedGetException, res.get_str)

    def testRoleIdName(self) -> None:
        self.assertEqual(role_id(role_name(1)), 1)
        self.assertEqual(role_name(role_id("IDENTIFIER")),  "IDENTIFIER")

    @staticmethod
    def _itTestTree() -> dict:
        def set_position(node: dict, start_offset: int, start_line: int, start_col: int,
                         end_offset: int, end_line: int, end_col: int) -> None:
            node["@pos"] = {
                "@type": "uast:Positions",
                "start": {
                    "@type": "uast:Position",
                    "offset": start_offset,
                    "line": start_line,
                    "col": start_col
                },
                "end": {
                    "@type": "uast:Position",
                    "offset": end_offset,
                    "line": end_line,
                    "col": end_col
                }
            }

        root = {"@type": "root"}
        set_position(root, 0,1,1, 1,1,2)

        son1 = {"@type": "son1"}
        set_position(son1, 2,2,2, 3,2,3)

        son1_1 = {"@type": "son1_1"}
        set_position(son1_1, 10,10,1, 12,2,2)

        son1_2 = {"@type": "son1_2"}
        set_position(son1_2, 10,10,1, 12,2,2)

        son1["children"] = [son1_1, son1_2]

        son2 = {"@type": "son2"}
        set_position(son2, 100,100,1,  101,100,2)

        son2_1 = {"@type": "son2_1"}
        set_position(son2_1, 5,5,1, 6,5,2)

        son2_2 = {"@type": "son2_2"}
        set_position(son2_2, 15,15,1, 16,15,2)

        son2["children"] = [son2_1, son2_2]
        root["children"] = [son1, son2]

        return root

    @staticmethod
    def _get_nodetypes(iterator: NodeIterator) -> t.List[str]:
        return [n["@type"] for n in
                filter(lambda x: isinstance(x, dict), iterator)]

    @staticmethod
    def _get_nodes(iterator: NodeIterator) -> t.List[dict]:
        return [n.get() for n in iterator]

    @staticmethod
    def _get_positions(iterator: NodeIterator):
        startPositions = [ n["@pos"]["start"] for n in
                           filter(lambda x: isinstance(x, dict) and
                                  "@pos" in x.keys() and
                                  "start" in x["@pos"].keys(), iterator) ]
        return [ (int(n["offset"]), int(n["line"]), int(n["col"])) for n in startPositions ]

    def decrefAndGC(self, obj) -> None:
        del obj
        gc.collect()

    def testIteratorPreOrder(self) -> None:
        root = self._itTestTree()
        it = iterator(root, TreeOrder.PRE_ORDER)
        self.assertIsNotNone(it)
        expanded = self._get_nodetypes(it)
        self.assertListEqual(expanded, ['root', 'son1', 'son1_1', 'son1_2',
                                        'son2', 'son2_1', 'son2_2'])

    def testIteratorPostOrder(self) -> None:
        root = self._itTestTree()
        it = iterator(root, TreeOrder.POST_ORDER)
        self.assertIsNotNone(it)
        expanded = self._get_nodetypes(it)
        self.assertListEqual(expanded, ['son1_1', 'son1_2', 'son1', 'son2_1',
                                        'son2_2', 'son2', 'root'])

    def testIteratorLevelOrder(self) -> None:
        root = self._itTestTree()
        it = iterator(root, TreeOrder.LEVEL_ORDER)
        self.assertIsNotNone(it)
        expanded = self._get_nodetypes(it)
        self.assertListEqual(expanded, ['root', 'son1', 'son2', 'son1_1',
                                        'son1_2', 'son2_1', 'son2_2'])

    def testIteratorPositionOrder(self) -> None:
        # Check first our homemade tree
        root = self._itTestTree()
        it = iterator(root, TreeOrder.POSITION_ORDER)
        self.assertIsNotNone(it)
        expanded = self._get_nodetypes(it)
        self.assertListEqual(expanded, ['root', 'son1', 'son2_1', 'son1_1',
                                        'son1_2', 'son2_2', 'son2'])
        # Check that when using the positional order the positions we get are
        # in fact sorted by (offset, line, col)
        it = iterator(root, TreeOrder.POSITION_ORDER)
        positions = self._get_positions(it)
        self.assertListEqual(positions, [(0,1,1), (2,2,2), (5,5,1), (10,10,1),
                                         (10,10,1), (15,15,1), (100,100,1)])

    def testAnyOrder(self) -> None:
        root = self._itTestTree()
        it = iterator(root, TreeOrder.ANY_ORDER)
        self.assertIsNotNone(it)
        expanded = self._get_nodetypes(it)
        # We only can test that the order gives us all the nodes
        self.assertEqual(set(expanded), {'root', 'son1', 'son2', 'son1_1',
                                         'son1_2', 'son2_1', 'son2_2'})

    def testChildrenOrder(self) -> None:
        root = self._itTestTree()
        it = iterator(root, TreeOrder.CHILDREN_ORDER)
        self.assertIsNotNone(it)
        expanded = self._get_nodetypes(it)
        # We only can test that the order gives us all the nodes
        self.assertEqual(expanded, ['son1', 'son2'])

    # Iterating from the root node should give the same result as
    # iterating from the tree, for every available node
    def testNodeIteratorEqualsCtxIterator(self) -> None:
        ctx = self._parse_fixture()
        root = ctx.root

        for order in TreeOrder:
            itCtx  = ctx.iterate(order)
            itRoot = root.iterate(order)
            self.assertListEqual(self._get_nodes(itCtx), self._get_nodes(itRoot))

    def _validate_ctx(self, ctx: ResultContext) -> None:
        self.assertIsNotNone(ctx)
        self.assertIsInstance(ctx, ResultContext)
        self.assertIsInstance(ctx.uast, Node)

    def testFilterInsideIter(self) -> None:
        ctx = self._parse_fixture()
        c2 = uast()
        for n in ctx.iterate(TreeOrder.PRE_ORDER):
            c2.filter("//uast:Positions", n)

    def testItersMixingIterations(self) -> None:
        ctx = self._parse_fixture()

        it = ctx.iterate(TreeOrder.PRE_ORDER)
        next(it); next(it); next(it); next(it)

        it2 = it.iterate(TreeOrder.PRE_ORDER)
        next(it2)

        a = next(it).get()
        b = next(it2).get()
        self.assertEqual(a, b)

    def testManyFilters(self) -> None:
        ctx = self._parse_fixture()

        before = resource.getrusage(resource.RUSAGE_SELF)
        for _ in range(10000):
            ctx.filter("//*[@role='Identifier']")

        after = resource.getrusage(resource.RUSAGE_SELF)

        # Check that memory usage has not doubled
        self.assertLess(after[2] / before[2], 2.0)

    def testManyParses(self) -> None:
        before = resource.getrusage(resource.RUSAGE_SELF)
        for _ in range(100):
            self.client.parse(self.fixtures_pyfile)

        after = resource.getrusage(resource.RUSAGE_SELF)

        # Check that memory usage has not doubled
        self.assertLess(after[2] / before[2], 2.0)

    def testManyParsesAndFilters(self) -> None:
        before = resource.getrusage(resource.RUSAGE_SELF)
        for _ in range(100):
            ctx = self.client.parse(self.fixtures_pyfile)
            ctx.filter("//*[@role='Identifier']")

        after = resource.getrusage(resource.RUSAGE_SELF)

        # Check that memory usage has not doubled
        self.assertLess(after[2] / before[2], 2.0)

    def testSupportedLanguages(self) -> None:
        res = self.client.supported_languages()
        self.assertGreater(len(res), 0)
        for l in res:
            for key in ('language', 'version', 'status', 'features'):
                self.assertTrue(hasattr(l, key))
                self.assertIsNotNone(getattr(l, key))

    def testSupportedLanguageManifests(self) -> None:
        langs_with_aliases = {'csharp', 'cpp', 'javascript', 'bash'}
        res = self.client.supported_language_manifests()
        self.assertGreater(len(res), 0)
        for l in res:
            for key in ('name', 'language', 'version', 'status', 'features'):
                self.assertTrue(hasattr(l, key))
                self.assertIsNotNone(getattr(l, key))
            if getattr(l, 'language') in langs_with_aliases:
                self.assertTrue(hasattr(l, 'aliases'))
                self.assertGreater(len(getattr(l, 'aliases')), 0)

    def testEncode(self) -> None:
        ctx = self._parse_fixture()
        # This test is here for backward compatibility purposes,
        # in case someone was relying on encoding contexts this way
        self.assertEqual(ctx.ctx.encode(None, 0), ctx._response.uast)
        self.assertEqual(ctx.encode(), ctx._response.uast)

    def testEncodeWithEmptyContext(self) -> None:
        ctx = ResultContext()
        obj = {"k1": "v1", "k2": "v2"}
        fmt = 1 # YAML

        # This test is here for backward compatibility purposes,
        # in case someone was relying on encoding contexts this way
        data = ctx.ctx.encode(obj, fmt)
        other_data = ctx.encode(obj, fmt)
        self.assertDictEqual(obj, decode(data, format = fmt).load())
        self.assertDictEqual(obj, decode(other_data, format = fmt).load())

    def testGetAll(self) -> None:
        ctx = self._parse_fixture()

        expected = ["os", "resource", "unittest", "docker", "bblfsh"]
        actual = []
        for k in ctx.get_all()["body"]:
            if "@type" in k and k["@type"] == "uast:RuntimeImport" and "Path" in k:
                path = k["Path"]
                if "Name" in path:
                    actual.append(k["Path"]["Name"])

        self.assertListEqual(expected, actual)

    def testLoad(self) -> None:
        ctx = self._parse_fixture()

        it = ctx.iterate(TreeOrder.PRE_ORDER)
        next(it); next(it); next(it); next(it)

        it2 = it.iterate(TreeOrder.PRE_ORDER)
        n = next(it2)
        node_ext = n.node_ext

        obj = node_ext.load()
        typ = obj["@type"]
        self.assertEqual("uast:RuntimeImport", typ)

        path = obj["Path"]
        self.assertEqual("uast:Identifier", path["@type"])
        self.assertEqual("os", path["Name"])

    # The following testOrphan{x} methods verifies that iterators and nodes work
    # correctly once the context they come from has been DECREFed. Loading an
    # (external) node and filtering it after the context / iterators have been
    # DECREFed are also checked. As an example, the following code should work
    # in Python:
    #
    # its = []
    # for file in files:
    #    ctx = client.parse(file)
    #    it = ctx.filter("blablablah")
    #    its.append(it)
    #
    # it = pick a it from its
    # node = next(it)
    #
    # Instead of testing with a while, we can just delete ctx before doing
    # something with the iterator
    def testOrphanFilter(self) -> None:
        ctx = self._parse_fixture()
        it = ctx.filter("//uast:RuntimeImport")
        self.decrefAndGC(ctx)
        # We should be able to retrieve values from the iterator
        # after the context has been DECREFed but the iterator
        # still exists
        obj = next(it).get()
        typ = obj["@type"]
        self.assertEqual("uast:RuntimeImport", typ)

        # Chaining calls has the same effect as splitting
        # the effect across different lines as above
        self.decrefAndGC(it)
        it = self._parse_fixture().filter("//uast:RuntimeImport")
        next(it)
        obj = next(it).get()
        typ = obj["@type"]
        self.assertEqual("uast:RuntimeImport", typ)

    def testOrphanIterator(self) -> None:
        ctx = self._parse_fixture()
        it = ctx.iterate(TreeOrder.PRE_ORDER)
        self.decrefAndGC(ctx)
        # We should be able to retrieve values from the iterator
        # after the context has been DECREFed but the iterator
        # still exists
        obj = next(it).get()
        self.assertIsInstance(obj, dict)

        # Chaining calls has the same effect as splitting
        # the effect across different lines as above
        self.decrefAndGC(it)
        it = self._parse_fixture().iterate(TreeOrder.POST_ORDER)
        obj = next(it)
        self.assertIsInstance(obj, Node)

    def testLoadOrphanNode(self) -> None:
        ctx = self._parse_fixture()
        it = ctx.iterate(TreeOrder.PRE_ORDER)
        # The underlying ctx should not be deallocated even if ctx goes
        # out of scope because the iterator is still alive
        self.decrefAndGC(ctx)
        next(it); next(it); next(it);
        node = next(it)
        self.decrefAndGC(it)
        # Context should not have been deallocated yet because we
        # want to iterate from the node onwards
        it2 = node.iterate(TreeOrder.PRE_ORDER)
        node_ext = node.node_ext
        # node could be deallocated here also, if we by, any chance,
        # we happen to be storing only the external nodes
        self.decrefAndGC(node)
        obj = node_ext.load()
        typ = obj["@type"]
        self.assertEqual("uast:RuntimeImport", typ)

    def testFilterOrphanNode(self) -> None:
        ctx = self._parse_fixture()
        root = ctx.root
        self.decrefAndGC(ctx)
        # filter should work here over the tree even if we ctx has
        # been DECREFed by the interpreter (it has gone out of scope)
        it = root.filter("//uast:RuntimeImport")
        obj = next(it).get()
        typ = obj["@type"]
        self.assertEqual("uast:RuntimeImport", typ)

    def testPythonContextIterate(self) -> None:
        # C++ memory context
        ctxC = self._parse_fixture()
        # Python memory context
        pyDict = ctxC.root.get()
        ctxPy = bblfsh.context(pyDict)

        for treeOrder in TreeOrder:
            itC = ctxC.iterate(treeOrder)
            itPy = ctxPy.iterate(treeOrder)

            for nodeC, nodePy in zip(itC, itPy):
                self.assertEqual(nodeC.get(), nodePy)

    def testPythonContextFilter(self) -> None:
        # C++ memory context
        ctxC = self._parse_fixture()
        # Python memory context
        pyDict = ctxC.root.get()
        ctxPy = bblfsh.context(pyDict)

        itC = ctxC.filter("//*[@role='Identifier']")
        itPy = ctxPy.filter("//*[@role='Identifier']")

        for nodeC, nodePy in zip(itC, itPy):
            self.assertEqual(nodeC.get(), nodePy)

    def testBinaryEncodeDecodePythonContext(self) -> None:
        # Binary encoding should be invertible
        # C++ memory context
        ctxC = self._parse_fixture()
        # Python memory context
        pyDict = ctxC.root.get()
        ctxPy = bblfsh.context(pyDict)
        encoded = ctxPy.encode(fmt = 0) # Binary encoding
        decoded = decode(encoded, format = 0)

        self.assertEqual(pyDict, decoded.load())

    def testInvalidDecodeBytes(self) -> None:
        with self.assertRaises(RuntimeError):
            decode(b'', format = 0)
        with self.assertRaises(RuntimeError):
            decode(b'abcdef', format = 0)

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


import logging
import logging.handlers
import pathlib
import tempfile
import time

from test import support
from unittest import TestCase

import gnuradio as gr
import gnuradio.blocks
import gnuradio.gr
import numpy as np

from sats_receiver.gr_modules.demodulators import GmskDemod
from sats_receiver.gr_modules.epb.prober import Prober

HERE = pathlib.Path(__file__).parent
FILES = HERE / 'files'
TIMEOUT = support.SHORT_TIMEOUT

def rolling_window(a, size):
    shape = a.shape[:-1] + (a.shape[-1] - size + 1, size)
    strides = a.strides + (a. strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

class DemodTopBlock(gr.gr.top_block):
    def __init__(self,
                 fp: pathlib.Path,
                 out_dir: pathlib.Path,
                 samp_rate: int,
                 channels: list[int],
                 demodulator):
        self.prefix = self.__class__.__name__
        self.log = logging.getLogger(self.prefix)

        super(DemodTopBlock, self).__init__('DemodTopBlock', catch_exceptions=False)

        self.samp_rate = samp_rate
        self.channels = channels

        self.fsrc = gr.blocks.file_source(gr.gr.sizeof_gr_complex, str(fp), False, 0, samp_rate)
        self.thr = gr.blocks.throttle(gr.gr.sizeof_gr_complex, samp_rate, True)
        self.ctr = gr.blocks.complex_to_real()
        self.probe = Prober()
        self.demod = demodulator
        self.fsinks = {}
        for rate in channels:
            fn = str(out_dir / str(rate))
            fsink = gr.blocks.file_sink(gr.gr.sizeof_float, fn, False)
            fsink.set_unbuffered(False)
            self.fsinks[rate] = fn, fsink

        self.connect(
            self.fsrc,
            self.thr,
            self.demod,
        )
        self.connect(self.thr, self.ctr, self.probe)
        for i, rate in enumerate(channels):
            self.connect((self.demod, i), self.fsinks[rate][1])

    def start(self, max_noutput_items=10000000):
        self.log.info('START')
        super(DemodTopBlock, self).start(max_noutput_items)

    def stop(self):
        self.log.info('STOP')
        super(DemodTopBlock, self).stop()
        for fn, fsink in self.fsinks.values():
            fsink.do_update()
            fsink.close()

    def wait(self):
        super(DemodTopBlock, self).wait()

class TestDemod(TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        cls.out_dir = tempfile.TemporaryDirectory('.d', 'sats-receiver-test', ignore_cleanup_errors=True)
        cls.out_dp = pathlib.Path(cls.out_dir.name)

    @classmethod
    def tearDownClass(cls) -> None:
        cls.out_dir.cleanup()
        cls.out_dir = None

    def setUp(self) -> None:
        self.tb = None

    def tearDown(self) -> None:
        if isinstance(self.tb, DemodTopBlock):
            self.tb.stop()
            self.tb.wait()

    def test_gmsk_9600_9600(self):
        samp_rate = 9600
        channels = [9600, 4800, 2400]
        f = FILES / 'gmsk_9600@9600_10010111.bin'
        subseq = np.array(list('10010111'), dtype=np.uint8)

        demod = GmskDemod(samp_rate, channels)
        self.tb = DemodTopBlock(f, self.out_dp, samp_rate, channels, demod)
        self.tb.start()

        while self.tb.probe.changes():
            time.sleep(self.tb.probe.measure_s)
        time.sleep(self.tb.probe.measure_s)

        self.tb.stop()
        self.tb.wait()

        f_9600 = np.fromfile(self.tb.fsinks[9600][0], dtype=np.float32).astype(np.uint8)
        f_4800 = np.fromfile(self.tb.fsinks[4800][0], dtype=np.float32).astype(np.uint8)
        f_2400 = np.fromfile(self.tb.fsinks[2400][0], dtype=np.float32).astype(np.uint8)

        rw_9600 = rolling_window(f_9600, subseq.size)
        rw_4800 = rolling_window(f_4800, subseq.size)
        rw_2400 = rolling_window(f_2400, subseq.size)

        x = np.all(rw_9600 == subseq, 1)
        self.assertTrue(np.any(x))
        y = np.argmax(x)
        x = np.resize(f_9600[y:], ((f_9600.size - y) // subseq.size, subseq.size))
        self.assertTrue(np.all(x == subseq))

        self.assertFalse(np.any(np.all(rw_4800 == subseq, 1)))
        self.assertFalse(np.any(np.all(rw_2400 == subseq, 1)))

    def test_gmsk_4800_9600(self):
        samp_rate = 9600
        channels = [9600, 4800, 2400]
        f = FILES / 'gmsk_4800@9600_10010111.bin'
        subseq = np.array(list('10010111'), dtype=np.uint8)

        demod = GmskDemod(samp_rate, channels)
        self.tb = DemodTopBlock(f, self.out_dp, samp_rate, channels, demod)
        self.tb.start()

        while self.tb.probe.changes():
            time.sleep(self.tb.probe.measure_s)
        time.sleep(self.tb.probe.measure_s)

        self.tb.stop()
        self.tb.wait()

        f_9600 = np.fromfile(self.tb.fsinks[9600][0], dtype=np.float32).astype(np.uint8)
        f_4800 = np.fromfile(self.tb.fsinks[4800][0], dtype=np.float32).astype(np.uint8)
        f_2400 = np.fromfile(self.tb.fsinks[2400][0], dtype=np.float32).astype(np.uint8)

        rw_9600 = rolling_window(f_9600[:subseq.size * 2], subseq.size)
        rw_4800 = rolling_window(f_4800[:subseq.size * 2], subseq.size)
        rw_2400 = rolling_window(f_2400[:subseq.size * 2], subseq.size)

        x = np.all(rw_4800 == subseq, 1)
        self.assertTrue(np.any(x))
        y = np.argmax(x)
        x = np.resize(f_4800[y:], ((f_4800.size - y) // subseq.size, subseq.size))
        self.assertTrue(np.all(x == subseq))

        self.assertFalse(np.any(np.all(rw_9600 == subseq, 1)))
        self.assertFalse(np.any(np.all(rw_2400 == subseq, 1)))

    def test_gmsk_2400_9600(self):
        samp_rate = 9600
        channels = [9600, 4800, 2400]
        f = FILES / 'gmsk_2400@9600_10010111.bin'
        subseq = np.array(list('10010111'), dtype=np.uint8)

        demod = GmskDemod(samp_rate, channels)
        self.tb = DemodTopBlock(f, self.out_dp, samp_rate, channels, demod)
        self.tb.start()

        while self.tb.probe.changes():
            time.sleep(self.tb.probe.measure_s)
        time.sleep(self.tb.probe.measure_s)

        self.tb.stop()
        self.tb.wait()

        f_9600 = np.fromfile(self.tb.fsinks[9600][0], dtype=np.float32).astype(np.uint8)
        f_4800 = np.fromfile(self.tb.fsinks[4800][0], dtype=np.float32).astype(np.uint8)
        f_2400 = np.fromfile(self.tb.fsinks[2400][0], dtype=np.float32).astype(np.uint8)

        rw_9600 = rolling_window(f_9600[:subseq.size * 2], subseq.size)
        rw_4800 = rolling_window(f_4800[:subseq.size * 2], subseq.size)
        rw_2400 = rolling_window(f_2400[:subseq.size * 2], subseq.size)

        x = np.all(rw_2400 == subseq, 1)
        self.assertTrue(np.any(x))
        y = np.argmax(x)
        x = np.resize(f_2400[y:], ((f_2400.size - y) // subseq.size, subseq.size))
        self.assertTrue(np.all(x == subseq))

        self.assertFalse(np.any(np.all(rw_9600 == subseq, 1)))
        self.assertFalse(np.any(np.all(rw_4800 == subseq, 1)))


"""Correct for relativistic clock effect due to orbit eccentricity

Description:
------------

Correct relativistic clock effect due to orbit eccentricity either based on precise or broadcast orbits.
"""

# Midgard imports
from midgard.dev import plugins

# Where imports
from where import apriori

@plugins.register
def gnss_relativistic_clock(dset):
    """Determine relativistic clock correction due to orbit eccentricity

    The correction is caluclated for precise and broadcast orbits after Eq. 10.10 and 10.11 in :cite:`iers2010`.

    Args:
        dset (Dataset):   Model data.

    Returns:
        numpy.ndarray:    Relativistic clock correction due to orbit eccentricity corrections for each observation

    """
    if "delay.gnss_relativistic_clock" in dset.fields:
        return dset.delay.gnss_relativistic_clock
    else:
        orbit = apriori.get(
            "orbit",
            apriori_orbit=dset.vars["orbit"],
            rundate=dset.analysis["rundate"],
            system=tuple(dset.unique("system")),
            station=dset.vars["station"],
        )

        return -orbit.relativistic_clock_correction(dset.sat_posvel.trs.pos.val, dset.sat_posvel.trs.vel.val)


print('customers: What are you serving today?')
menulist = input('server: We have ').split(', ')

menu = {}
for i in menulist:
  menu[i.split(' ($')[0]] = {
    'price': int(i.split(' ($')[1].replace(')', '')),
    'count': 0
  }

# print(menu)

for i in range(1, 5):
  order = input(f'customer{i}: ')
  for j in order.split(', '):
    # print(menu[j])
    menu[j]['count'] += 1

total = 0
print('server: Okay you ordered ', end='')
for i in menu:
  if menu[i]['count'] != 0:
    print(f'{i} * {menu[i]["count"]}, ', end='')
    total += menu[i]['price'] * menu[i]['count']
print(f'${total} in total.')


from citram_api.constants.hosts import Urls
from citram_api.utils.custom_exceptions import NotEnoughParametersException
from citram_api.utils.utils import common_request

def get_lines_by_mode(mode_cod):
    """
    Get transport lines of a transport mode given a transport mode id.

    You can use constants.TransportModes to get the available transport modes ids.

    Example:

    .. code-block:: python

        get_lines_by_mode(TransportModes.CERCANIAS.value)

    :param int mode_cod: Id of a public transport. Use constants.TransportModes to easily select transport modes ids.
    :return dict: Lines of the transport specified. The returned dictionary look likes the following example:

    .. code-block:: python

        {
            'lines': {
                'Line': [{
                    'codLine': '5__C1___',
                    'shortDescription': 'C1',
                    'description': 'P.Pío-Atocha-Recoletos-Chamartín-Aeropuerto T4',
                    'codMode': '5',
                    'updateDate': '2019-11-19T14:30:28+01:00',
                    'updateKmlDate': '2019-11-19T14:25:06+01:00',
                    'nightService': 0,
                    'active': True,
                    'shortItinerary': {
                        'Itinerary': [{
                            'codItinerary': '5__C1____1__IT_1',
                            'name': 'P.Pío-Atocha-Recoletos-Chamartín-Aeropuerto T4',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20191119_1425/cercaniaskmz/M5_LC-1_S1_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '5__C1____2__IT_1',
                            'name': 'Aeropuerto T4-Chamartín-Recoletos-Atocha-P.Pío',
                            'direction': 2,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20191119_1425/cercaniaskmz/M5_LC-1_S2_TRAMO.kmz',
                            'stops': {}
                        }]
                    },
                    'URLLine': 'http://www.crtm.es/tu-transporte-publico/cercanias-renfe/lineas/5__1___.aspx',
                    'colorLine': '#4FB0E5',
                    'text_colorLine': '#FFFFFF',
                    'companyCode': '301'
                },
                ...
                ]
            }
        }

    """
    if mode_cod is not None:
        url_formatted = (Urls.CITRAM_WIDGET_SERVICE.value +
                         '/GetLines.php?mode={mode}'
                         .format(mode=str(mode_cod)))
    else:
        raise NotEnoughParametersException('You must specify a transport mode.')

    return common_request(url_formatted)

def get_lines_by_municipality(cod_municipality, cod_mode=None):
    """
    Get transport lines of a transport mode given a municipality id.

    You can use constants.Municipalities to get the available municipalities ids.

    Example:

    .. code-block:: python

        get_lines_by_municipality(Municipalities.FUENLABRADA.value)

    :param int cod_municipality: Id of a municipality. Use constants.Municipalities to easily select transport modes ids.
    :param int cod_mode: If specified, the results will be filtered, returning only lines of that transport mode.
                         Optional, default: None (No transport mode filtering).
    :return dict: Lines of the municipality specified. The returned dictionary look likes the following example:

    .. code-block:: python

        {
            'lines': {
                'Line': [{
                    'codLine': '4__12___',
                    'shortDescription': '12',
                    'description': 'MetroSur',
                    'codMode': '4',
                    'updateDate': '2019-03-22T17:21:37+01:00',
                    'updateKmlDate': '2016-06-01T17:04:00+02:00',
                    'nightService': 0,
                    'active': True,
                    'shortItinerary': {
                        'Itinerary': [{
                            'codItinerary': '4__12____1__IT_1',
                            'name': 'METROSUR (ANDEN-1)',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/metrokmz/M4_L12-1_S1_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '4__12____2__IT_1',
                            'name': 'METROSUR (ANDEN-2)',
                            'direction': 2,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/metrokmz/M4_L12-2_S1_TRAMO.kmz',
                            'stops': {}
                        }]
                    },
                    'URLLine': 'http://www.crtm.es/tu-transporte-publico/metro/lineas/4__12___.aspx',
                    'colorLine': '#A49800',
                    'text_colorLine': '#FFFFFF',
                    'companyCode': '200'
                }, {
                    'codLine': '5__C5___',
                    'shortDescription': 'C5',
                    'description': 'Móstoles-El Soto-Atocha-Fuenlabrada-Humanes',
                    'codMode': '5',
                    'updateDate': '2019-11-19T14:30:28+01:00',
                    'updateKmlDate': '2019-11-19T14:25:06+01:00',
                    'nightService': 0,
                    'active': True,
                    'shortItinerary': {
                        'Itinerary': [{
                            'codItinerary': '5__C5____1__IT_1',
                            'name': 'Móstoles El Soto-Atocha-Fuenlabrada-Humanes',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20191119_1425/cercaniaskmz/M5_LC-5_S1_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '5__C5____2__IT_1',
                            'name': 'Humanes-Fuenlabrada-Atocha-Móstoles El Soto',
                            'direction': 2,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20191119_1425/cercaniaskmz/M5_LC-5_S2_TRAMO.kmz',
                            'stops': {}
                        }]
                    },
                    'URLLine': 'http://www.crtm.es/tu-transporte-publico/cercanias-renfe/lineas/5__5___.aspx',
                    'colorLine': '#F9BA13',
                    'text_colorLine': '#FFFFFF',
                    'companyCode': '301'
                }, {
                    'codLine': '8__455___',
                    'shortDescription': '455',
                    'description': '455-PINTO - GETAFE',
                    'codMode': '8',
                    'updateDate': '2018-05-10T15:25:50+02:00',
                    'updateKmlDate': '2016-06-01T17:04:00+02:00',
                    'nightService': 0,
                    'active': True,
                    'shortItinerary': {
                        'Itinerary': [{
                            'codItinerary': '8__455____1_-_IT_1',
                            'name': '455 GETAFE',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/interurbanoskmz/M8_L455_S1_obs[-]_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '8__455____1_a._IT_2',
                            'name': '455 GETAFE',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/interurbanoskmz/M8_L455_S1_obs[a.]_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '8__455____1_am_IT_2',
                            'name': 'Hasta ambulatorio de Getafe',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/interurbanoskmz/M8_L455_S1_obs[am]_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '8__455____1_h._IT_2',
                            'name': 'Hasta/desde hospital de Getafe',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/interurbanoskmz/M8_L455_S1_obs[h.]_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '8__455____2_h._IT_2',
                            'name': 'Hasta/desde hospital de Getafe',
                            'direction': 2,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/interurbanoskmz/M8_L455_S2_obs[h.]_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '8__455____2_jc_IT_2',
                            'name': 'Desde Avda. Juan de la Cierva, 28',
                            'direction': 2,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/interurbanoskmz/M8_L455_S2_obs[jc]_TRAMO.kmz',
                            'stops': {}
                        }]
                    },
                    'URLLine': 'http://www.crtm.es/tu-transporte-publico/autobuses-interurbanos/lineas/8__455___.aspx',
                    'colorLine': '#8EBF42',
                    'text_colorLine': '#FFFFFF',
                    'companyCode': '078'
                },
                ...
                ]
            }
        }
    """
    if cod_municipality is not None:
        url_formatted = (Urls.CITRAM_WIDGET_SERVICE.value +
                         '/GetLines.php?codMunicipality={codMunicipality}'
                         .format(codMunicipality=str(cod_municipality)))

        if cod_mode is not None:
            url_formatted = url_formatted + '&mode={mode}'.format(mode=cod_mode)
    else:
        raise NotEnoughParametersException('You must specify a municipality code.')

    return common_request(url_formatted)

def get_lines_by_line_code(cod_line):
    """
    Returns the line specified. This method results in a brief description of the line.

    Example:

    .. code-block:: python

        get_lines_by_line_code(create_line_cod(TransportModes.METRO.value, 10))

    :param str cod_line: Line id. Use utils.create_line_cod to create this id easily.
    :return: The line of the line id specified. The returned dictionary look likes the following example:

    .. code-block:: python

        {
            'lines': {
                'Line': {
                    'codLine': '4__10___',
                    'shortDescription': '10',
                    'description': 'Hospital del Norte-Puerta del Sur',
                    'codMode': '4',
                    'updateDate': '2019-03-22T17:21:37+01:00',
                    'updateKmlDate': '2016-06-01T17:04:00+02:00',
                    'nightService': 0,
                    'active': True,
                    'shortItinerary': {
                        'Itinerary': [{
                            'codItinerary': '4__10____1__IT_1',
                            'name': 'Hospital del Norte - Puerta del Sur',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/metrokmz/M4_L10a_S1_TRAMO.kmz#http://www.citram.es:8080/kml/itinerarios/20160601_1704/metrokmz/M4_L10b_S1_TRAMO.kmz',
                            'stops': {}
                        }, {
                            'codItinerary': '4__10____2__IT_1',
                            'name': 'Puerta del Sur - Hospital del Norte',
                            'direction': 2,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/metrokmz/M4_L10a_S2_TRAMO.kmz#http://www.citram.es:8080/kml/itinerarios/20160601_1704/metrokmz/M4_L10b_S2_TRAMO.kmz',
                            'stops': {}
                        }]
                    },
                    'URLLine': 'http://www.crtm.es/tu-transporte-publico/metro/lineas/4__10___.aspx',
                    'colorLine': '#005AA9',
                    'text_colorLine': '#FFFFFF',
                    'companyCode': '200'
                }
            }
        }

    """
    if cod_line is not None:
        url_formatted = (Urls.CITRAM_WIDGET_SERVICE.value +
                         '/GetLines.php?codLine={codLine}'
                         .format(codLine=str(cod_line)))
    else:
        raise NotEnoughParametersException('You must specify a line code.')

    return common_request(url_formatted)

def get_line_info(cod_line):
    """
    Returns line information from the line id specified.

    Example:

    .. code-block:: python

        get_line_info(create_line_cod(TransportModes.METRO.value, 10))

    :param str cod_line: Line id. Use utils.create_line_cod to create this id easily.
    :return: Info of the line id specified. The returned dictionary look likes the following example:

    .. code-block:: python

        {
            'lines': {
                'LineInformation': {
                    'codLine': '4__10___',
                    'shortDescription': '10',
                    'description': 'Hospital del Norte-Puerta del Sur',
                    'codMode': '4',
                    'codMunicipalities': {
                        'string': ['4278', '4279', '4350', '4401']
                    },
                    'itinerary': {
                        'Itinerary': [{
                            'codItinerary': '4__10____1__IT_1',
                            'name': 'Hospital del Norte - Puerta del Sur',
                            'direction': 1,
                            'kml': 'http://www.citram.es:8080/kml/itinerarios/20160601_1704/metrokmz/M4_L10a_S1_TRAMO.kmz#http://www.citram.es:8080/kml/itinerarios/20160601_1704/metrokmz/M4_L10b_S1_TRAMO.kmz',
                            'stops': {
                                'StopInformation': [{
                                    'codStop': '4_284',
                                    'shortCodStop': '',
                                    'codMode': '4',
                                    'name': 'HOSPITAL INFANTA SOFÍA',
                                    'address': 'Paseo  Europa SN ',
                                    'postCode': '',
                                    'codMunicipality': '4401',
                                    'coordinates': {
                                        'longitude': -3.61145,
                                        'latitude': 40.55977
                                    },
                                    'lines': {
                                        'Line': {
                                            'codLine': '4__10___',
                                            'shortDescription': '10',
                                            'description': 'Hospital del Norte-Puerta del Sur',
                                            'codMode': '4',
                                            'updateDate': '2019-03-22T17:21:37+01:00',
                                            'updateKmlDate': '2016-06-01T17:04:00+02:00',
                                            'nightService': 0,
                                            'active': True,
                                            'shortItinerary': {},
                                            'companyCode': ''
                                        }
                                    },
                                    'access': 0,
                                    'park': 0,
                                    'nightLinesService': 0
                                },
                                ...
                    },
                    'updateDate': '2019-03-22T17:21:37+01:00',
                    'updateKmlDate': '2016-06-01T17:04:00+02:00',
                    'nightService': 0,
                    'lineTimePlanning': {
                        'codLine': '4__10___',
                        'codItinerary': '',
                        'type': '',
                        'startService': '',
                        'endService': '',
                        'updateDate': '0001-01-01T00:00:00'
                    }
                }
            }
        }
    """
    url_formatted = (Urls.CITRAM_WIDGET_SERVICE.value +
                     '/GetLinesInformation.php?activeItinerary=1&codLine={codLine}'
                     .format(codLine=cod_line))

    return common_request(url_formatted)

def get_lines_timeplanning(cod_line):
    """
    Timeplanning of the specified line id.

    Example:

    .. code-block:: python

        get_lines_timeplanning(create_line_cod(TransportModes.METRO.value, 10))

    :param str cod_line: Line id. Use utils.create_line_cod to create this id easily.
    :return: Timeplanning of the line id specified.
    """
    url_formatted = (Urls.CITRAM_WIDGET_SERVICE.value +
                     '/GetLinesTimePlanning.php?activeItinerary=1&codLine={codLine}'
                     .format(codLine=cod_line))

    return common_request(url_formatted)

def get_line_location(mode_cod, cod_itinerary, cod_line, cod_stop, direction):
    """
    It returns the location of that line at the moment the request is performed. (i.e. Location of a bus of that line
    right now).

    Example:

    .. code-block:: python

        line = get_line_info(create_line_cod(TransportModes.METRO.value, 10))['lines']['LineInformation']
        get_line_location(int(line['codMode']),
                          line['itinerary']['Itinerary'][0]['codItinerary'],
                          line['codLine'],
                          line['itinerary']['Itinerary'][0]['stops']['StopInformation'][0]['codStop'],
                          line['itinerary']['Itinerary'][0]['direction'])

    :param int mode_cod: Id of a public transport. Use constants.TransportModes to easily select transport modes ids.
    :param int cod_itinerary: Itinerary of that line.
    :param str cod_line: Line id. Use utils.create_line_cod to create this id easily.
    :param str cod_stop: Stop id. In this case this is needed as a formality. Any stop of that line gives the same
                                  result.
    :param int direction: Direction of a itinerary.
    :return:
    """

    url_formatted = (Urls.CITRAM_WIDGET_SERVICE.value +
                     '/GetLineLocation.php?mode={mode}&codItinerary={codItinerary}&codLine={codLine}&codStop={codStop}&direction={direction}'
                     .format(mode=str(mode_cod), codItinerary=cod_itinerary, codLine=cod_line, codStop=cod_stop,
                             direction=str(direction)))

    return common_request(url_formatted)

def get_incidents_affectations(mode_cod, cod_line):
    """
    Returns incidents happening at the specified line.

    Example: get_incidents_affectations(TransportModes.METRO.value, create_line_cod(TransportModes.METRO.value, 10))

    :param int mode_cod: Id of a public transport. Use constants.TransportModes to easily select transport modes ids.
    :param str cod_line: Line id. Use utils.create_line_cod to create this id easily.
    :return dict: The current incidents going on in that line.
    """
    url_formatted = (Urls.CITRAM_WIDGET_SERVICE.value +
                     '/GetIncidentsAffectations.php?mode={mode}&codLine={codLine}'
                     .format(mode=str(mode_cod), codLine=cod_line))

    return common_request(url_formatted)