"""
DQAS for QFT QEM circuit design, deprecated DQAS implementation
"""

import sys

sys.path.insert(0, "../")

from functools import partial
import cirq
import numpy as np
import tensorflow as tf
from tensorcircuit.applications.vags import qft_qem_vag
from tensorcircuit.applications.dqas import (
    set_op_pool,
    DQAS_search,
    verbose_output,
)

def main_3():
    qft_3 = partial(qft_qem_vag, n=3)

    set_op_pool([cirq.X, cirq.Y, cirq.Z, cirq.I, cirq.T, cirq.S])
    DQAS_search(
        qft_3,
        nnp_initial_value=tf.zeros([6, 6]),
        p=6,
        prethermal=0,
        batch=32,
        verbose=False,
        epochs=30,
    )

def main_4():
    qft_4 = partial(qft_qem_vag, n=4)

    set_op_pool(
        [
            cirq.I,
            cirq.X,
            cirq.Y,
            cirq.Z,
            cirq.H,
            cirq.rx(np.pi / 3),
            cirq.rx(np.pi * 2.0 / 3),
            cirq.rz(np.pi / 3),
            cirq.rz(np.pi * 2.0 / 3),
            cirq.S,
            cirq.T,
        ]
    )
    DQAS_search(
        qft_4,
        nnp_initial_value=tf.zeros([12, 11]),
        p=12,
        prethermal=0,
        batch=32,
        verbose=False,
        verbose_func=verbose_output,
        epochs=6,
    )

if __name__ == "__main__":
    # main_3()
    main_4()


import discord
from discord.ext import commands
import random
from discord.utils import get
import pickle
import re

class Common(commands.Cog, name="기본"):
    """
    솔린디 봇의 기본 명령어들입니다
    """

    def __init__(self, app):
        self.app = app

    @commands.command(help="설정한 숫자의 범위 안에서 랜덤한 숫자를 하나 뽑습니다", usage="`!randomnumber/rn <숫자 1> <숫자 2>`")
    async def rn(self, ctx, num1, num2):
        try:
            picked = random.randint(int(num1), int(num2))
            await ctx.send(f'뽑힌 숫자는 **{str(picked)}** 입니다')
        except IndexError:
            await ctx.send("무슨 숫자를 뽑을지 알려주세요")
        except ValueError:
            await ctx.channel.send("정수를 입력해주세요")
        except ZeroDivisionError:
            await ctx.channel.send("0으로 나눌 수 없습니다")

    @commands.command(name="도움말", help="도움말을 출력합니다.")
    async def help_command(self, ctx, func=None):
        cog_list = ["기본","관리자", "음악"]
        if func is None:
            embed = discord.Embed(title="VGS Bot 도움말", description="접두사는 `?` 입니다.", color=0x00ffd8)  # Embed 생성
            for x in cog_list:  # cog_list에 대한 반복문
                cog_data = self.app.get_cog(x)  # x에 대해 Cog 데이터를 구하기
                command_list = cog_data.get_commands()  # cog_data에서 명령어 리스트 구하기
                embed.add_field(name=x, value=" ".join([c.name for c in command_list]), inline=True)  # 필드 추가
            await ctx.send(embed=embed)  # 보내기
        else:
            command_notfound = True  # 이걸 어떻게 쓸지 생각해보세요!
            for _title, cog in self.app.cogs.items():  # title, cog로 item을 돌려주는데 title은 필요가 없습니다.
                if not command_notfound:  # False면
                    break  # 반복문 나가기
                else:  # 아니면
                    for title in cog.get_commands():  # 명령어를 아까처럼 구하고 title에 순차적으로 넣습니다.
                        if title.name == func:  # title.name이 func와 같으면
                            cmd = self.app.get_command(title.name)  # title의 명령어 데이터를 구합니다.
                            embed = discord.Embed(title=f"명령어 : {cmd}", description=cmd.help, color=0x00ffd8)  # Embed 만들기
                            await ctx.send(embed=embed)  # 보내기
                            command_notfound = False
                            break  # 반복문 나가기
                        else:
                            command_notfound = True
            if command_notfound:  # 명령어를 찾지 못하면
                if func in cog_list:  # 만약 cog_list에 func가 존재한다면
                    cog_data = self.get_cog(func)  # cog 데이터 구하기
                    command_list = cog_data.get_commands()  # 명령어 리스트 구하기
                    embed = discord.Embed(title=f"카테고리 : {cog_data.qualified_name}",
                                          description=cog_data.description, color=0x00ffd8)  # 카테고리 이름과 설명 추가
                    embed.add_field(name="명령어들",
                                    value=", ".join([c.name for c in command_list]))  # 명령어 리스트 join
                    await ctx.send(embed=embed)  # 보내기
                else:
                    await ctx.send("그런 이름의 명령어나 카테고리는 없습니다.")  # 에러 메시지

def setup(app):
    app.add_cog(Common(app))


from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse
from .models import Project, Category, Expense
from django.views.generic import CreateView
from django.utils.text import slugify
from .forms import ExpenseForm
import json

def project_list(request):
    project_list = Project.objects.all()
    return render(request, "budget/project-list.html", {"project_list": project_list})

def project_detail(request, project_slug):
    project = get_object_or_404(Project, slug=project_slug)

    if request.method == "GET":
        category_list = Category.objects.filter(project=project)
        return render(
            request,
            "budget/project-detail.html",
            {
                "project": project,
                "expense_list": project.expenses.all(),
                "category_list": category_list,
            },
        )

    elif request.method == "POST":
        # request.POST has a dictionary-like object containing all HTTP POST params
        # providing that the request contains the form data
        form = ExpenseForm(request.POST)

        # If is_valid returns False, we go back to the form template with the previous values populated.
        if form.is_valid():
            # When is_valid returns True, we can access validated data in cleaned_data
            title = form.cleaned_data["title"]
            amount = form.cleaned_data["amount"]
            category_name = form.cleaned_data["category"]

            category = get_object_or_404(Category, project=project, name=category_name)

            Expense.objects.create(
                project=project, title=title, amount=amount, category=category
            )

    elif request.method == "DELETE":
        try:
            # this will raise when id is not passed into client.delete()
            id = json.loads(request.body)["id"]
            expense = Expense.objects.get(id=id)
            expense.delete()
        except Exception as e:
            print("[DELETE:project_detail]", e)
            return HttpResponse(status=404)

        return HttpResponse(status=204)

    return redirect(project)

class ProjectCreateView(CreateView):
    model = Project
    template_name = "budget/add-project.html"
    fields = ("name", "budget")

    def form_valid(self, form):
        self.object = form.save()

        categories = self.request.POST.get("categoriesString").split(",")
        for category in categories:
            Category.objects.create(
                project=Project.objects.get(id=self.object.id), name=category
            )

        return redirect(self.object)


import torchvision.transforms as transforms
from .. import constants
from ..util import max_vector_magnitude, log_vector, exp_vector

def create_transformer(img_size=(224,224), mean_std=None, aug=False):
    augmentations = []
    if aug:
        augmentations = [
            transforms.RandomHorizontalFlip(p=0.5),
            transforms.RandomAffine(degrees=0, translate=(0.1,0.1)),
        ]
    normalizations = []
    if mean_std is not None:
        normalizations = [transforms.Normalize(*mean_std)]
    return transforms.Compose([
        transforms.Resize(img_size),
        *augmentations,
        transforms.ToTensor(),
        *normalizations
    ])

class Normalizer:
    def __init__(self, dash_enabled=None, delta_mag=0, enemy_mag=0, negative_dash=False, log=False):
        self.dash_enabled = dash_enabled
        self.dash_cooldown = 2
        self.dash_length = 10
        self.max_health = 100
        self.max_bullets = 5
        self.delta_mag = delta_mag
        self.enemy_mag = enemy_mag
        self.n = 0
        self.negative_dash = negative_dash
        self.log = log

    def fit(self, df):
        dash_enabled = None
        delta_mag = 0
        enemy_mag = 0

        if "dash_enabled" in df.columns:
            dash_enabled = bool(df.iloc[-1]["dash_enabled"])

        if constants.last_movements[0] in df.columns:
            delta_mag = max(max_vector_magnitude(df[constants.last_movements]), max_vector_magnitude(df[constants.deltas]))
        else:
            delta_mag = max_vector_magnitude(df[constants.deltas])
        if constants.enemy_positions[0] in df.columns:
            enemy_mag = max_vector_magnitude(df[constants.enemy_positions], log=self.log)

        n = len(df)

        self.dash_enabled = self.dash_enabled if not dash_enabled else True
        self.delta_mag = max(self.delta_mag, delta_mag)
        self.enemy_mag = max(self.enemy_mag, enemy_mag)
        self.n += n

    def get_dash_enabled(self, df, dash_enabled=None):
        if dash_enabled is None:
            dash_enabled = self.dash_enabled
        if dash_enabled is None:
            if "dash_enabled" in df.columns:
                dash_enabled = bool(df.iloc[-1]["dash_enabled"])
            else:
                dash_enabled = True
        return dash_enabled

    def transform(self, df, dash_enabled=None):
        dash_enabled = self.get_dash_enabled(df, dash_enabled=dash_enabled)

        df = df.copy()

        if dash_enabled or not self.negative_dash:
            df["dash_cooldown"] /= self.dash_cooldown
            df["dash"] /= self.dash_length

        healths = [x for x in df.columns if "health" in x]
        df[healths] /= self.max_health
        df["bullets"] /= self.max_bullets

        if constants.last_movements[0] in df.columns:
            df[constants.deltas+constants.last_movements] /= self.delta_mag
        else:
            df[constants.deltas] /= self.delta_mag

        if constants.enemy_positions[0] in df.columns:
            pos = df[constants.enemy_positions]
            if self.log:
                pos = log_vector(pos)
            #print(df[constants.enemy_positions].shape, pos.shape)
            df[constants.enemy_positions] = pos / self.enemy_mag
        return df

    def inverse_transform(self, df):
        dash_enabled = self.get_dash_enabled(df, dash_enabled=dash_enabled)

        df = df.copy()

        if dash_enabled or not self.negative_dash:
            if "dash_cooldown" in df.columns:
                df["dash_cooldown"] *= self.dash_cooldown
            if "dash" in df.columns:
                df["dash"] *= self.dash_length

        if "health" in df.columns:
            healths = [x for x in df.columns if "health" in x]
            df[healths] *= self.max_health
        if "bullets" in df.columns:
            df["bullets"] *= self.max_bullets

        if constants.last_movements[0] in df.columns:
            df[constants.deltas+constants.last_movements] *= self.delta_mag
        else:
            df[constants.deltas] *= self.delta_mag

        if constants.enemy_positions[0] in df.columns:
            pos = df[constants.enemy_positions]
            if self.log:
                pos = exp_vector(pos)
            df[constants.enemy_positions] = pos * self.enemy_mag
        return df


import os
import torch
import string
import argparse

import numpy as np

from pingouin import mwu
from transformers import (BartForConditionalGeneration,
                          BartTokenizer,
                          MBartTokenizer,
                          MBart50TokenizerFast,
                          MBartForConditionalGeneration)

from eval_util import read_jsonl, get_final_index, compute_perplexity, count_distance_in_subwords, make_bar_plot, \
    make_density_plot

MBART_TABLE = {'en': 'en_XX',
               'de': 'de_DE',
               'fr': 'fr_FR',
               'ru': 'ru_RU'}

LANG2PRON = {'de': {'er': 'male', 'sie': 'female', 'es': 'neutral'},
             'fr': {'il': 'male', 'elle': 'female', 'ils': 'male', 'elles': 'female'},
             'ru': {'oн': 'male', 'oнa': 'female', 'oнo': 'neutral'}}

def _score_translation(src_sentence, tgt_sentence):
    """ Computes perplexity of contrastive translations """
    # Score target sequence conditioned on the input
    src = tokenizer(src_sentence, return_tensors='pt')
    with tokenizer.as_target_tokenizer():
        tgt = tokenizer(tgt_sentence, return_tensors='pt').input_ids

    # Do a forward pass
    with torch.no_grad():
        model_out = model(input_ids=src.input_ids.to(device),
                          attention_mask=src.attention_mask.to(device),
                          labels=tgt.to(device))
    # Extract probabilities
    tgt_input_ids = torch.squeeze(tgt).detach().cpu().numpy().tolist()
    model_logits = torch.squeeze(model_out.logits)
    tgt_probs = model_logits.softmax(axis=-1).detach().cpu().numpy().tolist()
    token_probabilities = [tgt_probs[probs_row][tok_id] for probs_row, tok_id in enumerate(tgt_input_ids)]
    return compute_perplexity(token_probabilities)

