from collections import OrderedDict
from urllib.parse import urlencode
from uuid import uuid4

import scrapy
import json

from scrapy.spiders import Rule
from scrapy_selenium import SeleniumRequest
import pandas as pd
from scraper_api import ScraperAPIClient
from ..items import ProductItem

def data_to_json(data):
    data.replace('<script id="__AER_DATA__" type="application/json">', '')
    data = json.loads(data)
    return data

def take_images(data):
    image_blocks = data['gallery']
    images = []
    for image in image_blocks:
        item = {}

        if image['imageUrl']:
            item['image'] = image['imageUrl']
        if image['videoUrl']:
            item['video'] = image['videoUrl']
        images.append(item)
    return images

def take_parameters(data):
    data = data['skuInfo']['propertyList']
    parameters = []
    for info in data:
        parameter = {'title': info['name']}
        values = []
        for value in info['values']:
            values.append({'name': value['displayName'], 'id': value['id']})
        parameter['info'] = values
        parameters.append(parameter)
    return parameters

def take_additional_parameters(data):
    data = data["widgets"][2]["children"][0]["children"][0]["children"][0]["children"][0]["children"][0]["children"][7]["children"][0]["children"][3]['props']["html"]
    return data

def take_prices(data):
    data = data['skuInfo']['priceList']
    prices = [(price['skuPropIds'], price['activityAmount']['value']) for price in data]
    return prices

class AliSpider(scrapy.Spider):
    name = "Ali"

    def __init__(self, *args, **kwargs):
        self.url = kwargs.get('url')
        self.domain = kwargs.get('domain')
        self.unique_id = kwargs.get("_job")
        self.user = kwargs.get("user")
        self.start_urls = [self.url]
        self.allowed_domains = [self.domain]

        AliSpider.rules = [
            Rule(SeleniumRequest(url=self.url, callback=self.parse, wait_time=5))
        ]

        super(AliSpider, self).__init__(*args, **kwargs)

    def parse(self, response, **kwargs):
        page_api = str(response.css('#__AER_DATA__::text').get())
        page_api = data_to_json(page_api)
        additional_parameters = take_additional_parameters(page_api)
        product_api = page_api['widgets'][2]['children'][0]['children'][0]['children'][0]['children'][0]['children'][0]['props']
        images = take_images(product_api)
        parameters = take_parameters(product_api)
        prices = take_prices(product_api)
        unique_id = str(uuid4())

        item = {
            'название': product_api['name'],
            'картинки': images,
            'параметры': parameters,
            'дополнительные параметры': additional_parameters,
            'цена': prices
        }

        product = ProductItem()
        product['unique_id'] = self.unique_id
        product['name'] = item['название']
        product['images'] = item['картинки']
        product['parameters'] = item['параметры']
        product['prices'] = item['цена']
        product['additional_parameters'] = item['дополнительные параметры']
        product['from_whom'] = "AliExpress"
        product['user'] = self.user

        yield product


'''
You are given a non-empty list of integers (X). For this task,
you should return a list consisting of only the non-unique elements
in this list. To do so you will need to remove all unique elements
(elements which are contained in a given list only once).
When solving this task, do not change the order of the list.
Example: [1, 2, 3, 1, 3] 1 and 3 non-unique elements and
result will be [1, 3, 1, 3].

Input: A list of integers.
Output: The list of integers.

How it is used: This mission will help you to understand how
to manipulate arrays, something that is the basis for solving
more complex tasks. The concept can be easily generalized for
real world tasks.

For example: if you need to clarify statistics by removing
low frequency elements (noise).

Precondition:
0 < len(data) < 1000
'''

def get_unique_keys(data):
	a_dict = get_hash(data)
	return [k for k, v in a_dict.items() if v == 1]

def get_hash(data):
	a_dict = {}
	for key in data:
		if key in a_dict:
			a_dict[key] += 1
		else:
			a_dict[key] = 1
	return a_dict

def remove_unique(data, unique_keys):
	data = data.copy()
	for key in unique_keys:
		indexes = [i for i,x in enumerate(data) if x == key]
		for index in indexes:
			del data[index]
	return data

def checkio_my_sln(data):
	data = data.copy()
	unique_keys = get_unique_keys(data)
	return remove_unique(data, unique_keys)

def checkio_online_sln(data):
	return [x for x in data if data.count(x) > 1]

l1 = [1, 2, 3, 1, 3]
l2 = [1, 2, 3, 4, 5]
l3 = [5, 5, 5, 5, 5]
l4 = [10, 9, 10, 10, 9, 8]
l5 = ['a', 'b', 'b', 'c', 'c', 'd', 'd', 'd']

lall = [l1, l2, l3, l4, l5]

for l in lall:
	print("{} {}".format(l,checkio_my_sln(l)))

print("\n")

for l in lall:
	print("{} {}".format(l,checkio_online_sln(l)))


from csv import DictWriter

problemTypes = ['U1', 'U2', 'U3', 'U4', 'U5', 'A', 'K', 'B']
batchNo = input('Číslo série: ')

ideal_dict = {}

for type in problemTypes:
    with open(f'../batch{batchNo}/problems/problem{batchNo}-{type}.tex', 'r') as lines:
        for line in lines:
            if '\probpoints' in line:
                value = line[line.find("{")+1:line.find("}")]
        ideal_dict[type] = value

ideal_nums = []
for type in problemTypes:
    ideal_nums.append(int(ideal_dict[type]))

ideal_dict['Jmeno'] = 'Student Pilný'
ideal_dict['Trida'] = 'MKi'
ideal_dict['Procento'] = 100
ideal_dict['Hashtag'] = 100
ideal_dict['Celkem'] = sum(ideal_nums)

# Number of entries
n = input('Počet Řešitelů: ')

for i in range(1, int(n)+1):
    # Vars init
    Name = input('Jméno: ')
    Class = input('Třída: ')

    u1 = input('U1: ')
    u2 = input('U2: ')
    u3 = input('U3: ')
    u4 = input('U4: ')
    u5 = input('U5: ')
    a = input('A: ')
    k = input('K: ')
    b = input('B: ')

    # Conditional summation
    temp = dict({'U1': u1, 'U2': u2, 'U3': u3, 'U4': u4, 'U5': u5, 'A': a, 'K': k, 'B': b})

    def int_test(var):
        if var.isnumeric():
            return(1)
        else:
            return(0)

    int_output = dict({'U1': int_test(u1), 'U2': int_test(u2), 'U3': int_test(u3), 'U4': int_test(u4), 'U5': int_test(u5), 'A': int_test(a), 'K': int_test(k), 'B': int_test(b)})

    int_keys = [k for k,v in int_output.items() if v == 1]

    integers = [temp[key] for key in int_keys]

    for i in range(0, len(integers)):
        integers[i]=int(integers[i])

    int_sum = sum(integers)

    ideal_correspoding_ints = [ideal_dict[key] for key in int_keys]

    for i in range(0, len(ideal_correspoding_ints)):
        ideal_correspoding_ints[i]=int(ideal_correspoding_ints[i])

    ideal_corresponding_sum = sum(ideal_correspoding_ints)

    # Percent calculation
    percent = int(round(100*int_sum/ideal_corresponding_sum, 0))

    # Hashtag calculation
    tag = int(round(100*int_sum/int(ideal_dict['Celkem']), 0))

    # Writing to csv
    Dict = dict({'Jmeno': Name, 'Trida': Class, 'U1': u1, 'U2': u2, 'U3': u3, 'U4': u4, 'U5': u5, 'A': a, 'K': k, 'B': b, 'Procento': percent, 'Hashtag': tag, 'Celkem': int_sum})

    field_names = ['Jmeno', 'Trida', 'U1', 'U2', 'U3', 'U4', 'U5', 'A', 'K', 'B', 'Procento', 'Hashtag', 'Celkem']

    with open(f'results{batchNo}.csv', 'a', encoding='utf-8') as results:
        dictwriter_object = DictWriter(results, fieldnames=field_names)
        dictwriter_object.writerow(Dict)

    # Incrementing i
    i+=1

    # Better UI
    print()


import cv2

# Initialize video capture object
cap = cv2.VideoCapture("cars.mp4")

# Create background subtractor object
fgbg = cv2.createBackgroundSubtractorMOG2()

while True:
    # Read a frame from the video capture
    ret, frame = cap.read()

    # Apply Gaussian blur to the frame
    blurred = cv2.GaussianBlur(frame, (11, 11), 0)

    # Apply background subtraction to the blurred frame
    fgmask = fgbg.apply(blurred)

    # Apply thresholding to the foreground mask
    thresh = cv2.threshold(fgmask, 127, 255, cv2.THRESH_BINARY)[1]

    # Find contours in the thresholded image
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # Draw bounding boxes around the detected contours
    for contour in contours:
        (x, y, w, h) = cv2.boundingRect(contour)
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # Display the resulting frame
    cv2.imshow('frame', frame)

    # Press 'q' to quit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture object and destroy all windows
cap.release()
cv2.destroyAllWindows()


import re
import sys

# command line argument for input file (TCDB.faa)
filename = sys.argv[1]

# read file
with open(filename, 'r') as inputfile:

    # output file
    with open("script1.out", 'w') as out:

        for i, line in enumerate(inputfile):

            # remove newlines
            line = line.strip()

            # check for header
            if line[0] == '>':
                if i != 0:
                    out.write('\n')
                match = re.match("^>\w+\|\S+\|(.+?)\|(\S+)", line)
                out.write(match.group(2) + '-' + match.group(1) + '\t')
            else:
                out.write(line)


from flask import Blueprint, request, session, redirect, url_for, jsonify
import hashlib
import datetime
import os
import base64
from lib.db import get_user_data, update_user_data, get_all_favorites, update_user_image_path

user_pages = Blueprint('user_pages', __name__)

@user_pages.route('/<user_id>', methods=['GET'])
def get_user_info(user_id):
    if user_id.isdigit():
        user_info = get_user_data(user_id)

        # Check for profile photo
        if user_info['image_path'] is None:
            user_info['image_path'] = url_for(
                'static', filename='images/placeholder.png')

        return jsonify(user_info)
    else:
        return redirect(url_for('base_pages.index'))

@user_pages.route('/', methods=['GET', 'POST'])
def redirect_to_user_info():
    if request.method == 'GET':
        return redirect(url_for('user_pages.get_user_info', user_id=session['user_id']))
    elif request.method == 'POST':
        if request.is_json:
            user_data = request.get_json()

            # Update user image
            db_operation = update_user_data(
                user_data, session['user_id'])

            if db_operation:
                return jsonify(message='Successfully updated in database', status='ok')
            else:
                return jsonify(message='Something went wrong during database operation', status='failed')
        else:
            return jsonify(message='Please provide json request', status='failed')

@user_pages.route('/favorites', methods=['GET'])
def get_user_favorites():
    # Get all user favorites
    favorites = get_all_favorites(session['user_id'])

    # Check if error occured
    if favorites is False:
        return jsonify(message='An error occured during database operation', status='failed')

    return jsonify(status='success', favorites=favorites)

