"""
Python code for the minimax algorithm
Some code from: https://github.com/lazuxd/playing-2048-with-minimax
"""

from game import AdversarialGame
from sys import maxsize as MAX_INT

# Find all possible moves for player
def get_max_moves(grid):
    moves = []
    if check_left(grid):
        moves.append(0)
    if check_up(grid):
        moves.append(1)
    if check_right(grid):
        moves.append(2)
    if check_down(grid):
        moves.append(3)
    return moves

# Check if left is possible move
def check_left(grid):
    for r in range(4):
        k = -1
        for c in range(3, -1, -1):
            if grid.grid[r][c] > 0:
                k = c
                break
        if k > -1:
            for c in range(k, 0, -1):
                if grid.grid[r][c - 1] == 0 or grid.grid[r][c] == grid.grid[r][c - 1]:
                    return True
    return False

# Check if up is possible move
def check_up(grid):
    for c in range(4):
        k = -1
        for r in range(3, -1, -1):
            if grid.grid[r][c] > 0:
                k = r
                break
        if k > -1:
            for r in range(k, 0, -1):
                if grid.grid[r - 1][c] == 0 or grid.grid[r][c] == grid.grid[r - 1][c]:
                    return True
    return False

# Check if right is possible move
def check_right(grid):
    for r in range(4):
        k = -1
        for c in range(4):
            if grid.grid[r][c] > 0:
                k = c
                break
        if k > -1:
            for c in range(k, 3):
                if grid.grid[r][c + 1] == 0 or grid.grid[r][c] == grid.grid[r][c + 1]:
                    return True
    return False

# Check if down is possible move
def check_down(grid):
    for c in range(4):
        k = -1
        for r in range(4):
            if grid.grid[r][c] > 0:
                k = r
                break
        if k > -1:
            for r in range(k, 3):
                if grid.grid[r + 1][c] == 0 or grid.grid[r][c] == grid.grid[r + 1][c]:
                    return True
    return False

# Find all placements for board
def get_min_moves(grid):
    moves = []
    empty = grid.get_empty()
    for r, c in empty:
        moves.append((r, c, 2))
        moves.append((r, c, 4))
    return moves

# Check if game is in terminal state
def is_terminal(grid, player):
    if player:
        if check_left(grid):
            return False
        if check_up(grid):
            return False
        if check_right(grid):
            return False
        if check_down(grid):
            return False
        return True
    else:
        empty = grid.get_empty()
        if empty:
            return False
        else:
            return True

# Check which move was performed
def get_move_to(grid, child):
    if check_left(grid):
        g = AdversarialGame(start_two=False, matrix=grid.get_grid())
        g.push_left()
        if g == child:
            return 0
    if check_up(grid):
        g = AdversarialGame(start_two=False, matrix=grid.get_grid())
        g.push_up()
        if g == child:
            return 1
    if check_right(grid):
        g = AdversarialGame(start_two=False, matrix=grid.get_grid())
        g.push_right()
        if g == child:
            return 2
    return 3

# Maximize of minimax algorithm
def maximize(grid, alpha, beta, depth):
    # Keep track of best options
    best_grid = None
    best_fitness = -1

    # Exit if it is over
    if depth == 0 or is_terminal(grid, True):
        return None, grid.fitness()

    # Check over every child
    for child in get_max_moves(grid):
        # Duplicate game and move
        g = AdversarialGame(start_two=False, matrix=grid.get_grid())
        g.game_move(child)

        # Check all minimize options
        _, fitness = minimize(g, alpha, beta, depth - 1)
        # Update if new maximum
        if fitness > best_fitness:
            best_grid, best_fitness = g, fitness

        # Alpha-beta pruning to speed up process
        if best_fitness >= beta:
            break
        if best_fitness > alpha:
            alpha = best_fitness

    # Returns best options
    return best_grid, best_fitness

# Minimize of minimax algorithm
def minimize(grid, alpha, beta, depth):
    # Keep track of best options
    worst_grid = None
    worst_fitness = MAX_INT

    # Exit if it is over
    if depth == 0 or is_terminal(grid, False):
        return None, grid.fitness()

    # Check over every child
    for child in get_min_moves(grid):
        # Duplicate game and place
        g = AdversarialGame(start_two=False, matrix=grid.get_grid())
        g.place_tile(child[0], child[1], child[2])

        # Check all maximize options
        _, fitness = maximize(g, alpha, beta, depth - 1)
        # Update if new minimum
        if fitness < worst_fitness:
            worst_grid, worst_fitness = g, fitness

        # Alpha-beta pruning to speed up process
        if worst_fitness <= alpha:
            break
        if worst_fitness < beta:
            beta = worst_fitness

    # Returns worst options
    return worst_grid, worst_fitness

def get_best_move(grid, depth=5):
    child, _ = maximize(AdversarialGame(start_two=False, matrix=grid.get_grid()), -1, MAX_INT, depth)
    return get_move_to(grid, child)


#!/usr/local/bin/python

def ToggleDisplay():
	db = mgGetCurrentDb ()
	geometry = mgGetSelectList (db)
	num = mgGetRecListCount (geometry)

	if (num == 0):
		mgSendMessage (MMSG_ERROR, "Nothing Selected")
		return

	for i in range (0, num):
		rec,matrix = mgGetNextRecInList (geometry)
		outs = mgGetAttList (rec, fltIOn)
		# outs[0] = number of attributes returned, 1 if successful
		# outs[1] = fltIOn
		# outs[2] = value of fltIOn
		if (outs[0] == 1):
			if (outs[2]):
				mgSetAttList (rec, fltIOn, 0)
			else:
				mgSetAttList (rec, fltIOn, 1)

ToggleDisplay ()


import sys
import re

def rpl(_str):
    """
    В каждой строке замените все вхождения подстроки "human" на подстроку "computer" и выведите полученные строки.
    :param _str:
    :return:
    """
    pattern = r"human"
    sub = r"computer"
    return re.sub(pattern, sub, _str)

if __name__ == "__main__":
    for line in sys.stdin:
        print(rpl(line), end='')


import logging
import shutil
import os
import subprocess

import sentry_sdk
from sentry_sdk.integrations.django import DjangoIntegration
from sentry_sdk.scrubber import EventScrubber, DEFAULT_DENYLIST

from benefits import VERSION

logger = logging.getLogger(__name__)

SENTRY_ENVIRONMENT = os.environ.get("SENTRY_ENVIRONMENT", "local")
SENTRY_CSP_REPORT_URI = None

def git_available():
    return bool(shutil.which("git"))

# https://stackoverflow.com/a/24584384/358804
def is_git_directory(path="."):
    with open(os.devnull, "w") as dev_null:
        return subprocess.call(["git", "-C", path, "status"], stderr=dev_null, stdout=dev_null) == 0

# https://stackoverflow.com/a/21901260/358804
def get_git_revision_hash():
    return subprocess.check_output(["git", "rev-parse", "HEAD"]).decode("ascii").strip()

def get_sha_file_path():
    current_file = os.path.dirname(os.path.abspath(__file__))
    return os.path.join(current_file, "..", "static", "sha.txt")

def get_sha_from_file():
    sha_path = get_sha_file_path()
    if os.path.isfile(sha_path):
        with open(sha_path) as f:
            return f.read().strip()
    else:
        return None

def get_release() -> str:
    """Returns the first available: the SHA from Git, the value from sha.txt, or the VERSION."""

    if git_available() and is_git_directory():
        return get_git_revision_hash()
    else:
        sha = get_sha_from_file()
        if sha:
            return sha
        else:
            # one of the above *should* always be available, but including this just in case
            return VERSION

def get_denylist():
    # custom denylist
    denylist = DEFAULT_DENYLIST + ["sub", "name"]
    return denylist

def get_traces_sample_rate():
    try:
        rate = float(os.environ.get("SENTRY_TRACES_SAMPLE_RATE", "0.0"))
        if rate < 0.0 or rate > 1.0:
            logger.warning("SENTRY_TRACES_SAMPLE_RATE was not in the range [0.0, 1.0], defaulting to 0.0")
            rate = 0.0
        else:
            logger.info(f"SENTRY_TRACES_SAMPLE_RATE set to: {rate}")
    except ValueError:
        logger.warning("SENTRY_TRACES_SAMPLE_RATE did not parse to float, defaulting to 0.0")
        rate = 0.0

    return rate

def configure():
    SENTRY_DSN = os.environ.get("SENTRY_DSN")
    if SENTRY_DSN:
        release = get_release()
        logger.info(f"Enabling Sentry for environment '{SENTRY_ENVIRONMENT}', release '{release}'...")

        # https://docs.sentry.io/platforms/python/configuration/
        sentry_sdk.init(
            dsn=SENTRY_DSN,
            integrations=[
                DjangoIntegration(),
            ],
            traces_sample_rate=get_traces_sample_rate(),
            environment=SENTRY_ENVIRONMENT,
            release=release,
            in_app_include=["benefits"],
            # send_default_pii must be False (the default) for a custom EventScrubber/denylist
            # https://docs.sentry.io/platforms/python/data-management/sensitive-data/#event_scrubber
            send_default_pii=False,
            event_scrubber=EventScrubber(denylist=get_denylist()),
        )

        # override the module-level variable when configuration happens, if set
        global SENTRY_CSP_REPORT_URI
        SENTRY_CSP_REPORT_URI = os.environ.get("SENTRY_REPORT_URI", "")
    else:
        logger.info("SENTRY_DSN not set, so won't send events")


import torch
import torch.nn.functional as F
from dataclasses import dataclass
import torch.nn as nn
from .sageconv import SAGEConv

class L2NormalizationLayer(torch.nn.Module):
    def __init__(self, dim=1, eps=1e-12):
        super(L2NormalizationLayer, self).__init__()
        self.dim = dim
        self.eps = eps

    def forward(self, x):
        return F.normalize(x, p=2, dim=self.dim, eps=self.eps)

class Swish(nn.Module):
    def forward(self, x):
        return x * torch.sigmoid(x)