def evaluate_models(json_file_path, out_dir):
    """ Checks model performance on the challenge data. """

    # Read-in data
    samples = read_jsonl(json_file_path)

    # Compute accuracy and track input features that may be indicative of the model using heuristics
    num_correct, num_incorrect, num_correct_pairs, num_incorrect_pairs = 0, 0, 0, 0

    gender_counts = {'reference_true': {v: 0 for v in PRON2GEN.values()},
                     'reference_false': {v: 0 for v in PRON2GEN.values()},
                     'model_preference': {v: 0 for v in PRON2GEN.values()},
                     'model_rejection': {v: 0 for v in PRON2GEN.values()}}

    ref_gender_counts_per_position = {'first': {v: 0 for v in PRON2GEN.values()},
                                      'second': {v: 0 for v in PRON2GEN.values()}}  # for correct translation only

    position_counts = {'reference_true': {'first': 0, 'second': 0},
                       'reference_false': {'first': 0, 'second': 0},
                       'model_preference': {'first': 0, 'second': 0},
                       'model_rejection': {'first': 0, 'second': 0}}

    token_distance = \
        {'reference_true': dict(), 'reference_false': dict(), 'model_preference': dict(), 'model_rejection': dict()}
    # This is intended to estimate the "influence" of the trigger phrases
    ppl_changes_trigger = {'same_choice': list(), 'both_right': list(), 'both_wrong': list()}
    # This is intended to estimate the "influence" of the target pronoun
    ppl_changes_pronoun = {'correct': list(), 'incorrect': list()}

    contrastive_pair_ppl = list()
    contrastive_pair_successes = list()
    for sample_id, sample in enumerate(samples):

        # Report
        print('Checking sample {:d}'.format(sample_id))
        if (sample_id - 1) > 0 and (sample_id - 1) % 100 == 0:
            print('Processed {:d} samples'.format(sample_id - 1))

        src = sample['sentence']
        tgt1 = sample['translation1']
        tgt2 = sample['translation2']
        tgt1_ppl = _score_translation(src, tgt1)
        tgt2_ppl = _score_translation(src, tgt2)
        score_pair = [tgt1_ppl, tgt2_ppl]
        label_pair = [int(int(sample['answer']) == 1), int(int(sample['answer']) == 2)]

        # Identify filler gender in both translations
        try:
            gen_pair = [PRON2GEN[samples[sample_id]['pronoun1']], PRON2GEN[samples[sample_id]['pronoun2']]]
        except KeyError:
            gen_pair = [None, None]
        true_ref_gen = gen_pair[label_pair.index(max(label_pair))]
        false_ref_gen = gen_pair[label_pair.index(min(label_pair))]

        # Establish the relative position of the correct referent
        sentence_tokens = [tok.strip(string.punctuation) for tok in sample['sentence'].split()]
        if int(sample['answer']) == 1:
            true_referent_is_first = get_final_index(sentence_tokens, sample['referent1_en']) < \
                                     get_final_index(sentence_tokens, sample['referent2_en'])
        else:
            true_referent_is_first = get_final_index(sentence_tokens, sample['referent2_en']) < \
                                     get_final_index(sentence_tokens, sample['referent1_en'])
        if true_referent_is_first:
            position_counts['reference_true']['first'] += 1
            position_counts['reference_false']['second'] += 1
            if true_ref_gen is not None:
                ref_gender_counts_per_position['first'][true_ref_gen] += 1
                ref_gender_counts_per_position['second'][false_ref_gen] += 1
        else:
            position_counts['reference_true']['second'] += 1
            position_counts['reference_false']['first'] += 1
            if true_ref_gen is not None:
                ref_gender_counts_per_position['first'][false_ref_gen] += 1
                ref_gender_counts_per_position['second'][true_ref_gen] += 1

        # Measure sub-word distance
        distance_pair = \
            [count_distance_in_subwords(sample['sentence'], sample['referent1_en'], 'it', None, None, None, tokenizer),
             count_distance_in_subwords(sample['sentence'], sample['referent2_en'], 'it', None, None, None, tokenizer)]

        # Check model preferences
        if score_pair[0] == score_pair[1]:
            num_incorrect += 1
            contrastive_pair_successes.append(0)
        else:
            min_ppl_id = score_pair.index(min(score_pair))
            correct_id = label_pair.index(max(label_pair))

            # Track model accuracy
            if min_ppl_id == correct_id:
                num_correct += 1
                contrastive_pair_successes.append(1)
            else:
                num_incorrect += 1
                contrastive_pair_successes.append(0)

            # Track model perplexity for the preferred translation
            contrastive_pair_ppl.append((min_ppl_id == correct_id, score_pair[min_ppl_id]))

            # Track heuristics
            # Gender
            if true_ref_gen is not None:
                gender_counts['reference_true'][gen_pair[correct_id]] += 1
                gender_counts['reference_false'][gen_pair[abs(1 - correct_id)]] += 1
                gender_counts['model_preference'][gen_pair[min_ppl_id]] += 1
                gender_counts['model_rejection'][gen_pair[abs(1 - min_ppl_id)]] += 1

            # Relative referent position
            if true_referent_is_first:
                pref_key, rej_key = ('first', 'second') if min_ppl_id == correct_id else ('second', 'first')
            else:
                pref_key, rej_key = ('second', 'first') if min_ppl_id == correct_id else ('first', 'second')
            position_counts['model_preference'][pref_key] += 1
            position_counts['model_rejection'][rej_key] += 1

            # Sub-word distance

            # Measure sub-word distance
            for key, tpl_id in [('reference_true', correct_id), ('reference_false', abs(1 - correct_id)),
                                ('model_preference', min_ppl_id), ('model_rejection', abs(1 - min_ppl_id))]:
                if token_distance[key].get(distance_pair[tpl_id], None) is None:
                    token_distance[key][distance_pair[tpl_id]] = 0
                token_distance[key][distance_pair[tpl_id]] += 1

            # Track perplexity changes within the sample
            ppl_diff = abs(score_pair[0] - score_pair[1])
            ppl_key = 'correct' if min_ppl_id == correct_id else 'incorrect'
            ppl_changes_pronoun[ppl_key].append(ppl_diff)

        # Track perplexity changes across samples
        if sample_id % 2 == 1:
            if len(contrastive_pair_ppl) == 2:
                if (contrastive_pair_ppl[0][0] is True) and (contrastive_pair_ppl[1][0] is True):
                    ppl_key = 'both_right'
                elif (contrastive_pair_ppl[0][0] is False) and (contrastive_pair_ppl[1][0] is False):
                    ppl_key = 'both_wrong'
                else:
                    ppl_key = 'same_choice'
                ppl_changes_trigger[ppl_key].append(
                    abs(contrastive_pair_ppl[0][1] - contrastive_pair_ppl[1][1]))
            contrastive_pair_ppl = list()

        # Update pair counts
        if sample_id % 2 == 1:
            if 0 not in contrastive_pair_successes:
                num_correct_pairs += 1
            else:
                num_incorrect_pairs += 1
            contrastive_pair_successes = list()

    # Report
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    sorted_gen = sorted(list(PRON2GEN.values()))
    gen2num = {p: p_id + 1 for p_id, p in enumerate(sorted_gen)}
    print('=' * 20)
    print('# of SAMPLES with lower perplexity assigned to the CORRECT option: {:d}'.format(num_correct))
    print('# of SAMPLES with lower perplexity assigned to the INCORRECT option: {:d}'.format(num_incorrect))
    print('# of PAIRS were resolved correctly: {:d}'.format(num_correct_pairs))
    print('# of PAIRS were resolved incorrectly: {:d}'.format(num_incorrect_pairs))
    print('Accuracy, SAMPLES: {:.4f}'.format(num_correct / (num_correct + num_incorrect)))
    print('Accuracy, PAIRS: {:.4f}'.format(num_correct_pairs / (num_correct_pairs + num_incorrect_pairs)))

    print('=' * 20)
    print('--- MODEL HEURISTICS ---')
    print('Total gender counts for CORRECT referents: male: {:d} | female: {:d} | neutral: {:d}'.format(
        gender_counts['reference_true'].get('male', 0), gender_counts['reference_true'].get('female', 0),
        gender_counts['reference_true'].get('neutral', 0)))
    print('Total gender counts for model-PREFERRED referents: male: {:d} | female: {:d} | neutral: {:d}'.format(
        gender_counts['model_preference'].get('male', 0), gender_counts['model_preference'].get('female', 0),
        gender_counts['model_preference'].get('neutral', 0)))
    print('Total gender counts for INCORRECT referents: male: {:d} | female: {:d} | neutral: {:d}'.format(
        gender_counts['reference_false'].get('male', 0), gender_counts['reference_false'].get('female', 0),
        gender_counts['reference_false'].get('neutral', 0)))
    print('Total gender counts for model-REJECTED referents: male: {:d} | female: {:d} | neutral: {:d}'.format(
        gender_counts['model_rejection'].get('male', 0), gender_counts['model_rejection'].get('female', 0),
        gender_counts['model_rejection'].get('neutral', 0)))
    # Compare correlation
    print('-' * 5)
    print('Gender correlations for references (MWU):')
    x, y = list(), list()
    for cat, var in [('reference_true', x), ('reference_false', y)]:
        for key in gender_counts[cat].keys():
            var += [gen2num[key]] * gender_counts[cat][key]
    print(mwu(x, y, tail='two-sided'))
    print('Gender correlations for model choices (MWU):')
    x, y = list(), list()
    for cat, var in [('model_preference', x), ('model_rejection', y)]:
        for key in gender_counts[cat].keys():
            var += [gen2num[key]] * gender_counts[cat][key]
    print(mwu(x, y, tail='two-sided'))
    # Plot
    make_bar_plot(gender_counts, 'target pronoun gender', 'frequency', sorted_gen, out_dir, 'gender_counts')

    print('-' * 10)
    print('Referent position for CORRECT referents: first {:d} | second {:d}'.format(
        position_counts['reference_true']['first'], position_counts['reference_true']['second']))
    print('Referent position for model-PREFERRED references: first {:d} | second {:d}'.format(
        position_counts['model_preference']['first'], position_counts['model_preference']['second']))
    print('Referent position for INCORRECT referents: first {:d} | second {:d}'.format(
        position_counts['reference_false']['first'], position_counts['reference_false']['second']))
    print('Referent position for model-REJECTED references: first {:d} | second {:d}'.format(
        position_counts['model_rejection']['first'], position_counts['model_rejection']['second']))
    print('   Referent gender per referent position:')
    for loc in ref_gender_counts_per_position.keys():
        print('   {:s}:'.format(loc))
        for gen in ref_gender_counts_per_position[loc].keys():
            print('      {:s} : {:d}'.format(gen, ref_gender_counts_per_position[loc][gen]))
    # Compare correlation
    print('-' * 5)
    print('Position correlations for references (MWU):')
    x, y = list(), list()
    for cat, var in [('reference_true', x), ('reference_false', y)]:
        for key in position_counts[cat].keys():
            var += [int(key == 'first') + 1] * position_counts[cat][key]
    print(mwu(x, y, tail='two-sided'))
    print('Position correlations for model choices (MWU):')
    x, y = list(), list()
    for cat, var in [('model_preference', x), ('model_rejection', y)]:
        for key in position_counts[cat].keys():
            var += [int(key == 'first') + 1] * position_counts[cat][key]
    print(mwu(x, y, tail='two-sided'))
    # Plot
    make_bar_plot(
        position_counts, 'relative referent position', 'frequency', ['first', 'second'], out_dir, 'position_counts')

    print('-' * 10)
    print('# of sub-words between the pronoun and its referent for the CORRECT source interpretation:')
    flattened_list = list()
    for key in token_distance['reference_true'].keys():
        flattened_list += [key] * token_distance['reference_true'][key]
    print('mean: {:.4f} | std: {:.4f}'.format(np.mean([flattened_list]), np.std(flattened_list)))
    print('-' * 5)
    print('# of sub-words between the pronoun and its referent for the interpretation PREFERRED by the model:')
    flattened_list = list()
    for key in token_distance['model_preference'].keys():
        flattened_list += [key] * token_distance['model_preference'][key]
    print('mean: {:.4f} | std: {:.4f}'.format(np.mean([flattened_list]), np.std(flattened_list)))
    print('-' * 5)
    print('# of sub-words between the pronoun and its referent for the INCORRECT source interpretation:')
    flattened_list = list()
    for key in token_distance['reference_false'].keys():
        flattened_list += [key] * token_distance['reference_false'][key]
    print('mean: {:.4f} | std: {:.4f}'.format(np.mean([flattened_list]), np.std(flattened_list)))
    print('-' * 5)
    print('# of sub-words between the pronoun and its referent for the interpretation REJECTED by the model:')
    flattened_list = list()
    for key in token_distance['model_rejection'].keys():
        flattened_list += [key] * token_distance['model_rejection'][key]
    print('mean: {:.4f} | std: {:.4f}'.format(np.mean([flattened_list]), np.std(flattened_list)))
    # Compare correlation
    print('-' * 5)
    print('Distance correlations for references (MWU):')
    x, y = list(), list()
    for cat, var in [('reference_true', x), ('reference_false', y)]:
        for key in token_distance[cat].keys():
            var += [key] * token_distance[cat][key]
    print(mwu(x, y, tail='two-sided'))
    print('Distance correlations for model choices (MWU):')
    x, y = list(), list()
    for cat, var in [('model_preference', x), ('model_rejection', y)]:
        for key in token_distance[cat].keys():
            var += [key] * token_distance[cat][key]
    print(mwu(x, y, tail='two-sided'))
    # Plot
    token_distance_plot = {'reference_true': token_distance['reference_true'],
                           'model_preference': token_distance['model_preference']}
    make_density_plot(token_distance_plot, ['category', '# sub-words'], out_dir, 'token_distance')

    # ACROSS both samples in each PAIR
    print('-' * 10)
    print('Perplexity difference when triggers are ignored (count, mean, std): {:d} | {:.4f} | {:.4f}'.format(
        len(ppl_changes_trigger['same_choice']), np.mean(ppl_changes_trigger['same_choice']),
        np.std(ppl_changes_trigger['same_choice'])))
    print('Perplexity difference when both predictions are correct (count, mean, std): {:d} | {:.4f} | {:.4f}'.format(
        len(ppl_changes_trigger['both_right']),
        np.mean(ppl_changes_trigger['both_right']), np.std(ppl_changes_trigger['both_right'])))
    print('Perplexity difference when both predictions are incorrect (count, mean, std): {:d} | {:.4f} | {:.4f}'.format(
        len(ppl_changes_trigger['both_wrong']), np.mean(ppl_changes_trigger['both_wrong']),
        np.std(ppl_changes_trigger['both_wrong'])))
    # Compare correlations
    print('MWU: same_choice - both_right')
    print(mwu(ppl_changes_trigger['same_choice'], ppl_changes_trigger['both_right'], tail='two-sided'))
    print('MWU: same_choice - both_wrong')
    print(mwu(ppl_changes_trigger['same_choice'], ppl_changes_trigger['both_wrong'], tail='two-sided'))
    print('MWU: both_right - both_wrong')
    print(mwu(ppl_changes_trigger['both_right'], ppl_changes_trigger['both_wrong'], tail='two-sided'))
    # Plot
    make_density_plot(ppl_changes_trigger, ['category', 'PPl difference'], out_dir, 'ppl_difference_trigger')

    # WITHIN each SAMPLE
    print('-' * 10)
    print('Perplexity difference for correct translation choice (count, mean, std): {:d} | {:.4f} | {:.4f}'.format(
        len(ppl_changes_pronoun['correct']), np.mean(ppl_changes_pronoun['correct']),
        np.std(ppl_changes_pronoun['correct'])))
    print('Perplexity difference for incorrect translation choice (count, mean, std): {:d} | {:.4f} | {:.4f}'.format(
        len(ppl_changes_pronoun['incorrect']), np.mean(ppl_changes_pronoun['incorrect']),
        np.std(ppl_changes_pronoun['incorrect'])))
    # Compare correlations
    print('MWU: correct - incorrect')
    print(mwu(ppl_changes_pronoun['correct'], ppl_changes_pronoun['incorrect'], tail='two-sided'))
    # Plot
    make_density_plot(ppl_changes_pronoun, ['category', 'PPl difference'], out_dir, 'ppl_difference_pronoun')

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--json_file_path', type=str, required=True,
                        help='path to the JSON file containing the contrastive samples')
    parser.add_argument('--checkpoint_dir', type=str, default=None,
                        help='path to the directory containing checkpoint files of the evaluated model')
    parser.add_argument('--out_dir', type=str, required=True,
                        help='path to the output directory')
    parser.add_argument('--model_type', type=str, choices=['bart', 'mbart50'],
                        help='Model type to evaluate')
    parser.add_argument('--use_multi', action='store_true',
                        help='Whether to use a multilingual language model; if disabled, uses a monolingual target '
                             'language model')
    parser.add_argument('--use_cpu', action='store_true', help='Whether to use the CPU')
    parser.add_argument('--tgt_lang', type=str, choices=['de', 'fr', 'ru'],
                        help='Target language of the challenge set; ONLY AFFECTS THE ANSWERS, as the context and '
                             'question are always presented in English')
    args = parser.parse_args()

    # Select relevant pronouns
    PRON2GEN = LANG2PRON[args.tgt_lang]

    # Assign checkpoints (change model size by changing checkpoint names)
    if args.model_type == 'bart':
        if args.use_multi:
            model_type = MBartForConditionalGeneration
            tokenizer_type = MBartTokenizer
        else:
            assert args.tgt_lang == 'en', 'Configuration not supported!'
            model_type = BartForConditionalGeneration
            tokenizer_type = BartTokenizer
    else:
        # mBART-50
        model_type = MBartForConditionalGeneration
        tokenizer_type = MBart50TokenizerFast

    # Load models and tokenizers
    if args.model_type != 'mbart50':
        assert args.checkpoint_dir is not None, 'Model checkpoint must be specified for models other than MBART50'
        tokenizer = tokenizer_type.from_pretrained(args.checkpoint_dir)
        model = model_type.from_pretrained(args.checkpoint_dir)
    else:
        model = model_type.from_pretrained('facebook/mbart-large-50-one-to-many-mmt')
        tokenizer = tokenizer_type.from_pretrained('facebook/mbart-large-50-one-to-many-mmt',
                                                   src_lang=MBART_TABLE['en'], tgt_lang=MBART_TABLE[args.tgt_lang])

    device = 'cpu' if args.use_cpu else 'cuda:0'
    model.to(device)

    evaluate_models(args.json_file_path, args.out_dir)