@user_pages.route('/image', methods=['POST'])
def update_user_image():
    if session['user_id'] is not None:
        if request.is_json:
            image_data = request.get_json()
            date_string = datetime.datetime.now().strftime('%c')
            unique_hash = hashlib.md5(date_string.encode())

            # Get and process image data
            img_data = base64.b64decode(image_data['image_base64'])
            image_path = 'static/images/upload/profile-picture-user-' + \
                str(session['user_id']) + '-' + \
                unique_hash.hexdigest() + '.jpg'
            with open(image_path, 'wb') as f:
                f.write(img_data)

            # Update user image
            db_operation = update_user_image_path(
                image_path, session['user_id'])

            if db_operation:
                # remove old image
                try:
                    os.remove(image_data['old_image_path'])
                except Exception as err:
                    print(err)

                return jsonify(message='Successfully updated in database', status='ok', new_image_path=image_path)
            else:
                return jsonify(message='Something went wrong during database operation', status='failed')

    else:
        return jsonify(message='No user found', status='failed')


import argparse
import asyncio
import datetime
import logging
import os.path
import sys

import uvicorn

from app.globals.global_config import AvailableScanner, InputType
from app.server.fs_scan_results.fs_scan_results_manager import FSScanResultsManager
from app.server.models.finding_models.finding_model import UploadNewFindingModel
from app.user.user_manager import UserManager
from config.config import LoggerConfig, GitleaksConfig

logger = logging.getLogger(__name__)

def init():
    if not (os.path.exists(GitleaksConfig.FS_RAW_INPUT_PATH)):
        logging.debug("Creating input-dir {}".format(GitleaksConfig.FS_RAW_INPUT_PATH))
        os.makedirs(GitleaksConfig.FS_RAW_INPUT_PATH)
    else:
        logging.debug("Input-dir {} already exists".format(GitleaksConfig.FS_RAW_INPUT_PATH))

if __name__ == "__main__":

    parser = argparse.ArgumentParser()
    parser.add_argument('--start-webserver', required=False, help='Start uvicorn webserver', action='store_true')
    parser.add_argument('--bulk-upload', required=False, help='Start bulk-upload of data', action='store_true')
    parser.add_argument('--repository-hoster', required=False, help="Provide the hoster of your repository, e.g. 'https://github.com'")

    logging.basicConfig(
        level=LoggerConfig.LOG_LEVEL,
        filename=LoggerConfig.LOG_FILE,
        filemode=LoggerConfig.FILE_MODE,
        format=LoggerConfig.LOG_FORMAT
    )
    init()

    args = parser.parse_args()

    if len(sys.argv) == 1:
        parser.print_help(sys.stderr)
        sys.exit(1)

    if args.start_webserver:
        logging.debug('Starting webserver and application')

        asyncio.run(UserManager().run())

        print("Backend is running ...")
        uvicorn.run(
            "app.server.app:app",
            host="0.0.0.0",
            port=8000,
            reload=True,
            log_config='config/uvicornConfig.yml'
        )
    else:
        if args.bulk_upload:
            logging.debug("Starting file-upload")

            fs_scan_results_manager = FSScanResultsManager()
            asyncio.run(fs_scan_results_manager.run(meta_data=UploadNewFindingModel(
                scannerType=AvailableScanner.GITLEAKS,
                scannerVersion='8.15',
                inputType=InputType.FileSystem,
                repositoryPath="",
                repositoryName="",
                scanDate=datetime.datetime.now()
            ),
                repository_hoster=args.repository_hoster,
                bulk_upload=True
            ))


# ディスプレイする方法とかを記したファイル
# クラスVer

class DrawDisplay:
    def __init__(self):
        pass

    # 諦観
    # def depth(self, k):
    #     # print(k)
    #     if not k:
    #         print("not k", k)
    #         return 0
    #     else:
    #         if isinstance(k, list):
    #             # print(k,end="")
    #             print()
    #             # return 1 + max(self.depth(i) for i in k)
    #             # print([self.depth(i) for i in k])
    #             return max(self.depth(i) for i in k)
    #         else:
    #             print(k, end="")
    #             return k

    # def initialDiplay(self, disp_data, end="\n", line_end="\n"):
    #     """
    #     初期部分を表示

    #     @param
    #         dips_data,list          : 表示するデータ
    #         end,str,default='\n'    : 最後に出力する文字列
    #     """
    #     for line in disp_data:
    #         print(line, end=end)

    #     print(end=line_end)  # 最後に出力するもの

    # def commandDisplay(self, disp_data, end="\n", line_end="\n"):
    #     """
    #     画面描画のコマンド部分
    #     """
    #     self.cursol = "▶ "
    #     self.command_number = 0

    #     for command_num, line in enumerate(disp_data):
    #         if command_num == self.command_number:
    #             print("{}{}".format(self.cursol, line))
    #         else:
    #             print(line)

    #     print(end=line_end)  # 最後に出力するもの

    end = "\n"
    line_end = ""
    initials = [""]
    commands = [""]
    cursol = "▶ "
    command_number = 0

    def initialDiplay(self):
        """
        初期部分を表示
        """
        for line in self.initials:
            print(line, end=self.end)

        print(end=self.line_end)  # 最後に出力するもの

    def commandDisplay(self):
        """
        画面描画のコマンド部分
        """

        for command_num, line in enumerate(self.commands):
            if command_num == self.command_number:
                print("{}{}".format(self.cursol, line))
            else:
                print(line)

        print(end=self.line_end)  # 最後に出力するもの

if __name__ == '__main__':
    drawDisplay = DrawDisplay()

    drawDisplay.initials = ["========= START ==========", "DEMO RPG!"]
    drawDisplay.commands = ["command A", "command B", "command C"]

    drawDisplay.cursol = "▶ "
    drawDisplay.command_number = 1
    drawDisplay.line_end = "\n"

    drawDisplay.initialDiplay()
    drawDisplay.commandDisplay()


from recurrent_ics.attendee import Attendee, Organizer
from recurrent_ics.grammar.parse import ContentLine
from recurrent_ics.serializers.serializer import Serializer
from recurrent_ics.utils import (arrow_date_to_iso, arrow_to_iso, escape_string,
                       timedelta_to_duration, uid_gen)
from recurrent_ics.serializers.event_serializer import EventSerializer

class RecurrentEventSerializer(EventSerializer):
    def serialize_recurrent(event, container):
        if event.recurrent:
            params = {
                "FREQ": event.recurrent,
                "BYDAY": ",".join(event.recurrence_weekdays),
                "INTERVAL": str(event.recurrence_interval)
            }
            if event.recurrence_count:
                params["COUNT"] = event.recurrence_count
            if event.recurrence_end:
                params["UNTIL"] = arrow_to_iso(event.recurrence_end)

            container.append(ContentLine("RRULE", value=parse_rrule_dict(params)))

def parse_rrule_dict(rrule) -> str:
    output = []
    for key in rrule:
        output.append(f"{key}={rrule[key]}")
    return ";".join(output)


class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def isCousins(root, x, y):
    """
    :type root: TreeNode
    :type x: int
    :type y: int
    :rtype: bool
    """
    if x.val == 1 or y.val == 1:
        return False

    x_f, x_l, _ = getFather(root, x.val, 0)
    y_f, y_l, _ = getFather(root, y.val, 0)

    if x_l == y_l and x_f != y_f:
        return True
    else:
        return False

def getFather(root, value, level):
    if root == None:
        return None, None, False
    if root.left:
        if root.left.val == value:
            return root, level+1, True
        else:
            temp, l, flag = getFather(root.left, value, level+1)
            if flag:
                return temp, l, flag
    if root.right:
        if root.right.val == value:
            return root, level + 1, True
        else:
            temp, l, flag = getFather(root.right, value, level + 1)
            if flag:
                return temp, l, flag

    return None, None, False


import collections
n, m = map(int, input().split())
graph = [list(input()) for _ in range(n)]
visited = [[False for _ in range(m)] for _ in range(n)]
dr = [-1, 1, 0, 0]
dc = [0, 0, -1, 1]
queue = collections.deque()
queue.append((0, 0, 1))
visited[0][0] = True
while queue:
    r, c, cnt = queue.popleft()
    if r == n - 1 and c == m - 1:
        print(cnt)
        exit(0)
    for i in range(4):
        new_r = r + dr[i]
        new_c = c + dc[i]
        if 0 <= new_r < n and 0 <= new_c < m:
            if not visited[new_r][new_c] and graph[new_r][new_c] == '1':
                visited[new_r][new_c] = True
                queue.append((new_r, new_c, cnt + 1))

backjoon/dfs + bfs 필수문제/2178미로탐색silver1.py


from pyclbr import Function
from typing import Dict, Optional, Tuple, Union

import numpy as np
import torch as th
from active_critic.model_src.whole_sequence_model import WholeSequenceModel
from active_critic.utils.pytorch_utils import make_partially_observed_seq
from stable_baselines3.common.policies import BaseModel
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
import os
import pickle

class ACPOptResult:
    def __init__(self, gen_trj: th.Tensor, inpt_trj: th.Tensor = None, expected_succes_before: th.Tensor = None, expected_succes_after: th.Tensor = None) -> None:
        self.gen_trj = gen_trj
        self.inpt_trj = inpt_trj
        self.expected_succes_before = expected_succes_before
        self.expected_succes_after = expected_succes_after

class ActiveCriticPolicySetup:
    def __init__(self) -> None:
        self.extractor: BaseFeaturesExtractor = None
        self.new_epoch: Function = None
        self.optimisation_threshold: float = None
        self.epoch_len: int = None
        self.opt_steps: int = None
        self.device: str = None
        self.inference_opt_lr: float = None
        self.optimize: bool = None
        self.batch_size: int = None
        self.stop_opt: bool = None
        self.opt_end: bool = None
        self.optimize_last: bool = False
        self.clip:bool = True

class ActiveCriticPolicyHistory:
    def __init__(self) -> None:
        self.reset()

    def reset(self):
        self.gen_scores = []
        self.opt_scores = []
        self.gen_trj = []

    def new_epoch(self, history:list([th.Tensor]), size:list([int, int, int]), device:str):
        new_field = th.zeros(size=size, device=device)
        if len(history) == 0:
            history.append(new_field)
        else:
            history[0] = th.cat((history[0], new_field))

    def add_value(self, history:list([th.Tensor]), value:th.Tensor, current_step:int):
        history[0][-value.shape[0]:, current_step] = value