class TransformerBlock(nn.Module):
    def __init__(self,dim=256, num_heads=4, expand=2, attn_dropout=0.1, drop_rate=0.1, activation=Swish()):
        super().__init__()
        self.norm1 = nn.LayerNorm(dim)
        self.attn = nn.MultiheadAttention(dim, num_heads, dropout=attn_dropout,batch_first=True)
        self.dropout1 = nn.Dropout(drop_rate)
        self.norm2 = nn.LayerNorm(dim)
        self.linear1 = nn.Linear(dim, dim*expand, bias=False)
        self.linear2 = nn.Linear(dim*expand, dim, bias=False)
        self.dropout2 = nn.Dropout(drop_rate)
        self.activation = activation

    def forward(self, inputs):
        x = self.norm1(inputs)
        x, _ = self.attn(x, x, x)
        x = self.dropout1(x)
        x = x + inputs
        attn_out = x

        x = self.norm2(x)
        x = self.activation(self.linear1(x))
        x = self.linear2(x)
        x = self.dropout2(x)
        x = x + attn_out
        return x

@dataclass
class GraphModelArugments:
    num_opcodes: int = 120
    opcode_dim: int = 64
    node_features: int = 112+opcode_dim
    node_feature_dim:int = 192
    config_features: int = 14
    conf_feature_dim: int = 64

    feature_dropout: float=0.0
    feature_expand: int = 1

    graphsage_in: int = node_feature_dim+conf_feature_dim
    graphsage_hidden: int = graphsage_in

    graphsage_layers: int = 2
    conv_aggregation_type: str = "max"
    mlp_layers: int = 2

    final_dropout: float = 0.0
    embedding_dropout: float = 0.0

    attention_blocks: int = 0
    drop_rate: float = 0.1
    attention_dropout: float = 0.1
    num_heads: int = 4

    is_pair_modeling: bool = False

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

class MLP(nn.Module):
    def __init__(self, input_dim, dims, alpha=0.2,use_bias=True):
        super(MLP, self).__init__()

        layers = []
        dims = [input_dim] + dims  # Add input dimension to the beginning
        for i in range(1, len(dims)):
            layers.append(nn.Linear(dims[i-1], dims[i], bias=use_bias))
            if i < len(dims) - 1:  # Do not append activation for the last layer
                layers.append(nn.LeakyReLU(alpha))
        self.net = nn.Sequential(*layers)

    def forward(self, x):
        return self.net(x)

class GraphSage(torch.nn.Module):
    def __init__(self,arguments: GraphModelArugments):
        super().__init__()
        self.sageconvs = torch.nn.ModuleList([SAGEConv(in_channels=arguments.graphsage_hidden,out_channels=arguments.graphsage_hidden,aggr=arguments.conv_aggregation_type) for _ in range(arguments.graphsage_layers)])
        self.mlps = torch.nn.ModuleList([MLP(input_dim=arguments.graphsage_hidden,dims=[arguments.node_feature_dim]*arguments.mlp_layers) for _ in range(arguments.graphsage_layers)])
        self.prenet = MLP(input_dim=arguments.graphsage_in,dims=[arguments.node_feature_dim]*arguments.mlp_layers)

    def forward(self,node_features, config_features, edges, *args,**kwargs):
        x = node_features
        x = torch.concat([config_features, x],dim=1)
        x = self.prenet(x)
        x = F.leaky_relu(x,negative_slope=0.2)

        for layer,mlps in zip(self.sageconvs,self.mlps):
            y = x
            y = torch.concat([config_features, y], dim=1)
            y = F.leaky_relu(mlps(layer(y,edges)),negative_slope=0.2)
            x += y
        return x

class LayoutGraphModel(torch.nn.Module):
    def __init__(self,arguments: GraphModelArugments):
        super().__init__()
        self.arguments = arguments
        self.opcode_embeddings = torch.nn.Embedding(arguments.num_opcodes,arguments.opcode_dim)
        if arguments.graphsage_layers>0:
            print("Skipping graph layer")
            self.graph_encoder = GraphSage(arguments=arguments)
        else:
            self.graph_encoder = None

        self.node_features_mlp = torch.nn.Sequential(
            torch.nn.Linear(arguments.node_features,arguments.node_features*arguments.feature_expand),
            torch.nn.Dropout(arguments.feature_dropout),
            torch.nn.LeakyReLU(inplace=True),
            torch.nn.Linear(arguments.node_features*arguments.feature_expand,arguments.node_feature_dim),
            torch.nn.LeakyReLU(inplace=True),
        )

        self.config_features_mlp = torch.nn.Sequential(
            torch.nn.Linear(arguments.config_features,arguments.config_features*arguments.feature_expand),
            torch.nn.Dropout(arguments.feature_dropout),
            torch.nn.LeakyReLU(inplace=True),
            torch.nn.Linear(arguments.config_features*arguments.feature_expand,arguments.conf_feature_dim),
            torch.nn.LeakyReLU(inplace=True),
        )

        if arguments.attention_blocks>0:
            self.aggregation_norm = torch.nn.LayerNorm(arguments.graphsage_hidden)

            self.attention_module = torch.nn.Sequential(
                *[
                    TransformerBlock(arguments.graphsage_hidden,arguments.num_heads,attn_dropout=arguments.attention_dropout,drop_rate=arguments.drop_rate) for _ in range(arguments.attention_blocks)
                ]
            )
        else:
            self.attention_module = None
        self.embed_drop = torch.nn.Dropout(arguments.embedding_dropout)
        if not self.arguments.is_pair_modeling:
            self.final_classifier = torch.nn.Sequential(
                torch.nn.Dropout(arguments.final_dropout),
                torch.nn.Linear(arguments.node_feature_dim,1,bias=False)
            )

    def forward(self,node_features, node_config_features,node_separation, node_ops, edges, batches,*args,**kwargs):
        opcode_embed = self.embed_drop(self.opcode_embeddings(node_ops))
        x = torch.cat([node_features,opcode_embed],dim=1)
        x = self.node_features_mlp(x)
        node_config_features = self.config_features_mlp(node_config_features)
        if self.graph_encoder is not None:
            x = self.graph_encoder(x,node_config_features,edges)
        start_idx = 0
        aggregated = [[] for _ in torch.unique(batches)]
        for ns,b in zip(node_separation,batches):
            end_idx = ns
            aggregated[b].append(torch.sum(x[start_idx:end_idx], dim=0))
            start_idx = end_idx
        aggregated = torch.stack([torch.stack(x) for x in aggregated])

        if self.arguments.is_pair_modeling:
            aggregated = self.aggregation_norm(aggregated)
            aggregated_fc = self.attention_module(aggregated)
            return torch.tanh(torch.bmm(aggregated,aggregated_fc.transpose(1,2)))   # This is like calculating the cosine between two vectors. We add 1 to make the value in range [0,2]
        elif self.attention_module is not None:
            aggregated = self.aggregation_norm(aggregated)
            aggregated = self.attention_module(aggregated)

        aggregated = torch.squeeze(self.final_classifier(aggregated),2)
        return aggregated


import fitz
import os
import sys
import tabulate

PDF_PATH = "MSC_Nastran_2022.4_Quick_Reference_Guide.pdf"
dims = os.get_terminal_size()
COLS = dims.columns

def reformat_format(table: list) -> list:
    # Make left adjust with 8 character spacing
    for ind, row in enumerate(table):
        table[ind] = [field.ljust(8) for field in row]
        if ind > 1:
            table[ind] = [''] + table[ind]
    return table

def reformat_describer(table: list, remarks: int) -> list:
    # Remove duplicate headers (if spanning multiple pages)
    while ['Describer', 'Meaning'] in table[1:]:
        ind = table.index(['Describer', 'Meaning'], 2)
        del table[ind]
        remarks -= 1
    # Combine entries and calculate maximum column widths
    maxcols = [len(table[0][0]), len(table[0][1])]
    for ind, row in enumerate(table):
        table[ind] = [row[0]] + [''.join(row[1:])]
        maxcols[0] = max(maxcols[0], len(table[ind][0]))
        maxcols[1] = max(maxcols[1], len(table[ind][1]))
    while ['v','v'] in table:
        ind = table.index(['v','v'])
        del table[ind]
        remarks -= 1
    while ['v', ''] in table:
        ind = table.index(['v',''])
        del table[ind]
        remarks -= 1
    if maxcols[1] > COLS:
        maxcols[1] = COLS - maxcols[0] - 7
    return table, remarks, maxcols

def main(card):
    with fitz.open(PDF_PATH) as doc:
        toc = doc.get_toc()
        for i, section in enumerate(toc):
            if section[1] == card:
                break
        pages = []
        for page in doc.pages(section[2]-1, toc[i+1][2]-1, 1):
            pix = page.get_pixmap()
            imgname = "page-%i.png" % page.number
            pix.save(imgname)
            # os.startfile(imgname)
            text = page.get_text("dict")
            text['blocks'] = sorted(text['blocks'], key=lambda d: d['bbox'][1])
            bbox = []
            img = mpimg.imread(imgname)
            imgplot = plt.imshow(img)
            ax = plt.gca()
            for val in text['blocks']:
                rect = Rectangle(
                    val['bbox'][:2],
                    val['bbox'][2]-val['bbox'][0],
                    val['bbox'][3]-val['bbox'][1],
                    linewidth=1,
                    edgecolor='r',
                    facecolor='none',
                    )
                ax.add_patch(rect)
                bbox.append(val['bbox'])
            pages.append(text['blocks'][1:-3])
            # text['blocks'][0]['lines'][0]['spans'][0]['text']
            # plt.show()

        text = []
        for sections in pages:
            for section in sections:
                tmp = []
                for line in section['lines']:
                    for span in line['spans']:
                        tmp.append(span['text'])
                text.append(tmp)
        # Find Example index
        i = 0
        while 'Example' not in text[i][0]:
            i+=1
        example = i
        # Find Describer index
        while 'Describer' not in text[i][0]:
            i+=1
        describer = i
        # Find Remarks index
        while 'Remarks' not in text[i][0]:
            i+=1
        remarks = i
        # Print card and short description
        print('\n'+':  '.join(text[0])+'\n')
        # Print long description
        print(''.join(text[1])+'\n')
        # Print card format
        print(text[2][0])
        text[3:example] = reformat_format(text[3:example])
        out = tabulate.tabulate(
            text[3:example],
            headers='firstrow',
            tablefmt='fancy_grid',
        )
        print(out+'\n')
        # Print describer table
        text[describer:remarks], remarks, maxcols = reformat_describer(text[describer:remarks], remarks)
        out = tabulate.tabulate(
            text[describer:remarks],
            headers='firstrow',
            tablefmt='fancy_grid',
            maxcolwidths=maxcols,
        )
        print(out+'\n')