from durable.lang import *
import datetime
import random
import sys

with statechart('fraud0'):
    with state('start'):
        to('standby')

    with state('standby'):
        @to('metering')
        @when_all(m.amount > 100)
        def start_metering(c):
            c.start_timer('velocity', 30)

    with state('metering'):
        @to('fraud')
        @when_all(m.amount > 100, count(2))
        def report_fraud(c):
            print('fraud0 detected')

        @to('standby')
        @when_all(timeout('velocity'))
        def clear_fraud(c):
            print('fraud0 cleared')

    state('fraud')

    @when_start
    def start(host):
        host.post('fraud0', {'id': 1, 'sid': 1, 'amount': 200})
        host.post('fraud0', {'id': 2, 'sid': 1, 'amount': 200})
        host.post('fraud0', {'id': 3, 'sid': 1, 'amount': 200})

with ruleset('fraud1'):
    @when_all(c.first << m.t == 'purchase',
              c.second << m.location != c.first.location)
    def detected(c):
        print ('fraud1 detected {0}, {1}'.format(c.first.location, c.second.location))

    @when_start
    def start(host):
        host.post('fraud1', {'id': 1, 'sid': 1, 't': 'purchase', 'location': 'US'})
        host.post('fraud1', {'id': 2, 'sid': 1, 't': 'purchase', 'location': 'CA'})

with ruleset('fraud2'):
    @when_all(c.first << m.amount > 10,
              c.second << m.amount > c.first.amount * 2)
    def detected(c):
        print('fraud2 detected {0}, {1}'.format(c.first.amount, c.second.amount))

    @when_start
    def start(host):
        host.post('fraud2', {'id': 1, 'sid': 1, 'amount': 50})
        host.post('fraud2', {'id': 2, 'sid': 1, 'amount': 150})

with ruleset('fraud3'):
    @when_all(c.first << m.amount > 100,
              c.second << m.amount > c.first.amount,
              c.third << m.amount > c.second.amount,
              c.fourth << m.amount > (c.first.amount + c.second.amount + c.third.amount) / 3)
    def detected(c):
        print('fraud3 detected -> {0}'.format(c.first.amount))
        print('                -> {0}'.format(c.second.amount))
        print('                -> {0}'.format(c.third.amount))
        print('                -> {0}'.format(c.fourth.amount))

    @when_start
    def start(host):
        host.post('fraud3', {'id': 1, 'sid': 1, 'amount': 101})
        host.post('fraud3', {'id': 2, 'sid': 1, 'amount': 102})
        host.post('fraud3', {'id': 3, 'sid': 1, 'amount': 103})
        host.post('fraud3', {'id': 4, 'sid': 1, 'amount': 104})

with ruleset('fraud4'):
    @when_all(pri(3), m.amount < 300)
    def first_detect(c):
        print('fraud4 first detect {0}'.format(c.m.amount))

    @when_all(pri(2), m.amount < 200)
    def second_detect(c):
        print('fraud4 second detect {0}'.format(c.m.amount))

    @when_all(pri(1), m.amount < 100)
    def third_detect(c):
        print('fraud4 third detect {0}'.format(c.m.amount))

    @when_start
    def start(host):
        host.post('fraud4', {'id': 1, 'sid': 1, 'amount': 50})
        host.post('fraud4', {'id': 2, 'sid': 1, 'amount': 150})
        host.post('fraud4', {'id': 3, 'sid': 1, 'amount': 250})

with ruleset('fraud5'):
    @when_all(c.first << m.t == 'purchase',
              c.second << m.location != c.first.location,
              count(2))
    def detected(c):
        print ('fraud5 detected {0}, {1}'.format(c.m[0].first.location, c.m[0].second.location))
        print ('               {0}, {1}'.format(c.m[1].first.location, c.m[1].second.location))

    @when_start
    def start(host):
        host.assert_fact('fraud5', {'id': 1, 'sid': 1, 't': 'purchase', 'location': 'US'})
        host.assert_fact('fraud5', {'id': 2, 'sid': 1, 't': 'purchase', 'location': 'CA'})

with ruleset('fraud6'):
    @when_all(pri(3), count(3), m.amount < 300)
    def first_detect(c):
        print('fraud6 first detect ->{0}'.format(c.m[0].amount))
        print('                    ->{0}'.format(c.m[1].amount))
        print('                    ->{0}'.format(c.m[2].amount))

    @when_all(pri(2), count(2), m.amount < 200)
    def second_detect(c):
        print('fraud6 second detect ->{0}'.format(c.m[0].amount))
        print('                     ->{0}'.format(c.m[1].amount))

    @when_all(pri(1), m.amount < 100)
    def third_detect(c):
        print('fraud6 third detect ->{0}'.format(c.m.amount))

    @when_start
    def start(host):
        host.assert_fact('fraud6', {'id': 1, 'sid': 1, 'amount': 50})
        host.assert_fact('fraud6', {'id': 2, 'sid': 1, 'amount': 150})
        host.assert_fact('fraud6', {'id': 3, 'sid': 1, 'amount': 250})

with ruleset('fraud7'):
    @when_all(c.first << m.t == 'deposit',
              none(m.t == 'balance'),
              c.third << m.t == 'withrawal',
              c.fourth << m.t == 'chargeback')
    def detected(c):
        print('fraud7 detected {0}, {1}, {2}'.format(c.first.t, c.third.t, c.fourth.t))

    @when_start
    def start(host):
        host.post('fraud7', {'id': 1, 'sid': 1, 't': 'deposit'})
        host.post('fraud7', {'id': 2, 'sid': 1, 't': 'withrawal'})
        host.post('fraud7', {'id': 3, 'sid': 1, 't': 'chargeback'})
        host.assert_fact('fraud7', {'id': 4, 'sid': 1, 't': 'balance'})
        host.post('fraud7', {'id': 5, 'sid': 1, 't': 'deposit'})
        host.post('fraud7', {'id': 6, 'sid': 1, 't': 'withrawal'})
        host.post('fraud7', {'id': 7, 'sid': 1, 't': 'chargeback'})
        host.retract_fact('fraud7', {'id': 4, 'sid': 1, 't': 'balance'})