class ActiveCriticPolicy(BaseModel):
    def __init__(
        self,
        observation_space,
        action_space,
        actor: WholeSequenceModel,
        critic: WholeSequenceModel,
        acps: ActiveCriticPolicySetup = None
    ):

        super().__init__(observation_space, action_space)

        self.actor = actor
        self.critic = critic
        self.args_obj = acps
        self.register_buffer('gl', th.ones(
            size=[acps.batch_size, acps.epoch_len, critic.wsms.model_setup.d_output], dtype=th.float, device=acps.device))
        self.history = ActiveCriticPolicyHistory()
        self.clip_min = th.tensor(self.action_space.low, device=acps.device)
        self.clip_max = th.tensor(self.action_space.high, device=acps.device)
        self.reset()

    def reset(self):
        self.last_goal = None
        self.current_step = 0
        self.history.reset()

    def reset_epoch(self, vec_obsv: th.Tensor):
        self.current_step = 0
        self.last_goal = vec_obsv
        self.current_result = None

        scores_size = [vec_obsv.shape[0], self.args_obj.epoch_len, self.critic.wsms.model_setup.d_output]
        self.history.new_epoch(self.history.gen_scores, size=scores_size, device=self.args_obj.device)
        self.history.new_epoch(self.history.opt_scores, size=scores_size, device=self.args_obj.device)

        trj_size = [vec_obsv.shape[0], self.args_obj.epoch_len, self.action_space.shape[0]]
        self.history.new_epoch(self.history.gen_trj, size=trj_size, device=self.args_obj.device)

        self.obs_seq = th.zeros(
            size=[vec_obsv.shape[0], self.args_obj.epoch_len, vec_obsv.shape[-1]], device=self.args_obj.device)

    def predict(
        self,
        observation: Union[th.Tensor, Dict[str, th.Tensor]],
        state: Optional[Tuple[np.ndarray, ...]] = None,
        episode_start: Optional[np.ndarray] = None,
        deterministic: bool = False,
    ) -> th.Tensor:
        vec_obsv = self.args_obj.extractor.forward(
            observation).to(self.args_obj.device).unsqueeze(1)
        if (self.last_goal is None) or (self.args_obj.new_epoch(self.last_goal, vec_obsv)):
            self.reset_epoch(vec_obsv=vec_obsv)
            action_seq = None
        else:
            self.current_step += 1
            action_seq = self.current_result.gen_trj

        self.obs_seq[:, self.current_step:self.current_step+1, :] = vec_obsv

        self.current_result = self.forward(
            observation_seq=self.obs_seq, action_seq=action_seq,
            optimize=self.args_obj.optimize,
            current_step=self.current_step,
            stop_opt=self.args_obj.stop_opt,
            opt_end=self.args_obj.opt_end,
            opt_last=self.args_obj.optimize_last
            )

        if self.args_obj.optimize:
            self.history.add_value(
                history=self.history.opt_scores,
                value=self.current_result.expected_succes_after[:, self.current_step].detach(),
                current_step=self.current_step
            )
        self.history.add_value(self.history.gen_scores, value=self.current_result.expected_succes_before[:, self.current_step].detach(), current_step=self.current_step)

        return self.current_result.gen_trj[:, self.current_step].detach().cpu().numpy()

    def forward(self,
            observation_seq: th.Tensor,
            action_seq: th.Tensor,
            optimize: bool,
            current_step: int,
            stop_opt: bool,
            opt_end: bool,
            opt_last: bool):
        # In inference, we want the maximum eventual reward.
        actor_input = self.get_actor_input(
            obs=observation_seq, actions=action_seq, rew=self.gl[:observation_seq.shape[0]])
        actions = self.actor.forward(actor_input)

        if self.args_obj.clip:
            actions = th.clamp(actions, min=self.clip_min, max=self.clip_max)

        if action_seq is not None:
            actions = self.proj_actions(
                action_seq, actions, current_step)

        self.history.add_value(self.history.gen_trj, actions[:, self.current_step].detach(), current_step=self.current_step)

        critic_input = self.get_critic_input(
            acts=actions, obs_seq=observation_seq)

        expected_success = self.critic.forward(
            inputs=critic_input)  # batch_size, seq_len, 1

        if not optimize:
            result = ACPOptResult(
                gen_trj=actions, expected_succes_before=expected_success.detach())
            return result

        else:
            actions, expected_success_opt = self.optimize_act_sequence(
                actions=actions,
                observations=observation_seq,
                current_step=current_step,
                stop_opt=stop_opt,
                opt_end=opt_end,
                opt_last=opt_last)

            return ACPOptResult(
                gen_trj=actions.detach(),
                expected_succes_before=expected_success,
                expected_succes_after=expected_success_opt)

    def optimize_act_sequence(self,
            actions: th.Tensor,
            observations: th.Tensor,
            current_step: int,
            stop_opt:bool,
            opt_end:bool,
            opt_last:bool):
        optimized_actions = th.clone(actions.detach())
        final_actions = th.clone(optimized_actions)
        optimized_actions.requires_grad_(True)
        optimizer = th.optim.AdamW(
            [optimized_actions], lr=self.args_obj.inference_opt_lr, weight_decay=0)
        expected_success = th.zeros(
            size=[actions.shape[0], self.critic.wsms.model_setup.seq_len, self.critic.wsms.model_setup.d_output], dtype=th.float, device=actions.device)
        final_exp_success = th.clone(expected_success)
        goal_label = self.gl[:actions.shape[0]]
        step = 0
        if self.critic.model is not None:
            self.critic.model.eval()

        while (not th.all(final_exp_success[:, -1] >= self.args_obj.optimisation_threshold)) and (step <= self.args_obj.opt_steps):
            mask = (final_exp_success[:, -1] < self.args_obj.optimisation_threshold).reshape(-1)
            optimized_actions, expected_success = self.inference_opt_step(
                org_actions=actions,
                opt_actions=optimized_actions,
                obs_seq=observations,
                optimizer=optimizer,
                goal_label=goal_label,
                current_step=current_step,
                opt_end=opt_end,
                opt_last=opt_last)
            step += 1

            if stop_opt:
                final_actions[mask] = optimized_actions[mask]
                final_exp_success[mask] = expected_success[mask]
            else:
                final_actions = optimized_actions
                final_exp_success = expected_success

        if self.args_obj.clip:
            with th.no_grad():
                th.clamp(final_actions, min=self.clip_min, max=self.clip_max, out=final_actions)
        return final_actions, final_exp_success

    def inference_opt_step(self,
            org_actions: th.Tensor,
            opt_actions: th.Tensor,
            obs_seq: th.Tensor,
            optimizer: th.optim.Optimizer,
            goal_label: th.Tensor,
            current_step: int,
            opt_end:bool= False,
            opt_last:bool= False):
        critic_inpt = self.get_critic_input(acts=opt_actions, obs_seq=obs_seq)
        critic_result = self.critic.forward(inputs=critic_inpt)
        if opt_end:
            critic_loss = self.critic.loss_fct(
                result=critic_result[:,current_step:], label=goal_label[:,current_step:])
        elif opt_last:
            critic_loss = self.critic.loss_fct(
                result=critic_result[:,-1:], label=goal_label[:,-1:])
        else:
            critic_loss = self.critic.loss_fct(
                result=critic_result, label=goal_label)
        optimizer.zero_grad()
        critic_loss.backward()
        optimizer.step()

        actions = self.proj_actions(
            org_actions=org_actions, new_actions=opt_actions, current_step=current_step)
        return actions, critic_result

    def get_critic_input(self, acts, obs_seq):
        critic_input = make_partially_observed_seq(
            obs=obs_seq, acts=acts, seq_len=self.args_obj.epoch_len, act_space=self.action_space)
        return critic_input

    def get_actor_input(self, obs: th.Tensor, actions: th.Tensor, rew: th.Tensor):
        last_reward = rew[:, -1:].repeat([1, obs.shape[1], 1])

        actor_inpt = th.cat((obs, last_reward), dim=-1)
        return actor_inpt

    def proj_actions(self, org_actions: th.Tensor, new_actions: th.Tensor, current_step: int):
        with th.no_grad():
            new_actions[:, :current_step] = org_actions[:, :current_step]
            if self.args_obj.clip:
                th.clamp(new_actions, min=self.clip_min, max=self.clip_max, out=new_actions)
        return new_actions

    def save_policy(self, add, data_path):

        path_to_file = os.path.join(data_path, "Data/Model/", add)
        if not os.path.exists(path_to_file):
            os.makedirs(path_to_file)

        th.save(self.state_dict(), path_to_file + "/policy_network")
        th.save(self.actor.optimizer.state_dict(), path_to_file + "/optimizer_actor")
        th.save(self.critic.optimizer.state_dict(), path_to_file + "/optimizer_critic")
        with open(path_to_file + '/policy_args.pkl', 'wb') as f:
            pickle.dump(self.args_obj, f)


import numpy as np
from numpy import random
import warnings
warnings.filterwarnings("ignore") #suppress warnings

np.random.seed(0)

class Layer_Dense:
    def __init__(self, n_inputs, n_neurons):
        # Making weights inputs by neurons so that we don't need to transpose the weight matrix in every forward pass
        # to match the inputs. Randomly generationg weights by guassion distribution
        self.weights = 0.001 * np.random.randn(n_inputs, n_neurons)

        #first initializing all biases to zeros, if the activation function doesn't fire, we should change it to 0.1
        self.biases = np.zeros((1, n_neurons))

    def forward(self, inputs):
        # Multiplying the dataset matrix with the weight's and then adding the bias at the end.
        self.inputs = inputs
        self.output = np.dot(inputs, self.weights) + self.biases

    # Backward pass
    def backward(self, dvalues):
        # Gradients on parameters
        self.dweights = np.dot(self.inputs.T, dvalues)
        self.dbiases = np.sum(dvalues, keepdims=True)
        # Gradient on values
        self.dvalues = np.dot(dvalues, self.weights.T)

class Activation_ReLU:
    def forward(self, inputs):
        # If the number is above 0 it keeps it, if it's below it sets it to 0
        self.inputs = inputs
        self.output = np.maximum(0, inputs)

    # Backward pass
    def backward(self, dvalues):
        # Since we need to modify original variable,
        # let's make a copy of values first
        self.dvalues = dvalues.copy()

        # Zero gradient where input values were negative
        # self.dvalues[self.inputs <= 0] = 0
        self.dvalues = np.maximum(0, self.inputs)

# Task 1: Build fully connected layer model

# Input layer receiving 2 values (x, y data. 2 unique features) with 2 neurons
inputLayer = Layer_Dense(2, 10)

# Two fully connected layers of 10 neurons each, first receiving from the two neurons in input layer
# then sending to output
layer1 = Layer_Dense(10, 10)
layer2 = Layer_Dense(10, 2)

# Activation function receiving from the 10 neurons of the last hidden layer, and outputting by two neurons.
# Setting the activation function
activation1 = Activation_ReLU()
activation2 = Activation_ReLU()


import json
import os
import sys
import logging
import unittest
import ssl
import time
import unittest

import Constant
import lib.HTMLTestRunner as HTMLTestRunner

from HCXSaasRestExt import HCXSaasRestExt
from util.PrecheckSites import PrecheckSites

TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), '../testdata/testdata.json')
TESTBED_FILENAME = os.path.join(os.path.dirname(__file__), '../testdata/testbed_info.json')

"""Set up local logger"""
logger = logging.getLogger(os.path.basename(__file__))
logger.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
logger.addHandler(ch)
"""Set up local logger End"""

class PreflightTest(unittest.TestCase):

    def setUp(self):
        self.precheck = False
        self.testfile = open(TESTDATA_FILENAME)
        self.testbedfile = open(TESTBED_FILENAME)
        self.testdata=json.load(self.testfile)
        self.testbed_info=json.load(self.testbedfile)
        self.urls=[]
        self.urls.append(self.testdata["csp_url"])
        if "https://" not in self.testdata["dev_stack"]:
            self.urls.append("https://"+self.testdata["dev_stack"])
        else:
            self.urls.append(self.testdata["dev_stack"])
        sites=["onpremhcm1", "hmva"]
        hosts=self.testbed_info["hosts"]
        for x in sites:
            if x in hosts:
                self.urls.append("https://"+hosts[x]["fqdn"])

    def test_precheck_sites(self):
        """precheck if all related sites are active."""
        obj=PrecheckSites(self.urls)
        result=obj.checkUrls()
        self.precheck = result
        self.assertEqual(True, result)

    def test_Dev_Stack_Cleanup(self):
        """Remove sites from HCX Saas portal."""
        self.shortDescription()
        obj=HCXSaasRestExt(self.testdata["dev_stack"], self.testdata["csp_url"],self.testdata["api_token"])
        result = False
        for _ in range(Constant.RETRY_CLEANUP):
            obj.cleanup_sites(self.testdata["org_id"], ["DISCONNECTED", "CONNECTED", "DEREGISTRATION_REQUESTED"])
            result=obj.size_of_sites(self.testdata["org_id"]) == 0
            if result:
                break
            time.sleep(15)
        self.assertEqual(True, result)