if __name__ == "__main__":
    from bulk_data import BULK_DATA
    entry = BULK_DATA(sys.argv[1])
    print(entry)


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

# Python 3.6
# author: EJ Jang
# date: 2018.06.14

# Options - Batch or Backfill (bkfil: False, True)
add_lback_kwarg = dict(add_lback_yr=34, add_lback_qtr=48)
fileName = 'SustG'
mapping = 'worldscope'
# option = 'batch'
# freq = 'W'
import sys
option = sys.argv[1]
freq = sys.argv[2]
print('# Starting Factor - {}_{} ({})'.format(mapping, fileName, freq))

import numpy as np
import pandas as pd
import datetime as dt
import time
import re
from functools import reduce

from batch_utils.utils_dateSeq import batch_sequence
from batch_utils.utils_mapping import get_Mapping, getUnique_TMSRS_CD
from batch_utils.utils_mapping_orig import get_Mapping_orig
from batch_utils.ItemInfo import Item_lst, RatioItem_lst, CurrItem_lst
from batch_utils.common import chunker, chunker_count, chg_to_type, add_mapped_tick
from batch_utils.common import firstCheck_duplicates, secondCheck_columns
from batch_utils.common import check_mapping_df, save_batch
from batch_utils.common import batch_monitor_msg, batch_finish_msg

from batch_utils import WS_retrieve_custom, WS_year, WS_qtr_currToHist, WS_resample
from batch_utils import simple_add, simple_mult, simple_div, simple_subtract
from batch_utils import align_add, align_mult, align_div, align_subtract
from batch_utils import substitute_Value
from batch_utils.WS.WS_histChg import get_HistAvg, get_HistChgAvg

# Date Sequence to be made by this batch
bkfil, rtvStart, seq_DT = batch_sequence(option, freq)

# Getting the Universe in TMSRS_CD ~ Code Map
allSec = getUnique_TMSRS_CD()
codeMap = get_Mapping_orig(mapping)
trim_codeMap = codeMap[codeMap['TMSRS_CD'].isin(allSec)].copy()
trim_codeMap_uniq = trim_codeMap['Code'].unique()

print(trim_codeMap.iloc[:2])
print('\n>>> Total Mapping Securities #: {}'.format(trim_codeMap.shape[0]))
print('>>> Total Performing Securities #: {}'.format(trim_codeMap_uniq.shape[0]))

# Checking Level of Duplicates in codeMap
chk_codeMap = check_mapping_df(trim_codeMap)

DF_ROE_qtr, DF_ROE_yr = pd.DataFrame(), pd.DataFrame()
DF_Payout_qtr, DF_Payout_yr = pd.DataFrame(), pd.DataFrame()
DF_epsg_qtr, DF_epsg_yr = pd.DataFrame(), pd.DataFrame()

# Transform Security List into Batch Chunks
tot_n = chunker_count(trim_codeMap_uniq, 50)
Code_lst_tot = chunker(trim_codeMap_uniq.tolist(), 50)

# Bring needed items
re_item = RatioItem_lst.loc['ROE_ws']
ni_item = Item_lst.loc['NetIncome_EPS']
po_item = RatioItem_lst.loc['Payout_ws']
poc_item = CurrItem_lst.loc['Payout_curr']

st_time = time.time()
for i, Code_lst in enumerate(Code_lst_tot):
    # Get Data
    roe_yr, roe_qtr = WS_retrieve_custom(
        re_item['Item'], re_item['Table'], Code_lst, None, bkfil, **add_lback_kwarg)
    eps_yr, eps_qtr = WS_retrieve_custom(
        ni_item['Item'], ni_item['Table'], Code_lst, 'sum', bkfil, **add_lback_kwarg)

    payout_yr = WS_year(po_item['Item'], po_item['Table'], Code_lst, bkfil, add_lback=34)
    payout_qtr = WS_qtr_currToHist(poc_item['Item'], poc_item['Table'], Code_lst, bkfil, add_lback=48)

    # Qtr
    roe_qtr_ = get_HistAvg(roe_qtr, k=8)
    payout_qtr_ = get_HistAvg(payout_qtr, k=8)
    epsg_qtr = get_HistChgAvg(eps_qtr, k=5, k2=4, growth=True)

    fill_cols = ['FiscalPrd', 'FiscalPrd2', 'CalPrdEndDate', 'Value_']
    roe_qtr_samp = WS_resample(seq_DT, roe_qtr_, fill_cols=fill_cols + ['FILLyr'])
    payout_qtr_samp = WS_resample(seq_DT, payout_qtr_, fill_cols=fill_cols)
    epsg_qtr_samp = WS_resample(seq_DT, epsg_qtr, fill_cols=fill_cols + ['Ratio'])

    DF_ROE_qtr = DF_ROE_qtr.append(roe_qtr_samp)
    DF_Payout_qtr = DF_Payout_qtr.append(payout_qtr_samp)
    DF_epsg_qtr = DF_epsg_qtr.append(epsg_qtr_samp)

    # Year
    roe_yr_ = get_HistAvg(roe_yr, k=2)
    payout_yr_ = get_HistAvg(payout_yr, k=2)
    epsg_yr = get_HistChgAvg(eps_yr, k=2, k2=1, growth=True)

    fill_cols = ['FiscalPrd', 'CalPrdEndDate', 'Value_']
    roe_yr_samp = WS_resample(seq_DT, roe_yr, fill_cols=fill_cols + ['FILLyr'])
    payout_yr_samp = WS_resample(seq_DT, payout_yr, fill_cols=fill_cols + ['FILLyr'])
    epsg_yr_samp = WS_resample(seq_DT, epsg_yr, fill_cols=fill_cols + ['Ratio'])

    DF_ROE_yr = DF_ROE_yr.append(roe_yr_samp, sort=False)
    DF_Payout_yr = DF_Payout_yr.append(payout_yr_samp, sort=False)
    DF_epsg_yr = DF_epsg_yr.append(epsg_yr_samp, sort=False)

    batch_monitor_msg(i, tot_n, st_time)
batch_finish_msg(tot_n, st_time)

DF_ROE_trail = substitute_Value(DF_ROE_yr, DF_ROE_qtr)
DF_Payout_trail = substitute_Value(DF_Payout_yr, DF_Payout_qtr)
DF_epsg_trail = substitute_Value(DF_epsg_yr, DF_epsg_qtr)

DF_ROE_trail = DF_ROE_trail[
    DF_ROE_trail['Value_'].notnull()
    ].sort_values(['Code', 'BASE_DT']).copy()
DF_ROE_trail.loc[
    DF_ROE_trail['Value_'].abs() > 100, 'Value_'] = DF_ROE_trail.loc[
    DF_ROE_trail['Value_'].abs() > 100, 'Value_'].apply(lambda x: 100 * np.sign(x))

DF_Payout_trail.loc[DF_Payout_trail['Value_'] < 0, 'Value_'] = np.nan
DF_Payout_trail = DF_Payout_trail[
    DF_Payout_trail['Value_'].notnull()
    ].sort_values(['Code', 'BASE_DT']).copy()
DF_Payout_trail.loc[DF_Payout_trail['Value_'] > 100, 'Value_'] = 100

DF_epsg_trail = DF_epsg_trail[
    DF_epsg_trail['Value_'].notnull()
    ].sort_values(['Code', 'BASE_DT']).copy()

DF_ROE_trail.reset_index(drop=True, inplace=True)
DF_Payout_trail.reset_index(drop=True, inplace=True)
DF_epsg_trail.reset_index(drop=True, inplace=True)

cols = ['BASE_DT', 'TMSRS_CD', 'Code', 'Value_yr', 'Value_qtr', 'Value_',
        'RGN_TP_CD', 'freq', 'ref']
DF_ROE_trail = add_mapped_tick(DF_ROE_trail, trim_codeMap)[cols]
DF_Payout_trail = add_mapped_tick(DF_Payout_trail, trim_codeMap)[cols]
DF_epsg_trail = add_mapped_tick(DF_epsg_trail, trim_codeMap)[cols]

DF_ROE_trail['StyleName'] = 'ROE_l2yr'
DF_Payout_trail['StyleName'] = 'Payout_l2yr'
DF_epsg_trail['StyleName'] = 'EPSg_l2yr'

#*------------
secondCheck_columns(DF_ROE_trail, DF_Payout_trail, DF_epsg_trail)
#*------------

DF = reduce(
    lambda x, y: pd.DataFrame.append(x, y, sort=False),
    [DF_ROE_trail, DF_Payout_trail])
DF.reset_index(drop=True, inplace=True)

# Save!
save_batch(bkfil, DF, mapping, fileName + '_ROEnPayout')

# Save!
save_batch(bkfil, DF_epsg_trail, mapping, fileName + '_EPSg')

from batch_utils.fill_monitor import print_fillReport
out = print_fillReport(bkfil, freq, DF)
out = print_fillReport(bkfil, freq, DF_epsg_trail)

# <<Sustainable Growth Script>>
dir_ = 'save_total' if bkfil else 'save_batch'
DF_IBES_Payout = pd.read_pickle('{}/IBES_refIBES_Payout.p'.format(dir_))
DF_IBES_ROE = pd.read_pickle('{}/IBES_refIBES_ROE.p'.format(dir_))

# Merge IBES with Worldscope for (normalized) Payout & ROE (comb. average)
TMP = DF_IBES_Payout[
    ['BASE_DT', 'TMSRS_CD', 'Payout_avg']
    ].rename(columns={'Payout_avg': 'Value_1'}).copy()
DF_Payout_norm = pd.merge(
    DF_Payout_trail, TMP, on=['BASE_DT', 'TMSRS_CD'], how='left')
DF_Payout_norm['Value_norm'] = DF_Payout_norm.apply(
    lambda x: (x['Value_'] + x['Value_1']) / 2 if pd.notnull(x['Value_1'])
    else x['Value_'], axis=1)

TMP = DF_IBES_ROE[
    ['BASE_DT', 'TMSRS_CD', 'ROE_avg']
    ].rename(columns={'ROE_avg': 'Value_1'}).copy()