with ruleset('a0'):
    @when_all((m.subject == 'go') | (m.subject == 'approve') | (m.subject == 'ok'))
    def approved(c):
        print ('a0 approved ->{0}'.format(c.m.subject))

    @when_start
    def start(host):
        host.post('a0', {'id': 1, 'sid': 1, 'subject': 'approve'})
        host.post('a0', {'id': 2, 'sid': 2, 'subject': 'go'})
        host.post('a0', {'id': 3, 'sid': 3, 'subject': 'ok'})

with ruleset('a1'):
    @when_all((m.subject == 'approve') & (m.amount > 1000))
    def denied(c):
        print ('a1 denied from: {0}'.format(c.s.sid))
        c.s.status = 'done'

    @when_all((m.subject == 'approve') & (m.amount <= 1000))
    def request(c):
        print ('a1 request approval from: {0}'.format(c.s.sid))
        c.s.status = 'pending'

    @when_all(m.subject == 'approved', s.status == 'pending')
    def second_request(c):
        print ('a1 second request approval from: {0}'.format(c.s.sid))
        c.s.status = 'approved'

    @when_all(s.status == 'approved')
    def approved(c):
        print ('a1 approved from: {0}'.format(c.s.sid))
        c.s.status = 'done'

    @when_all(m.subject == 'denied')
    def denied(c):
        print ('a1 denied from: {0}'.format(c.s.sid))
        c.s.status = 'done'

    @when_start
    def start(host):
        host.post('a1', {'id': 1, 'sid': 1, 'subject': 'approve', 'amount': 100})
        host.post('a1', {'id': 2, 'sid': 1, 'subject': 'approved'})
        host.post('a1', {'id': 3, 'sid': 2, 'subject': 'approve', 'amount': 100})
        host.post('a1', {'id': 4, 'sid': 2, 'subject': 'denied'})
        host.post('a1', {'id': 5, 'sid': 3, 'subject': 'approve', 'amount': 10000})

with statechart('a2'):
    with state('input'):
        @to('denied')
        @when_all((m.subject == 'approve') & (m.amount > 1000))
        def denied(c):
            print ('a2 denied from: {0}'.format(c.s.sid))

        @to('pending')
        @when_all((m.subject == 'approve') & (m.amount <= 1000))
        def request(c):
            print ('a2 request approval from: {0}'.format(c.s.sid))

    with state('pending'):
        @to('pending')
        @when_all(m.subject == 'approved')
        def second_request(c):
            print ('a2 second request approval from: {0}'.format(c.s.sid))
            c.s.status = 'approved'

        @to('approved')
        @when_all(s.status == 'approved')
        def approved(c):
            print ('a2 approved from: {0}'.format(c.s.sid))

        @to('denied')
        @when_all(m.subject == 'denied')
        def denied(c):
            print ('a2 denied from: {0}'.format(c.s.sid))

    state('denied')
    state('approved')
    @when_start
    def start(host):
        host.post('a2', {'id': 1, 'sid': 1, 'subject': 'approve', 'amount': 100})
        host.post('a2', {'id': 2, 'sid': 1, 'subject': 'approved'})
        host.post('a2', {'id': 3, 'sid': 2, 'subject': 'approve', 'amount': 100})
        host.post('a2', {'id': 4, 'sid': 2, 'subject': 'denied'})
        host.post('a2', {'id': 5, 'sid': 3, 'subject': 'approve', 'amount': 10000})

with flowchart('a3'):
    with stage('input'):
        to('request').when_all((m.subject == 'approve') & (m.amount <= 1000))
        to('deny').when_all((m.subject == 'approve') & (m.amount > 1000))

    with stage('request'):
        @run
        def request(c):
            print ('a3 request approval from: {0}'.format(c.s.sid))
            if c.s.status:
                c.s.status = 'approved'
            else:
                c.s.status = 'pending'

        to('approve').when_all(s.status == 'approved')
        to('deny').when_all(m.subject == 'denied')
        to('request').when_all(m.subject == 'approved')

    with stage('approve'):
        @run
        def approved(c):
            print ('a3 approved from: {0}'.format(c.s.sid))

    with stage('deny'):
        @run
        def denied(c):
            print ('a3 denied from: {0}'.format(c.s.sid))

    @when_start
    def start(host):
        host.post('a3', {'id': 1, 'sid': 1, 'subject': 'approve', 'amount': 100})
        host.post('a3', {'id': 2, 'sid': 1, 'subject': 'approved'})
        host.post('a3', {'id': 3, 'sid': 2, 'subject': 'approve', 'amount': 100})
        host.post('a3', {'id': 4, 'sid': 2, 'subject': 'denied'})
        host.post('a3', {'id': 5, 'sid': 3, 'subject': 'approve', 'amount': 10000})

with ruleset('a4'):
    @when_any(all(m.subject == 'approve', m.amount == 1000),
              all(m.subject == 'jumbo', m.amount == 10000))
    def action(c):
        print ('a4 action {0}'.format(c.s.sid))

    @when_start
    def start(host):
        host.post('a4', {'id': 1, 'sid': 1, 'subject': 'approve'})
        host.post('a4', {'id': 2, 'sid': 1, 'amount': 1000})
        host.post('a4', {'id': 3, 'sid': 2, 'subject': 'jumbo'})
        host.post('a4', {'id': 4, 'sid': 2, 'amount': 10000})

with ruleset('a5'):
    @when_all(any(m.subject == 'approve', m.subject == 'jumbo'),
              any(m.amount == 100, m.amount == 10000))
    def action(c):
        print ('a5 action {0}'.format(c.s.sid))

    @when_start
    def start(host):
        host.post('a5', {'id': 1, 'sid': 1, 'subject': 'approve'})
        host.post('a5', {'id': 2, 'sid': 1, 'amount': 100})
        host.post('a5', {'id': 3, 'sid': 2, 'subject': 'jumbo'})
        host.post('a5', {'id': 4, 'sid': 2, 'amount': 10000})

with statechart('a6'):
    with state('work'):
        with state('enter'):
            @to('process')
            @when_all(m.subject == 'enter')
            def continue_process(c):
                print('a6 continue_process')

        with state('process'):
            @to('process')
            @when_all(m.subject == 'continue')
            def continue_process(c):
                print('a6 processing')

        @to('work')
        @when_all(m.subject == 'reset')
        def reset(c):
            print('a6 resetting')

        @to('canceled')
        @when_all(m.subject == 'cancel')
        def cancel(c):
            print('a6 canceling')

    state('canceled')
    @when_start
    def start(host):
        host.post('a6', {'id': 1, 'sid': 1, 'subject': 'enter'})
        host.post('a6', {'id': 2, 'sid': 1, 'subject': 'continue'})
        host.post('a6', {'id': 3, 'sid': 1, 'subject': 'continue'})

with ruleset('a7'):
    @when_all(m.amount < c.s.max_amount)
    def approved(c):
        print ('a7 approved {0}'.format(c.m.amount))

    @when_start
    def start(host):
        host.patch_state('a7', {'sid': 1, 'max_amount': 100})
        host.post('a7', {'id': 1, 'sid': 1, 'amount': 10})
        host.post('a7', {'id': 2, 'sid': 1, 'amount': 100})

with ruleset('a8'):
    @when_all((m.amount < c.s.max_amount) & (m.amount > c.s.id('global').min_amount))
    def approved(c):
        print ('a8 approved {0}'.format(c.m.amount))

    @when_start
    def start(host):
        host.patch_state('a8', {'sid': 1, 'max_amount': 500})
        host.patch_state('a8', {'sid': 'global', 'min_amount': 300})
        host.post('a8', {'id': 1, 'sid': 1, 'amount': 400})
        host.post('a8', {'id': 2, 'sid': 1, 'amount': 1600})

with ruleset('a9'):
    @when_all(m.amount < c.s.max_amount * 2)
    def approved(c):
        print ('a9 approved {0}'.format(c.m.amount))

    @when_start
    def start(host):
        host.patch_state('a9', {'sid': 1, 'max_amount': 100})
        host.post('a9', {'id': 1, 'sid': 1, 'amount': 100})
        host.post('a9', {'id': 2, 'sid': 1, 'amount': 300})

with ruleset('a10'):
    @when_all(m.amount < c.s.max_amount + c.s.id('global').max_amount)
    def approved(c):
        print ('a10 approved {0}'.format(c.m.amount))

    @when_start
    def start(host):
        host.patch_state('a10', {'sid': 1, 'max_amount': 500})
        host.patch_state('a10', {'sid': 'global', 'max_amount': 300})
        host.post('a10', {'id': 1, 'sid': 1, 'amount': 400})
        host.post('a10', {'id': 2, 'sid': 1, 'amount': 900})

with ruleset('a11'):
    @when_all((m.subject == 'approve') & (m.amount == 100), count(3))
    def approved(c):
        print ('a11 approved ->{0}'.format(c.m[0].amount))
        print ('             ->{0}'.format(c.m[1].amount))
        print ('             ->{0}'.format(c.m[2].amount))

    @when_start
    def start(host):
        host.post_batch('a11', [{'id': 1, 'sid': 1, 'subject': 'approve', 'amount': 100},
                               {'id': 2, 'sid': 1, 'subject': 'approve', 'amount': 100},
                               {'id': 3, 'sid': 1, 'subject': 'approve', 'amount': 100},
                               {'id': 4, 'sid': 1, 'subject': 'approve', 'amount': 100},
                               {'id': 5, 'sid': 1, 'subject': 'approve', 'amount': 100},
                               {'id': 6, 'sid': 1, 'subject': 'approve', 'amount': 100}])

with ruleset('a12'):
    @when_any(m.subject == 'approve', m.subject == 'approved', count(2))
    def approved(c):
        print ('a12 approved ->{0}'.format(c.m[0].m_0.subject))
        print ('             ->{0}'.format(c.m[1].m_0.subject))

    @when_start
    def start(host):
        host.post_batch('a12', [{'id': 1, 'sid': 1, 'subject': 'approve'},
                                {'id': 2, 'sid': 1, 'subject': 'approve'},
                                {'id': 3, 'sid': 1, 'subject': 'approve'},
                                {'id': 4, 'sid': 1, 'subject': 'approve'}])

with ruleset('t0'):
    @when_all(timeout('my_timer') | (s.count == 0))
    def start_timer(c):
        c.s.count += 1
        c.post('t0', {'id': c.s.count, 'sid': 1, 't': 'purchase'})
        c.start_timer('my_timer', random.randint(1, 3))

    @when_all(span(5), m.t == 'purchase')
    def pulse(c):
        print('t0 pulse -> {0}'.format(len(c.m)))

    @when_start
    def start(host):
        host.patch_state('t0', {'sid': 1, 'count': 0})

with ruleset('t1'):
    @when_all(m.start == 'yes')
    def start_timer(c):
        c.s.start = datetime.datetime.now().strftime('%I:%M:%S%p')
        c.start_timer('my_timer', 5)

    @when_all(timeout('my_timer'))
    def end_timer(c):
        print('t1 started @%s' % c.s.start)
        print('t1 ended @%s' % datetime.datetime.now().strftime('%I:%M:%S%p'))

    @when_start
    def start(host):
        host.post('t1', {'id': 1, 'sid': 1, 'start': 'yes'})

run_all()


#!/home/saeed/Programs/miniconda3/bin/python

import obspy as obs

"""

# Extract station information from dlsv files.

"""
inv = input("\n\n+++ Enter dataless file name:\n")
inv = obs.read_inventory(inv)

stations = []

with open('dataless.dat', 'w') as f:

    for net in inv:

        for station in net:

            if station.code not in stations:

                stations.append(station.code)

                f.write('%2s %4s %7.3f %7.3f %5d\n'%(net.code, station.code,
                        station.longitude, station.latitude, station.elevation))


from __future__ import division, print_function, absolute_import
# noinspection PyUnresolvedReferences
from six.moves import range

from scipy.stats import rv_discrete
import numpy as np

__all__ = ['nonuniform', 'gibbs']

# noinspection PyMethodOverriding,PyPep8Naming
class nonuniform_gen(rv_discrete):
    """A nonuniform discrete random variable.

    %(before_notes)s

    %(example)s

    .. note::
        Adapted from Matlab:

        | Project: `Probabilistic Modeling Toolkit for Matlab/Octave <https://github.com/probml/pmtk3>`_.
        | Copyright (2010) Kevin Murphy and Matt Dunham
        | License: `MIT <https://github.com/probml/pmtk3/blob/5fefd068a2e84ae508684d3e4750bd72a4164ba0/license.txt>`_

    """
    def _argcheck(self, a):
        self.a = a
        return abs(a.sum() - 1) <= np.finfo(np.float16).eps

    def _pmf(self, x, a):
        # port discreteLogprob
        raise NotImplementedError

    def _ppf(self, q, a):
        raise NotImplementedError

    def _stats(self, a):
        raise NotImplementedError

    # noinspection PyArgumentList
    def _rvs(self, a):
        r = np.random.rand()
        if self._size is not None:
            r = np.random.rand(self._size)
        s = np.zeros(self._size, dtype=np.int32)

        cum_prob = np.cumsum(a.ravel())

        if self._size is None:
            cum_prob2 = cum_prob[0:-1]
            s = np.sum(r > cum_prob2)
        else:
            n = a.size
            if n < self._size:
                for i in range(n - 1):
                    s += r > cum_prob[i]
            else:
                cum_prob2 = cum_prob[0:-1]
                for i in range(self._size):
                    # noinspection PyTypeChecker
                    s[i] = np.sum(r[i] > cum_prob2)

        return s