def fake_attrs():
    g2attrs = [
        ('My Project Name', 'Fake Project Name'),
        ('Reponsible Team', 'Fake Team'),
        ('Build Number', '42'),
    ]
    g3attrs = [
        ('Produc Under Test', 'The Fake Product Site'),
        ('Product Team', 'Fake Product Team')
    ]
    attrs = {'group2': g2attrs, 'group3': g3attrs}
    return attrs

def fake_description():
    desc = """This is a fake description
    divided in two lines."""
    return desc

if __name__ == '__main__':
    html_report = open('../../report/test_results.html', 'wb')
    # Create the runner and set the file as output and higher verbosity
    ssl._create_default_https_context = ssl._create_unverified_context
    runner = HTMLTestRunner.HTMLTestRunner(stream=html_report, verbosity=2, attrs=fake_attrs(),
                                           description=fake_description())

    '''
    # Create a test list
    tests = [
        PreflightTestCase
    ]
    # Load test cases
    loader = unittest.TestLoader()
    # Create a SuiteCase
    test_list = []
    for test in tests:
        cases = loader.loadTestsFromTestCase(test)
        test_list.append(cases)
    suite = unittest.TestSuite(test_list)
    '''
    suite = unittest.TestLoader().loadTestsFromTestCase(PreflightTest)
    # Run the suite
    runner.run(suite)


print("Bienvenidos a la calculadora \nPara salir escribe Salir\nLas operaciones son suma, multi, div, y resta")
n_1 = 0
while True:
    if not n_1:
        n_1 = input("Número uno ")
        if n_1.lower == "salir":
            break
        n_1 = int(n_1)

    operacion = input("operacion ")
    if operacion.lower == "salir":
        break
    n_2 = input("Número 2")
    if n_2.lower == "salir":
        break
    n_2 = int(n_2)

    if operacion.lower() == "suma":
        n_1 += n_2
    elif operacion.lower() == "multi":
        n_1 *= n_2
    elif operacion.lower() == "div":
        n_1 /= n_2
    elif operacion.lower() == "resta":
        n_1 -= n_2
    else:
        print("Operación no válida")
        break

    print(f"El resultado es {n_1}")


from time import clock

def pentagon(n):  # Pn=n(3n−1)/2
    return n * (3 * n - 1) / 2

def main():
    start = clock()

    pent_nums = [pentagon(n) for n in range(1, 10001)]

    D = pent_nums[-1]
    print(D)
    pair = [0, 0]

    for (j, p1) in enumerate(pent_nums):
        print(p1)
        for (k, p2) in enumerate(pent_nums[j + 1:]):
            isPentagon = (p1 + p2) in pent_nums and (p2 - p1) in pent_nums
            if p2 - p1 < D and isPentagon:
                D = p2 - p1
                pair = [p1, p2]
                break
        if pair != [0, 0]:
            break
    print(pair, D)
    print(clock() - start)

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

__doc__ = """
This script will upload JSON files created by rpm_db_builder into the database
created with create_tables.py. This should only need to be run once, then the
data will be available in the database for future queries.
"""
import sys
import time
from json import load
from os import listdir, path
from argparse import ArgumentParser

from lib import *

try:
    import psycopg2
except ImportError:
    utility.terminal_msg(0, "Psycopg2 must be installed to use this script.")

"""
The format of the json database looks roughly like the following.

{
    "BIG-IP:v11.5.1": {
        "libattr-2.4.32-1.1.0.0.110.i686.rpm": {
            "All dependencies": [
                "libc.so.6"
            ],
            "All executables": [
                "libattr.so.1.1.0",
                "libattr.so.1"
            ],
            "architecture": "i686",
            "executables": {
                "libattr.so.1": {
                    "Symlink Target": "libattr.so.1.1.0",
                    "dependencies": [
                        "libc.so.6"
                    ],
                    "symbols": {
                        "__cxa_finalize@GLIBC_2.1.3": {
                            "at": "GLIBC_2.1.3",
                            "binding": "WEAK",
                            "defined": "NO",
                            "type": "FUNC"
                        },
                        "__errno_location@GLIBC_2.0": {
                            "at": "GLIBC_2.0",
                            "binding": "GLOBAL",
                            "defined": "NO",
                            "type": "FUNC"
                        },
                        "__rawmemchr@GLIBC_2.1": {
                            "at": "GLIBC_2.1",
                        }
                    }
                }
            }
            <More data>
            "package": "libattr-2.4.32-1.1.0.0.110.i686.rpm",
            "release": "1.1.0.0.110",
            "version": "2.4.32"
        },
    },
},
"""
# SQL format strings
prod_str = ("INSERT INTO products (product) "
            "VALUES (%s) "
            "RETURNING prod_id;")

vers_str = ("INSERT INTO versions (prod_id, version) "
            "VALUES (%s, %s) "
            "RETURNING vers_id;")

rpm_sql_str = ("INSERT INTO rpms "
               "(vers_id, rpm, release, rpm_version, x86_64, i686, ppc, noarch, other_arch) "
               "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
               "RETURNING rpm_id;")

exec_sql_str = ("INSERT INTO execs "
                "(rpm_id, exec) "
                "VALUES (%s, %s) "
                "RETURNING exec_id;")

alias_sql_str = ("INSERT INTO aliases "
                 "(exec_id, alias) "
                "VALUES (%s, %s) "
                "RETURNING alias_id;")

dep_sql_str = ("INSERT INTO deps "
               "(exec_id, dep, static) "
               "VALUES (%s, %s, %s) "
               "RETURNING dep_id;")

rpath_sql_str = ("INSERT INTO rpaths "
               "(exec_id, rpath) "
               "VALUES (%s, %s) "
               "RETURNING rpath_id;")

decl_str = ("INSERT INTO decl_funcs "
            "(exec_id, func) "
            "VALUES (%s, %s) "
            "RETURNING func_id;")

at_version_str = ("INSERT INTO at_versions "
                  "(func_id, at) "
                  "VALUES (%s, %s) "
                  "RETURNING at_id;")

def_str = ("INSERT INTO def_funcs "
           "(func_id, binding) "
           "VALUES (%s, %s) "
           "RETURNING def_func_id;")

callee_str = ("INSERT INTO callee_funcs "
              "(func_id, callee_func) "
              "VALUES (%s, %s) "
              "RETURNING callee_func_id;")

rollback_str = ("DELETE FROM versions "
                "WHERE versions.version = %s;")

def existing_index(curs, table, _id, key, value):
    query_str = "SELECT %s from %s " % (_id, table)
    where_str = "WHERE %s = " % (key)
    full_query_str = query_str + where_str + " %s;"

    curs.execute(full_query_str, (value,))
    ret = curs.fetchone()

    if ret:
        return ret[0]
    else:
        return False

def insert_row(curs, sql_str, value_tuple):
    # execute statement
    curs.execute(sql_str, value_tuple)
    output = curs.fetchone()[0]

    return output

def upload(filedir):
    conn = psycopg2.connect(utility.get_conn_str())

    json_files = [path.join(filedir, x) for x in listdir(filedir) if x.endswith(".json")]

    for filename in json_files:
        terminal_msg(2, "Examining %s" % filename)
        time_import_start = time.time()
        with open(filename, "r") as f:
            json_data = load(f)
        time_import_end = time.time()
        terminal_msg(2, "File import time: {}".format(time_import_end - time_import_start))

        time_upload_start = time.time()
        for x in json_data:
            # Expecting a version string like <prod>:<vers>
            split = x.split(":")
            product = split[0]
            version = split[1]
            json_data = json_data[x]
            break
        with conn:
            with conn.cursor() as curs:
                try:
                    #debug
                    #print("inserting product cur id %d" % prod_id)
                    prod_id = existing_index(curs, "products", "prod_id", "product", product)
                    if prod_id == False:
                        prod_id = insert_row(curs, prod_str, (product,))

                    vers_id = existing_index(curs, "versions", "vers_id", "version", version)
                    if vers_id == False:
                        vers_id = insert_row(curs, vers_str, (prod_id, version))

                    for rpm in json_data:
                        try:
                            package = json_data[rpm]["package"]
                            release = json_data[rpm]["release"]
                            version = json_data[rpm]["version"]
                            x86_64 = json_data[rpm]["x86_64"]
                            i686 = json_data[rpm]["i686"]
                            ppc = json_data[rpm]["ppc"]
                            noarch = json_data[rpm]["noarch"]
                            otherarch = json_data[rpm]["other_arch"]
                            #print("inserting rpm")
                            rpm_id = insert_row(curs, rpm_sql_str, (vers_id, rpm, release, version, x86_64, i686, ppc, noarch, otherarch))

                            execs = json_data[rpm]["executables"]

                            alias_table = [] # aliases [{target_exec:blah, exec_:blah}...]
                            exist_dict = {} # [{<exec_name>: exec_id}]

                            for exe in execs:
                                #print("inserting exec")
                                try:
                                    target_exec = execs[exe]["Symlink Target"]
                                    if target_exec != "" and target_exec != exe:
                                        # Make alias table pairing the executable
                                        # and the executable it symlinks to.
                                        alias_table.append({"target_exec": target_exec, "exec": exe})
                                        continue
                                except:
                                    pass

                                exec_id = insert_row(curs, exec_sql_str, (rpm_id, exe))

                                exist_dict[exe] = exec_id; #Add real exec to existing_dict

                                dep_list = execs[exe]["dependencies"]
                                for dep in dep_list:
                                    #print ("inserting dep")
                                    dep_id = insert_row(curs, dep_sql_str, (exec_id, dep, False))
                                #print("deps inserted")
                                rpath_list = execs[exe]["rpath"]
                                for rpath in rpath_list:
                                    #print ("inserting rpath")
                                    if rpath:
                                        rpath_id = insert_row(curs, rpath_sql_str, (exec_id, rpath))
                                #print ("rpaths inserted")
                                symbol_list = execs[exe]["symbols"]

                            # getting around extra callees
                                callee_funcs = set()

                                for symbol in symbol_list:
                                    symbol_data = symbol_list[symbol]
                                    #print ("inserting symbol")
                                    sym_id = insert_row(curs, decl_str, (exec_id, symbol))
                                    try:
                                        #print ("inserting at")
                                        at = symbol_data["at"]
                                        if at:
                                            insert_row(curs, at_version_str, (sym_id, at))
                                    except:
                                        pass

                                    binding = symbol_data["binding"]
                                    defined = symbol_data["defined"]
                                    #print ("inserting definition")

                                    if defined == "YES":
                                        #print("inserted definition now")
                                        def_func_id = insert_row(curs, def_str, (sym_id, binding))
                                        #print("inserted definition %d" % def_func_id)

                                    try:
                                        #print("got here")
                                        called_funcs = symbol_data["called_functions"]
                                        for x in called_funcs:
                                            callee = x["function"]
                                            if callee == symbol:
                                                #Don't record self-references
                                                continue
                                            callee_id = insert_row(curs, callee_str, (sym_id, callee))
                                    except:
                                        pass

                            alias_passes = 0
                            while alias_table and alias_passes <= len(alias_table):
                                alias_candidate = alias_table.pop()
                                try:
                                    alias_exec_id = exist_dict[alias_candidate["target_exec"]]
                                    insert_row(curs, alias_sql_str, (alias_exec_id, alias_candidate["exec"]))
                                    exist_dict[alias_candidate["exec"]] = alias_exec_id
                                    #Reset the number of times we've looked through alias_table
                                    #Why? We might have added the right exec into the table
                                    alias_passes = 0
                                except KeyError:
                                    alias_passes += 1
                                    alias_table.insert(0, alias_candidate)
                                    #Try again, we're working with a chain of aliases it seems
                                    #print("passed through loop")

                        except Exception as e:
                            terminal_msg(1, "Exception {} occurred during processing json data".format(e))
                            raise e

                # Overall Exception handler for database access
                except (Exception, KeyboardInterrupt) as e:
                    utility.terminal_msg(1, "Exception/Interrupt {} caught during database processing static dependencies. Rolling back all changes with version {}".format(e, version))
                    try:
                        # rollback database changes
                        curs.execute(rollback_str, (version,))
                        utility.terminal_msg(2, "Database rollback complete. Program terminated.")
                        sys.exit(0)
                    except (Exception, KeyboardInterrupt) as e2:
                        terminal_msg(0, "Failed to rollback database change. Version {} within database may be corrupted. \n\t Error message: {}".format(version, e2))

        time_upload_end = time.time()
        terminal_msg(2, "Time upload: {}".format(time_upload_end - time_upload_start))

    conn.close()