DF_ROE_norm = pd.merge(
    DF_ROE_trail, TMP, on=['BASE_DT', 'TMSRS_CD'], how='left')
DF_ROE_norm['Value_norm'] = DF_ROE_norm.apply(
    lambda x: (x['Value_'] + x['Value_1']) / 2 if pd.notnull(x['Value_1'])
    else x['Value_'], axis=1)

# Calculate Sustainable Growth Factor
TMP0 = DF_ROE_norm[
    ['BASE_DT', 'TMSRS_CD', 'Value_norm']].rename(
    columns={'Value_norm': 'ROE_norm'})
TMP1 = DF_Payout_norm[
    ['BASE_DT', 'TMSRS_CD', 'Value_norm']].rename(
    columns={'Value_norm': 'Payout_norm'})

DF_SustG_tot = pd.merge(TMP0, TMP1, on=['BASE_DT', 'TMSRS_CD'])
DF_SustG_tot['Value_'] = DF_SustG_tot['ROE_norm'] * (
    1 - DF_SustG_tot['Payout_norm'] / 100)
DF_SustG_tot['StyleName'], DF_SustG_tot['freq'] = 'SustG', None
DF_SustG_tot['Code'], DF_SustG_tot['RGN_TP_CD'] = None, None
#*------------
secondCheck_columns(DF_SustG_tot, DF)
#*------------

# Save!
save_batch(bkfil, DF_SustG_tot, 'comb', fileName)
out = print_fillReport(bkfil, freq, DF_SustG_tot, chk_col='Value_')


from django.contrib import admin
from import_export import resources
from import_export.admin import ImportExportModelAdmin
from recipes.models import Cart, Ingredient, IngredientAmount, Recipe, Tag
from users.models import Follow, User

class UserResource(resources.ModelResource):
    class Meta:
        model = User
        fields = (
            'id',
            'username',
            'email',
            'first_name',
            'last_name',
            'password',
        )

class TagResource(resources.ModelResource):

    class Meta:
        model = Tag
        fields = (
            'color',
            'name',
            'slug',
            'id'
        )

class IngredientAmountResource(resources.ModelResource):

    class Meta:
        model = IngredientAmount
        fields = (
            'recipe',
            'ingredient',
            'amount',
        )

@admin.register(IngredientAmount)
class IngredientAmountAdmin(ImportExportModelAdmin):
    resource_classes = [IngredientAmountResource]
    list_display = (
        'recipe',
        'ingredient',
        'amount',
    )

class CartResource(resources.ModelResource):

    class Meta:
        model = Cart
        fields = (
            'recipe',
            'user',
            'date_added',
        )

@admin.register(Cart)
class CartAdmin(ImportExportModelAdmin):
    resource_classes = [CartResource]
    list_display = (
        'recipe',
        'user',
        'date_added',
    )

@admin.register(Tag)
class TagAdmin(ImportExportModelAdmin):
    resource_classes = [TagResource]
    list_display = (
        'color',
        'name',
        'slug',
        'id'
    )

class RecipeResource(resources.ModelResource):

    class Meta:
        model = Recipe
        fields = (
            'id',
            'name',
            'author',
            'tags',
            'ingredients',
            'slug',
            'pub_date',
            'image',
            'text',
            'cooking_time',
        )

@admin.register(Recipe)
class RecipeAdmin(ImportExportModelAdmin):
    resource_classes = [RecipeResource]
    list_display = (
        'name',
        'author',
        'favourite_count',
    )
    list_filter = ('name', 'author', 'tags')

    def favourite_count(self, obj):
        return obj.in_favourites.count()

class IngredientResource(resources.ModelResource):

    class Meta:
        model = Ingredient
        fields = (
            'id',
            'name',
            'measurement_unit',
        )

@admin.register(Ingredient)
class IngredientsAdmin(ImportExportModelAdmin):
    resource_classes = [IngredientResource]
    list_display = (
        'name',
        'measurement_unit',
    )
    list_filter = ('name',)

@admin.register(User)
class UserAdmin(ImportExportModelAdmin):
    resource_classes = [UserResource]
    list_display = (
        'username',
        'email',
        'first_name',
        'last_name',
        'password',
    )
    list_filter = ('username', 'email')

class FollowResource(resources.ModelResource):

    class Meta:
        model = Follow
        firleds = (
            'author',
            'user',
        )

@admin.register(Follow)
class FollowAdmin(ImportExportModelAdmin):
    resource_classes = [FollowResource]
    list_display = (
        'author',
        'user',
    )


from flask import Blueprint, render_template, session, render_template_string, redirect, url_for
from app.models import UserSimple
from app.models import User, Role

from app import db

from flask_security import Security, SQLAlchemyUserDatastore, auth_required, hash_password, login_required

user_datastore = SQLAlchemyUserDatastore(db, User, Role)

from flask_security.models import fsqla_v3 as fsqla

from flask_login import current_user

users_bp = Blueprint('users_bp', __name__)

@users_bp.route('/app/users/getall')
def getallusers():
    users = UserSimple.get_users()
    return render_template('users_simple.html', users=users)

@users_bp.route('/app/users/setsession')
def setsession():
    userid = session['_user_id']
    all_ret = User.get_user(userid)
    email_ret = all_ret.email
    session['useremail'] = all_ret.email
    return render_template_string('hello {{ what }}', what=email_ret)

@users_bp.route('/app/users/getusername')
def getusername():
    userid = session['_user_id']
    username_full = User.get_username(userid)
    return render_template_string('hello {{ what }}', what=userid)

@users_bp.route('/app/user/removeself', methods=['GET', 'POST'])
@login_required
def remove():
    userid = session['_user_id']
    delete_user = User.query.filter_by(fs_uniquifier=userid).first()
    db.session.delete(delete_user)
    db.session.commit()
    return redirect(url_for('home_bp.home'))


import requests
import whisper
import torch
from pydub import AudioSegment
from io import BytesIO
import io
import queue
import threading
import datetime
import os
import gradio as gr

import matplotlib as mpl
font_cache_path = mpl.get_cachedir() + '/fontList.cache'
print(font_cache_path)
#%rm $font_cache_path

# Step 1: Get the radio stream
stream_url = "http://stream.zeno.fm/y9y2bhvzs4zuv"  # Your stream URL

# Set inference device
device = "cuda" if torch.cuda.is_available() else "cpu"

# Set language
language_whisper = "english"

model_fp32 = whisper.load_model(
    name="small",
    device=device)

# Create a queue to store the audio files
audio_queue = queue.Queue()

# Create placeholders for the audio player, log text area, and transcript text area
log_text_area = gr.outputs.Textbox(label="Log")
transcript_text_area = gr.outputs.Textbox(label="Transcript")
audio_player = gr.outputs.Audio(type='filepath', label="Audio")

# Function to transcribe audio files
def transcribe_audio():
    while True:
        # Get the next audio file from the queue
        audio_file = audio_queue.get()
        print(audio_file)
        print("start transcribe")

        # Log the start of transcription
        gr.set_output(log_text_area="transcription start")

        # Transcribe the audio
        result = model_fp32.transcribe(audio_file)

        # Update the audio player and the text box
        audio_player.audio(audio_file)
        gr.set_output(transcript_text_area=result["text"])
        gr.set_output(log_text_area="transcription complete")

        # Log the end of transcription
        gr.set_output(log_text_area="transcription complete of " + audio_file)
        # Mark the task as done
        audio_queue.task_done()

# Start the transcription thread
transcription_thread = threading.Thread(target=transcribe_audio)
transcription_thread.start()

# Download the stream
response = requests.get(stream_url, stream=True)

# Create a buffer for the incoming audio data
buffer = BytesIO()

gr.set_output(log_text_area="Starting stream processing")

# Process the stream in chunks of 10 seconds
for block in response.iter_content(1024):
    # Write the audio data to our buffer
    buffer.write(block)
    # If we have 10 seconds of audio data
    if buffer.tell() >= 10 * 1024 * 100:
        gr.set_output(log_text_area="Saving audio file")
        # Get the current datetime
        now = datetime.datetime.now()

        # Create a directory for the audio files
        os.makedirs('audio', exist_ok=True)

        # Create a filename with the datetime and directory path
        filename = f'audio/stream_{now.strftime("%Y%m%d_%H%M%S")}.wav'

        # Save the buffer to a file
        with open(filename, 'wb') as f:
            f.write(buffer.getvalue())

        # Add the filename to the queue
        audio_queue.put(filename)

        # Log the creation of the audio file
        gr.set_output(log_text_area="Created audio file " + filename)

        # Clear the buffer
        buffer.seek(0)
        buffer.truncate()


from django.conf.urls import url

from FeeApp import views

urlpatterns = [
    url(r'^fee_list/', views.fee_list, name='fee_list'),
    url(r'^fee_modi/', views.fee_modi, name='fee_modi'),
    url(r'^fee_detail/', views.fee_detail, name='fee_detail'),
    url(r'^fee_add/', views.fee_add, name='fee_add'),
    url(r'^get_cost_list/', views.AllCostView.as_view(), name='get_cost_list'),
    url(r'^get_cost/', views.CostView.as_view(), name='get_cost'),
    url(r'^add_cost/', views.add_cost, name='add_cost'),
    url(r'^update_to_cost_status/', views.update_to_cost_status, name='update_to_cost_status'),
    url(r'^update_to_cost/', views.update_to_cost, name='update_to_cost'),
    url(r'^delete_to_cost/', views.delete_to_cost, name='delete_to_cost'),
]


import random
import numpy as np
import librosa
import nlpaug.augmenter.audio as naa

def loudness(
    sig: np.ndarray,
    augment_times: int,
    factor_low: int,
    factor_high: int
) -> list:
    """Changes the loudness of the signal.

    Args:
        sig: Input signal.
        augment_times: Number of times to augment original signal.
        factor_low: Factor to change the lower loudness of the signal.
        factor_high: Factor to change the upper loudness of the signal.

    Returns:
        loud_sig: Returns the loudness changed signal.
    """

    loud_sig = []
    for i in range(augment_times):
        factor = tuple(random.uniform(factor_low, factor_high)
                       for i in range(2))
        aug = naa.LoudnessAug(factor=factor)
        loud_sig.append(np.array(aug.augment(sig)).flatten())
    return loud_sig