nonuniform = nonuniform_gen(name='nonuniform', longname='A discrete non-uniform '
                            '(random integer)')

# noinspection PyMethodOverriding,PyPep8Naming
class gibbs_gen(rv_discrete):
    """A Gibbs distributed discrete random variable.

    %(before_notes)s

    Notes
    -----
    The probability mass function for `gibbs` is::

                        exp(a/t)
        gibbs.pmf(x) = ------------
                       sum(exp(a/t)

    %(example)s

    """
    def _argcheck(self, t):
        """Default check for correct values on args and keywords.

        Returns condition array of 1's where arguments are correct
        and 0's where they are not.

        """
        return t >= 0

    def _nonzero(self, k, t):
        return k == k

    def _pmf(self, a, t):
        values = np.exp(a / t)

        # noinspection PyTypeChecker
        if np.any(t <= np.finfo(np.float16).eps):
            max_value = max(a)
            values = np.asarray([val if val == max_value else 0. for val in a])
        return values / np.sum(values)

    def _ppf(self, a, t):
        raise NotImplementedError

    def _stats(self, t):
        raise NotImplementedError

gibbs = gibbs_gen(name='gibbs', longname='Gibbs distribution '
                  '(random integer)')


#!/usr/bin/env python

import argparse
import subprocess
import sys
import yaml

def parse_args(args):
    description = """\
Partial implementation of "helmfile sync" in Python. This will run the
same Helm commands that "helmfile sync" would run. Use --dry-run to
print the list of commands.

helmfile selectors (allows selective partial deployment) are not
implemented, nor are any other commands or arguments. Use the proper
Helmfile if you require that
"""
    p = argparse.ArgumentParser(description=description)
    p.add_argument('-f', '--file', default='helmfile.yaml', help='Helmfile')
    p.add_argument('--dry-run', action='store_true', help='Dry run')
    return p.parse_args(args)

def load_config(helmfile):
    with open(helmfile) as f:
        y = list(yaml.load_all(f))
    if len(y) != 1:
        raise ValueError('Expected one YAML document, found %d' % len(y))
    y = y[0]
    if 'releases' not in y:
        raise ValueError('Expected releases in helmfile')
    return y

def get_helm_command(r):
    command = [
        'helm',
        'upgrade',
        '--install',
        r['name'],
        r['chart'],
    ]
    if 'version' in r:
        command.extend(['--version', r['version']])
    if 'namespace' in r:
        command.extend(['--namespace', r['namespace']])
    for v in r['values']:
        command.extend(['--values', v])
    return command

def main(args):
    cfg = load_config(args.file)
    commands = [get_helm_command(r) for r in cfg['releases']]
    for c in commands:
        print(' '.join(c))
        if not args.dry_run:
            subprocess.check_call(c)

if __name__ == '__main__':
    args = parse_args(sys.argv[1:])
    main(args)


import pytest
import numpy as np
import numpy.testing as npt
import scipy.stats as st
from scipy.special import expit
from scipy import linalg
import numpy.random as nr
import theano

import pymc3 as pm
from pymc3.distributions.distribution import (draw_values,
                                              _DrawValuesContext,
                                              _DrawValuesContextBlocker)
from .helpers import SeededTest
from .test_distributions import (
    build_model, Domain, product, R, Rplus, Rplusbig, Runif, Rplusdunif,
    Unit, Nat, NatSmall, I, Simplex, Vector, PdMatrix,
    PdMatrixChol, PdMatrixCholUpper, RealMatrix, RandomPdMatrix
)

def pymc3_random(dist, paramdomains, ref_rand, valuedomain=Domain([0]),
                 size=10000, alpha=0.05, fails=10, extra_args=None,
                 model_args=None):
    if model_args is None:
        model_args = {}
    model = build_model(dist, valuedomain, paramdomains, extra_args)
    domains = paramdomains.copy()
    for pt in product(domains, n_samples=100):
        pt = pm.Point(pt, model=model)
        pt.update(model_args)
        p = alpha
        # Allow KS test to fail (i.e., the samples be different)
        # a certain number of times. Crude, but necessary.
        f = fails
        while p <= alpha and f > 0:
            s0 = model.named_vars['value'].random(size=size, point=pt)
            s1 = ref_rand(size=size, **pt)
            _, p = st.ks_2samp(np.atleast_1d(s0).flatten(),
                               np.atleast_1d(s1).flatten())
            f -= 1
        assert p > alpha, str(pt)

def pymc3_random_discrete(dist, paramdomains,
                          valuedomain=Domain([0]), ref_rand=None,
                          size=100000, alpha=0.05, fails=20):
    model = build_model(dist, valuedomain, paramdomains)
    domains = paramdomains.copy()
    for pt in product(domains, n_samples=100):
        pt = pm.Point(pt, model=model)
        p = alpha
        # Allow Chisq test to fail (i.e., the samples be different)
        # a certain number of times.
        f = fails
        while p <= alpha and f > 0:
            o = model.named_vars['value'].random(size=size, point=pt)
            e = ref_rand(size=size, **pt)
            o = np.atleast_1d(o).flatten()
            e = np.atleast_1d(e).flatten()
            observed = dict(zip(*np.unique(o, return_counts=True)))
            expected = dict(zip(*np.unique(e, return_counts=True)))
            for e in expected.keys():
                expected[e] = (observed.get(e, 0), expected[e])
            k = np.array([v for v in expected.values()])
            if np.all(k[:, 0] == k[:, 1]):
                p = 1.
            else:
                _, p = st.chisquare(k[:, 0], k[:, 1])
            f -= 1
        assert p > alpha, str(pt)

class TestDrawValues(SeededTest):
    def test_draw_scalar_parameters(self):
        with pm.Model():
            y = pm.Normal('y1', mu=0., sigma=1.)
            mu, tau = draw_values([y.distribution.mu, y.distribution.tau])
        npt.assert_almost_equal(mu, 0)
        npt.assert_almost_equal(tau, 1)

    def test_draw_dependencies(self):
        with pm.Model():
            x = pm.Normal('x', mu=0., sigma=1.)
            exp_x = pm.Deterministic('exp_x', pm.math.exp(x))

        x, exp_x = draw_values([x, exp_x])
        npt.assert_almost_equal(np.exp(x), exp_x)

    def test_draw_order(self):
        with pm.Model():
            x = pm.Normal('x', mu=0., sigma=1.)
            exp_x = pm.Deterministic('exp_x', pm.math.exp(x))

        # Need to draw x before drawing log_x
        exp_x, x = draw_values([exp_x, x])
        npt.assert_almost_equal(np.exp(x), exp_x)

    def test_draw_point_replacement(self):
        with pm.Model():
            mu = pm.Normal('mu', mu=0., tau=1e-3)
            sigma = pm.Gamma('sigma', alpha=1., beta=1., transform=None)
            y = pm.Normal('y', mu=mu, sigma=sigma)
            mu2, tau2 = draw_values([y.distribution.mu, y.distribution.tau],
                                                     point={'mu': 5., 'sigma': 2.})
        npt.assert_almost_equal(mu2, 5)
        npt.assert_almost_equal(tau2, 1 / 2.**2)

    def test_random_sample_returns_nd_array(self):
        with pm.Model():
            mu = pm.Normal('mu', mu=0., tau=1e-3)
            sigma = pm.Gamma('sigma', alpha=1., beta=1., transform=None)
            y = pm.Normal('y', mu=mu, sigma=sigma)
            mu, tau = draw_values([y.distribution.mu, y.distribution.tau])
        assert isinstance(mu, np.ndarray)
        assert isinstance(tau, np.ndarray)

class TestDrawValuesContext:
    def test_normal_context(self):
        with _DrawValuesContext() as context0:
            assert context0.parent is None
            context0.drawn_vars['root_test'] = 1
            with _DrawValuesContext() as context1:
                assert id(context1.drawn_vars) == id(context0.drawn_vars)
                assert context1.parent == context0
                with _DrawValuesContext() as context2:
                    assert id(context2.drawn_vars) == id(context0.drawn_vars)
                    assert context2.parent == context1
                    context2.drawn_vars['leaf_test'] = 2
                assert context1.drawn_vars['leaf_test'] == 2
                context1.drawn_vars['root_test'] = 3
            assert context0.drawn_vars['root_test'] == 3
            assert context0.drawn_vars['leaf_test'] == 2

    def test_blocking_context(self):
        with _DrawValuesContext() as context0:
            assert context0.parent is None
            context0.drawn_vars['root_test'] = 1
            with _DrawValuesContext() as context1:
                assert id(context1.drawn_vars) == id(context0.drawn_vars)
                assert context1.parent == context0
                with _DrawValuesContextBlocker() as blocker:
                    assert id(blocker.drawn_vars) != id(context0.drawn_vars)
                    assert blocker.parent is None
                    blocker.drawn_vars['root_test'] = 2
                    with _DrawValuesContext() as context2:
                        assert id(context2.drawn_vars) == id(blocker.drawn_vars)
                        assert context2.parent == blocker
                        context2.drawn_vars['root_test'] = 3
                        context2.drawn_vars['leaf_test'] = 4
                    assert blocker.drawn_vars['root_test'] == 3
                assert 'leaf_test' not in context1.drawn_vars
            assert context0.drawn_vars['root_test'] == 1

class BaseTestCases:
    class BaseTestCase(SeededTest):
        shape = 5

        def setup_method(self, *args, **kwargs):
            super().setup_method(*args, **kwargs)
            self.model = pm.Model()

        def get_random_variable(self, shape, with_vector_params=False, name=None):
            if with_vector_params:
                params = {key: value * np.ones(self.shape, dtype=np.dtype(type(value))) for
                          key, value in self.params.items()}
            else:
                params = self.params
            if name is None:
                name = self.distribution.__name__
            with self.model:
                if shape is None:
                    return self.distribution(name, transform=None, **params)
                else:
                    return self.distribution(name, shape=shape, transform=None, **params)

        @staticmethod
        def sample_random_variable(random_variable, size):
            try:
                return random_variable.random(size=size)
            except AttributeError:
                return random_variable.distribution.random(size=size)

        @pytest.mark.parametrize('size', [None, 5, (4, 5)], ids=str)
        def test_scalar_parameter_shape(self, size):
            rv = self.get_random_variable(None)
            if size is None:
                expected = 1,
            else:
                expected = np.atleast_1d(size).tolist()
            actual = np.atleast_1d(self.sample_random_variable(rv, size)).shape
            assert tuple(expected) == actual

        @pytest.mark.parametrize('size', [None, 5, (4, 5)], ids=str)
        def test_scalar_shape(self, size):
            shape = 10
            rv = self.get_random_variable(shape)

            if size is None:
                expected = []
            else:
                expected = np.atleast_1d(size).tolist()
            expected.append(shape)
            actual = np.atleast_1d(self.sample_random_variable(rv, size)).shape
            assert tuple(expected) == actual

        @pytest.mark.parametrize('size', [None, 5, (4, 5)], ids=str)
        def test_parameters_1d_shape(self, size):
            rv = self.get_random_variable(self.shape, with_vector_params=True)
            if size is None:
                expected = []
            else:
                expected = np.atleast_1d(size).tolist()
            expected.append(self.shape)
            actual = self.sample_random_variable(rv, size).shape
            assert tuple(expected) == actual

        @pytest.mark.parametrize('size', [None, 5, (4, 5)], ids=str)
        def test_broadcast_shape(self, size):
            broadcast_shape = (2 * self.shape, self.shape)
            rv = self.get_random_variable(broadcast_shape, with_vector_params=True)
            if size is None:
                expected = []
            else:
                expected = np.atleast_1d(size).tolist()
            expected.extend(broadcast_shape)
            actual = np.atleast_1d(self.sample_random_variable(rv, size)).shape
            assert tuple(expected) == actual

        @pytest.mark.parametrize('shape', [(), (1,), (1, 1), (1, 2), (10, 10, 1), (10, 10, 2)], ids=str)
        def test_different_shapes_and_sample_sizes(self, shape):
            prefix = self.distribution.__name__

            rv = self.get_random_variable(shape, name='%s_%s' % (prefix, shape))
            for size in (None, 1, 5, (4, 5)):
                if size is None:
                    s = []
                else:
                    try:
                        s = list(size)
                    except TypeError:
                        s = [size]
                    if s == [1]:
                        s = []
                if shape not in ((), (1,)):
                    s.extend(shape)
                e = tuple(s)
                a = self.sample_random_variable(rv, size).shape
                assert e == a