if __name__ == "__main__":
    p = ArgumentParser(description=__doc__)

    p.add_argument("-j", "--json_directory", type=str, required=True,
                   help="The root directory JSON RPMDB files will be found.")

    args = p.parse_args()

    upload(args.json_directory)


import random

words = ('Python', 'Hockey', 'Cycling', 'PC', 'King', 'Out')
hints = ('A snake', 'A sport with stick and ball', 'Kings of the roads', 'The MasterRace', 'Kai', 'Opposite of In')
i = random.randint(0, len(words))

word = words[i]
hint = hints[i]

correct = word
jumble = ''

while word:
    p = random.randrange(len(word))
    jumble += word[p]
    word = word[:p] + word[p + 1:]

print('''
    HELLO THERE

WELCOME TO WORD JUMBLE
UNSCRAMBLE THE LETTERS
    TO WIN A PRIZE!

Enter !hint to get a hint
''')

print(f'The scrambled word is {jumble}')
guess = input('Please enter your guess: ')

hintUsed = False

if guess.title() == correct: print('Well done you\'ve guessed it on your first attempt')
elif guess == '!hint':
    hintUsed = True
    print(hint)

while guess.title() != correct and guess:
    print('Unlucky thats not correct. Try again')
    guess = input('Please enter your guess: ')
    if guess == '!hint':
        hintUsed = False
        print(hint)

if hintUsed: points = 1
else: points = 10

print(f'Well done you guessed the word! You earned {points}') if guess.title() == correct else print('Unfortunately you did not guess the word.')


# Licensed under a 3-clause BSD style license - see LICENSE.rst

import numpy as np

from sofia_redux.toolkit.utilities.func import bytes_string

def test_standard():
    assert bytes_string(0) == '0B'
    exponents = np.arange(9) * 3
    values = [2 * (10 ** int(e)) for e in exponents]
    bvals = [bytes_string(v) for v in values]

    assert bvals == ['2.0B', '1.95KB', '1.91MB', '1.86GB', '1.82TB',
                     '1.78PB', '1.73EB', '1.69ZB', '1.65YB']


n = int(input())
s = input()

if s.count('1') != s.count('0'):
    print('1')
    print(s)
else:
    k = 1
    for i in range(n):
        k = k + 1
        s1 = s[0:i+1]
        s2 = s[i+1:]

        if s1.count('1') != s1.count('0') and s2.count('1') != s2.count('0'):
            print(k)
            print("".join(s1),"".join(s2))
            break

1189A_Киану Ривз.py

1189A_Киану Ривз.py


#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
from config import globales
import sys
from ventanas import *

if __name__ == "__main__":
	globales.dir_work=os.path.dirname(os.path.abspath(__file__))
	globales.dir_work_aux=os.path.dirname(os.path.abspath(__file__))
	recuperar_variable_total()
	Init_cuad()
	init_dep()

	app = QtWidgets.QApplication([])

	Ventana_Inicio=Ui_Inicio()
	Ventana_Inicio.show()
	#wConfig.show()
	app.exec_()


import jwt
import traceback

from .models import UserProfile, Authority, Plaza, Booth, Ministry

def is_logged_in(request):
    try:
        # cleaing token as postman sends token in header is format :
        # 'HTTP_AUTHORIZATION' = Bearer b'<token>'
        # so formatting token as '<token>'

        token = request.META['HTTP_AUTHORIZATION'][9:]
        data = jwt.decode(token[:len(token)-1], 'SECRET_KEY')
        # extract the user id from token
        email_mobile = data['id']
        user_type = data['user_type']

        #identify is user id is email or mobile and find corresponding user
        if '@' in email_mobile:
            if user_type == 'ministry':
                user = Ministry.objects.get(email = email_mobile)
                if "b'"+token == user.token:
                    return user.email, 'ministry'

            elif user_type == 'authority':
                user = Authority.objects.get(email = email_mobile)
                if "b'"+token == user.token:
                    return user.email, 'authority'

            elif user_type == 'plaza':
                #print(email_mobile)
                user = Plaza.objects.get(email = email_mobile)
                if "b'"+token == user.token:
                    return user.email, 'plaza'

            elif user_type == 'booth':
                user = Booth.objects.get(email = email_mobile)
                if "b'"+token == user.token:
                    return user.email, 'booth'
            else:
                user = UserProfile.objects.get(email = email_mobile)
        else:
            user = UserProfile.objects.get(mobile_number = email_mobile)

        if "b'"+token == str(user):
            return user.mobile_number, 'customer'
        else:
            return False, ''
    except:
        traceback.print_exc()
        return False, ''


from setuptools import setup, find_packages

with open("README.md", "r") as fh:
    long_description = fh.read()

setup(
    name='iqss_gh_reporting',
    version='0.5',
    description='collects raw data from github and transforms it into a format that can be used for reporting',
    author='Mike Reekie',
    author_email='mike@reekie.us',
    url='https://github.com/thisaintwork/iqss_gh_reporting/tree/master/workflows',
    license='MIT',
    packages=find_packages(exclude=['deprecated', 'tests']),
    long_description=long_description,
    long_description_content_type="text/markdown",
    install_requires=[
        'PyGithub',
        'gql',
        'pathvalidate',
        'pandas',
        'pyyaml',
        'graphql-py',
        'aiohttp',
        'numpy'
    ],
    scripts=['workflows/create_iq_snapshot_init',
             'workflows/create_iq_snapshot',
             'workflows/process_labels'
             ],
)


import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
from sklearn.linear_model import LinearRegression
from sklearn import svm, preprocessing
from sklearn.cluster import KMeans
from statsmodels.stats.multicomp import pairwise_tukeyhsd

######### CONFIG #########

sns.set_theme(style = "darkgrid")
sns.color_palette("flare", as_cmap = True)

######### BASICS #########

def excel_check(file):
	if ".xlsx" in file:
		print("Detected an Excel file, boss. \n")
		worksheet = int(input("Which worksheet number to load, Boss? \n"))
		df = pd.read_excel(file, sheet_name = worksheet)
		return df
	else:
		df = pd.read_csv(file, decimal = ".", delimiter = ",")
		return df

def info():
	print("\nHere are the basics about this data, Boss: \n")
	print(df.info())

def head():
	print(df.head(10))

def tail():
	print(df.tail(10))

def desc():
	print(df.describe())

def count():
	print(df.value_counts())

def count_missing():
	print("\nI've counted these missing values, Boss: \n")
	print(df.isna().sum())

######### DATAFRAME JUGGLEZ #########

def multi_select():
	payload = []
	state = True

	while (state):
		entry = input("Which column to select, boss? (Press XX for pushing the payload.) \n")

		if (entry == "XX"):
			state = False
			print("\nAllright, Boss – I'm pushing the payload to process!\n")
		else:
			payload.append(entry)
			print("Added this column to the payload, Boss!\n")
			print("Current payload:")
			print(payload)
			print("\n")

	return payload

def load_new_df():
	payload = multi_select()
	return df_save[payload]

def remove_column():
	payload = multi_select()
	return df.drop(payload, axis = 1)

def pivot(column, row, value):
	return df.pivot(columns = column, index = row, values = value)

def crosstab(x, y):
	return pd.crosstab(df[x], df[y])

def drop_dup():
	return df.drop_duplicates().reset_index(drop = True)

def drop_nan():
	return df.dropna().reset_index(drop = True)

def fill_nan(value):
	return df.fillna(value)

def normalize():
	x = df.values
	min_max_scaler = preprocessing.MinMaxScaler()
	x_normalized = min_max_scaler.fit_transform(x)
	return pd.DataFrame(x_normalized, columns = df.columns)

######### VISUALS #########

def plot(y):
	sns.lineplot(x = range(len(df)), y = y, data = df)

	mean = df[y].mean()
	std = df[y].std()
	std_lo = mean - std
	std_hi = mean + std

	plt.axhline(mean, 0, 1, color = "red", label = "Mean")
	plt.axhline(std_lo, 0, 1, color = "black", linestyle = "--")
	plt.axhline(std_hi, 0, 1, color = "black", linestyle = "--")

	plt.title(y)
	plt.legend()

	plt.show()

def scat(x, y):

	sns.regplot(x = x, y = y, data = df)

	mean = df[y].mean()
	std = df[y].std()
	std_lo = mean - std
	std_hi = mean + std

	plt.axhline(mean, 0, 1, color = "red", label = "Mean")
	plt.axhline(std_lo, 0, 1, color = "black", linestyle = "--")
	plt.axhline(std_hi, 0, 1, color = "black", linestyle = "--")

	plt.title(x + " vs " + y)
	plt.show()

def heat(x, y, z):

	df_pivot = df.pivot(x, y, z)

	f, ax = plt.subplots(figsize=(9, 6))

	sns.heatmap(df_pivot, annot=True, linewidths=.5, ax=ax)

	plt.title("Heatmap of " + x + "," + y + "," + z)
	plt.show()

def box(y):
	if (y == "All" or y == "all"):
		sns.boxplot(data = df)
	else:
		sns.boxplot(data = df, y = y)

	plt.show()

def violin(y):
	if (y == "All" or y == "all"):
		sns.violinplot(data = df)
	else:
		sns.violinplot(data = df, y = y)

	plt.show()

def hist(y):

	if (y == "All" or y == "all"):
		sns.histplot(data = df, kde = True)
	else:
		sns.histplot(data = df, x = y, kde = True)

		mean = df[y].mean()
		std = df[y].std()
		std_lo = mean - std
		std_hi = mean + std

		plt.axvline(mean, 0, 1, color = "red", label = "Mean")
		plt.axvline(std_lo, 0, 1, color = "black", linestyle = "--")
		plt.axvline(std_hi, 0, 1, color = "black", linestyle = "--")

	plt.show()

def pairplot():
	sns.pairplot(df)

	plt.show()

######### TESTS #########

def side_switch():
	switch = input("""What kind of test are we running, Mr.Boss? \n
		<TwoSided>      Is the observed X different than our expectation?
		<LeftSided>     Is the observed X smaller than our expectation?
		<RightSided>    Is the observed X bigger than our expectation? \n
		""")

	if (switch == "LeftSided"):
		return "LeftSided"
	elif (switch == "RightSided"):
		return "RightSided"
	else:
		return "TwoSided"