def time_stretch(
    signal: np.ndarray,
    augment_times: int,
    factor: float
) -> list:
    """Changes the speed of the signal.

    Args:
        signal: Input signal.
        augment_times: Number of times to augment original signal.
        factor: Factor to change the speed of the signal.

    Returns:
        stretched_sig: Returns the speed changed signal.
    """

    stretched_signal = []
    for i in range(augment_times):
        stretched_signal.append(librosa.effects.time_stretch(signal, factor))
        factor = np.random.uniform(0.1, 1)
    return stretched_signal

def pitch_shift(
        signal: np.ndarray,
        augment_times: int,
        sr: int,
        factor: tuple,
        zone: tuple = (0, 1),
        coverage: int = 1):
    """Changes the pitch of the signal.

    Args:
        signal: Input signal.
        augment_times: Number of times to augment original signal.
        sr: Sampling rate of the input signal.
        factor: Factor to change the pitch of the signal.
        zone: Range of pitch shift. Default value is (0, 1).
        coverage: Percentage of audio to apply pitch shift. Default value is 1.

    Returns:
        pitched_sig: Returns the pitch changed signal.
    """

    pitched_signal = []
    for i in range(augment_times):
        pitched_signal.append(naa.PitchAug(
            sampling_rate=sr, zone=zone, coverage=coverage,
            factor=factor).augment(signal)[0])
        factor = np.random.uniform(0, 50, size=2)
        factor = np.sort(factor)
    return pitched_signal


class Scanner:
    current = 0

    def scan(self, line):
        data = []

        def isValid(pos):
            return pos < len(line)

        def isDigit(pos):
            return line[pos].isdigit()

        def isAlpha():
            return line[self.current].isalpha()

        def number():
            num = 0
            while isValid(self.current) and isDigit(self.current):
                num = num * 10 + int(line[self.current])
                self.current += 1
            data.append(("INTEGER", num))

        def identifier():
            id = ""
            while isValid(self.current) and isAlpha():
                id += line[self.current]
                self.current += 1

            if id == "and":
                data.append(("AND", None))
            elif id == "or":
                data.append(("OR", None))
            elif id == "not":
                data.append(("NOT", None))
            elif id == "True":
                data.append((True, None))
            elif id == "False":
                data.append((False, None))
            else:
                data.append(("IDENTIFIER", id))

        while self.current < len(line):
            if line[self.current] == '+':
                data.append(("PLUS", None))
                self.current += 1
            elif line[self.current] == '-':
                data.append(("MINUS", None))
                self.current += 1
            elif line[self.current] == '*':
                data.append(("MULTIPLY", None))
                self.current += 1
            elif line[self.current] == '/':
                data.append(("DIVIDE", None))
                self.current += 1
            elif line[self.current] == '>':
                if isValid(self.current + 1) and line[self.current + 1] == '=':
                    data.append(("GREATER_EQUAL", None))
                    self.current += 2
                else:
                    data.append(("GT", None))
                    self.current += 1
            elif line[self.current] == '<':
                if isValid(self.current + 1) and line[self.current + 1] == '=':
                    data.append(("LESS_EQUAL", None))
                    self.current += 2
                else:
                    data.append(("LT", None))
                    self.current += 1
            elif line[self.current] == '=':
                if isValid(self.current + 1) and line[self.current + 1] == '=':
                    data.append(("EQUAL_EQUAL", None))
                    self.current += 2
                else:
                    data.append(("EQUAL", None))
                    self.current += 1
            elif line[self.current] == '!':
                if isValid(self.current+1) and line[self.current+1] == '=':
                    data.append(("NOT_EQUAL", None))
                    self.current += 2

            elif isDigit(self.current):
                number()

            elif isAlpha():
                identifier()

            elif line[self.current] == ' ':
                self.current += 1

            else:
                raise Exception("Invalid character")
        self.current = 0
        return data

class Parser:
    def __init__(self):
        self.data = []

    def parse(self, tokens):
        current = 0

        def isValid(pos):
            return pos < len(tokens)

        def isConstant(token):
            return token[0] == "INTEGER"

        def isVariable(token):
            return token[0] == "IDENTIFIER"

        def isBinaryExpression():
            if isValid(current+2) and isValid(current+3) and isValid(current+4):
                return True
            return False

        def findTuple(x):
            for v in self.data:
                if type(v) == tuple:
                    if v[0] == x[1]:
                        return v[1]
            raise Exception("Variable not found")

        def operateBinary(op, ta, tb):
            t1 = 0
            t2 = 0
            if isVariable(ta):
                t1loc = findTuple(ta)
                t1 = self.data[t1loc]
            else:
                t1 = ta[1]
            if isVariable(tb):
                t2loc = findTuple(tb)
                t2 = self.data[t2loc]
            else:
                t2 = tb[1]

            if op == "PLUS":
                return t1+t2
            elif op == "MINUS":
                return t1-t2
            elif op == "MULTIPLY":
                return t1*t2
            elif op == "DIVIDE":
                return t1//t2
            elif op == "GT":
                return t1 > t2
            elif op == "LT":
                return t1 < t2
            elif op == "GREATER_EQUAL":
                return t1 >= t2
            elif op == "LESS_EQUAL":
                return t1 <= t2
            elif op == "EQUAL_EQUAL":
                return t1 == t2
            elif op == "NOT_EQUAL":
                return t1 != t2
            elif op == "AND":
                return t1 and t2
            elif op == "OR":
                return t1 or t2

        def isUnaryExpression():
            if isValid(current+2) and isValid(current+3):
                return True
            return False

        def operateUnary(op, ta):
            t1 = 0
            if isVariable(ta):
                t1loc = findTuple(ta)
                t1 = t1loc[1]
            else:
                t1 = ta[1]

            if op == "MINUS":
                return -t1
            elif op == "NOT":
                return not t1

        def insert(i):
            if type(i) == int:
                if i in self.data:
                    return self.data.index(i)
                self.data.append(i)
                return len(self.data)-1
            elif isConstant(i):
                if i[1] in self.data:
                    return self.data.index(i[1])
                self.data.append(i[1])
                return len(self.data)-1
            else:
                tuploc = findTuple(i)
                return insert(self.data[tuploc])

        def replace(x, j):
            found = False
            for (ind, d) in enumerate(self.data):
                if type(d) == tuple:
                    if d[0] == x:
                        self.data[ind] = (x, j)
                        found = True
            if not found:
                self.data.append((x, j))

        while current < len(tokens):
            token = tokens[current]
            if isVariable(token):
                if isValid(current+1) and tokens[current+1][0] == 'EQUAL':
                    if isBinaryExpression():
                        insert(tokens[current+2])
                        insert(tokens[current+4])
                        res = operateBinary(
                            tokens[current+3][0], tokens[current+2], tokens[current+4])
                        pos = insert(res)
                        replace(token[1], pos)
                        current += 5
                    elif isUnaryExpression():
                        insert(tokens[current+1])
                        res = operateUnary(
                            tokens[current+1][1], tokens[current+1])
                        pos = insert(res)
                        replace(token[1], pos)
                        current += 4
                    elif isConstant(tokens[current+2]):
                        pos = insert(tokens[current+2])
                        replace(token[1], pos)
                        current += 3
                    elif isVariable(tokens[current+2]):
                        pos = findTuple(tokens[current+2])
                        replace(token[1], pos)
                        current += 3
                    else:
                        raise Exception("Invalid expression")

if __name__ == "__main__":
    line1 = "q = 6"
    line2 = "p = q+5"
    line3 = "r = p"

    scanner = Scanner()
    t1 = scanner.scan(line1)
    print("t1 = ", t1)
    t2 = scanner.scan(line2)
    print("t2 = ", t2)
    t3 = scanner.scan(line3)
    print("t3 = ", t3)

    parser = Parser()
    d1 = parser.parse(t1)
    print("d1 = ", parser.data)
    d2 = parser.parse(t2)
    print("d2 = ", parser.data)
    d3 = parser.parse(t3)
    print("d3 = ", parser.data)


from typing import Dict, Optional, Sequence, Tuple, Union

import hydra
import omegaconf
import torch
from torch import nn as nn
from torch.nn import functional as F

from cmrl.models.util import gaussian_nll
from cmrl.models.layers import ParallelEnsembleLinearLayer, truncated_normal_init
from cmrl.models.networks.mlp import EnsembleMLP
from cmrl.models.util import to_tensor