class TestNormal(BaseTestCases.BaseTestCase):
    distribution = pm.Normal
    params = {'mu': 0., 'tau': 1.}

class TestTruncatedNormal(BaseTestCases.BaseTestCase):
    distribution = pm.TruncatedNormal
    params = {'mu': 0., 'tau': 1., 'lower': -0.5, 'upper': 0.5}

class TestTruncatedNormalLower(BaseTestCases.BaseTestCase):
    distribution = pm.TruncatedNormal
    params = {'mu': 0., 'tau': 1., 'lower': -0.5}

class TestTruncatedNormalUpper(BaseTestCases.BaseTestCase):
    distribution = pm.TruncatedNormal
    params = {'mu': 0., 'tau': 1., 'upper': 0.5}

class TestSkewNormal(BaseTestCases.BaseTestCase):
    distribution = pm.SkewNormal
    params = {'mu': 0., 'sigma': 1., 'alpha': 5.}

class TestHalfNormal(BaseTestCases.BaseTestCase):
    distribution = pm.HalfNormal
    params = {'tau': 1.}

class TestUniform(BaseTestCases.BaseTestCase):
    distribution = pm.Uniform
    params = {'lower': 0., 'upper': 1.}

class TestTriangular(BaseTestCases.BaseTestCase):
    distribution = pm.Triangular
    params = {'c': 0.5, 'lower': 0., 'upper': 1.}

class TestWald(BaseTestCases.BaseTestCase):
    distribution = pm.Wald
    params = {'mu': 1., 'lam': 1., 'alpha': 0.}

class TestBeta(BaseTestCases.BaseTestCase):
    distribution = pm.Beta
    params = {'alpha': 1., 'beta': 1.}

class TestKumaraswamy(BaseTestCases.BaseTestCase):
    distribution = pm.Kumaraswamy
    params = {'a': 1., 'b': 1.}

class TestExponential(BaseTestCases.BaseTestCase):
    distribution = pm.Exponential
    params = {'lam': 1.}

class TestLaplace(BaseTestCases.BaseTestCase):
    distribution = pm.Laplace
    params = {'mu': 1., 'b': 1.}

class TestLognormal(BaseTestCases.BaseTestCase):
    distribution = pm.Lognormal
    params = {'mu': 1., 'tau': 1.}

class TestStudentT(BaseTestCases.BaseTestCase):
    distribution = pm.StudentT
    params = {'nu': 5., 'mu': 0., 'lam': 1.}

class TestPareto(BaseTestCases.BaseTestCase):
    distribution = pm.Pareto
    params = {'alpha': 0.5, 'm': 1.}

class TestCauchy(BaseTestCases.BaseTestCase):
    distribution = pm.Cauchy
    params = {'alpha': 1., 'beta': 1.}

class TestHalfCauchy(BaseTestCases.BaseTestCase):
    distribution = pm.HalfCauchy
    params = {'beta': 1.}

class TestGamma(BaseTestCases.BaseTestCase):
    distribution = pm.Gamma
    params = {'alpha': 1., 'beta': 1.}

class TestInverseGamma(BaseTestCases.BaseTestCase):
    distribution = pm.InverseGamma
    params = {'alpha': 0.5, 'beta': 0.5}

class TestChiSquared(BaseTestCases.BaseTestCase):
    distribution = pm.ChiSquared
    params = {'nu': 2.}

class TestWeibull(BaseTestCases.BaseTestCase):
    distribution = pm.Weibull
    params = {'alpha': 1., 'beta': 1.}

class TestExGaussian(BaseTestCases.BaseTestCase):
    distribution = pm.ExGaussian
    params = {'mu': 0., 'sigma': 1., 'nu': 1.}

class TestVonMises(BaseTestCases.BaseTestCase):
    distribution = pm.VonMises
    params = {'mu': 0., 'kappa': 1.}

class TestGumbel(BaseTestCases.BaseTestCase):
    distribution = pm.Gumbel
    params = {'mu': 0., 'beta': 1.}

class TestLogistic(BaseTestCases.BaseTestCase):
    distribution = pm.Logistic
    params = {'mu': 0., 's': 1.}

class TestLogitNormal(BaseTestCases.BaseTestCase):
    distribution = pm.LogitNormal
    params = {'mu': 0., 'sigma': 1.}

class TestBinomial(BaseTestCases.BaseTestCase):
    distribution = pm.Binomial
    params = {'n': 5, 'p': 0.5}

class TestBetaBinomial(BaseTestCases.BaseTestCase):
    distribution = pm.BetaBinomial
    params = {'n': 5, 'alpha': 1., 'beta': 1.}

class TestBernoulli(BaseTestCases.BaseTestCase):
    distribution = pm.Bernoulli
    params = {'p': 0.5}

class TestDiscreteWeibull(BaseTestCases.BaseTestCase):
    distribution = pm.DiscreteWeibull
    params = {'q': 0.25, 'beta': 2.}

class TestPoisson(BaseTestCases.BaseTestCase):
    distribution = pm.Poisson
    params = {'mu': 1.}

class TestNegativeBinomial(BaseTestCases.BaseTestCase):
    distribution = pm.NegativeBinomial
    params = {'mu': 1., 'alpha': 1.}

class TestConstant(BaseTestCases.BaseTestCase):
    distribution = pm.Constant
    params = {'c': 3}

class TestZeroInflatedPoisson(BaseTestCases.BaseTestCase):
    distribution = pm.ZeroInflatedPoisson
    params = {'theta': 1., 'psi': 0.3}

class TestZeroInflatedNegativeBinomial(BaseTestCases.BaseTestCase):
    distribution = pm.ZeroInflatedNegativeBinomial
    params = {'mu': 1., 'alpha': 1., 'psi': 0.3}

class TestZeroInflatedBinomial(BaseTestCases.BaseTestCase):
    distribution = pm.ZeroInflatedBinomial
    params = {'n': 10, 'p': 0.6, 'psi': 0.3}

class TestDiscreteUniform(BaseTestCases.BaseTestCase):
    distribution = pm.DiscreteUniform
    params = {'lower': 0., 'upper': 10.}

class TestGeometric(BaseTestCases.BaseTestCase):
    distribution = pm.Geometric
    params = {'p': 0.5}

class TestCategorical(BaseTestCases.BaseTestCase):
    distribution = pm.Categorical
    params = {'p': np.ones(BaseTestCases.BaseTestCase.shape)}

    def get_random_variable(self, shape, with_vector_params=False, **kwargs):  # don't transform categories
        return super().get_random_variable(shape, with_vector_params=False, **kwargs)

    def test_probability_vector_shape(self):
        """Check that if a 2d array of probabilities are passed to categorical correct shape is returned"""
        p = np.ones((10, 5))
        assert pm.Categorical.dist(p=p).random().shape == (10,)
        assert pm.Categorical.dist(p=p).random(size=4).shape == (4, 10)
        p = np.ones((3, 7, 5))
        assert pm.Categorical.dist(p=p).random().shape == (3, 7)
        assert pm.Categorical.dist(p=p).random(size=4).shape == (4, 3, 7)