def pval_check_ttest(tstat, pval, sig, test_side):

		if (test_side == "LeftSided"):
			if ((pval / 2) < sig and tstat < 0):
				print("P-Value is: " + str((pval / 2)) + ". T-Value is: " + str(tstat) + ". Result is significant, Boss!")
				print("This means, that the observed X is smaller than our expectation, boss!")
			else:
				print("P-Value is: " + str((pval / 2)) + ". T-Value is: " + str(tstat) + ". Result is insignificant, Boss!")
				print("This means, that the observed X is not smaller than our expectation, boss!")

		elif (test_side == "RightSided"):
			if ((pval / 2) < sig and tstat > 0):
				print("P-Value is: " + str((pval / 2)) + ". T-Value is: " + str(tstat) + ". Result is significant, Boss!")
				print("This means, that the observed X is bigger than our expectation, boss!")
			else:
				print("P-Value is: " + str((pval / 2)) + ". T-Value is: " + str(tstat) + ". Result is insignificant, Boss!")
				print("This means, that the observed X is not bigger than our expectation, boss!")

		else:

			if (pval < sig):
				print("P-Value is: " + str(pval) + ". Result is significant, Boss!")
				print("This means, that the observed X is different than our expectation, boss!")

			else:
				print("P-Value is: " + str(pval) + ". Result is insignificant, Boss!")
				print("This means, that the observed X is not different than our expectation, boss!")

def pval_check(pval, sig):
	if (pval < sig):
		print("P-Value is: " + str(pval) + ". Result is significant, Boss!")
		print("This means, that the observed values are different, boss! \n")
	else:
		print("P-Value is: " + str(pval) + ". Result is insignificant, Boss!")
		print("This means, that the observed values are not different, boss! \n")

def corr(x, y):
	corr, p = stats.pearsonr(df[x], df[y])
	print(corr)

def ttest_1samp(sample_distribution, expected_mean, sig, test_side):
	tstat, pval = stats.ttest_1samp(df[sample_distribution], expected_mean)
	pval_check_ttest(tstat, pval, sig, test_side)

def ttest_2samp(sample_a, sample_b, sig, test_side):
	tstat, pval = stats.ttest_ind(df[sample_a], df[sample_b])
	pval_check_ttest(tstat, pval, sig, test_side)

def anova(sample_a, sample_b, sample_c, sig):
	fstat, pval = stats.f_oneway(df[sample_a], df[sample_b], df[sample_c])
	pval_check(pval, sig)

def tukey(sample_a, sample_b, sig):
	tukey_results = pairwise_tukeyhsd(df[sample_a], df[sample_a], sig)
	print(tukey_results)

def chi(sample_a, sample_b, sig):
	xtable = pd.crosstab(df[sample_a], df[sample_b])
	chi2, pval, dof, expected = stats.chi2_contingency(xtable)
	pval_check(pval, sig)

def bino(successes, expected_probability, sig):
	suc_res = np.sum(df[successes] == 1)
	n = len(df[successes])
	pval = stats.binom_test(suc_res, n, p = expected_probability)
	pval_check(pval, sig)

######### MACHINE INTELLIGENCE #########

def linreg(x, y, predvalue):
	line_fitter = LinearRegression()

	x_in = df[x].values.reshape(-1, 1)
	y_in = df[y].values.reshape(-1, 1)

	line_fitter.fit(x_in, y_in)

	a = round(line_fitter.intercept_[0], 2)
	b = round(line_fitter.coef_[0][0], 2)

	print("\nLinear Regression formula for this model is:")
	print("Y = " + str(a) + " + " + str(b) + "x \n")

	pred_in = np.array(predvalue).reshape(-1, 1)
	y_predicted = round(line_fitter.predict(pred_in)[0][0], 2)

	print("With " + str(predvalue) + " (" + x + ") we expect " + str(y_predicted) + " (" + y + "), Boss!")

def svm_run(sample_a, predvalue):
	y = df[sample_a]
	X = df.drop(columns = sample_a, axis = 1)

	SVM = svm.LinearSVC()
	SVM.fit(X, y)
	print("\nSVM is fit, Boss!\n")

	print("Mean accuracy of the training data is:")

	score = SVM.score(X,y)
	print(round(score, 4))

	pred = SVM.predict(predvalue)
	print("\nPredicted label is:")
	print(str(int(pred[0])) + "\n")

def cluster(clusters):

	X = df.values

	kmeans = KMeans(n_clusters = clusters)
	kmeans.fit(X)
	print(kmeans.cluster_centers_)

	to_plot = input("\nBoss, do you want see the plot for these clusters? (Yes / No) \n")

	if (to_plot == "Yes"):

		plt.scatter(X[:,0],X[:,1], c = kmeans.labels_)

		columns = df.columns

		plt.xlabel(columns[0])
		plt.ylabel(columns[1])
		plt.title(columns[0] + " vs " + columns[1] + " Cluster")

		plt.show()

######### BONUS #########

def calc_samplesize(std, aim, baseline):
	z = 1.96
	sig = 0.05
	power = 0.8416
	std = std
	mde = (aim - baseline) / 100
	print("\nMinimum detectable effect is " + str(mde * 100) + " %.")

	n = ( 2 * ((z + power) * 2) * ((std) * 2) ) / ( (mde) * 2 )
	n = round(n)

	print("Sample size of " + str(n) + " is required, Boss!")

######### ENGINE #########

def help():

	print("""
*********************************************************************************************************************************
* * * * * *                                               ◊ DATAWIZ ◊                                                 * * * * * *
* *                                           v1.0             ◊                                                              * *
*                                                                                *
*                                  by David Weicht – Project Manager for Digital Marketing                                      *
*                                                     www.davidweicht.de                                                        *
*********************************************************************************************************************************
*                                                                                *
*    COMMANDS   ______________________________________________________________________________________________________________  *
*                                                                                *
*                                                                                *
*    _BASICS                                  _PLOTS                                 _JUGGLEZ                                   *
*                                                                                *
*    <Info>     Data Meta                     <Plot>     Lineplot                    <New>      New DataFrame                   *
*    <Head>     Data Heads                    <Scat>     Scatterplot                 <Reload>   Reload Original DataFrame       *
*    <Tail>     Data Tails                    <Heat>     Heatmap                     <Delete>   Delete Column(s)                *
*    <Desc>     Descriptive Stats             <Box>      Boxplot                     <Pivot>    Pivot DataFrame                 *
*    <Count>    Count Values                  <Violin>   Violinplot                  <Cross>    Create Crosstable               *
*    <CountM>   Count Missing Values          <Hist>     Histogram                   <DropD>    Drop Duplicates                 *
*                                             <Pair>     Pairplot                    <DropN>    Drop NaN                        *
*                                                                                <FillN>    Fill NaN                        *
*                                                                                <Norm>     Normalize DataFrame             *
*                                                                                *
*                                                                                *
*    _ANALYSIS                                _MACHINE INTELLIGENCE                  _BONUS                                     *
*                                                                                *
*    <Corr>     Correlation                   <LinR>     Linear Regression           <Size>     Sample Size Calculator          *
*    <Test1>    T-Test (One Sample)           <SVM>      SVM (Two Samples)                                                      *
*    <Test2>    T-Test (Two Samples)          <Cluster>  K-Means Clustering                                                     *
*    <Anova>    Anova (Three Samples)                                                                                *
*    <Tukey>    Tukey-Test                                                                                *
*    <Chi2>     Chi-Square-Test                                                                                *
*    <Bino>     Binomial Test                                                                                *
*                                                                                *
*                                                                                *
*    <Help>     Commands                                                                                *
*    <Quit>     Quit Datawiz                                                                                *
*                                                                                *
*********************************************************************************************************************************
	""")

def commander(cmd):
	global df, df_save

	if (cmd == "Info" or cmd == "info"):
		info()

	elif (cmd == "Head" or cmd == "head"):
		head()

	elif (cmd == "Tail" or cmd == "tail"):
		tail()

	elif (cmd == "Desc" or cmd == "desc"):
		desc()

	elif (cmd == "Count" or cmd == "count"):
		count()

	elif (cmd == "CountM" or cmd == "countm"):
		count_missing()

	elif (cmd == "Plot" or cmd == "plot"):
		y = input("Which column to plot as Y, Boss? \n")
		plot(y)

	elif (cmd == "Scat" or cmd == "scat"):
		x = input("Which column to plot as X, Boss? \n")
		y = input("Which column to plot as Y, Boss? \n")
		scat(x, y)

	elif (cmd == "Heat" or cmd == "heat"):
		x = input("Which column to plot as X, Boss? \n")
		y = input("Which column to plot as Y, Boss? \n")
		z = input("Which column to plot as Z, Boss? \n")
		heat(x, y, z)

	elif (cmd == "Box" or cmd == "box"):
		y = input("Which column(s) to plot, Boss? (All for all columns.) \n")
		box(y)

	elif (cmd == "Violin" or cmd == "violin"):
		y = input("Which column(s) to plot, Boss? (All for all columns.) \n")
		violin(y)

	elif (cmd == "Hist" or cmd == "hist"):
		y = input("Which column(s) to plot, Boss? (All for all columns.) \n")
		hist(y)

	elif (cmd == "Pair" or cmd == "pair"):
		pairplot()

	elif (cmd == "Corr" or cmd == "corr"):
		x = input("Which column to plot as X, Boss? \n")
		y = input("Which column to plot as Y, Boss? \n")
		corr(x, y)

	elif (cmd == "Test1" or cmd == "test1"):
		sample_distribution = input("What is the sample, Boss? \n")
		expected_mean = float(input("What is the expected mean, Boss? \n"))
		test_side = side_switch()
		sig = float(input("What significance level, Boss? \n"))
		ttest_1samp(sample_distribution, expected_mean, sig, test_side)

	elif (cmd == "Test2" or cmd == "test2"):
		sample_a = input("What is first sample group, Boss? \n")
		sample_b = input("What is second sample group, Boss? \n")
		test_side = side_switch()
		sig = float(input("What significance level, Boss? \n"))
		ttest_2samp(sample_a, sample_b, sig, test_side)

	elif (cmd == "Anova" or cmd == "anova"):
		sample_a = input("What's the first sample group, Boss? \n")
		sample_b = input("What's the second sample group, Boss? \n")
		sample_c = input("What's the third sample group, Boss? \n")
		sig = float(input("What's the significance level, Boss? \n"))
		anova(sample_a, sample_b, sample_c, sig)

	elif (cmd == "Tukey" or cmd == "tukey"):
		sample_a = input("What's the float sample, Boss? \n")
		sample_b = input("What's the grouped sample, Boss? \n")
		sig = float(input("What's the significance level, Boss? \n"))
		tukey(sample_a, sample_b, sig)

	elif (cmd == "Chi2" or cmd == "chi2"):
		sample_a = input("What is first sample group, Boss? \n")
		sample_b = input("What is second sample group, Boss? \n")
		sig = float(input("What significance level, Boss? \n"))
		chi(sample_a, sample_b, sig)

	elif (cmd == "Bino" or cmd == "bino"):
		successes = input("Which column shall I take for successes, Boss? \n")
		expected_probability = float(input("What is expected probability, Boss? \n"))
		sig = float(input("What significance level, Boss? \n"))
		bino(successes, expected_probability, sig)

	elif (cmd == "LinR" or cmd == "linr"):
		x = input("Which column for X, Boss? \n")
		y = input("Which column for Y, Boss? \n")
		predvalue = float(input("Which x-value to predict a y-value, Boss? \n"))
		linreg(x, y, predvalue)

	elif (cmd == "SVM" or cmd == "svm"):

		print("\nBoss, you remember to better normalize that data first? \n")

		y = input("Which column is featuring the label to be classified, Boss? \n")
		pred_a = input("What's the first value to predict, boss? \n")
		pred_b = input("What's the second value to predict, boss? \n")
		predvalue = np.array([[float(pred_a), float(pred_b)]])
		svm_run(y, predvalue)

	elif (cmd == "Cluster" or cmd == "cluster"):
		clusters = int(input("How many clusters to try, Boss? \n"))
		cluster(clusters)

	elif (cmd == "Size" or cmd == "size"):
		aim = float(input("What aim (in XX %) do we want to reach, Boss? \n"))
		baseline = float(input("What's the baseline (in XX %), Boss? \n"))
		std = float(input("What's the standard deviation (in XX %), Boss? \n"))
		calc_samplesize(std, aim, baseline)

	elif (cmd == "New" or cmd == "new"):
		df = load_new_df()
		print("New DataFrame created, boss!")

	elif (cmd == "Reload" or cmd == "reload"):
		df = df_save
		print("Original DataFrame reloaded, boss!")

	elif (cmd == "Delete" or cmd == "delete"):
		df = remove_column()
		print("Deleted, Boss!\n")

	elif (cmd == "Pivot" or cmd == "pivot"):
		column = input("Which column to pivot, Boss? \n")
		row = input("Which column to take as rows, boss? \n")
		value = input("Which column to take as values, Boss? \n")
		df = pivot(column, row, value)
		print("Pivot done, boss!\n")

	elif (cmd == "Cross" or cmd == "cross"):
		x = input("Which column for X, Boss? \n")
		y = input("Which column for Y, Boss? \n")
		df = crosstab(x, y)
		print(df)

	elif (cmd == "DropD" or cmd == "dropd"):
		df = drop_dup()
		print("Dropped the dups, Boss!\n")

	elif (cmd == "DropN" or cmd == "dropn"):
		df = drop_nan()
		print("Dropped the NaNs, Boss!\n")

	elif (cmd == "FillN" or cmd == "filln"):
		fill_value = input("\nWhat to fill the missing values with, Boss? \n")
		df = fill_nan(fill_value)
		print("\nFilled all NaNs with " + str(fill_value) + ", boss!\n")

	elif (cmd == "Norm" or cmd == "norm"):
		df = normalize()
		print("Normlized the data, boss!\n")

	elif (cmd == "Help" or cmd == "help"):
		help()

	elif (cmd == "Quit" or cmd == "quit"):
		print("Allright – I'm out, Boss! \n")
		exit()

	else:
		print("I'm sorry, Boss. I'm stupid. Dunno whattu do...")