class TransitionConditionalMutualInformationTest(EnsembleMLP):
    _MODEL_FILENAME = "conditional_mutual_information_test.pth"

    def __init__(
        self,
        # transition info
        obs_size: int,
        action_size: int,
        # algorithm parameters
        ensemble_num: int = 7,
        elite_num: int = 5,
        residual: bool = True,
        learn_logvar_bounds: bool = False,
        # network parameters
        num_layers: int = 4,
        hid_size: int = 200,
        activation_fn_cfg: Optional[Union[Dict, omegaconf.DictConfig]] = None,
        # others
        device: Union[str, torch.device] = "cpu",
    ):
        super().__init__(
            ensemble_num=ensemble_num,
            elite_num=elite_num,
            device=device,
        )
        self.obs_size = obs_size
        self.action_size = action_size
        self.residual = residual
        self.learn_logvar_bounds = learn_logvar_bounds

        self.num_layers = num_layers
        self.hid_size = hid_size

        self.parallel_num = self.obs_size + self.action_size + 1

        self._input_mask = 1 - torch.eye(self.parallel_num, self.obs_size + self.action_size).to(self.device)

        def create_activation():
            if activation_fn_cfg is None:
                return nn.ReLU()
            else:
                return hydra.utils.instantiate(activation_fn_cfg)

        hidden_layers = [
            nn.Sequential(
                self.create_linear_layer(obs_size + action_size, hid_size),
                create_activation(),
            )
        ]
        for i in range(num_layers - 1):
            hidden_layers.append(
                nn.Sequential(
                    self.create_linear_layer(hid_size, hid_size),
                    create_activation(),
                )
            )
        self.hidden_layers = nn.Sequential(*hidden_layers)

        self.mean_and_logvar = self.create_linear_layer(hid_size, 2 * self.obs_size)
        self.min_logvar = nn.Parameter(
            -10 * torch.ones(self.parallel_num, 1, 1, self.obs_size), requires_grad=learn_logvar_bounds
        )
        self.max_logvar = nn.Parameter(
            0.5 * torch.ones(self.parallel_num, 1, 1, self.obs_size), requires_grad=learn_logvar_bounds
        )

        self.apply(truncated_normal_init)
        self.to(self.device)

    def create_linear_layer(self, l_in, l_out):
        return ParallelEnsembleLinearLayer(l_in, l_out, parallel_num=self.parallel_num, ensemble_num=self.ensemble_num)

    @property
    def input_mask(self):
        return self._input_mask

    def mask_input(self, x: torch.Tensor) -> torch.Tensor:
        assert x.ndim == 4
        assert self._input_mask.ndim == 2
        input_mask = self._input_mask[:, None, None, :]
        return x * input_mask

    def forward(
        self,
        batch_obs: torch.Tensor,  # shape: (parallel_num, )ensemble_num, batch_size, obs_size
        batch_action: torch.Tensor,  # shape: ensemble_num, batch_size, action_size
    ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
        assert len(batch_action.shape) == 3 and batch_action.shape[-1] == self.action_size

        batch_action = batch_action.repeat((self.parallel_num, 1, 1, 1))
        if len(batch_obs.shape) == 3:  # non-repeat or first repeat
            batch_obs = batch_obs.repeat((self.parallel_num, 1, 1, 1))

        batch_input = torch.concat([batch_obs, batch_action], dim=-1)

        masked_input = self.mask_input(batch_input)
        hidden = self.hidden_layers(masked_input)
        mean_and_logvar = self.mean_and_logvar(hidden)

        mean = mean_and_logvar[..., : self.obs_size]
        logvar = mean_and_logvar[..., self.obs_size :]
        logvar = self.max_logvar - F.softplus(self.max_logvar - logvar)
        logvar = self.min_logvar + F.softplus(logvar - self.min_logvar)

        if self.residual:
            mean += batch_obs

        return mean, logvar

    def get_nll_loss(self, model_in: Dict[(str, torch.Tensor)], target: torch.Tensor) -> torch.Tensor:
        pred_mean, pred_logvar = self.forward(**model_in)
        target = target.repeat((self.parallel_num, 1, 1, 1))

        nll_loss = gaussian_nll(pred_mean, pred_logvar, target, reduce=False)
        nll_loss += 0.01 * (self.max_logvar.sum() - self.min_logvar.sum())
        return nll_loss


"""
TODO:
    [ ] Interact with API
        [ ] Investigate Facebook API
        [ ] Investigate Discord API
    [ ] create "calendar-to-post" pipeline
"""

from __future__ import print_function

import datetime
import os.path

# = Google API =

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# = Discord API =

import discord

# = Facebook API =

import requests

# Important variables that are private
from var import *
# `var` file contains the following variables:
#   BKB_CAL_ID [string] -> Identifying string for a particular calendar

# If modifying these scopes, delete the file token.json.

def Get_2w_google_api():
    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """

    SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
    creds = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('./tolken/token.json'):
        creds = Credentials.from_authorized_user_file('./tolken/token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                './tolken/credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('./tolken/token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('calendar', 'v3', credentials=creds)

        # Call the Calendar API
        now_datetime = datetime.datetime.utcnow()
        now = now_datetime.isoformat() + 'Z'  # 'Z' indicates UTC time
        print('Upcoming events for the next 2 weeks')
        events_result = service.events().list(calendarId= BKB_CAL_ID , timeMin=now,
                                              timeMax= (now_datetime + datetime.timedelta(weeks=2)).isoformat() + 'Z', singleEvents=True,
                                              orderBy='startTime').execute()
        events = events_result.get('items', [])

        if not events:
            print('No upcoming events found.')
            return

        # Prints the start and name of the next 10 events
        return events

    except HttpError as error:
        print('An error occurred: %s' % error)
        return None

def send_to_facebook(events: list[dict]) -> Exception | None:

    page_id_1 = BKB_FACEBOOK_PAGE_ID
    facebook_access_token_1 = BKB_FACEBOOK_PAGE_TOKEN

    msg: list[str] = message_generator(events=events)

    post_url = 'https://graph.facebook.com/{}/feed'.format(page_id_1) # Figure out if correct link.
    payload = {
    'message': msg,
    'access_token': facebook_access_token_1
    }
    r = requests.post(post_url, data=payload)
    print(r.text)

    return None

async def send_to_discord(events: list[dict]) -> list[Exception]:
    """
        events er en dictonary med alle relevante envents for den kommende uke[^1]

        [^1] kommende uke er 7 dager etter den dagen hvor programmet hentet eventer.
    """

    if "discord_announcment_client" not in globals():
        print("Client has not been inisiated")
        return NameError("func 'send_to_discord': 'discord_announcment_client' does not exist.")
    # lim inn kode for å sende en str til "annonser", pass på formatering og at det er på riktig kanal
    # IKKE RAISE ERROR! Programmet må kjøre kontinuelig heletiden. Heller returner en Error isteded.
    ret_messages = list()
    for event in message_generator(events):
        try:
            await discord_announcment_client.send(event)
        except Exception as err:
            ret_messages.append(err)

    return ret_messages

def main():
    pass

def message_generator(events: dict) -> list[str]:
    """
        Generates a string meant to be sendt to end-clients.
        Fokuserer på 3 nøkkelord i root:
            - item["description"] -> str
            - item["start"]       -> dict
            - item["end"]         -> dict
        NOTE:
            Det er mange nøkkelord vi kan bruke... Dette krever lengere undersøkelse etter vi går live.
    """
    messages = list()
    for item in events: # is going to be replaced by a "standard" function so we can have fledxible text generation
        start = datetime.datetime.fromisoformat(item["start"])
        end   = datetime.datetime.fromisoformat(item["end"])
        top    = "date: {}\nStart: {} -> End: {}".format(start.date(),":".join(str(start.time()).split(":")[:2]),":".join(str(end.time()).split(":")[:2]))
        middel = item["description"]
        end    = ""

        messages.append("--------------".join([top,middel,end]))

    return messages

def create_contact() -> Exception | None:
    """
        Creates the nessesary connections to services.
        services:
            - Google calendar API (håndter et annet sted, se "Get_2w_google_api()" )
            - Facebook Graph API (muligens trenger ikke?)
            - Discord API
    """
    global discord_announcment_client, facebook_client

    discord_announcment_client = discord.Client().get_guild(BKB_SERVER_ID).get_channel(BKB_ANNOUNCMENT_CHANNEL_ID)
    facebook_client = ""

    return None

def time_diff(date1: datetime.datetime, date2: datetime.datetime) -> Exception | datetime.timedelta:
    diff = date2 - date1

    if datetime.timedelta() < diff < datetime.timedelta(hour = 24):
        return diff
    elif diff < datetime.timedelta():
        return datetime.timedelta()
    elif diff > datetime.timedelta(days=1):
        return datetime.timedelta(days=1)
    else:
        return ValueError("The difference is not messurable.")

if __name__ == "__main__":
    create_contact()
    send_to_discord({})


from typing import List

class Solution:
    def getWinner(self, arr: List[int], k: int) -> int:
        if k == 1:
            return max(arr[0], arr[1])
        if k >= len(arr):
            return max(arr)

        current_winner = arr[0]
        consecutive_wins = 0

        for i in range(1, len(arr)):
            if current_winner > arr[i]:
                consecutive_wins += 1
            else:
                current_winner = arr[i]
                consecutive_wins = 1

            if consecutive_wins == k:
                return current_winner

        return current_winner

if __name__ == '__main__':
    solution = Solution()

    # Test Case 1
    arr1 = [2, 1, 3, 5, 4, 6, 7]
    k1 = 2
    result1 = solution.getWinner(arr1, k1)
    print("Result 1:", result1)

    # Test Case 2
    arr2 = [3, 2, 1]
    k2 = 10
    result2 = solution.getWinner(arr2, k2)
    print("Result 2:", result2)


# -*- coding:utf-8 -*-
from __future__ import print_function, unicode_literals, division
from io import open
import glob
import os
import unicodedata
import string
import argparse

import torch
import torch.nn as nn
import random

import time
import math

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

all_letters = string.ascii_letters + " .,;'-"
n_letters = len(all_letters) + 1  # plus EOS marker

category_line = {}
all_category = []
n_categories = 0
train_category = None

save_dir="data/save"

def parse():
    parser = argparse.ArgumentParser(description="rnn model for name generator")
    parser.add_argument('-it', '--iteration', type=int, default=100000, help="iterations of training")
    parser.add_argument('-p', '--print_every', type=int, default=5000, help="print the training result every iterations")
    parser.add_argument('-pl', '--plot_every', type=int, default=500, help="plotting the loss every iterations")
    parser.add_argument('-s', '--save_every', type=int, default=5000, help="save model params every iterations")
    parser.add_argument('-tr', '--train', action='store_true', help="Train the model with dataset")
    parser.add_argument('-te', '--test', action='store_true', help="test the saved model")
    parser.add_argument('-lm', '--load_model', help="load the saved model(e.g.model/name_generator_model_100000.tar)")
    parser.add_argument('-fn', '--filename', help="dataset file for training (e.g.data/names/*.txt)")
    parser.add_argument('-sl', '--single_letter', help="generate name with a letter, e.g. -sl A")
    parser.add_argument('-ml', '--multi_letters', help="generate names with letters, e.g. -ml ACD")
    parser.add_argument('-lr', '--learning_rate', type=float, default=0.0001, help="learning rate for training")
    parser.add_argument('-c', '--category', type=str, choices=['Arabic', 'Chinese', 'Czech', 'Dutch', 'English',
                                                               'French', 'German', 'Greek', 'Irish', 'Italian',
                                                               'Japanese', 'Korean', 'Polish', 'Portuguese', 'Russian',
                                                               'Scottish', 'Spanish', 'Vietnamese'],
                        help="language category to train or test")

    args = parser.parse_args()
    return args

# search specify file type
def findFiles(path):
    return glob.glob(path)

# turn unicode string to ascii plain, thanks to https://stackoverflow.com/a/518232/2809427
def Unicode2Ascii(s):
    return "".join(
        c for c in unicodedata.normalize("NFD", s)
        if c in all_letters
        and "MN" != unicodedata.category(c))

# read line from file and split by '\n'
def readLines(filePath):
    lines = open(filePath, encoding="utf-8").read().strip().split('\n')
    return [Unicode2Ascii(line) for line in lines]

# create dataset from files
"""
args: filename with regular expression like data/names/*.txt
"""
def loadTrainingDataset(filenames):
    global category_line
    global all_category
    global n_categories
    for fileName in findFiles(filenames):
        category = os.path.splitext(os.path.basename(fileName))[0]
        all_category.append(category)
        lines = readLines(fileName)
        category_line[category] = lines

    n_categories = len(all_category)
    if n_categories == 0:
        raise RuntimeError('Data not found. Make sure that you downloaded data '
        'from https://download.pytorch.org/tutorial/data.zip and extract it to '
        'the current directory.')

   # print(all_category)
    return category_line, all_category, n_categories

class RNN(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(RNN, self).__init__()
        self.hidden_size = hidden_size
        self.i2h = nn.Linear(n_categories + input_size + hidden_size, hidden_size)
        self.i2o = nn.Linear(n_categories + input_size + hidden_size, output_size)
        self.o2o = nn.Linear(output_size + hidden_size, output_size)
        self.dropout = nn.Dropout(0.1)

        self.softmax = nn.LogSoftmax(dim=1)

    def forward(self, categories, input, hidden):
        in_combined = torch.cat((categories, input, hidden), dim=1)
        hidden = self.i2h(in_combined)
        output = self.i2o(in_combined)

        out_combined = torch.cat((output, hidden), dim=1)
        output = self.o2o(out_combined)

        output = self.softmax(self.dropout(output))
        return output, hidden

    def InitHidden(self):
        return torch.zeros(1, self.hidden_size)

# prepare data for training
# choose a item from list randomly
def randomChoice(l):
    return l[random.randint(0, len(l) -1)]

# choose training data pairs
def randomTrainingPairs(category=None):
    global train_category
    if category is None:
        category = randomChoice(all_category)
    train_category = category
    name = randomChoice(category_line[category])
    return category, name

# one-hot vector for category
def CategoryTensor(category):
    tensor = torch.zeros(1, n_categories)
    idx = all_category.index(category)
    tensor[0][idx] = 1
    return tensor

# one-hot matrix for input, ont include EOS
def InputTensor(line):
    tensor = torch.zeros(len(line), 1, n_letters)
    for idx in range(len(line)):
        letter = line[idx]
        tensor[idx][0][all_letters.find(letter)] = 1

    return tensor

# longTensor for second letter to EOS
def TargetTensor(line):
    letter_indexes = [all_letters.find(line[idx]) for idx in range(1, len(line))]
    letter_indexes.append(n_letters - 1)  # add index of EOS
    return torch.LongTensor(letter_indexes)

# make category, input and target tensors from random category, line pairs

def randomTrainingSample(category=None):
    category, line = randomTrainingPairs(category)
    category_tensor = CategoryTensor(category)
    input_line_tensor = InputTensor(line)
    target_line_tensor = TargetTensor(line)

    return category_tensor, input_line_tensor, target_line_tensor

def train(category_tensor, input_line_tensor, target_line_tensor):
    target_line_tensor.unsqueeze_(-1)
    hidden = rnn.InitHidden()
    rnn.zero_grad()
    loss = 0

    for i in range(input_line_tensor.size(0)):
        output, hidden = rnn(category_tensor, input_line_tensor[i], hidden)
        per_loss = criterion(output, target_line_tensor[i])

        loss += per_loss

    loss.backward()

    for p in rnn.parameters():
        p.data.add_(-lr, p.grad.data)

    return output, loss.item() / input_line_tensor.size(0)

def TimeCalulate(since):
    now = time.time()
    interval = now - since
    m = math.floor(interval/60)
    s = interval - 60 * m
    return "%dm %ds" %(m,s)

def runTrainingModel(n_iters=100000, print_every=5000, plot_every=500, save_every=5000, category=None, modelFile=None):
    all_losses = []
    total_loss = 0 # Reset every plot_every iters
    start = time.time()

    checkpoint = None
    start_iteration = 1
    if modelFile:
        checkpoint = torch.load(modelFile)
        rnn.load_state_dict(checkpoint["rnn"])
        start_iteration = checkpoint["iteration"]

    for iter in range(start_iteration, n_iters + 1):
        output, loss = train(*randomTrainingSample(category))
        total_loss += loss

        if iter % print_every == 0:
            print('%s (%d %d%%) %.4f' % (TimeCalulate(start), iter, iter / n_iters * 100, loss))

        if iter % plot_every == 0:
            all_losses.append((total_loss / plot_every) if (iter - start_iteration >= plot_every) else loss)
            total_loss = 0

        if iter % save_every == 0:
            directory = os.path.join(save_dir, 'model')
            if not os.path.exists(directory):
                os.makedirs(directory)
            torch.save({
                'iteration': iter,
                'rnn': rnn.state_dict(),
                'category': train_category,
                'loss': loss
            }, os.path.join(directory, '{}_{}.tar'.format('name_generator_model', iter)))

    return all_losses

# sample from a category and starting letter
def Sample(category, start_letter='A', modelFile=None, max_lenght = 20):
    if modelFile:
        checkpoint = torch.load(modelFile)
        rnn.load_state_dict(checkpoint["rnn"])
        if category is None:
            category = checkpoint["category"]

    hidden = rnn.InitHidden()
    category_tensor = CategoryTensor(category)
    input_tensor = InputTensor(start_letter)
    output_name = start_letter
    for i in range(max_lenght):
        output, hidden = rnn(category_tensor, input_tensor[0], hidden)
        topv, topi = output.topk(1)

        idx = topi[0][0]
        if idx == n_letters - 1: break
        else:
            letter = all_letters[idx]
            output_name += letter
            input_tensor = InputTensor(letter)
    return output_name

def Sampeles(category, start_letters="ABC", modelFile=None):
    names = []
    for letter in start_letters:
        names.append(Sample(category, letter, modelFile))
    return names

def run(args):
    modelFile = None
    if args.load_model:
        modelFile = args.load_model

    category = None
    if args.category:
        category = args.category
    if args.test:
        if modelFile is None:
            raise RuntimeError('Please choose a saved model to load')

        if args.single_letter:
            start_letter = args.single_letter
            print(Sample(category, start_letter, modelFile))
        elif args.multi_letters:
            print(Sampeles(category, args.multi_letters, modelFile))

        else:
            raise RuntimeError("please specify evaluate mode")

    elif args.train:
        runTrainingModel(category=category, modelFile=modelFile)

    else:
        raise RuntimeError("please specify running mode[test/train]")

if __name__=="__main__":

    args = parse()
    filename = "data/names/*.txt"
    if args.filename:
        filename = args.filename
    loadTrainingDataset(filename)

    criterion = nn.NLLLoss()
    lr = 0.0001
    if args.learning_rate:
        lr = args.learning_rate

    rnn = RNN(n_letters, 128, n_letters)
    run(args)


def is_isogram(string):
  result = True
  string = string.upper()
  word = string
  for letter in string:
    word = word[1:]
    if letter in word:
      result = False
  return result

# The best:
def is_isogram(string):
  return len(string) == len(set(string.lower()))

# Kata Link: https://www.codewars.com/kata/54ba84be607a92aa900000f1


from xcp2k.inputsection import InputSection
from xcp2k.classes._temperature4 import _temperature4
from xcp2k.classes._langevin_regions1 import _langevin_regions1

class _print11(InputSection):
    def __init__(self):
        InputSection.__init__(self)
        self.TEMPERATURE = _temperature4()
        self.LANGEVIN_REGIONS = _langevin_regions1()
        self._name = "PRINT"
        self._subsections = {'TEMPERATURE': 'TEMPERATURE', 'LANGEVIN_REGIONS': 'LANGEVIN_REGIONS'}


import logging
from typing import Tuple, Union, Dict

import torch
import torch_geometric as tg

from torch_bce.interfaces import ModelInterface
from torch_bce.models import GraphSAGE
from torch_bce.interfaces.trainer_interface import AlignmentTrainerInterface
from torch_bce.utils import PositiveNegativeNeighbourSampler

class GSAlignmentTrainer(AlignmentTrainerInterface):
    def __init__(self, *args, **kwargs):
        super(GSAlignmentTrainer, self).__init__(*args, **kwargs)

    def train_model(self,
                    train_data: tg.data.Data,
                    walk_length: int = 3,
                    sizes: Tuple = (5, 2),
                    batch_size: int = 256,
                    shuffle: bool = False,
                    log_stats: bool = False,
                    *args, **kwargs) -> \
            Tuple[torch.Tensor, torch.Tensor, Dict]:
        self.__asserts(train_data, sizes)
        x_train, edge_index_train = train_data.x.to(self.device), train_data.edge_index.to(self.device)
        train_loader = PositiveNegativeNeighbourSampler(walk_length, edge_index_train, sizes=sizes,
                                                        batch_size=batch_size, shuffle=shuffle,
                                                        num_nodes=train_data.num_nodes)

        assert isinstance(self.current_model, GraphSAGE), "Model was not GraphSAGE or relative"
        loss, external_loss, statistics = self.current_model.train_loop(
            x_train,
            train_loader,
            optimizer=None,
            num_nodes=train_data.num_nodes,
            optimize=False,
            external_loss_fn=self.alignment_loss
        )
        if log_stats:
            if isinstance(self.logger, logging.Logger):
                self.logger.info(statistics)
        return loss, external_loss, statistics

    def validate_model(self,
                       val_data: tg.data.Data,
                       walk_length: int = 3,
                       sizes: Tuple = (5, 2),
                       batch_size: int = 256,
                       shuffle: bool = False,
                       log_stats: bool = False,
                       *args, **kwargs) -> \
            Tuple[torch.Tensor, Union[torch.Tensor, None], Union[torch.Tensor, None]]:
        self.__asserts(val_data, sizes)
        x_val, edge_index_val = val_data.x.to(self.device), val_data.edge_index.to(self.device)
        val_loader = PositiveNegativeNeighbourSampler(walk_length, edge_index_val, sizes=sizes,
                                                      batch_size=batch_size, shuffle=shuffle,
                                                      num_nodes=val_data.num_nodes)

        assert isinstance(self.current_model, GraphSAGE), "Model was not GraphSAGE or relative"
        predictions, statistics = self.current_model.predict(
            x_val,
            val_loader,
            num_nodes=val_data.num_nodes,
            compute_loss=True,
            external_loss_fn=self.alignment_loss
        )
        if log_stats:
            if isinstance(self.logger, logging.Logger):
                self.logger.info(statistics)
        return predictions, statistics["mean_loss"], statistics["mean_external_loss"]

    def initialize_new_model(self, prev_model: ModelInterface, new_model: ModelInterface, *args, **kwargs) -> None:
        assert isinstance(prev_model, GraphSAGE) and isinstance(new_model, GraphSAGE), \
            "One or both models are not of type GraphSAGE"
        if len(prev_model.convs) != len(new_model.convs):
            self.logger.warning(
                f"""
                Previous model convs len: {len(prev_model.convs)}
                New model convs len: {len(new_model.convs)}
                Do not copy layers, so as don't know how
                """
            )
            return
        for conv_old, conv_new in zip(prev_model.convs, new_model.convs):
            if (conv_old.in_channels == conv_new.in_channels) and (
                    conv_old.out_channels == conv_new.out_channels):
                for target_param, param in zip(conv_new.parameters(), conv_old.parameters()):
                    target_param.data.copy_(param.data)
            else:
                self.logger.info(f"Skipped param copying for conv {conv_old}")

    def __asserts(self, data: tg.data.Data, sizes: Tuple) -> None:
        assert isinstance(self.current_model, GraphSAGE), "Model was not GraphSAGE or relative"
        assert self.current_model.in_channels == data.num_node_features, "Num nodes in data is not equal to in_channels"
        assert self.current_model.n_layers == len(sizes), "model.n_layers must be == sampler sizes"

    def __eq__(self, other):
        if isinstance(other, GSAlignmentTrainer) and isinstance(self.current_model, GraphSAGE):
            return len(self.models) == len(other.models) and \
                   self.current_model.n_layers == other.current_model.n_layers and \
                   self.current_model.in_channels == other.current_model.in_channels and \
                   self.current_model.hid_channels == other.current_model.hid_channels and \
                   self.current_model.out_channels == other.current_model.out_channels and \
                   len(self.alignment.alignment.all_backward_transformations) == len(
                other.alignment.alignment.all_backward_transformations) and \
                   self.prev_embeddings.x == other.prev_embeddings.x
        else:
            raise NotImplementedError()


###############################################################################
# Define everything needed to do per-commit testing.  This is the "separted
# testing" that @staticfloat has been going on about for so many years...
###############################################################################

@util.renderer
def run_julia_tests(props_obj):
    props = props_obj_to_dict(props_obj)
    cmd = ["bin/julia", "-e", "Base.runtests([\"all\"]; ncores=min(Sys.CPU_THREADS, 8))"]

    if is_windows(props_obj):
        cmd[0] += ".exe"
    return cmd

# Steps to download a linux tarball, extract it, run testing on it, and maybe trigger coverage
julia_testing_factory = util.BuildFactory()
julia_testing_factory.useProgress = True
julia_testing_factory.addSteps([
    # Clean the place out from previous runs
    steps.ShellCommand(
        name="clean it out",
        command=["/bin/sh", "-c", "rm -rf *"],
        flunkOnFailure=False,
    ),

    # Download the appropriate tarball and extract it
    steps.ShellCommand(
        name="Download Julia",
        command=download_julia,
    ),

    # Run tests!
    steps.ShellCommand(
        name="Run tests",
        command=run_julia_tests,
        haltOnFailure=True,
        timeout=3600,
    ),

    # Promote from pretesting to a nightly if it worked!
    steps.MasterShellCommand(
        name="Promote on AWS",
        command=render_promotion_command,
        haltOnFailure=True,
        doStepIf=should_promote,
    ),
    steps.MasterShellCommand(
        name="Promote on AWS (latest)",
        command=render_latest_promotion_command,
        haltOnFailure=True,
        doStepIf=should_promote,
    ),

    # Cleanup AWS
    steps.MasterShellCommand(
        name="Cleanup pretesting",
        command=render_cleanup_pretesting_command,
        doStepIf=should_promote,
    ),

    # Trigger coverage build if everything goes well
    steps.Trigger(
        schedulerNames=["Julia Coverage Testing"],
        set_properties={
            'download_url': render_download_url,
            'commitmessage': util.Property('commitmessage'),
            'commitname': util.Property('commitname'),
            'commitemail': util.Property('commitemail'),
            'authorname': util.Property('authorname'),
            'authoremail': util.Property('authoremail'),
            'shortcommit': util.Property('shortcommit'),
            'scheduler': util.Property('scheduler'),
        },
        waitForFinish=False,
        doStepIf=is_assert_nightly,
    ),

    # Trigger a build of a non-assert version if the assert version finished properly
    steps.Trigger(
        schedulerNames=["Julia CI (non-assert build)"],
        set_properties={
            'assert_build': False,
        },
        waitForFinish=False,
        doStepIf=is_assert_nightly,
    ),
])

for builder, workers in builder_mapping.items():
    tester_name = "tester_%s"%(builder)
    # Add a dependent scheduler for running tests after we build tarballs
    c['schedulers'].append(schedulers.Triggerable(
        name="Julia CI (%s testing)"%(builder),
        builderNames=[tester_name],
    ))

    # Add testing builders
    c['builders'].append(util.BuilderConfig(
        name=tester_name,
        workernames=["tabularasa_"+w for w in workers],
        collapseRequests=False,
        tags=["Testing"],
        factory=julia_testing_factory,
    ))

c['schedulers'].append(schedulers.ForceScheduler(
    name="force_test",
    label="Force test build",
    builderNames=["tester_%s"%(k) for k in builder_mapping.keys()],
    reason=util.FixedParameter(name="reason", default=""),
    codebases=[
        util.CodebaseParameter(
            "",
            name="",
            branch=util.FixedParameter(name="branch", default=""),
            revision=util.FixedParameter(name="revision", default=""),
            repository=util.FixedParameter(name="repository", default=""),
            project=util.FixedParameter(name="project", default="Coverage"),
        )
    ],
    properties=[
        util.StringParameter(
            name="url",
            size=60,
            default="https://julialangnightlies-s3.julialang.org/bin/linux/x64/julia-latest-linux64.tar.gz"
        ),
    ]
))


from PyQt5 import QtCore

from misc.Functions import *
from dialogs.Dialog import *

class AddPlayerDialogWorker(QtCore.QThread):
    """Worker class is for executing background tasks
    """

    setPlayerNickname = QtCore.pyqtSignal(str)

    def __init__(self, dialog: Dialog):
        """Initialising QtCore.QThread, connecting slots

        Args:
            dialog (Dialog): Dialog object that this class was instantiated in
        """
        super().__init__()
        self.dialog = dialog
        self.cancel = False
        self.setPlayerNickname.connect(self.dialog.nick.setText)

    def run(self):
        """Running the Worker task
        """
        response = None
        try:
            response = createRequest("https://stats.xonotic.org/player/" + str(self.dialog.id))
            self.showRate.emit(response.headers["X-Ratelimit-Remaining"], response.headers["X-Ratelimit-Limit"])
        except:
            pass
        # Canceling
        if self.cancel:
            return
        # Checking response
        if response is not None and response:
            data = response.json()
            self.setPlayerNickname.emit(processNick( data["player"]["nick"] ))


from falcon import testing

from monasca_events_api.app.core import request
from monasca_events_api.tests.unit import base

class TestRequest(base.BaseTestCase):

    def setUp(self):
        super(TestRequest, self).setUp()

    def test_use_context_from_request(self):
        req = request.Request(
            testing.create_environ(
                path='/',
                headers={
                    'X_AUTH_TOKEN': '1111',
                    'X_USER_ID': '2222',
                    'X_PROJECT_ID': '3333',
                    'X_ROLES': 'goku,vegeta'
                }
            )
        )
        self.assertEqual('1111', req.context.auth_token)
        self.assertEqual('2222', req.context.user_id)
        self.assertEqual('3333', req.context.project_id)
        self.assertItemsEqual(['goku', 'vegeta'], req.context.roles)

    def test_check_is_admin_from_request(self):
        req = request.Request(
            testing.create_environ(
                path='/',
                headers={
                    'X_USER_ID': '2222',
                    'X_PROJECT_ID': '3333',
                    'X_ROLES': 'admin,burger'
                }
            ),

        )
        self.assertTrue(req.is_admin)

    def test_request_context_admin_uppercase(self):
        req = request.Request(
            testing.create_environ(
                path='/',
                headers={
                    'X_USER_ID': '1111',
                    'X_PROJECT_ID': '2222',
                    'X_ROLES': 'Admin,bob'
                }
            )
        )
        self.assertTrue(req.is_admin)


"""Deck module for BlackJack game."""
from random import shuffle
from card import Card

class Deck:
    """Deck abstraction"""
    def __init__(self,list_of_colours,list_of_values):
        self.deck=[]
        for i in range(len(list_of_colours)):
            for j in range(len(list_of_values)):
                self.deck.append(Card(list_of_colours[i], list_of_values[j]))
    def shuffle(self):
        """
        This method shuffles deck in place
        """
        shuffle(self.deck)


'''
Extracts a particular chromosome/sequence from a fasta file
Usage:
python extract_chrom.py <fasta-file> <chrom>
'''

import sys

fasta_file = sys.argv[1]
chrom = sys.argv[2]

fasta_handle = open(fasta_file, 'r')

#Input the first line of the file
cur_line = fasta_handle.readline()
while (cur_line.strip() != ('>' + chrom)): #Loop through until we find the chromosome/seq we want
    cur_line = fasta_handle.readline()
    if (cur_line == ''):
        break

print(cur_line.strip()) #Print the first line of the chrom/seq
cur_line = fasta_handle.readline() #Read the next line
if cur_line != '':
    while (cur_line[0] != '>'): #Check if we've encountered a new sequence
        print(cur_line.strip()) #If we haven't, print out the current line and read the next one
        cur_line = fasta_handle.readline()
        if (cur_line == ''):
            break

fasta_handle.close() #We're all done, so close