class TestScalarParameterSamples(SeededTest):
    def test_bounded(self):
        # A bit crude...
        BoundedNormal = pm.Bound(pm.Normal, upper=0)

        def ref_rand(size, tau):
            return -st.halfnorm.rvs(size=size, loc=0, scale=tau ** -0.5)
        pymc3_random(BoundedNormal, {'tau': Rplus}, ref_rand=ref_rand)

    def test_uniform(self):
        def ref_rand(size, lower, upper):
            return st.uniform.rvs(size=size, loc=lower, scale=upper - lower)
        pymc3_random(pm.Uniform, {'lower': -Rplus, 'upper': Rplus}, ref_rand=ref_rand)

    def test_normal(self):
        def ref_rand(size, mu, sigma):
            return st.norm.rvs(size=size, loc=mu, scale=sigma)
        pymc3_random(pm.Normal, {'mu': R, 'sigma': Rplus}, ref_rand=ref_rand)

    def test_truncated_normal(self):
        def ref_rand(size, mu, sigma, lower, upper):
            return st.truncnorm.rvs((lower - mu) / sigma, (upper - mu) / sigma, size=size, loc=mu, scale=sigma)
        pymc3_random(pm.TruncatedNormal, {'mu': R, 'sigma': Rplusbig, 'lower': -Rplusbig, 'upper': Rplusbig},
                     ref_rand=ref_rand)

    def test_truncated_normal_lower(self):
        def ref_rand(size, mu, sigma, lower):
            return st.truncnorm.rvs((lower - mu) / sigma, np.inf, size=size, loc=mu, scale=sigma)
        pymc3_random(pm.TruncatedNormal, {'mu': R, 'sigma': Rplusbig, 'lower': -Rplusbig},
                     ref_rand=ref_rand)

    def test_truncated_normal_upper(self):
        def ref_rand(size, mu, sigma, upper):
            return st.truncnorm.rvs(-np.inf, (upper - mu) / sigma, size=size, loc=mu, scale=sigma)
        pymc3_random(pm.TruncatedNormal, {'mu': R, 'sigma': Rplusbig, 'upper': Rplusbig},
                     ref_rand=ref_rand)

    def test_skew_normal(self):
        def ref_rand(size, alpha, mu, sigma):
            return st.skewnorm.rvs(size=size, a=alpha, loc=mu, scale=sigma)
        pymc3_random(pm.SkewNormal, {'mu': R, 'sigma': Rplus, 'alpha': R}, ref_rand=ref_rand)

    def test_half_normal(self):
        def ref_rand(size, tau):
            return st.halfnorm.rvs(size=size, loc=0, scale=tau ** -0.5)
        pymc3_random(pm.HalfNormal, {'tau': Rplus}, ref_rand=ref_rand)

    def test_wald(self):
        # Cannot do anything too exciting as scipy wald is a
        # location-scale model of the *standard* wald with mu=1 and lam=1
        def ref_rand(size, mu, lam, alpha):
            return st.wald.rvs(size=size, loc=alpha)
        pymc3_random(pm.Wald,
                     {'mu': Domain([1., 1., 1.]), 'lam': Domain(
                         [1., 1., 1.]), 'alpha': Rplus},
                     ref_rand=ref_rand)

    def test_beta(self):
        def ref_rand(size, alpha, beta):
            return st.beta.rvs(a=alpha, b=beta, size=size)
        pymc3_random(pm.Beta, {'alpha': Rplus, 'beta': Rplus}, ref_rand=ref_rand)

    def test_exponential(self):
        def ref_rand(size, lam):
            return nr.exponential(scale=1. / lam, size=size)
        pymc3_random(pm.Exponential, {'lam': Rplus}, ref_rand=ref_rand)

    def test_laplace(self):
        def ref_rand(size, mu, b):
            return st.laplace.rvs(mu, b, size=size)
        pymc3_random(pm.Laplace, {'mu': R, 'b': Rplus}, ref_rand=ref_rand)

    def test_lognormal(self):
        def ref_rand(size, mu, tau):
            return np.exp(mu + (tau ** -0.5) * st.norm.rvs(loc=0., scale=1., size=size))
        pymc3_random(pm.Lognormal, {'mu': R, 'tau': Rplusbig}, ref_rand=ref_rand)

    def test_student_t(self):
        def ref_rand(size, nu, mu, lam):
            return st.t.rvs(nu, mu, lam**-.5, size=size)
        pymc3_random(pm.StudentT, {'nu': Rplus, 'mu': R, 'lam': Rplus}, ref_rand=ref_rand)

    def test_cauchy(self):
        def ref_rand(size, alpha, beta):
            return st.cauchy.rvs(alpha, beta, size=size)
        pymc3_random(pm.Cauchy, {'alpha': R, 'beta': Rplusbig}, ref_rand=ref_rand)

    def test_half_cauchy(self):
        def ref_rand(size, beta):
            return st.halfcauchy.rvs(scale=beta, size=size)
        pymc3_random(pm.HalfCauchy, {'beta': Rplusbig}, ref_rand=ref_rand)

    def test_gamma_alpha_beta(self):
        def ref_rand(size, alpha, beta):
            return st.gamma.rvs(alpha, scale=1. / beta, size=size)
        pymc3_random(pm.Gamma, {'alpha': Rplusbig, 'beta': Rplusbig}, ref_rand=ref_rand)

    def test_gamma_mu_sigma(self):
        def ref_rand(size, mu, sigma):
            return st.gamma.rvs(mu**2 / sigma**2, scale=sigma ** 2 / mu, size=size)
        pymc3_random(pm.Gamma, {'mu': Rplusbig, 'sigma': Rplusbig}, ref_rand=ref_rand)

    def test_inverse_gamma(self):
        def ref_rand(size, alpha, beta):
            return st.invgamma.rvs(a=alpha, scale=beta, size=size)
        pymc3_random(pm.InverseGamma, {'alpha': Rplus, 'beta': Rplus}, ref_rand=ref_rand)

    def test_pareto(self):
        def ref_rand(size, alpha, m):
            return st.pareto.rvs(alpha, scale=m, size=size)
        pymc3_random(pm.Pareto, {'alpha': Rplusbig, 'm': Rplusbig}, ref_rand=ref_rand)

    def test_ex_gaussian(self):
        def ref_rand(size, mu, sigma, nu):
            return nr.normal(mu, sigma, size=size) + nr.exponential(scale=nu, size=size)
        pymc3_random(pm.ExGaussian, {'mu': R, 'sigma': Rplus, 'nu': Rplus}, ref_rand=ref_rand)

    def test_vonmises(self):
        def ref_rand(size, mu, kappa):
            return st.vonmises.rvs(size=size, loc=mu, kappa=kappa)
        pymc3_random(pm.VonMises, {'mu': R, 'kappa': Rplus}, ref_rand=ref_rand)

    def test_triangular(self):
        def ref_rand(size, lower, upper, c):
            scale = upper - lower
            c_ = (c - lower) / scale
            return st.triang.rvs(size=size, loc=lower, scale=scale, c=c_)
        pymc3_random(pm.Triangular, {'lower': Runif, 'upper': Runif + 3, 'c': Runif + 1}, ref_rand=ref_rand)

    def test_flat(self):
        with pm.Model():
            f = pm.Flat('f')
            with pytest.raises(ValueError):
                f.random(1)

    def test_half_flat(self):
        with pm.Model():
            f = pm.HalfFlat('f')
            with pytest.raises(ValueError):
                f.random(1)

    def test_binomial(self):
        pymc3_random_discrete(pm.Binomial, {'n': Nat, 'p': Unit}, ref_rand=st.binom.rvs)

    def test_beta_binomial(self):
        pymc3_random_discrete(pm.BetaBinomial, {'n': Nat, 'alpha': Rplus, 'beta': Rplus},
                              ref_rand=self._beta_bin)

    def _beta_bin(self, n, alpha, beta, size=None):
        return st.binom.rvs(n, st.beta.rvs(a=alpha, b=beta, size=size))

    def test_bernoulli(self):
        pymc3_random_discrete(pm.Bernoulli, {'p': Unit},
                              ref_rand=lambda size, p=None: st.bernoulli.rvs(p, size=size))

    def test_poisson(self):
        pymc3_random_discrete(pm.Poisson, {'mu': Rplusbig}, size=500, ref_rand=st.poisson.rvs)

    def test_negative_binomial(self):
        def ref_rand(size, alpha, mu):
            return st.nbinom.rvs(alpha, alpha / (mu + alpha), size=size)
        pymc3_random_discrete(pm.NegativeBinomial, {'mu': Rplusbig, 'alpha': Rplusbig},
                              size=100, fails=50, ref_rand=ref_rand)

    def test_geometric(self):
        pymc3_random_discrete(pm.Geometric, {'p': Unit}, size=500, fails=50, ref_rand=nr.geometric)

    def test_discrete_uniform(self):
        def ref_rand(size, lower, upper):
            return st.randint.rvs(lower, upper + 1, size=size)
        pymc3_random_discrete(pm.DiscreteUniform, {'lower': -NatSmall, 'upper': NatSmall},
                              ref_rand=ref_rand)

    def test_discrete_weibull(self):
        def ref_rand(size, q, beta):
            u = np.random.uniform(size=size)

            return np.ceil(np.power(np.log(1 - u) / np.log(q), 1. / beta)) - 1

        pymc3_random_discrete(pm.DiscreteWeibull, {'q': Unit, 'beta': Rplusdunif},
                              ref_rand=ref_rand)

    @pytest.mark.parametrize('s', [2, 3, 4])
    def test_categorical_random(self, s):
        def ref_rand(size, p):
            return nr.choice(np.arange(p.shape[0]), p=p, size=size)
        pymc3_random_discrete(pm.Categorical, {'p': Simplex(s)}, ref_rand=ref_rand)

    def test_constant_dist(self):
        def ref_rand(size, c):
            return c * np.ones(size, dtype=int)
        pymc3_random_discrete(pm.Constant, {'c': I}, ref_rand=ref_rand)

    def test_mv_normal(self):
        def ref_rand(size, mu, cov):
            return st.multivariate_normal.rvs(mean=mu, cov=cov, size=size)

        def ref_rand_tau(size, mu, tau):
            return ref_rand(size, mu, linalg.inv(tau))

        def ref_rand_chol(size, mu, chol):
            return ref_rand(size, mu, np.dot(chol, chol.T))

        def ref_rand_uchol(size, mu, chol):
            return ref_rand(size, mu, np.dot(chol.T, chol))

        for n in [2, 3]:
            pymc3_random(pm.MvNormal, {'mu': Vector(R, n), 'cov': PdMatrix(n)},
                         size=100, valuedomain=Vector(R, n), ref_rand=ref_rand)
            pymc3_random(pm.MvNormal, {'mu': Vector(R, n), 'tau': PdMatrix(n)},
                         size=100, valuedomain=Vector(R, n), ref_rand=ref_rand_tau)
            pymc3_random(pm.MvNormal, {'mu': Vector(R, n), 'chol': PdMatrixChol(n)},
                         size=100, valuedomain=Vector(R, n), ref_rand=ref_rand_chol)
            pymc3_random(
                pm.MvNormal,
                {'mu': Vector(R, n), 'chol': PdMatrixCholUpper(n)},
                size=100, valuedomain=Vector(R, n), ref_rand=ref_rand_uchol,
                extra_args={'lower': False}
            )

    def test_matrix_normal(self):
        def ref_rand(size, mu, rowcov, colcov):
            return st.matrix_normal.rvs(mean=mu, rowcov=rowcov, colcov=colcov, size=size)

        # def ref_rand_tau(size, mu, tau):
        #     return ref_rand(size, mu, linalg.inv(tau))

        def ref_rand_chol(size, mu, rowchol, colchol):
            return ref_rand(size, mu, rowcov=np.dot(rowchol, rowchol.T),
                            colcov=np.dot(colchol, colchol.T))

        def ref_rand_uchol(size, mu, rowchol, colchol):
            return ref_rand(size, mu, rowcov=np.dot(rowchol.T, rowchol),
                            colcov=np.dot(colchol.T, colchol))

        for n in [2, 3]:
            pymc3_random(pm.MatrixNormal, {'mu': RealMatrix(n, n), 'rowcov': PdMatrix(n), 'colcov': PdMatrix(n)},
                         size=n, valuedomain=RealMatrix(n, n), ref_rand=ref_rand)
            # pymc3_random(pm.MatrixNormal, {'mu': RealMatrix(n, n), 'tau': PdMatrix(n)},
            #              size=n, valuedomain=RealMatrix(n, n), ref_rand=ref_rand_tau)
            pymc3_random(pm.MatrixNormal, {'mu': RealMatrix(n, n), 'rowchol': PdMatrixChol(n), 'colchol': PdMatrixChol(n)},
                         size=n, valuedomain=RealMatrix(n, n), ref_rand=ref_rand_chol)
            # pymc3_random(
            #     pm.MvNormal,
            #     {'mu': RealMatrix(n, n), 'rowchol': PdMatrixCholUpper(n), 'colchol': PdMatrixCholUpper(n)},
            #     size=n, valuedomain=RealMatrix(n, n), ref_rand=ref_rand_uchol,
            #     extra_args={'lower': False}
            # )

    def test_kronecker_normal(self):
        def ref_rand(size, mu, covs, sigma):
            cov = pm.math.kronecker(covs[0], covs[1]).eval()
            cov += sigma**2 * np.identity(cov.shape[0])
            return st.multivariate_normal.rvs(mean=mu, cov=cov, size=size)

        def ref_rand_chol(size, mu, chols, sigma):
            covs = [np.dot(chol, chol.T) for chol in chols]
            return ref_rand(size, mu, covs, sigma)

        def ref_rand_evd(size, mu, evds, sigma):
            covs = []
            for eigs, Q in evds:
                covs.append(np.dot(Q, np.dot(np.diag(eigs), Q.T)))
            return ref_rand(size, mu, covs, sigma)

        sizes = [2, 3]
        sigmas = [0, 1]
        for n, sigma in zip(sizes, sigmas):
            N = n**2
            covs = [RandomPdMatrix(n), RandomPdMatrix(n)]
            chols = list(map(np.linalg.cholesky, covs))
            evds = list(map(np.linalg.eigh, covs))
            dom = Domain([np.random.randn(N)*0.1], edges=(None, None), shape=N)
            mu = Domain([np.random.randn(N)*0.1], edges=(None, None), shape=N)

            std_args = {'mu': mu}
            cov_args = {'covs': covs}
            chol_args = {'chols': chols}
            evd_args = {'evds': evds}
            if sigma is not None and sigma != 0:
                std_args['sigma'] = Domain([sigma], edges=(None, None))
            else:
                for args in [cov_args, chol_args, evd_args]:
                    args['sigma'] = sigma

            pymc3_random(
                 pm.KroneckerNormal, std_args, valuedomain=dom,
                 ref_rand=ref_rand, extra_args=cov_args, model_args=cov_args)
            pymc3_random(
                 pm.KroneckerNormal, std_args, valuedomain=dom,
                 ref_rand=ref_rand_chol, extra_args=chol_args,
                 model_args=chol_args)
            pymc3_random(
                 pm.KroneckerNormal, std_args, valuedomain=dom,
                 ref_rand=ref_rand_evd, extra_args=evd_args,
                 model_args=evd_args)

    def test_mv_t(self):
        def ref_rand(size, nu, Sigma, mu):
            normal = st.multivariate_normal.rvs(cov=Sigma, size=size).T
            chi2 = st.chi2.rvs(df=nu, size=size)
            return mu + np.sqrt(nu) * (normal / chi2).T
        for n in [2, 3]:
            pymc3_random(pm.MvStudentT,
                         {'nu': Domain([5, 10, 25, 50]), 'Sigma': PdMatrix(
                             n), 'mu': Vector(R, n)},
                         size=100, valuedomain=Vector(R, n), ref_rand=ref_rand)

    def test_dirichlet(self):
        def ref_rand(size, a):
            return st.dirichlet.rvs(a, size=size)
        for n in [2, 3]:
            pymc3_random(pm.Dirichlet, {'a': Vector(Rplus, n)},
                         valuedomain=Simplex(n), size=100, ref_rand=ref_rand)

    def test_multinomial(self):
        def ref_rand(size, p, n):
            return nr.multinomial(pvals=p, n=n, size=size)
        for n in [2, 3]:
            pymc3_random_discrete(pm.Multinomial, {'p': Simplex(n), 'n': Nat},
                                  valuedomain=Vector(Nat, n), size=100, ref_rand=ref_rand)

    def test_gumbel(self):
        def ref_rand(size, mu, beta):
            return st.gumbel_r.rvs(loc=mu, scale=beta, size=size)
        pymc3_random(pm.Gumbel, {'mu': R, 'beta': Rplus}, ref_rand=ref_rand)

    def test_logistic(self):
        def ref_rand(size, mu, s):
            return st.logistic.rvs(loc=mu, scale=s, size=size)
        pymc3_random(pm.Logistic, {'mu': R, 's': Rplus}, ref_rand=ref_rand)

    def test_logitnormal(self):
        def ref_rand(size, mu, sigma):
            return expit(st.norm.rvs(loc=mu, scale=sigma, size=size))
        pymc3_random(pm.LogitNormal, {'mu': R, 'sigma': Rplus}, ref_rand=ref_rand)

    @pytest.mark.xfail(condition=(theano.config.floatX == "float32"), reason="Fails on float32")
    def test_interpolated(self):
        for mu in R.vals:
            for sigma in Rplus.vals:
                #pylint: disable=cell-var-from-loop
                def ref_rand(size):
                    return st.norm.rvs(loc=mu, scale=sigma, size=size)

                class TestedInterpolated (pm.Interpolated):

                    def __init__(self, **kwargs):
                        x_points = np.linspace(mu - 5 * sigma, mu + 5 * sigma, 100)
                        pdf_points = st.norm.pdf(x_points, loc=mu, scale=sigma)
                        super().__init__(
                            x_points=x_points,
                            pdf_points=pdf_points,
                            **kwargs
                        )

                pymc3_random(TestedInterpolated, {}, ref_rand=ref_rand)

    @pytest.mark.skip('Wishart random sampling not implemented.\n'
                      'See https://github.com/pymc-devs/pymc3/issues/538')
    def test_wishart(self):
        # Wishart non current recommended for use:
        # https://github.com/pymc-devs/pymc3/issues/538
        # for n in [2, 3]:
        #     pymc3_random_discrete(Wisvaluedomainhart,
        #                           {'n': Domain([2, 3, 4, 2000]) , 'V': PdMatrix(n) },
        #                           valuedomain=PdMatrix(n),
        #                           ref_rand=lambda n=None, V=None, size=None: \
        #                           st.wishart(V, df=n, size=size))
        pass

    def test_lkj(self):
        for n in [2, 10, 50]:
            #pylint: disable=cell-var-from-loop
            shape = n*(n-1)//2

            def ref_rand(size, eta):
                beta = eta - 1 + n/2
                return (st.beta.rvs(size=(size, shape), a=beta, b=beta)-.5)*2

            class TestedLKJCorr (pm.LKJCorr):

                def __init__(self, **kwargs):
                    kwargs.pop('shape', None)
                    super().__init__(n=n, **kwargs)

            pymc3_random(TestedLKJCorr,
                     {'eta': Domain([1., 10., 100.])},
                     size=10000//n,
                     ref_rand=ref_rand)

    def test_normalmixture(self):
        def ref_rand(size, w, mu, sigma):
            component = np.random.choice(w.size, size=size, p=w)
            return np.random.normal(mu[component], sigma[component], size=size)

        pymc3_random(pm.NormalMixture, {'w': Simplex(2),
                     'mu': Domain([[.05, 2.5], [-5., 1.]], edges=(None, None)),
                     'sigma': Domain([[1, 1], [1.5, 2.]], edges=(None, None))},
                     extra_args={'comp_shape': 2},
                     size=1000,
                     ref_rand=ref_rand)
        pymc3_random(pm.NormalMixture, {'w': Simplex(3),
                     'mu': Domain([[-5., 1., 2.5]], edges=(None, None)),
                     'sigma': Domain([[1.5, 2., 3.]], edges=(None, None))},
                     extra_args={'comp_shape': 3},
                     size=1000,
                     ref_rand=ref_rand)