def run():
	help()

	while True:
		cmd = input("What now, Boss? \n")
		commander(cmd)
		print("\n")

######### RUNNER #########

file = "./data.csv"

df = excel_check(file)
df_save = df

run()

######### IDEEN #########
#
# Check des Sample Size Rechners
#
# Weiteres Machine Learning
#	SVM (Multivariater Input).
#	Multi-Class Classifier.
#   PyTorch.
#
# Detailed Plot Selector
#	Select Plot-Type
#		Weitere Plots
#			Swarm
#			Countplot
#	Select X-Value
#   Select Y-Value
#	Select Variable as Hue
#
# Aktualisiere Tests mit Alternativen-Testseitenparameter
#
# Anova mit Multiauswahl von Variablen
#
# Data Science Wiki
#
# Input-Fehler ableiten
#
# Panda DataFrame Operationen
#	Füge kalkulierte Spalte hinzu
#		Inklusive Text-Input als Operation (eval("2 + 2"))
#
# GeoMaps
#
# CI-Extractor (zieht z.B. Farbcodes einer URL und erstellt ein Seaborn-Farbschema)
#
# ColorScheme Selector
#
# SQL-Uploader
#
# Tableau-API-Connector
#
# Webscraper
#
# Allround Report als PDF
#	Save to Report
#	Print Report as PDF
#
# Mailer
#
# Ablage weiterer Dataframes
#	Automatische Aufteilung in Trainings- und Test-Daten.
# Übersicht aktueller Dataframes
# Auswahl bestimmter Dataframes
#
# Plot auf der Website anzeigen
#
#


with open('./rosalind_ba3h (1).txt','r') as f:
    k=int(f.readline().strip())
    X = f.readlines()
    dna = [i.rstrip('\n') for i in X]

def DeBrujinGraph( text):
    graph = {}
    for i in text:
        prvi_node = i[:- 1]
        drugi_node = i[1:]
        if prvi_node not in graph.keys():
            graph[prvi_node] = drugi_node
        else:
            graph[prvi_node] += "," + drugi_node
    return graph

res = DeBrujinGraph( dna)
print(res)
string=''
key=''
for re in res.keys():
    if re not in res.values():
        string=re
        key=re
while key in res:
    string += res[key][-1]
    key = string[-k+1:]

print(string)
#with open(output_filename, 'w') as output_file:
   # for key in sorted(res.keys()):
       # output_file.write(key + " -> " + res[key] + "\n")


import plotly_express as px
import csv
import numpy as np

def getDataSource(data_path):
    icec_sales = []
    cold_sales = []
    with open(data_path) as csv_file:
        csv_reader = csv.DictReader(csv_file)
        for row in csv_reader:
            icec_sales.append(float(row["Temperature"]))
            cold_sales.append(float(row["Ice-cream Sales( â‚¹ )"]))

    return{"x":icec_sales,"y":cold_sales}

def findCorrel(datasource):
    correl = np.corrcoef(datasource["x"],datasource["y"])
    print("Correlation between Temperature and Ice Cream : \n",correl[0,1])

def setup():
    data_path = "c.csv"
    datasource = getDataSource(data_path)
    findCorrel(datasource)

setup()


from . import views
from django.urls import path, include

urlpatterns = [

    path('category/', views.category_list),

    path('product/', views.product_list),
    path('product/<int:pk>/', views.product_details),

    path('order/', views.order_list),
    path('order/<int:pk>/', views.order_details),

    path('user/', views.user_list),
    path('user/<int:pk>/', views.user_details),

    path('bot/', views.bot_list),
    path('bot/<int:pk>/', views.bot_details),
]


# -*- coding: utf-8 -*-
import os, re
from shutil import copytree
from toolset.utils.metadata import Metadata