def test_mixture_random_shape():
    # test the shape broadcasting in mixture random
    y = np.concatenate([nr.poisson(5, size=10),
                        nr.poisson(9, size=10)])
    with pm.Model() as m:
        comp0 = pm.Poisson.dist(mu=np.ones(2))
        w0 = pm.Dirichlet('w0', a=np.ones(2))
        like0 = pm.Mixture('like0',
                           w=w0,
                           comp_dists=comp0,
                           observed=y)

        comp1 = pm.Poisson.dist(mu=np.ones((20, 2)),
                                shape=(20, 2))
        w1 = pm.Dirichlet('w1', a=np.ones(2))
        like1 = pm.Mixture('like1',
                           w=w1,
                           comp_dists=comp1,
                           observed=y)

        comp2 = pm.Poisson.dist(mu=np.ones(2))
        w2 = pm.Dirichlet('w2',
                          a=np.ones(2),
                          shape=(20, 2))
        like2 = pm.Mixture('like2',
                           w=w2,
                           comp_dists=comp2,
                           observed=y)

        comp3 = pm.Poisson.dist(mu=np.ones(2),
                                shape=(20, 2))
        w3 = pm.Dirichlet('w3',
                          a=np.ones(2),
                          shape=(20, 2))
        like3 = pm.Mixture('like3',
                           w=w3,
                           comp_dists=comp3,
                           observed=y)

    rand0, rand1, rand2, rand3 = draw_values([like0, like1, like2, like3],
                                             point=m.test_point,
                                             size=100)
    assert rand0.shape == (100, 20)
    assert rand1.shape == (100, 20)
    assert rand2.shape == (100, 20)
    assert rand3.shape == (100, 20)

    with m:
        ppc = pm.sample_posterior_predictive([m.test_point], samples=200)
    assert ppc['like0'].shape == (200, 20)
    assert ppc['like1'].shape == (200, 20)
    assert ppc['like2'].shape == (200, 20)
    assert ppc['like3'].shape == (200, 20)

def test_density_dist_with_random_sampleable():
    with pm.Model() as model:
        mu = pm.Normal('mu', 0, 1)
        normal_dist = pm.Normal.dist(mu, 1)
        pm.DensityDist('density_dist', normal_dist.logp, observed=np.random.randn(100), random=normal_dist.random)
        trace = pm.sample(100)

    samples = 500
    ppc = pm.sample_posterior_predictive(trace, samples=samples, model=model, size=100)
    assert len(ppc['density_dist']) == samples

def test_density_dist_without_random_not_sampleable():
    with pm.Model() as model:
        mu = pm.Normal('mu', 0, 1)
        normal_dist = pm.Normal.dist(mu, 1)
        pm.DensityDist('density_dist', normal_dist.logp, observed=np.random.randn(100))
        trace = pm.sample(100)

    samples = 500
    with pytest.raises(ValueError):
        pm.sample_posterior_predictive(trace, samples=samples, model=model, size=100)


import solution
import utils

class GC(solution.Solution):

    def _read(self, f):
        return utils.read_fasta(f)

    def solve(self, data):
        max_gc_id = None
        max_gc = 0

        for id_, dna in data:
            gc = sum([1 for i in dna if i == utils.CYTOSINE or i == utils.GUANINE]) * 1. / len(dna)
            if gc > max_gc:
                max_gc_id = id_
                max_gc = gc

        return max_gc_id, max_gc * 100

    def _write(self, f, answer):
        f.write('{}\n{}'.format(answer[0][1:], '%.6f' % answer[1]))


from flask import Flask, request, abort
import os
import products_db

app = Flask(__name__)

@app.errorhandler(products_db.ValidationError)
def handle_validation_error(e):
    return {"ok": False}, 400

@app.post("/products")
def post_products():
    products = request.json
    products_db.set_products(products)
    return {"ok": True}

@app.get("/products")
def get_products():
    return products_db.get_products()

@app.post("/products/<string:sku>")
def post_product(sku):
    product = request.json
    product['sku'] = sku
    products_db.upsert_product(product)
    return {"ok": True}

@app.get("/products/<string:sku>")
def get_product(sku):
    product = products_db.get_product(sku)
    if not product:
        abort(404)
    return product

if __name__ == '__main__':
    products_db.init(os.path.join(os.path.dirname(__file__), "data", "db.sqlite"))
    app.run()


import time
import os
from .logger import logger
from .notifier import CrowdAiNotifier
import threading
import uuid

class NoClientInteractionError(Exception):
    pass

class InteractionVerifier:
    __last_request = None
    __time_out = None
    __instance_id = None

    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super().__new__(cls)
            cls.instance.start()
        return cls.instance

    def __init__(self):
        # timeout in seconds or client <-> server interaction
        self.__time_out = int(os.getenv('CS_INTERACTION_TIMEOUT', 180))
        self.__instance_id = uuid.uuid1()
        logger.info('client <-> server interaction verifier id: %s', self.__instance_id)

    def start(self):
        self.__last_request = time.time()
        Caller()
        logger.info('Client <-> Server interaction monitor started...')

    def mark(self):
        self.__last_request = time.time()

    def verify(self):
        now = time.time()
        duration = now - self.__last_request
        if duration > self.__time_out:
            logger.error('Client has not sent any requests to to the server for more than %ss', duration)
            CrowdAiNotifier.no_client_interaction()
            raise NoClientInteractionError(
                "Client has not sent any requests to to the server for more than {}s ".format(duration)
            )

class Caller:

    def __init__(self):
        # interval in seconds to check client <-> server interaction
        self.__cs_interaction_verifier = InteractionVerifier()
        self.__interval = int(os.getenv('CS_INTERACTION_CHECK_INTERVAL', 5))
        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True
        thread.start()

    def run(self):
        while True:
            self.__cs_interaction_verifier.verify()
            time.sleep(self.__interval)


import telebot
from telebot import types
from django.core.management.base import BaseCommand

from user.models import User

bot = telebot.TeleBot("You Bot Token")

class Command(BaseCommand):
    help = 'Run the Telegram bot'

    def handle(self, *args, **options):
        @bot.message_handler(commands=['start'])
        def handle_start(message: types.Message):
            telegram_id = message.from_user.id
            if not User.objects.filter(telegram_id= telegram_id):
                User.objects.create(telegram_id=telegram_id, username=message.from_user.username)
            bot.reply_to(message, f"Welcome to your Django integrated Telegram bot: {message.from_user.username}!")

        @bot.message_handler(commands=['contact'])
        def handle_contact(message):
            keyboard = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
            contact_button = types.KeyboardButton(text="Share Contact", request_contact=True)
            keyboard.add(contact_button)
            bot.send_message(message.chat.id, "Please provide your contact information.", reply_markup=keyboard)

        @bot.message_handler(content_types=['contact'])
        def get_contact(message: types.Message):
            phone_number = message.contact.phone_number
            User.objects.filter(telegram_id=message.from_user.id).update(phone_number=phone_number)
            bot.reply_to(message, f"Phone number updated: {phone_number}", reply_markup=types.ReplyKeyboardRemove())

        bot.polling()


def leiaInt(msg):
    ok = False
    valor = 0
    while True:
        n = str(input(msg))
        if n.isnumeric():
            valor = int(n)
            ok = True
        else:
            print('\033[1;31mVALOR INVÁLIDO TENTE NOVAMENTE!!\33[m')
        if ok:
            break
    return valor

def leiaDinheiro(msg):
    valido = False
    while not valido:
        entrada = str(input(msg)).replace(',', '.')
        if entrada.isalpha() or entrada.strip() == '':
            print(f'\033[0;31mERRO: \"{entrada}\" NÃO É VALIDO!!\033[m')
        else:
            valido = True
            return float(entrada)

def contador(*num):
    cont = 0
    cont2 = 1
    while True:
        valor = float(input(f'{cont2}º valor? ').replace(',', '.'))
        cont2 += 1
        if valor == 0:
            break
        cont += valor
    return cont

def lin():
    print('-'*60)

#Programa principal
from datetime import datetime
data_atual = datetime.now()
data_em_texto = data_atual.strftime('%d-%m-%Y')
ano = data_atual.strftime("%Y")
print(ano)

#Código refatorado em 14/09/2022
#Lista com valores para o café

cafe = ["cafe", 55.00, "infantil", 27.50, "vinho", 10.90] #Valores dos produtos do café
print('-'*46)
print('\033[1;31mCAFÉ COLONIAL DIA V 2.0'.center(50))
print(f'{data_em_texto}\033[m'.center(50))
print('-'*46)
try:
    n1 = leiaInt(f'\033[1;32m Digite a Quantidade de cafés Uni. R$ {cafe[1]}0? ')
    n2 = leiaInt(f'\033[1;32m Quantidade de cafés infantil Uni R$ {cafe[3]}0? ')
    n3 = leiaInt(f'\033[1;32m Quantas taças de vinho Uni. R$ {cafe[5]}0 ? ')
except:
    print('Houve um erro na execução do programa :(')
try:
    outros = soma1 = 0
    while True:
        outros = leiaDinheiro('Mais alguma coisa (FINALIZAR..000>>)? ')
        if outros == 0:
            break
        soma1 += outros
except:
    print('\033[1;31mHouve um erro de digitação de Valor :(\033[m')
soma = (n1 * cafe[1]) + (n2 * cafe[3]) + (n3 * cafe[5]) + soma1
print(f'\033[1;31mO valor total da comanda é R$ {soma:.2f}\033[m')
valor = leiaDinheiro('Valor recebido: R$ ')
troco = (valor - soma)
print(f'\033[1;32m O valor do troco é R$ {troco:.2f}')