class Scaffolding:
    def __init__(self, benchmarker):
        print("""
-------------------------------------------------------------------------------
    This wizard is intended to help build the scaffolding required for a new
    test to be benchmarked.

    From here, you will be prompted for values related to the test you
    wish to add.
-------------------------------------------------------------------------------"""
              )

        self.benchmarker = benchmarker
        self.benchmarker_config = benchmarker.config

        try:
            self.__gather_display_name()
            self.__gather_language()
            self.__gather_approach()
            self.__gather_classification()
            self.__gather_database()
            self.__gather_orm()
            self.__gather_webserver()
            self.__gather_versus()
            self.__confirm_values()
            self.__print_success()
        except:
            print("")

    def __gather_display_name(self):
        print("""
  The name of your test as you wish it to be displayed on the results page.

  Example: Gemini, Gin, Express
    """)
        self.__prompt_display_name()
        while not self.display_name:
            self.__prompt_display_name()
        self.name = self.display_name.lower()

    def __prompt_display_name(self):
        self.display_name = input("Name: ").strip()

        found = False
        for framework in self.benchmarker.metadata.gather_frameworks():
            if framework.lower() == self.display_name.lower():
                found = True

        if found:
            print("""
  It appears that there is already a '%s' framework in the test suite. You will
  have to pick a different name.
      """ % self.display_name)
            self.display_name = None

    def __gather_language(self):
        print("""
  The language in which your test implementation is written.

  Example: Java, Go, PHP
    """)
        self.language = None
        while not self.language:
            self.__prompt_language()

    def __prompt_language(self):
        self.language = input("Language: ").strip()

        known_languages = self.benchmarker.metadata.gather_languages()
        language = None
        for lang in known_languages:
            if lang.lower() == self.language.lower():
                language = lang

        if not language:
            similar = []
            for lang in known_languages:
                if lang.lower()[:1] == self.language.lower()[:1]:
                    similar.append(lang)
            similar = ', '.join(similar)

            print("""
  That language is not currently in our list of known languages.

  Here is a list of similar languages present in our benchmark suite that you
  may have meant:

  %s

  Did you mean to add the new language, '%s', to the benchmark suite?
      """ % (similar, self.language))
            valid = self.__prompt_confirm_new_language()
            while not valid:
                valid = self.__prompt_confirm_new_language()

            if self.confirm_new_lang == 'n':
                self.language = None
            else:
                self.language = self.language.title()

        return self.language

    def __prompt_confirm_new_language(self):
        self.confirm_new_lang = input("Create New Language '%s' (y/n): " %
                                          self.language).strip().lower()
        return self.confirm_new_lang == 'y' or self.confirm_new_lang == 'n'

    def __gather_approach(self):
        print("""
  The approach of your test implementation.

  1) Realistic: Uses the framework with most out-of-the-box functionality
                enabled. We consider this realistic because most applications
                built with the framework will leave these features enabled.
  2) Stripped:  Removes or outright avoids implementing features that are
                unnecessary for the particulars of the benchmark exercise. This
                might illuminate the marginal improvement available in fine-
                tuning a framework to your application's use-case.

  Note: If you are unsure, then your approach is probably Realistic. The
        Stripped approach is seldom used and will not have results displayed
        by default on the results website.
    """)
        valid = self.__prompt_approach()
        while not valid:
            valid = self.__prompt_approach()

    def __prompt_approach(self):
        self.approach = input("Approach [1/2]: ").strip()
        if self.approach == '1':
            self.approach = 'Realistic'
        if self.approach == '2':
            self.approach = 'Stripped'
        return self.approach == 'Realistic' or self.approach == 'Stripped'

    def __gather_classification(self):
        print("""
  The classification of your test implementation.

  1) Fullstack: Robust framework expected to provide high-level functionality
                for serving as a web application; for example, ability to
                compose views, provide functions for responding with several
                data types (json, html, etc), connecting to a database, form
                processing, etc.
  2) Micro:     Simple framework expected to provide enough middleware to build
                a robust web application such as request routing and some
                simple plumbing, but may not include built-in functionality
                such as, for example, server-composed views.
  3) Platform:  Barebones infrastructure for servicing HTTP requests, but does
                not include a framework at all.
    """)
        valid = self.__prompt_classification()
        while not valid:
            valid = self.__prompt_classification()
        if self.classification == 'Platform':
            self.platform = 'None'
            self.framework = 'None'
        else:
            self.framework = self.display_name
            self.__gather_platform()

    def __prompt_classification(self):
        self.classification = input("Classification [1/2/3]: ").strip()
        if self.classification == '1':
            self.classification = 'Fullstack'
        if self.classification == '2':
            self.classification = 'Micro'
        if self.classification == '3':
            self.classification = 'Platform'
        return self.classification == 'Fullstack' or \
               self.classification == 'Micro' or \
               self.classification == 'Platform'

    def __gather_platform(self):
        print("""
  The platform of your test implementation.

  The platform is the low-level software or API used to host web applications
  for the framework; the platform provides an implementation of the HTTP
  fundamentals.

  Not all frameworks have a platform and if your programming language provides
  much of that by which we define a platform, leave blank.

  Example: Servlet, Wai, .NET
    """)
        self.__prompt_platform()

    def __prompt_platform(self):
        self.platform = input("Platform (optional): ").strip()
        if self.platform == '':
            self.platform = 'None'

    def __gather_database(self):
        print("""
  Which database will you be using for your test?
    """)
        i = 1
        prompt = "Database ["
        options = []
        for db in Metadata.supported_dbs:
            print("  {!s}) {!s}".format(i, db[0]))
            prompt += "{!s}/".format(i)
            options.append(db[0])
            i += 1
        print("  {!s}) None: No database at this time{!s}".format(
            i, os.linesep))
        prompt += "{!s}]: ".format(i)
        options.append("None")
        valid = self.__prompt_database(prompt, options)
        while not valid:
            valid = self.__prompt_database(prompt, options)

    def __prompt_database(self, prompt, options):
        self.database = input(prompt).strip()
        if 0 < int(self.database) <= len(options):
            self.database = options[int(self.database) - 1]
            return True
        else:
            return False

    def __gather_orm(self):
        if self.database == 'None':
            self.orm = 'None'
            return

        print("""
  How you would classify the ORM (object relational mapper) of your test?

  1) Full:  A feature-rich ORM which provides functionality for interacting
            with a database without writing a query in all but the most edge
            cases.
  2) Micro: An ORM which provides functionality for interacting with a database
            for many trivial operations (querying, updating), but not more
            robust cases (for example, gathering relations).
  3) Raw:   No ORM; raw database access.
    """)
        valid = self.__prompt_orm()
        while not valid:
            valid = self.__prompt_orm()

    def __prompt_orm(self):
        self.orm = input("ORM [1/2/3]: ").strip()
        if self.orm == '1':
            self.orm = 'Full'
        if self.orm == '2':
            self.orm = 'Micro'
        if self.orm == '3':
            self.orm = 'Raw'
        return self.orm == 'Full' or \
               self.orm == 'Micro' or \
               self.orm == 'Raw'

    def __gather_webserver(self):
        print("""
  Name of the front-end webserver sitting in front of your test implementation.

  Your test implementation may not use a web-server and may act as its own; you
  can leave this blank in this case.

  Example: nginx, Meinheld, httplight
    """)
        self.__prompt_webserver()

    def __prompt_webserver(self):
        self.webserver = input("Webserver (optional): ").strip()
        if self.webserver == '':
            self.webserver = 'None'

    def __gather_versus(self):
        print("""
  The name of another test (elsewhere in this project) that is a subset of this
  framework.
  This allows for the generation of the framework efficiency chart in the
  results web site.
  For example, Compojure is compared to "servlet" since Compojure is built on
  the Servlet platform.

  Example: Servlet, Wai, Undertow
    """)
        self.__prompt_versus()

    def __prompt_versus(self):
        self.versus = input("Versus (optional): ").strip()
        if self.versus == '':
            self.versus = 'None'

    def __confirm_values(self):
        print("""
    Name: %s
    Language: %s
    Approach: %s
    Classification: %s
    Platform: %s
    ORM: %s
    Webserver: %s
    Versus: %s

  Finalize the initialization of your test given the above values?

  Note: once you have initialized your test, you can change these values later.
    """ % (self.display_name, self.language, self.approach,
           self.classification, self.platform, self.orm, self.webserver,
           self.versus))

        valid = self.__prompt_confirmation()
        while not valid:
            valid = self.__prompt_confirmation()

        if self.confirmation == 'y':
            self.__build_scaffolding()
        else:
            print('Aborting')

    def __prompt_confirmation(self):
        self.confirmation = input("Initialize [y/n]: ").strip().lower()
        return self.confirmation == 'y' or self.confirmation == 'n'

    def __build_scaffolding(self):
        if self.__create_test_folder():
            self.__copy_scaffold_files()
            self.__edit_scaffold_files()

    def __create_test_folder(self):
        self.language_dir = os.path.join(self.benchmarker_config.lang_root,
                                         self.language)
        self.test_dir = os.path.join(self.language_dir, self.name)

        if os.path.exists(self.test_dir):
            print("Test '%s' already exists; aborting." % self.name)
            return False

        return True

    def __copy_scaffold_files(self):
        copytree(self.benchmarker_config.scaffold_root, self.test_dir)

    def __edit_scaffold_files(self):
        for file in os.listdir(os.path.join(self.test_dir)):
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$NAME", self.name)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$DISPLAY_NAME",
                self.display_name)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$APPROACH", self.approach)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$CLASSIFICATION",
                self.classification)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$FRAMEWORK",
                self.framework)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$LANGUAGE", self.language)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$DATABASE", self.database)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$ORM", self.orm)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$PLATFORM", self.platform)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$WEBSERVER",
                self.webserver)
            self.__replace_text(
                os.path.join(self.test_dir, file), "\$VERSUS", self.versus)

    def __print_success(self):
        print("""
-------------------------------------------------------------------------------
  Success!

  Your new test structure has been built to the specifications of the suite.
  Here is a brief run-down of what has been built:

    frameworks
        └─── %s
              └─── %s
                    ├─── benchmark_config.json
                    ├─── README.md

  The next step is to read through your README.md and follow the instructions
  provided therein.
-------------------------------------------------------------------------------"""
              % (self.language, self.name))

    # Replaces all text found using the regular expression to_replace with the supplied replacement.
    def __replace_text(self, file, to_replace, replacement):
        with open(file, "r") as conf:
            contents = conf.read()
        replaced_text = re.sub(to_replace, replacement, contents)
        with open(file, "w") as f:
            f.write(replaced_text)


# 가위 = 1 바위 =2 보 =3
A,B = map(int, input().split())
ans = ""
if A>B and A!=3:
    ans = "A"
elif A==3 and B!=1:
    ans = "A"
else:
    ans = "B"
print(ans)


from django.urls import re_path

from olympia.addons.urls import ADDON_ID
from olympia.amo.views import frontend_view

from . import views

urlpatterns = [
    re_path(r'^$', frontend_view, name='addons.versions'),
    re_path(
        r'^(?P<version_num>[^/]+)/updateinfo/$',
        views.update_info,
        name='addons.versions.update_info',
    ),
]

download_patterns = [
    # /<locale>/<app>/file/<id>/filename.xpi
    # /<locale>/<app>/file/<id>/type:attachment/filename.xpi
    # See comment in File.get_url_path(): do not change this without checking
    # with Fenix first, the pattern is hardcoded in their code.
    re_path(
        (
            r'^file/(?P<file_id>\d+)/'
            r'(?:type:(?P<download_type>\w+)/)?'
            r'(?:(?P<filename>[\w+.-]*))?$'
        ),
        views.download_file,
        name='downloads.file',
    ),
    re_path(
        r'^source/(?P<version_id>\d+)', views.download_source, name='downloads.source'
    ),
    # /latest/<id>/type:xpi/platform:5/lol.xpi - everything after the addon id
    # is ignored though.
    re_path(
        (
            r'^latest/%s/'
            r'(?:type:(?P<download_type>\w+)/)?'
            r'(?:platform:(?P<platform>\d+)/)?'
            r'(?:(?P<filename>[\w+.-]*))?$'
        )
        % ADDON_ID,
        views.download_latest,
        name='downloads.latest',
    ),
]


import sys
inputs = sys.stdin.readline

N = int(input())

dp = [[0]*10 for _ in range(N+1)]
dp[1] = [1]*10
dp[1][0] = 0
if N > 1:   # 1보다 크면 => 마지막 자리수 수를 기준으로 +,- 1에 ++
    for i in range(2,N+1):
        for j in range(10):
            if j == 0:
                dp[i][j+1] += dp[i-1][j]
            elif j == 9:
                dp[i][j-1] += dp[i-1][j]
            else:
                dp[i][j + 1] += dp[i - 1][j]
                dp[i][j - 1] += dp[i - 1][j]

print(sum(dp[-1])%1000000000)


import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import pickle
import math
import glob
from random import randint

iDebugPlot=3

def cal_undistort(img, objpoints, imgpoints):
    # Use cv2.calibrateCamera and cv2.undistort()
    #print(img.shape[::-1])
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    #print(gray.shape[::-1])
    ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
    undist = cv2.undistort(img, mtx, dist, None, mtx)
    return undist,mtx, dist

def calibrateOnFrame(img):
    nx = 9 # the number of inside corners in x
    ny = 6 # the number of inside corners in y
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    ret, corners = cv2.findChessboardCorners(gray, (9,6),None)
    img2 = cv2.drawChessboardCorners(img, (9,6), corners, ret)

    objpoints = [] # 3D points in real world
    imgpoints =[] # 2D points in image plane

    objp = np.zeros((nx*ny,3),np.float32)
    objp[:,:2] = np.mgrid[0:nx,0:ny].T.reshape(-1,2)

    return corners, objp, ret

def undistoredFrame(img,mtx,dist):
    undist = cv2.undistort(img, mtx, dist, None, mtx)
    return undist

img_calibration = glob.glob(r'.\camera_cal\calibration*.jpg')

iIndex =0
objpoints = [] # 3D points in real world
imgpoints =[] # 2D points in image plane
for imgPath in img_calibration:
    img = cv2.imread(imgPath)
    corners, objp ,ret= calibrateOnFrame(img)
    if (ret==True):
        imgpoints.append(corners)
        objpoints.append(objp)

img_undist, mtx, dist=cal_undistort(img,objpoints,imgpoints)

save_calibration = {'mtx': mtx, 'dist': dist}
with open('calibrate_camera.p', 'wb') as f:
    pickle.dump(save_calibration, f)

if (iDebugPlot==3):
    iRand=randint(0,len(img_calibration))
    img = cv2.imread(img_calibration[iRand])
    img_undist=undistoredFrame(img,mtx,dist)
    f, ax = plt.subplots(2, 1)
    f.tight_layout()
    ax[0].imshow(img)
    ax[0].set_title('Original Image ', fontsize=50)
    ax[1].imshow(img_undist)
    ax[1].set_title('Undistorted ', fontsize=50)
    plt.subplots_adjust(left=0., right=1, top=0.9, bottom=0.)
    plt.show()


import requests
import os

from domain.contracts.abstract_models_discovery_service import AbstractModelsDiscoveryService
from typing import List

from domain.excpetions.inference_apis_exceptions import ModelsDiscoveryError
from domain.models.evaluation_job_parameters import EvaluationJobParameters

from shared.helpers.json_helpers import jsonify_string

class ModelsDiscoveryService(AbstractModelsDiscoveryService):

    def discover_models(self, url: str) -> List[str]:

        url = os.path.join(url, 'load')
        response = requests.get(url)

        if response.status_code == 200:
            models = response.json()
            return list(models.keys())

        else:
            raise ModelsDiscoveryError(response.status_code, response.reason)

    def check_model_validity(self, evaluation_job_parameters:EvaluationJobParameters) -> bool:
        url = os.path.join(evaluation_job_parameters.url, 'models')
        url = os.path.join(url, evaluation_job_parameters.model_name)
        url = os.path.join(url, 'load')

        response = requests.get(url)

        if response.status_code == 200:
            json_response = response.json()
            return json_response["success"]

        else:
            raise Exception