""""""

import numpy as np
from pyssp import optimal

def test_kalman():
    av = 1
    aw = 0.36
    A = 0.8
    C = 1
    N = 10

    rng = np.random.default_rng(seed=100)

    rw, rv = rng.spawn(2)

    wn = rw.normal(0, aw, N)
    vn = rv.normal(0, av, N)

    xn = 0.8 * np.ones(N) + wn
    yn = xn + vn

    P0, P1, K, xhat0, xhat1 = optimal.kalman(yn, A, C, aw, av)


# -*- coding: utf-8 -*-
""" Test ProcessIDFile """

import os
import sys
import signal
import time
import logging

from commonutil_fileio_runtimerecord.processid import ProcessIDFile

_DEFAULT_PIDFILE = "/tmp/pidfile-test-1"

_log = logging.getLogger(__name__)

_CAUGHT_SIG = 0

def _handle_sig(*args, **kwds):  # pylint: disable=unused-argument
	global _CAUGHT_SIG
	_CAUGHT_SIG = 1

def get_options():
	pidfile_path = _DEFAULT_PIDFILE
	wait_before_remove = 3
	for arg in sys.argv[1:]:
		try:
			v = int(arg)
			wait_before_remove = v
			continue
		except Exception:
			pass
		pidfile_path = arg
	return (pidfile_path, wait_before_remove)

def main():
	global _CAUGHT_SIG
	logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
	signal.signal(signal.SIGHUP, _handle_sig)
	pidfile_path, wait_before_remove = get_options()
	_log.info("PID file: %r (wait_before_remove=%d)", pidfile_path, wait_before_remove)
	pid_fp = ProcessIDFile(pidfile_path)
	v_nocheck = pid_fp.fetch()
	v_checked = pid_fp.fetch(check_running=True)
	_log.info("fetch: %r (no-check), %r (checked)", v_nocheck, v_checked)
	is_running = pid_fp.is_running()
	_log.info("is-running: %r", is_running)
	if v_checked and (v_checked != os.getpid()):
		pid_fp.signal(signal.SIGHUP)
		_log.info("emitted SIGHUP.")
	pid_fp.save()
	_log.info("save-ed ! waitt %d seconds before remove.", wait_before_remove)
	for cnt in range(wait_before_remove):
		if _CAUGHT_SIG:
			_CAUGHT_SIG = 0
			sys.stdout.write("\033[2K\r>> caught signal.\n")
		tnc = wait_before_remove - cnt
		sys.stdout.write("\033[2K\rwaiting: %d." % (tnc, ))
		sys.stdout.flush()
		time.sleep(1)
	sys.stdout.write("\033[2K\rwait: 0.\n")
	pid_fp.remove()
	sys.stdout.write("\nExit.\n")

if __name__ == '__main__':
	main()


# 히든 넘버   @ 시간초과 뜸... ㅠㅠ
# 최대한 효울적으로 짜자 -> 복잡도 고려
# 코드가 돌아간다고 만사 아님

import sys
input = sys.stdin.readline

input()
s = input()
hidden_numbers = []
is_number = False
num = ""
for i in s:
    if i not in ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']:
        if len(num) < 7 and len(num) != 0:
            hidden_numbers.append(int(num))
        num = ""
        continue
    num += i
if len(num) < 7 and len(num) != 0:
        hidden_numbers.append(int(num))
print(sum(hidden_numbers))
# 아스키 코드 크기 비교로 풀어도 됨


"""frase = input()
passou_do_ponto = False

for index, caractere in enumerate(frase):
    if index == 0:
        print(frase[0].upper(), end='')
        continue
    if caractere == '.':
        passou_do_ponto = True
    if passou_do_ponto and caractere not in ' .':
        print(caractere.upper(), end='')
        passou_do_ponto = False
    else:
        print(caractere, end='')"""

import string

frase = input()
capitalizar = True
frase_final = ''
for letra in frase:
    if capitalizar and letra in string.ascii_letters:
        frase_final += letra.upper()
        capitalizar = False
    else:
        frase_final += letra
    if letra == '.':
        capitalizar = True
print(frase_final)


# import secrets and tokens from config.py
from config import client_id, client_secret, refresh_token

import requests
import urllib3

# import packages for data manipulation
import pandas as pd
from pandas.io.json import json_normalize
import numpy as np

# disable warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

auth_url = "https://www.strava.com/oauth/token"
activites_url = "https://www.strava.com/api/v3/athlete/activities"

payload = {
    'client_id': client_id,
    'client_secret': client_secret,
    'refresh_token': refresh_token,
    'grant_type': "refresh_token",
    'f': 'json'
}

print("Requesting Token...\n")
res = requests.post(auth_url, data=payload, verify=False)
access_token = res.json()['access_token']
print("Access Token = {}\n".format(access_token))

header = {'Authorization': 'Bearer ' + access_token}
param = {'per_page': 200, 'page': 1}
my_dataset = requests.get(activites_url, headers=header, params=param).json()

print(my_dataset[0]["name"])
print(my_dataset[0]["map"]["summary_polyline"])

activities = json_normalize(my_dataset)
#activities.columns #See a list of all columns in the table
#activities.shape #See the dimensions of the table.

#Create new dataframe with only columns I care about
#cols = ['name', 'upload_id', 'type', 'distance', 'moving_time',
#         'average_speed', 'max_speed','total_elevation_gain',
#         'start_date_local'
#       ]
#activities = activities[cols]
#Break date into start time and date
activities['start_date_local'] = pd.to_datetime(activities['start_date_local'])
activities['start_time'] = activities['start_date_local'].dt.time
activities['start_date_local'] = activities['start_date_local'].dt.date
activities.head(5)

# For testing, only take top 1 record(s)
activities = activities.query("type == 'Ride'")
activities = activities.head(1)

print(my_dataset[0]["name"])
print(my_dataset[0]["map"]["summary_polyline"])
print(np.average(activities["average_speed"]))
print(np.average(activities["distance"]))
###################
# import modules
import os
import time
import matplotlib.pyplot as plt
import folium
import polyline
import base64
from tqdm import tqdm
# disable warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# add decoded summary polylines
activities['map.polyline'] = activities['map.summary_polyline'].apply(polyline.decode)
print("turkey")
#####################
# define function to get elevation data using the open-elevation API
def get_elevation(latitude, longitude):
    base_url = 'https://api.open-elevation.com/api/v1/lookup'
    payload = {'locations': f'{latitude},{longitude}'}
    r = requests.get(base_url, params=payload).json()['results'][0]
    return r['elevation']
# get elevation data
elevation_data = list()
for idx in tqdm(activities.index):
    activity = activities.loc[idx, :]
    elevation = [get_elevation(coord[0], coord[1]) for coord in activity['map.polyline']]
    elevation_data.append(elevation)
# add elevation data to dataframe
activities['map.elevation'] = elevation_data
print("turkey")
print("turkey_two")
######################
# convert data types
activities.loc[:, 'start_date'] = pd.to_datetime(activities['start_date']).dt.tz_localize(None)
activities.loc[:, 'start_date_local'] = pd.to_datetime(activities['start_date_local']).dt.tz_localize(None)
# convert values
activities.loc[:, 'distance'] /= 1000 # convert from m to km
activities.loc[:, 'average_speed'] *= 3.6 # convert from m/s to km/h
activities.loc[:, 'max_speed'] *= 3.6 # convert from m/s to km/h
# set index
activities.set_index('start_date_local', inplace=True)
# drop columns
activities.drop(
    [
        'map.summary_polyline',
        'resource_state',
        'external_id',
        'upload_id',
        'location_city',
        'location_state',
        'has_kudoed',
        'start_date',
        'athlete.resource_state',
        'utc_offset',
        'map.resource_state',
        'athlete.id',
        'visibility',
        'heartrate_opt_out',
        'upload_id_str',
        'from_accepted_tag',
        'map.id',
        'manual',
        'private',
        'flagged',
    ],
    axis=1,
    inplace=True
)
print("turkey")
print("turkey_two")
######################
# select one activity
from IPython.display import display
my_ride = activities.iloc[0, :] # first activity (most recent)
# plot ride on map
centroid_lat_val_list = list()
centroid_long_val_list = list()
counter = 0
for idx in my_ride['map.polyline']:
    centroid_lat_val = my_ride['map.polyline'][counter][0]
    centroid_long_val = my_ride['map.polyline'][counter][1]
    counter += 1
    centroid_lat_val_list.append(centroid_lat_val)
    centroid_long_val_list.append(centroid_long_val)

#centroid = [
    #np.mean([my_ride['map.polyline'][0][0] for coord in my_ride['map.polyline'][0]]),
    #np.mean([coord[0] for coord in my_ride['map.polyline'][0]]),
    #np.mean([coord[0] for coord in my_ride['map.polyline']]),
    #np.mean([coord[1] for coord in my_ride['map.polyline'][0]])
#]
centroid = [np.mean(centroid_lat_val_list), np.mean(centroid_long_val_list)]

m = folium.Map(location=centroid, zoom_start=10)
folium.PolyLine(my_ride['map.polyline'], color='red').add_to(m)
display(m)

print("turkey")
print("turkey_two")


# Bounding box generator
import numpy as np

def rot(n):
    n = np.asarray(n).flatten()
    assert(n.size == 3)

    theta = np.linalg.norm(n)
    if theta:
        n /= theta
        K = np.array([[0, -n[2], n[1]], [n[2], 0, -n[0]], [-n[1], n[0], 0]])

        return np.identity(3) + np.sin(theta) * K + (1 - np.cos(theta)) * K @ K
    else:
        return np.identity(3)

def get_bbox(p0, p1):
    """
    Input:
    *   p0, p1
        (3)
        Corners of a bounding box represented in the body frame.

    Output:
    *   v
        (3, 8)
        Vertices of the bounding box represented in the body frame.
    *   e
        (2, 14)
        Edges of the bounding box. The first 2 edges indicate the `front` side
        of the box.
    """
    v = np.array([
        [p0[0], p0[0], p0[0], p0[0], p1[0], p1[0], p1[0], p1[0]],
        [p0[1], p0[1], p1[1], p1[1], p0[1], p0[1], p1[1], p1[1]],
        [p0[2], p1[2], p0[2], p1[2], p0[2], p1[2], p0[2], p1[2]]
    ])
    e = np.array([
        [2, 3, 0, 0, 3, 3, 0, 1, 2, 3, 4, 4, 7, 7],
        [7, 6, 1, 2, 1, 2, 4, 5, 6, 7, 5, 6, 5, 6]
    ], dtype=np.uint8)

    return v, e


import requests

from spotify_client.settings import spotify_settings
from spotify_client.utils import safe_dict

def authenticated_request(method, url, **kwargs):
    access_token = spotify_settings.get_required("access_token")
    headers = kwargs.get("headers", {})
    headers["Authorization"] = "Bearer " + access_token
    kwargs["headers"] = headers

    r = requests.request(method, url, **kwargs)
    if r.status_code >= 400:
        print(f"Request failed failed (status={r.status_code}): {safe_dict(r.json())}")
    r.raise_for_status()
    return r


# -*- coding: utf-8 -*-
from flask import Blueprint
from flask import request
from ..models import *

dictionary_api = Blueprint('dictionary_api', __name__)

@dictionary_api.route('/dictionary/new', methods=['GET','POST'])
def new_dict():
    """create new dict for user """
    if request.method == "POST":
        return Dictionary.new_dict(request)

@dictionary_api.route('/dictionary/get-all-dicts-name', methods=['GET','POST'])
def get_all_dicts_name():
    """create new dict for user """
    if request.method == "POST":
        return Dictionary.get_all_dicts_name(request)


import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F

import config
from attacks.attacks import AttackInstance

def dct(x, norm="ortho"):
    """
    Discrete Cosine Transform, Type II (a.k.a. the DCT)
    For the meaning of the parameter `norm`, see:
    https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html
    :param x: the input signal
    :param norm: the normalization, None or 'ortho'
    :return: the DCT-II of the signal over the last dimension
    """
    x_shape = x.shape
    N = x_shape[-1]
    x = x.reshape(-1, N)

    v = torch.cat([x[:, ::2], x[:, 1::2].flip([1])], dim=1)

    Vc = torch.view_as_real(torch.fft.fft(v, dim=1))

    k = -torch.arange(N, dtype=x.dtype, device=x.device)[None, :] * np.pi / (2 * N)
    W_r = torch.cos(k)
    W_i = torch.sin(k)

    V = Vc[:, :, 0] * W_r - Vc[:, :, 1] * W_i

    if norm == "ortho":
        V[:, 0] /= np.sqrt(N) * 2
        V[:, 1:] /= np.sqrt(N / 2) * 2

    V = 2 * V.view(*x_shape)

    return V

def idct(X, norm="ortho"):
    """
    The inverse to DCT-II, which is a scaled Discrete Cosine Transform, Type III
    Our definition of idct is that idct(dct(x)) == x
    For the meaning of the parameter `norm`, see:
    https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html
    :param X: the input signal
    :param norm: the normalization, None or 'ortho'
    :return: the inverse DCT-II of the signal over the last dimension
    """

    x_shape = X.shape
    N = x_shape[-1]

    X_v = X.reshape(-1, x_shape[-1]) / 2

    if norm == "ortho":
        X_v[:, 0] *= np.sqrt(N) * 2
        X_v[:, 1:] *= np.sqrt(N / 2) * 2

    k = (
        torch.arange(x_shape[-1], dtype=X.dtype, device=X.device)[None, :]
        * np.pi
        / (2 * N)
    )
    W_r = torch.cos(k)
    W_i = torch.sin(k)

    V_t_r = X_v
    V_t_i = torch.cat([X_v[:, :1] * 0, -X_v.flip([1])[:, :-1]], dim=1)

    V_r = V_t_r * W_r - V_t_i * W_i
    V_i = V_t_r * W_i + V_t_i * W_r

    V = torch.cat([V_r.unsqueeze(2), V_i.unsqueeze(2)], dim=2)

    v = torch.fft.irfft(torch.view_as_complex(V), n=V.shape[1], dim=1)
    x = v.new_zeros(v.shape)
    x[:, ::2] += v[:, : N - (N // 2)]
    x[:, 1::2] += v.flip([1])[:, : N // 2]

    return x.view(*x_shape)

def dct_2d(x, norm="ortho"):
    """
    2-dimentional Discrete Cosine Transform, Type II (a.k.a. the DCT)
    For the meaning of the parameter `norm`, see:
    https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html
    :param x: the input signal
    :param norm: the normalization, None or 'ortho'
    :return: the DCT-II of the signal over the last 2 dimensions
    """
    X1 = dct(x - 128, norm=norm)
    X2 = dct(X1.transpose(-1, -2), norm=norm)
    return X2.transpose(-1, -2)

def idct_2d(X, norm="ortho"):
    """
    The inverse to 2D DCT-II, which is a scaled Discrete Cosine Transform, Type III
    Our definition of idct is that idct_2d(dct_2d(x)) == x
    For the meaning of the parameter `norm`, see:
    https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.fftpack.dct.html
    :param X: the input signal
    :param norm: the normalization, None or 'ortho'
    :return: the DCT-II of the signal over the last 2 dimensions
    """
    x1 = idct(X, norm=norm)
    x2 = idct(x1.transpose(-1, -2), norm=norm)
    return x2.transpose(-1, -2) + 128

# 3. Block splitting
# From https://stackoverflow.com/questions/41564321/split-image-tensor-into-small-patches
def image_to_patches(image):
    """Splits an image into 8 by 8 patches, each of which has the jpeg compression applied seperately"""
    k = 8
    batch_size, num_channels, height, width = image.shape

    image_reshaped = image.view(batch_size, num_channels, height // k, k, width // k, k)
    image_transposed = torch.transpose(image_reshaped, 3, 4)
    return image_transposed.reshape(batch_size, num_channels, -1, k, k)

# -3. Block joining
def patches_to_image(patches, image_shape):
    """Reverses the process of splitting an image into patches"""

    k = 8
    batch_size, num_channels, height, width = image_shape
    image_reshaped = patches.view(
        batch_size, num_channels, height // k, width // k, k, k
    )
    image_transposed = torch.transpose(image_reshaped, 3, 4)

    return image_transposed.reshape(batch_size, num_channels, height, width)

def ycbcr_to_rgb_jpeg(image):
    """Converts a batch of YCbCr image tensors to RGB image tensor, using the jpeg conversion matrix"""

    matrix_yuv = torch.tensor(
        np.array(
            [[1.0, 0.0, 1.402], [1, -0.344136, -0.714136], [1, 1.772, 0]],
            dtype=np.float32,
        ).T,
        device=config.device,
    )

    shift_yuv = torch.FloatTensor([0, -128, -128]).to(config.device)

    image = image.permute(0, 2, 3, 1)
    image = torch.tensordot(image + shift_yuv, matrix_yuv, dims=1)
    image = image.permute(0, 3, 1, 2)

    return image

def rgb_to_ycbcr_jpeg(image):
    """Converts a batch of RGB image tensors to YCbCr image tensors"""

    matrix_rgb = torch.as_tensor(
        np.array(
            [
                [0.299, 0.587, 0.114],
                [-0.168736, -0.331264, 0.5],
                [0.5, -0.418688, -0.081312],
            ],
            dtype=np.float32,
        ).T,
        device=config.device,
    )

    shift_rgb = torch.as_tensor([0.0, 128.0, 128.0], device=config.device)

    image = image.permute(0, 2, 3, 1)
    image = torch.tensordot(image, matrix_rgb, dims=1) + shift_rgb
    image = image.permute(0, 3, 1, 2)

    return image

def jpeg_encode(image, noise_vars):
    """Applies JPEG compression to an image, and adds the noise variables to the quantized coefficients"""

    # Whole algorithm functions with the assumption images are in the range [0, 255], so transform to this range
    noise_vars = noise_vars * 255
    image = image * 255

    # "Compression"
    # Change to the ycbr colour space, which is more suited for compression due to the human eye's sensitivity to luminance (which is concentrated in  the Y channel)
    image = rgb_to_ycbcr_jpeg(image)
    comp = image_to_patches(image)  # Split the image into 8x8 blocks
    # Apply the dicrete cosine transform to each block, changing it from the spatial domain to the frequency domain
    comp = dct_2d(comp)

    comp = (
        comp + noise_vars
    )  # Add the noise variables to the frequency domain coefficients

    return comp

def jpeg_decode(components, image_shape):
    """
    Transforms from a jpeg compressed image to a normal image.
    """
    comp = idct_2d(components)
    image = patches_to_image(comp, image_shape)
    image = ycbcr_to_rgb_jpeg(image)

    image = torch.clamp(image / 255.0, 0, 1)

    return image

def apply_jpeg(image, quantiz_err_vars):
    """
    Applies JPEG compression to an image, and adds the noise variables to the quantized coefficients.
    """
    jpeg_image = jpeg_encode(image, quantiz_err_vars)
    rgb_image = jpeg_decode(jpeg_image, image.shape)
    return rgb_image

class JPEGAdversary(nn.Module):
    """
    Implements the JPEG attack, which works by transforming an image into the JPEG domain,
    adding noise to the quantization error, and then transforming it back into the RGB domain. Has been
    edited from the original implementation in https://arxiv.org/pdf/1908.08016.pdf.

    Parameters
    ---

    num_steps : int
        The number of steps to take in the optimization process.

    step_size : float
        The step size to take in the optimization process.

    epislon: float
        The maximum amount of noise to add to the quantization error.

    """

    def __init__(self, epsilon, num_steps, step_size):
        super().__init__()
        self.num_steps = num_steps
        self.step_size = step_size
        self.epsilon = epsilon

    def forward(self, model, inputs, targets):
        batch_size, num_channels, height, width = inputs.size()

        if height % 8 != 0 or width % 8 != 0:
            raise Exception

        noise_vars = self.epsilon * torch.rand(
            (batch_size, num_channels, height // 8 * width // 8, 8, 8)
        ).to(config.device)
        noise_vars.requires_grad = True

        for _ in range(self.num_steps):
            adv_inputs = apply_jpeg(inputs.detach(), noise_vars)

            outputs = model(adv_inputs)
            loss = F.cross_entropy(outputs, targets)

            grads = torch.autograd.grad(loss, noise_vars)[0]

            noise_vars = noise_vars + self.step_size * torch.sign(grads)
            noise_vars = torch.clamp(noise_vars, -self.epsilon, self.epsilon)

        return apply_jpeg(inputs.detach(), noise_vars)

class JPEGAttack(AttackInstance):
    def __init__(self, model, args):
        super().__init__(model, args)
        self.attack = JPEGAdversary(
            epsilon=args.epsilon, num_steps=args.num_steps, step_size=args.step_size
        )

    def generate_attack(self, batch):
        xs, ys = batch
        return self.attack(self.model, xs, ys)

def get_attack(model, args):
    return JPEGAttack(model, args)


from fastapi import FastAPI
from game import *

#{'selectDifficult': 'eazy', 'numberInput': '100', 'infinityCheckbox': 'No'}

app = FastAPI()

@app.post("/startParam")
async def receive_data(data: dict):

    difficult = data['selectDifficult']
    value = 1000

    params = start(value, difficult)

    return params

@app.post("/do")
async def receive_data(data: dict):
    data = data['do']
    params = action(data)
    return params


"""
    Computations for GISANS
"""

import logging
from multiprocessing import Pool

import numpy as np

H_OVER_M_NEUTRON = 3.956034e-7  # h/m_n [m^2/s]

class GISANS(object):
    """
    Compute grazing-incident SANS
    """

    def __init__(self, cross_section_data):
        """
        :param CrossSectionData cross_section_data: processed data object

        The calculations here are meant to match QuickNXS v1. The following are
        items to improve on:
            - Background subtraction
            - Trim the TOF distribution to the chopper bandwidth

        """
        self.data_set = cross_section_data

    def __call__(self, direct_beam=None):
        x_pos = self.data_set.configuration.peak_position
        y_pos = self.data_set.configuration.low_res_position
        scale = 1.0 / self.data_set.proton_charge * self.data_set.configuration.scaling_factor

        rad_per_pixel = self.data_set.det_size_x / self.data_set.dist_sam_det / self.data_set.xydata.shape[1]

        # QuickNXS v1 uses the whole detector for GISANS calculations and doesn't trim the edges
        # active_area_x = self.data_set.active_area_x
        # active_area_y = self.data_set.active_area_y
        active_area_x = [0, 304]
        active_area_y = [0, 256]
        xtth = self.data_set.direct_pixel - np.arange(self.data_set.data.shape[0])[active_area_x[0] : active_area_x[1]]
        pix_offset_spec = self.data_set.direct_pixel - x_pos
        delta_dangle = self.data_set.dangle - self.data_set.angle_offset
        tth_spec = delta_dangle * np.pi / 180.0 + pix_offset_spec * rad_per_pixel
        af = delta_dangle * np.pi / 180.0 + xtth * rad_per_pixel - tth_spec / 2.0
        ai = np.ones_like(af) * tth_spec / 2.0

        phi = (np.arange(self.data_set.data.shape[1])[active_area_y[0] : active_area_y[1]] - y_pos) * rad_per_pixel

        # To be compatible with QuickNXS v1, take the whole TOF range rather than trimming the edges
        # ws = self.data_set.event_workspace
        # tof_edges = np.arange(ws.getTofMin(), ws.getTofMax(), self.data_set.configuration.tof_bins)
        tof_edges = self.data_set.tof_edges

        v_edges = self.data_set.dist_mod_det / tof_edges * 1e6  # m/s
        lambda_edges = H_OVER_M_NEUTRON / v_edges * 1e10  # A

        wavelengths = np.asarray((lambda_edges[:-1] + lambda_edges[1:]) / 2.0)
        k = 2.0 * np.pi / wavelengths
        # calculate ROI intensities and normalize by number of points
        # Note: the number of points here may need to be adjusted from the specular reflectivity
        # calculation if we used a final rebining.
        P0 = self.data_set.configuration.cut_first_n_points
        PN = len(self.data_set.tof) - self.data_set.configuration.cut_last_n_points
        self.wavelengths = wavelengths[P0:PN]

        # calculate reciprocal space, incident and outgoing perpendicular wave vectors
        self.Qy = k[np.newaxis, np.newaxis, P0:PN] * (np.sin(phi) * np.cos(af)[:, np.newaxis])[:, :, np.newaxis]
        p_i = k[np.newaxis, np.newaxis, P0:PN] * ((0.0 * phi) + np.sin(ai)[:, np.newaxis])[:, :, np.newaxis]
        self.p_f = k[np.newaxis, np.newaxis, P0:PN] * ((0.0 * phi) + np.sin(af)[:, np.newaxis])[:, :, np.newaxis]
        self.Qz = p_i + self.p_f

        raw = self.data_set.data[active_area_x[0] : active_area_x[1], active_area_y[0] : active_area_y[1], P0:PN]

        intensity = scale * np.array(raw)
        d_intensity = scale * np.sqrt(raw)

        if direct_beam is not None:
            if not direct_beam.configuration.tof_bins == self.data_set.configuration.tof_bins:
                logging.error("Trying to normalize with a direct beam data set with different binning")

            norm_y_min, norm_y_max = direct_beam.configuration.low_res_roi
            norm_x_min, norm_x_max = direct_beam.configuration.peak_roi
            norm_raw_multi_dim = direct_beam.data[norm_x_min:norm_x_max, norm_y_min:norm_y_max, P0:PN]

            norm_raw = norm_raw_multi_dim.sum(axis=0).sum(axis=0)
            norm_d_raw = np.sqrt(norm_raw)
            norm_scale = (float(norm_x_max) - float(norm_x_min)) * (float(norm_y_max) - float(norm_y_min))
            norm_raw /= norm_scale * direct_beam.proton_charge
            norm_d_raw /= norm_scale * direct_beam.proton_charge

            idxs = norm_raw > 0.0
            d_intensity[:, :, idxs] = np.sqrt(
                (d_intensity[:, :, idxs] / norm_raw[idxs][np.newaxis, np.newaxis, :]) ** 2
                + (
                    intensity[:, :, idxs]
                    / norm_raw[idxs][np.newaxis, np.newaxis, :] ** 2
                    * norm_d_raw[idxs][np.newaxis, np.newaxis, :]
                )
                ** 2
            )
            intensity[:, :, idxs] /= norm_raw[idxs][np.newaxis, np.newaxis, :]
            intensity[:, :, np.logical_not(idxs)] = 0.0
            d_intensity[:, :, np.logical_not(idxs)] = 0.0

        self.S = intensity
        self.dS = d_intensity

        # Create plotting data
        # TODO: use options to plot the right data (for instance: qz or pf)
        self.SGrid, qy, qz = np.histogram2d(
            self.Qy.flatten(), self.Qz.flatten(), bins=(50, 50), weights=intensity.flatten()
        )
        npoints, _, _ = np.histogram2d(self.Qy.flatten(), self.Qz.flatten(), bins=(50, 50))
        self.SGrid[npoints > 0] /= npoints[npoints > 0]
        self.SGrid = self.SGrid.transpose()
        qy = (qy[:-1] + qy[1:]) / 2.0
        qz = (qz[:-1] + qz[1:]) / 2.0
        self.QyGrid, self.QzGrid = np.meshgrid(qy, qz)

def merge(reduction_list, pol_state, wl_min=0, wl_max=100):
    """
    Merge the off-specular data from a reduction list.
    :param list reduction_list: list of NexusData objects
    :param string pol_state: polarization state to consider

    The scaling factors should have been determined at this point. Just use them
    to merge the different runs in a set.

    TODO: This doesn't deal with the overlap properly. It assumes that the user
    cut the overlapping points by hand.
    """
    _qy = np.zeros(0)
    _qz = np.zeros(0)
    _pf = np.zeros(0)
    _s = np.zeros(0)
    _ds = np.zeros(0)
    _wl = np.zeros(0)

    for item in reduction_list:
        gisans = item.cross_sections[pol_state].gisans_data
        Qy, Qz, pf, S, dS = (gisans.Qy, gisans.Qz, gisans.p_f, gisans.S, gisans.dS)

        # Filter according to wavelength
        filtered = np.where((gisans.wavelengths >= wl_min) & (gisans.wavelengths <= wl_max))
        _qy = np.concatenate((_qy, Qy[:, :, filtered].flatten()))
        _qz = np.concatenate((_qz, Qz[:, :, filtered].flatten()))
        _pf = np.concatenate((_pf, pf[:, :, filtered].flatten()))
        _s = np.concatenate((_s, S[:, :, filtered].flatten()))
        _ds = np.concatenate((_ds, dS[:, :, filtered].flatten()))
        _wl = np.concatenate((_wl, gisans.wavelengths[filtered]))

    return _qy, _qz, _pf, _s, _ds, _wl

def rebin_extract(reduction_list, pol_state, wl_min, wl_max, qy_npts=50, qz_npts=50, use_pf=False):

    binning = (qy_npts + 1, qz_npts + 1)
    qy, qz, pf, intensity, d_intensity, _ = merge(reduction_list, pol_state, wl_min=wl_min, wl_max=wl_max)
    if use_pf:
        _z_axis = pf
    else:
        _z_axis = qz

    n_points, _qy, _qz_axis = np.histogram2d(qy, _z_axis, bins=binning)
    _intensity_summed, _, _ = np.histogram2d(qy, _z_axis, bins=(_qy, _qz_axis), weights=intensity)
    _intensity_err, _, _ = np.histogram2d(qy, _z_axis, bins=(_qy, _qz_axis), weights=d_intensity**2)

    _intensity_summed[n_points > 0] /= n_points[n_points > 0]
    _intensity_err = np.sqrt(_intensity_err)
    _intensity_err[n_points > 0] /= n_points[n_points > 0]

    _qy = (_qy[:-1] + _qy[1:]) / 2.0
    _qz_axis = (_qz_axis[:-1] + _qz_axis[1:]) / 2.0

    return _intensity_summed, _qy, _qz_axis, _intensity_err

def _rebin_proc(data):
    # Filter data
    wl = data["wl"]
    filtered = np.where((wl >= data["wl_min"]) & (wl <= data["wl_max"]))
    qy = data["qy"][filtered]
    _z_axis = data["qz"][filtered]
    intensity = data["intensity"][filtered]
    d_intensity = data["d_intensity"][filtered]

    # Perform binning
    n_points, _qy, _qz_axis = np.histogram2d(qy, _z_axis, bins=data["binning"])
    _intensity_summed, _, _ = np.histogram2d(qy, _z_axis, bins=(_qy, _qz_axis), weights=intensity)
    _intensity_err, _, _ = np.histogram2d(qy, _z_axis, bins=(_qy, _qz_axis), weights=d_intensity**2)

    _intensity_summed[n_points > 0] /= n_points[n_points > 0]
    _intensity_err = np.sqrt(_intensity_err)
    _intensity_err[n_points > 0] /= n_points[n_points > 0]

    _qy = (_qy[:-1] + _qy[1:]) / 2.0
    _qz_axis = (_qz_axis[:-1] + _qz_axis[1:]) / 2.0

    return _intensity_summed, _qy, _qz_axis, _intensity_err

def rebin_parallel(reduction_list, pol_state, wl_min, wl_max, wl_npts=2, qy_npts=50, qz_npts=50, use_pf=False):
    """
    Process the wavelength bands in parallel.
    """
    # First, merge all the data
    binning = (qy_npts + 1, qz_npts + 1)
    qy, qz, pf, intensity, d_intensity, wl_array = merge(reduction_list, pol_state, wl_min=0, wl_max=100.0)
    if use_pf:
        _z_axis = pf
    else:
        _z_axis = qz

    # Create one job per wavelength band
    inputs = []
    for i in range(wl_npts):
        wl_step = (wl_max - wl_min) / wl_npts
        _wl_min = wl_min + i * wl_step
        _wl_max = wl_min + (i + 1) * wl_step
        _d = dict(
            qy=qy,
            qz=_z_axis,
            intensity=intensity,
            d_intensity=d_intensity,
            wl=wl_array,
            wl_min=_wl_min,
            wl_max=_wl_max,
            binning=binning,
        )
        inputs.append(_d)

    pool = Pool(wl_npts)
    results = pool.map(_rebin_proc, inputs)
    return results


# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        l1_list = []
        l2_list = []

        while l1:
            l1_list = [str(l1.val)] + l1_list
            l1 = l1.next

        while l2:
            l2_list = [str(l2.val)] + l2_list
            l2 = l2.next

        l1_num = int(''.join(l1_list))
        l2_num = int(''.join(l2_list))

        l_sum = str(l1_num + l2_num)

        # create ans linked lists
        dummy = ListNode(val=None)
        ans = dummy

        for i in range(len(l_sum) - 1, -1, -1):
            dummy.next = ListNode(val=int(l_sum[i]))
            dummy = dummy.next

        return ans.next


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

url = 'https://raw.githubusercontent.com/AdiPersonalWorks/Random/master/student_scores%20-%20student_scores.csv'
df = pd.read_csv(url)

fig = plt.figure(figsize=(8,6))
sns.scatterplot(data=df, x='Hours', y='Scores')
# plt.show()
plt.close()

# splitting the data into train and test values.
X = df[['Hours']].values
y = df['Scores'].values

# taking 30% fo the data for testing and rest for training.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.3)

# training a linearRegression model.
lr = LinearRegression()
lr.fit(X_train, y_train)

# predicting the scores for given hours in test dataset.
yhat_train = lr.coef_ * X_train + lr.intercept_

fig = plt.figure(figsize=(8,6))
plt.scatter(X_train, y_train)
plt.plot(X_train, yhat_train, '-r')
# plt.show()
plt.close()

# predicting values on test data
yhat_test = lr.predict(X_test)

fig = plt.figure(figsize=(8,6))
plt.scatter(X_test, y_test)
plt.plot(X_test, yhat_test, '-r')
# plt.show()
plt.close()

# evaluating the model based on test results.
r_score = r2_score(y_test, yhat_test)
MSE = mean_squared_error(y_test, yhat_test)
MAE = mean_absolute_error(y_test, yhat_test)

eval_df = pd.DataFrame({"Evalution Method": ['R2 score', 'Mean Sqaured Error', 'Mean Absolute Error'], "Values": [r_score, MSE, MAE]})
print(eval_df)
print(lr.predict([[9.25]]))


from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('payment_schedule.apps.main_app.views',
    # Examples:
    url(r'^$', 'schedule_table_view', name='home'),
	url(r'^', include('payment_schedule.apps.home.urls')),
	url(r'^', include('payment_schedule.apps.main_app.urls')),
    # Uncomment the next line to enable the admin:
    url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
	url(r'^admin/', include(admin.site.urls)),

)


import torch
import PIL.Image as Image
import numpy as np
import matplotlib.pyplot as plt
import argparse
from pathlib import Path

DATA = '/multiview/datasets/Panthera_tigris/all_flanks_splits_600'

def get_image_file(opt):
    if not opt.isnumeric() or opt == 'rand':
        img_file = opt
    else:
        imglist = list(Path(DATA).iterdir())
        if opt == 'rand':
            img_file = np.random.choice(imglist)
        else:
            img_file = imglist[int(opt)]
    return img_file

def get_image(img_file, size):
    img = Image.open(img_file)
    scale = size / max(img.size)
    w, h = img.size
    img = img.convert('L')
    img = img.resize((int(w * scale), int(h * scale)), Image.BICUBIC)
    img = np.array(img) / np.float32(255)
    return img

def get_point(point, k, height, width):
    if point[0] == -1 and point[1] == -1:
        x = np.random.randint(0, width - k)
        y = np.random.randint(0, height - k)
        point = (x, y)
    return point

def calculate_distance(img, point, k=11, whiten=False):
    img = torch.from_numpy(img).view(1, 1, *img.shape)
    if torch.cuda.is_available():
        img = img.cuda()

    ps = torch.nn.functional.unfold(img, k)
    ps = ps.view(k**2, img.shape[-2] - k + 1, img.shape[-1] - k + 1)

    if whiten:
        mu = ps.mean(0, keepdim=True)
        sig = ps.std(0, keepdim=True)
        ps = (ps - mu) / sig

    x, y = point
    dist = torch.pow(ps - ps[:, y, x].view(-1, 1, 1), 2).sum(0)
    return dist

def show_closest(img, dist, k, n=300, tol=0.75):

    val, ind = torch.sort(dist.view(-1))

    plt.imshow(img)

    cm = plt.get_cmap('autumn', 500)
    tol = int(tol * k)
    pts = []
    for ii, i in enumerate(ind[:n]):
        i = i.item()
        y = i // dist.shape[1]
        x = i - y * dist.shape[1]
        suppress = False
        for yy, xx in pts:
            if (xx - x)**2 + (yy - y)**2 <= tol**2:
                suppress = True
                break
        if suppress: continue
        pts.append([y, x])
        plt.vlines([x, x + k], [y, y], [y + k, y + k], colors=cm(ii))
        plt.hlines([y, y + k], [x, x], [x + k, x + k], colors=cm(ii))
        plt.text(x + 1, y + 1, str(ii), fontsize=8, color='k',
                 verticalalignment='top')
    plt.show()

def main():
    parser = argparse.ArgumentParser('Visualize patch distances')
    parser.add_argument('-i', '--img', type=str, default='0',
        help='Image. If an integer, uses it as an index into a list of image'
             'files. If a filename, uses the image in that file. If the string '
             '"rand", chooses a random image from the list of image files.')
    parser.add_argument('-p', '--point', type=int, nargs=2, default=(-1, -1),
        help='(x, y) point to use as top right corner of reference patch. If '
             '(-1, -1), then choose a random point.')
    parser.add_argument('-k', '--patch-size', type=int, default=15,
        help='Size of a patch (square).')
    parser.add_argument('-s', '--size', type=int, default=320,
        help='Size of the longer side of the image after resize')
    parser.add_argument('-w', '--whiten', action='store_true',
        help='Whiten each patch individually before calculating distances.')

    args = parser.parse_args()

    whiten = args.whiten
    img_file = get_image_file(args.img)
    img = get_image(img_file, args.size)
    k = args.patch_size
    point = get_point(args.point, k, *img.shape)

    print('Calculate distance')
    dist = calculate_distance(img, point, k, whiten)
    print('Show closest patches')
    show_closest(img, dist, k)

if __name__ == '__main__':
    main()


'''
    Name : tidyjson.py

    Function :
    This takes all the JSON files in the referencedata folder and tidies them up.

'''

__author__ = "Denis J Jackman (denis_jackman@hotmail.com)"
__version__ = "$Revision: 1.00 $"
__date__ = "$Date: 2022/11/01 00:00:00 $"
__copyright__ = "Copyright (c) 2022 Denis J Jackman"
__license__ = "Python"

import os
import json

FILEPATH = "Y:/Resources/development/"
ROOTDIR = f"{FILEPATH}referencedata/"

def main():
    ''' main '''
    for dirName, subdirList, fileList in os.walk(ROOTDIR):
        for fname in fileList:
            filename = f"{ROOTDIR}/{fname}"
            with open(filename, "r", encoding='utf-8-sig') as file:
                data = json.load(file)
            with open(filename, "w", encoding='utf-8-sig') as file:
                json.dump(data, file, indent=4, ensure_ascii=False)

if __name__ == "__main__":
    main()


# Exit Founder
# Tom and Jerry decided to play a game together. The game is a maze of which they need to find a way out.
# Monitor their moves closely and find out who the winner will be!
# First, you will be given the names "Tom" and "Jerry", separated by a comma and a space ", ".
# The order in which they are received determines the order in which they will take turns. The first player starts first.
# Next, you will be given a matrix with 6 rows and 6 columns representing the maze board. It consists of:
# •	Only one Exit - marked with the "E" letter
# •	Trap (one, many, or none) - marked with the "T" letter
# •	Wall (one, many, or none) - marked with the "W" letter
# •	Empty positions will be marked with "."
# In the beginning, Tom and Jerry are outside the board. On each line, after the matrix is given,
# you will be receiving coordinates for each of the players.
# They will be taking turns and stepping on different positions on the board until one of them find the Exit or falls into a Trap.
# Here are the rules:
# •	If a player hits the letter "E", he escapes the maze and wins the game.
# o	Print "{player} found the Exit and wins the game!" and end the program.
# •	If the letter "T" is hit, the player falls into a Trap, the game ends, and his opponent wins automatically.
# o	Print "{player} is out of the game! The winner is {winner}." and end the program.
# •	If the letter "W" is hit, the player hits a wall, and he needs to rest. The player's next move is ignored.
# o	Print "{player} hits a wall and needs to rest."
# •	If a player steps on an empty position ".", nothing happens.
# •	Both players can step in the same position at the same time.
# Input
# •	On the first line, you will receive "Tom" and "Jerry" separated by ", ". The first player starts first.
# •	On the following 6 lines, you will receive the maze board (elements will be separated by a space)
# •	On the following lines, you will be receiving coordinates in the format: "({row}, {column})"
# Output
# •	You should print the output as described above.
# •	The input coordinates will always be valid.

# 1. Read the input
# 2. Find the positions of the players in the matrix
# 3. Set the initial status of the players
# 4. Set the initial winner
# 5. Set the initial status of the game
# 6. While the game is still going:
# 7.     Check if the first player needs rest
# 8.     If he doesn't need rest:
# 9.         Get the coordinates of the first player
# 10.        Check if the first player hits the Exit
# 11.        If he hits the Exit:
# 12.            Print the message and end the program
# 13.        Check if the first player hits the Trap
# 14.        If he hits the Trap:
# 15.            Print the message and end the program
# 16.        Check if the first player hits the Wall
# 17.        If he hits the Wall:
# 18.            Print the message and set the status of the first player to "needs rest"
# 19.        Check if the first player is out of the board
# 20.        If he is:
# 21.            Set the winner and end the game
# 22.        Check if both players are in the same position
# 23.        If they are:
# 24.            Set the winner and end the game
# 25.    Check if the second player needs rest
# 26.    If he doesn't need rest:
# 27.        Get the coordinates of the second player
# 28.        Check if the second player hits the Exit
# 29.        If he hits the Exit:
# 30.            Print the message and end the program
# 31.        Check if the second player hits the Trap
# 32.        If he hits the Trap:
# 33.            Print the message and end the program
# 34.        Check if the second player hits the Wall
# 35.        If he hits the Wall:
# 36.            Print the message and set the status of the second player to "needs rest"
# 37.        Check if the second player is out of the board
# 38.        If he is:
# 39.            Set the winner and end the game
# 40.        Check if both players are in the same position
# 41.        If they are:
# 42.            Set the winner and end the game
# 43.    Swap the players
# 44. If the game is over:
# 45.     Print the winner
# 46.     End the program

# Read the input
first_player, second_player = input().split(", ")
matrix = [input().split() for _ in range(6)]

# Set the initial positions of the players to outside the board
player_positions = {first_player: [-1, -1], second_player: [-1, -1]}

# Find the positions of the players in the matrix
for i in range(6):
    for j in range(6):
        if matrix[i][j] == "1":  # "T" or "J"
            player_positions[first_player] = [i, j]
        elif matrix[i][j] == "2":
            player_positions[second_player] = [i, j]

# Set the initial status of the players
# True - needs rest, False - can move - The players start the game with the status "False"
player_status = {first_player: False, second_player: False}

# Set the initial winner
winner = ""

# Set the initial status of the game
# True - the game is still going, False - the game is over
game_status = True

def hiting_wall(player, player_position):
    """Prints the message when a player hits a wall and needs to rest."""
    print(f"{player} hits a wall and needs to rest.")
    player_status[player] = True
    player_positions[player] = player_position
    return True

def is_out_of_board(player_position):
    """Checks if the player is out of the board and sets the winner if he is."""
    global winner, game_status
    if player_position[0] < 0 or player_position[0] > 5 or player_position[1] < 0 or player_position[1] > 5:
        winner = second_player if first_player else first_player
        game_status = False
        return True

def check_if_both_in_same_position():
    """Checks if both players are in the same position and sets the winner if they are."""
    global winner, game_status
    if player_positions[first_player] == player_positions[second_player]:
        winner = second_player if first_player else first_player
        game_status = False
        return True

def check_if_player_hits_exit(player, player_position):
    """Checks if the player hits the Exit and sets the winner if he does."""
    global winner, game_status
    if matrix[player_position[0]][player_position[1]] == "E":
        winner = player
        game_status = False
        return True

def check_if_player_hits_trap(player, player_position):
    """Checks if the player hits the Trap and sets the winner if he does."""
    global winner, game_status
    if matrix[player_position[0]][player_position[1]] == "T":
        winner = second_player if player == first_player else first_player
        game_status = False
        return True

# Read the coordinates of the players
while game_status:
    # Read the coordinates of the first player
    first_player_coordinates = input()
    if not player_status[first_player]:
        row, column = map(
            int, first_player_coordinates.strip("(").strip(")").split(", ")
        )
        is_out_of_board([row, column]) # Check if the player is out of the board

        position = matrix[row][column]
        if position == "E":
            check_if_player_hits_exit(first_player, [row, column])
            break
        elif position == "T":
            check_if_player_hits_trap(first_player, [row, column])
            break
        elif position == "W":
            hiting_wall(first_player, [row, column])
        else:
            player_positions[first_player] = [row, column]
            check_if_both_in_same_position()
    else:
        player_status[first_player] = False

    # Read the coordinates of the second player
    second_player_coordinates = input()
    if not player_status[second_player]:
        row, column = map(
            int, second_player_coordinates.strip("(").strip(")").split(", ")
        )
        is_out_of_board([row, column]) # Check if the player is out of the board

        position = matrix[row][column]
        if position == "E":
            check_if_player_hits_exit(second_player, [row, column])
            break
        elif position == "T":
            check_if_player_hits_trap(second_player, [row, column])
            break
        elif position == "W":
            hiting_wall(second_player, [row, column])
        else:
            player_positions[second_player] = [row, column]
            check_if_both_in_same_position()
    else:
        player_status[second_player] = False

# Print the result
if winner:
    print(f"{winner} found the Exit and wins the game!")
else:
    print(f"{first_player} is out of the game! The winner is {second_player}.")


import math

def prime(n):
    if(n < 2):
        return False
    for i in range(2, int(math.sqrt(n)) + 1):
        if(n % i == 0):
            return False
    return True

def ucln(a, b):
    a = int(a)
    b = int(b)
    while(a * b != 0):
        if(a > b):
            a %= b
        else:
            b %= a
    return a + b

t = int(input())
while(t > 0):
    t -= 1
    s = int(input())
    sum = 0
    for i in range(1, s):
        if(ucln(i, s) == 1):
            sum += 1

    if(prime(sum)):
        print("YES")
    else:
        print("NO")


from collections import deque

def search(lines, pattern, history=5):
    previous_lines = deque(maxlen=history)
    for line in lines:
        if pattern in line:
            yield line, previous_lines
        previous_lines.append(line)

if __name__ == '__main__':
    with open('somefile.txt') as f:
        for line, prev_lines in search(f, 'python', 5):
            for p_line in prev_lines:
                print(p_line, end='')
            print(line, end='')
            print('-'*20)


# Написати програм који учитава низ целих бројева a затим га трансформише тако што се окрећу задати делови
# низа, од елемента са индексом p до елемента са индексом q, све док се не унесе пар бројева, p и q, у коме је
# p веће од q.
#
# Улаз: У једној линији стандардног улаза налази се број елемената низа, природан број N (2 ≤ N ≤ 10000), а
# затим се, у свакој од N наредних линија стандардног улаза, налази по један члан низа. У наредним редовима
# (њих највише N) се уносе по два цела броја p и q (0 ≤ p ≤ q < N), одвојена празнином док се не унесе ред
# у коме је први број већи од другог.
#
# Излаз: У свакој линији стандардног излаза исписује се по један елемент трансформисаног низа.
#
# Пример
# Улаз
# 4
# 1
# 2
# 3
# 4
# 0 1
# 2 3
# 0 3
# 1 0
# Излаз
# 3
# 4
# 1
# 2

def unos_niza():
    n = int(input("Unesi broj elmenata niza: "))
    return [int(input("Unesi element: ")) for i in range(n)]

def ispis_niza(a):
    for x in a:
        print(x)

# obrtanje dela niza izmedju pozicija p i q (ukljucujuci i njih)
def obrni(a, p, q):
    i = p
    j = q
    while i < j:
        a[i], a[j] = a[j], a[i]
        i += 1
        j -= 1

# ucitavamo niz
a = unos_niza()

while True:
    # ucitavamo interval [p, q] koji treba obrnuti
    (p, q) = map(int, input("Unesi parove za mogucu rotaciju: ").split())
    # ako je interval prazan, prekidamo postupak
    if p > q:
        break;
    # vrsimo obrtanje
    obrni(a, p, q)

# ispisujemo rezultat
ispis_niza(a)


from Domain.Client import Client

class ClientService:
    def __init__(self, client_repo):
        self._client_repo = client_repo

    def add_client(self, client_id, name, email, phone):
        """
        Instantiates a Client object with a given [client_movie], a[name] and adds it to the repo
        :param phone: Client's phone
        :param email: Client's email
        :param client_id: The Client's id
        :param name: Client's title
        :return:
        """
        client = Client(client_id, name, email, phone)
        if self.find(client.client_id) != -1:
            raise ValueError('Client already exists!')
        else:
            self._client_repo.add(client)
        return client

    def update_client(self, id, name):
        """
       Updates the name of an instance of a Client object with a given id
       :param id: Client's id
       :param name: Client's name
       :return:
       """
        for c in self._client_repo.get_all():
            if c.client_id == id:
                old_name = c.name
        new_client = self._client_repo.update(id, name)
        return new_client, old_name

    def display(self):
        """
        Return a shallow copy of the list
        :return: the list of clients
        """
        return self._client_repo.get_all()

    def delete_client(self, id):
        """
        Deletes a Client object with the given [id]
        :param id: the client's id to be deleted
        :return:
        """
        client = self._client_repo.delete(id)
        return client

    def find(self, id):
        """
        Find by id a client
        :param id: Client's id
        :return: the index if there exist or -1 otherwise
        """
        for i in range(len(self._client_repo)):
            if self._client_repo[i].client_id == id:
                return i
        return -1

    def search_client_name(self, name):
        result = []
        for c in self._client_repo.get_all():
            if name.lower() in c.name.lower():
                result.append(c)
        return result

    def search_id(self, client_id):
        result = []
        id = str(client_id)
        for c in self._client_repo.get_all():
            client = str(c.client_id)
            if id.lower() in client.lower():
                result.append(c)
        return result


#!/usr/bin/env python

import re

commentRegex = r'<!--(?!.*build-o-matic)'
devRegex = r'<!--\s?dev'
devRegexClose = r'<!--\s?\/dev\s?-->'

# removes html comments (except for build-o-matic tags)
def removeComments(html):

    modHtml = html

    while re.search(devRegex, modHtml):
        start = re.search(devRegex, modHtml).start()
        end = re.search(devRegexClose, modHtml).end()
        modHtml = modHtml.replace(modHtml[start:end], "")

    while re.search(commentRegex, modHtml):
        start = re.search(commentRegex, modHtml).start()
        end = modHtml[start:].find("-->") + 3
        modHtml = modHtml.replace(modHtml[start:end+start], "")

    return modHtml

def removeWhitespace(html):
    mod = re.sub(r'  ', "", html)
    mod = re.sub(r'\n\n', "", mod)
    return mod


def sendSMS(Tpot,phone_to):
	'''
	send Tpot via SMS.
	Syntax:
	-------
	sendSMS(Tpot,phone_to)
	Parameters:
	-----------
	Tpot: float, pot temperature.
	phone_to: str, phone number to with country code in front, e.g. +1352*******.
	'''
	# we import the Twilio client from the dependency we just installed
	from twilio.rest import Client

	# the following line needs your Twilio Account SID and Auth Token
	client = Client("ACc087d2949d11e86bfe0c50d333f53218", "77a1f0fd87293cda99c70f6759842576")

	# change the "from_" number to your Twilio number and the "to" number
	# to the phone number you signed up for Twilio with, or upgrade your
	# account to send SMS to any phone number
	client.messages.create(to=phone_to,
			       from_="+13192505950",
			       body="Tpot=%.3f K"%Tpot)


from display import *
from matrix import *
from draw import *
import time

"""
Goes through the file named filename and performs all of the actions listed in that file.
The file follows the following format:
     Every command is a single character that takes up a line
     Any command that requires arguments must have those arguments in the second line.
     The commands are as follows:
         line: add a line to the edge matrix -
	    takes 6 arguemnts (x0, y0, z0, x1, y1, z1)
	 ident: set the transform matrix to the identity matrix -
	 scale: create a scale matrix,
	    then multiply the transform matrix by the scale matrix -
	    takes 3 arguments (sx, sy, sz)
	 move: create a translation matrix,
	    then multiply the transform matrix by the translation matrix -
	    takes 3 arguments (tx, ty, tz)
	 rotate: create a rotation matrix,
	    then multiply the transform matrix by the rotation matrix -
	    takes 2 arguments (axis, theta) axis should be x, y or z
	 apply: apply the current transformation matrix to the
	    edge matrix
	 display: draw the lines of the edge matrix to the screen
	    display the screen
	 save: draw the lines of the edge matrix to the screen
	    save the screen to a file -
	    takes 1 argument (file name)
	 quit: end parsing

See the file script for an example of the file format
"""
def parse_file( fname, points, transform, screen, color ):
    f = open(fname, 'r')
    c = f.read().splitlines()
    for i in range(0, len(c)):
        if c[i] == 'line':
            p = c[i+1].split(' ')
            p = map(int, p)
            add_edge(points, p[0], p[1], p[2], p[3], p[4], p[5])
        elif c[i] == 'ident':
            ident(transform)
        elif c[i] == 'scale':
            p = c[i+1].split(' ')
            p = map(int, p)
            t = make_scale(p[0], p[1], p[2])
            matrix_mult(t, transform)
        elif c[i] == 'move':
            p = c[i+1].split(' ')
            p = map(int, p)
            t = make_translate(p[0], p[1], p[2])
            matrix_mult(t, transform)
        elif c[i] == 'rotate':
            p = c[i+1].split(' ')
            p[1] = int(p[1])
            if p[0] == 'x':
                t = make_rotX(p[1])
            elif p[0] == 'y':
                t = make_rotY(p[1])
            elif p[0] == 'z':
                t = make_rotZ(p[1])
            matrix_mult(t, transform)
        elif c[i] == 'apply':
            matrix_mult(transform, points)
        elif c[i] == 'display':
            clear_screen(screen)
            draw_lines(points, screen, color)
            display(screen)
            time.sleep(3)
        elif c[i] == 'save':
            clear_screen(screen)
            draw_lines(points, screen, color)
            n = c[i+1]
            save_extension(screen, n)
        elif c[i] == 'quit':
            break
    pass


import re
import pyautogui as g
from time import sleep
import pyperclip as clip
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
from graphviz import Source
from sklearn.tree import export_graphviz
from sklearn import tree
try:
    from PIL import Image
except ImportError:
    import Image
import pytesseract
g.FAILSAFE = True
sleep(2)
g.size()
g.position()

def c():
    g.mouseDown()
    g.mouseUp()

def c2():
    c()
    c()

def rc():
    g.click(button='right')

def select_all_and_copy():
    rc()
    g.keyDown('a')
    g.keyUp('a')
    g.keyDown('ctrl')
    g.keyDown('c')
    g.keyUp('c')
    g.keyUp('ctrl')

im2 = g.screenshot('output/labels3/{}.png'.format(str(i).zfill(4)))

from PIL import Image

def crop(image_path, coords, saved_location):
    image_obj = Image.open(image_path)
    cropped_image = image_obj.crop(coords)
    cropped_image.save(saved_location)

for i in range(4410):
    image = 'output/labels3/{}.png'.format(str(i).zfill(4))
    crop(image, (300,817,900,860), 'output/cropped_labels3/{}.png'.format(str(i).zfill(4)))

    pytesseract.pytesseract.tesseract_cmd = '/usr/local/Cellar/tesseract/4.0.0_1/bin/tesseract'

labels3 = []
for i in range(4410):
    s = pytesseract.image_to_string(Image.open('output/cropped_labels3/{}.png'.format(str(i).zfill(4))))
    match1 = re.match("(.*?\d+?.\d) ", s)
    try:
        number = float(match1.group(1).strip())
        labels3.append(number)
    except:
        labels3.append(None)

for i, label in zip(range(len(labels3)), labels3):
    print(i, label)


from math import radians, cos, sin, asin, sqrt, degrees, atan2

def validate_point(p):
    lat, lon = p
    assert -90 <= lat <= 90, "bad latitude"
    assert -180 <= lon <= 180, "bad longitude"

# original formula from  http://www.movable-type.co.uk/scripts/latlong.html
def distance_haversine(p1, p2):

    """
    Calculate the great circle distance between two points
    on the earth (specified in decimal degrees)
    Haversine
    formula:
        a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
                        _   ____
        c = 2 ⋅ atan2( √a, √(1−a) )
        d = R ⋅ c

    where   φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km);
            note that angles need to be in radians to pass to trig functions!
    """
    lat1, lon1 = p1
    lat2, lon2 = p2
    for p in [p1, p2]:
        validate_point(p)

    R = 6371 # km - earths's radius

    # convert decimal degrees to radians
    lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1

    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) # 2 * atan2(sqrt(a), sqrt(1-a))
    d = R * c
    return d

data=distance_haversine({9.9097187,78.1104244},{9.9005285,78.1389344})
print(data)


import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import sys

def get_scatter(df=None):

	if df is None:
		# x = [0, 50, 100, 200, 300, 400, 500, 600]
		# y = [0, 1.5, 2, 4, 7.5, 12.5, 20, 40.6]
		# y1 = [0, 1.7, 3, 5, 8.5, 15.5, 24, 42.6]

		d1 = np.random.normal(5, 0.5, 200)
		d2 = np.random.normal(30, 1.2, 60)
		d3 = np.random.normal(6, 1, 60)
		d11 = np.random.normal(5, 0.5, 200)
		d22 = np.random.normal(30, 1.2, 60)
		d33 = np.random.normal(6, 1, 60)

		y = np.concatenate((d1, d2, d3)).flatten()
		y1 = np.concatenate((d11, d22, d33)).flatten()
		x = np.arange(len(y))

	else:
		x = np.arange(len(df))
		y = df['S1']
		y1 = df['S2']

	fig = go.Figure()
	fig.add_trace(go.Scatter(x=x,
	                         y=y,
	                         name='Sensor 1',
	                         marker_color='#E48F72'))
	fig.add_trace(go.Scatter(x=x,
	                         y=y1,
	                         name='Sensor 2',
	                         marker_color='lightgreen'))

	fig.update_layout(title=dict(
					    x=0.5,
					    y=0.8,
	                    font=dict(size=20, color='black')),
					legend=dict(
				        x=0,
				        y=1,
				        bgcolor = '#373a40',
				        traceorder='normal',
				        font=dict(
				            size=12,
				            color= 'white'),
				    ),
					template='plotly_dark',
					height=330,
					width=800,
					font=dict(family="Courier",
					        size=12, color='black'),
					paper_bgcolor='rgba(0,0,0,0)',
					plot_bgcolor='gray',
				    margin=dict(t=50, b=70, l=80, r=1))
	fig.update_xaxes(title='Time Interval [100ms]')
	fig.update_yaxes(title='PRESSURE in PSI')
	return fig

def get_bar(color='steelblue', title='', df=None):

	SIZE = 10

	if df is None:
	    d1 = np.random.normal(5, 0.5, 200)
	    d2 = np.random.normal(30, 1.2, 60)
	    d3 = np.random.normal(6, 1, 60)

	    data = np.concatenate((d1, d2, d3))
	    df = pd.DataFrame()
	    df['data'] = data
	else:

		data = df.values
		modulo = len(data) % SIZE
		df = pd.DataFrame()
		df['data'] = data
		if modulo> 0:
			df = df[:-modulo]
		df.dropna(inplace = True)

	x = []
	for i in range(int(len(df.data)/SIZE)):
	    for r in range(SIZE):
	    	x.append(i)
	df['bin'] = np.array(x)
	df = df.groupby('bin').max()

	fig = go.Figure()
	fig.add_trace(go.Bar(x=df.index,
	                     y=df.values.flatten(),
	                     name='Sensor 1',
	                     marker_color= color))

	fig.update_layout(title=dict(
						text = "<b>{}</b>".format(title),
				        x=0.6,
				        y= 0.8,
                      	font=dict(size=20, color='black')),
					template='plotly_dark',
					barmode = 'stack',
					height=330,
					width= 400,
					font=dict(family="Courier",
					        size=12, color='black'),
					paper_bgcolor='rgba(0,0,0,0)',
					plot_bgcolor='gray',
				    margin=dict(r=1))
	fig.update_xaxes(title='Time Interval [1s]')
	fig.update_yaxes(title='PRESSURE in PSI')
	return fig


#学生信息
data=[
    {
        "name":"Tommy",
        "age":18,
        "sex":"男"
    },
    {
        "name": "Susan",
        "age": 14,
        "sex": "女"
    }
]

#输入名字的优化 （不输入和输入空格的去除）
def input_name():
    while True:
        name = input("请输入名字：").strip() #strip()是去除头尾的空格
        if name: # 如果有输入名字，就返回名字
            return name
        else:
            continue
# 选择性别

def beauty_output(data):
    for index,student in enumerate(data):
        print(f'序号:{index}',end='\t')
        print(f'姓名:{student["name"]}',end='\t')
        print(f'年龄:{student["age"]}',end='\t')
        print(f'性别:{student["sex"]}')

#1.显示所有学生信息
def selectAll():
    beauty_output(data)

#2.新建学生信息
def addStudent():
    name = input("请输入新增学生的姓名：")
    age = input("请输入新增学生的年龄：")
    sex = input("请输入新增学生的性别：")
    data.append({'name':name,'age':age,'sex':sex})

#3.查询学生信息
def searchStudent():
    name = input("请输入您要查询的学生姓名:")
    for student in data:
        if student['name']==name:
            print(student)
            return
    else:
        print("查无此人")

# 4.修改学生信息
def updateStudent():
    name = input("请输入您要修改的学生姓名:")
    for student in data:
        if student['name'] == name:
            student['name'] = input("请输入您要修改的名字：")
            student['age'] = input("请输入您要修改的年龄：")
            student['sex'] = input("请输入您要修改的性别：")
            return
    else:
        print("查无此人")

# 5.删除学生信息
def deleteStudent():
    name = input("请输入您要删除的学生姓名：")
    for student in data:
        if student['name'] == name:
            data.remove(student)
            return
    else:
         print("查无此人")

while True:
    print("""
    ***************学生垃圾管理系统***************
    1.显示所有学生信息
    2.新建学生信息
    3.查询学生信息
    4.修改学生信息
    5.删除学生信息
    0.退出系统
    **********************************************
    """)
    op = input("请输入数字操作")
    if op=='1':
        selectAll()
    elif op=='2':
        addStudent()
    elif op == '3':
        searchStudent()
    elif op == '4':
        updateStudent()
    elif op == '5':
        deleteStudent()
    elif op == '0':
        print("退出系统")
        break


"""
* user:  VR437327000
* fname: MADDALENA
* lname: BUSATTO
* task:  prova-game123-123
* score: 0.0
* date:  2019-02-27 10:55:16.102247
"""
#!/usr/bin/env python3
# Template di soluzione di game123_123

# INIZIO area entro la quale ti richiediamo/consigliamo di operare.

def play(n1, n2):
    a=0
    c=0
    if (n1+n2)%4==0:
        return (0,0)
    elif n1>n2:
        c=4*n2
        a=c-(n1+n2)
        return (a, 0)
    elif n1<n2:
        c=4*n1
        a=c-(n1+n2)
        return (0, a)

# FINE area entro la quale ti richiediamo/consigliamo di operare.

n1 = int(input())
n2 = int(input())
togli1, togli2 = play(n1, n2)
print(togli1)
print(togli2)


from anytree import Node, RenderTree, search, Walker

def getPath(cdStack):
  return '/'.join(cdStack)

with open('day7/input.in', 'r', encoding="utf-8") as f:
  commands = f.read().split('\n')
  cdStack = [] # tracks the current cd and its path
  root = Node('~', None, type='dir', size=0)

  nodes = {'/': root}
  sumToDelete = 0
  w = Walker()
  # print(commands)
  for line in commands:
    # move up a level by popping the dir off the stack
    if line == '$ cd ..':
      cdStack.pop()

    # move into the dir by pushing to the stack
    elif line.startswith('$ cd'):
      cdStack.append(line[5:])
      # print(cdStack)

    # make new directory
    elif line.startswith('dir'):
      dirName = line[4:]
      # add a node to the dictionary with the dir path as the key and the Node
      # object as the value, and the top of the cdStack as the parent
      parentPath = getPath(cdStack)
      dpath = parentPath + '/' + dirName
      nodes[dpath] = Node(dirName, nodes[parentPath], type='dir', size=0)
      # print(f'new dir: {nodes[dpath]}')

    # ignore
    elif line.startswith('$ ls'):
      continue

    # add new file to directory
    else:
      fsize, fname = line.split(' ')
      parentPath = getPath(cdStack)
      fpath = parentPath + '/' + fname
      nodes[fpath] = Node(fname, nodes[parentPath], type='file', size=int(fsize))

  sumToDelete2 = float('inf')

  # calculate the size of each dir
  for dir in search.findall(root, filter_=lambda node: node.type == 'dir'):
    files = search.findall(dir, filter_=lambda node: node.type == 'file')
    # print(f'chilren of {dir.name}: {files}')
    dir.size = sum(int(f.size) for f in files)
    if(dir.size <= 100000):
      sumToDelete += dir.size

    TOTAL_DISK_SPACE = 70000000
    SPACE_NEEDED = 30000000
    SPACE_USED = nodes['/'].size
    SPACE_AVAILABLE = TOTAL_DISK_SPACE - SPACE_USED
    SPACE_TO_FREE = SPACE_NEEDED - SPACE_AVAILABLE
    print (SPACE_NEEDED, SPACE_AVAILABLE, SPACE_TO_FREE)
    if(dir.size < sumToDelete2 and dir.size > SPACE_TO_FREE):
      sumToDelete2 = dir.size

  # print(RenderTree(root))

  print(f'[PART 1]: sumToDelete: {sumToDelete}')
  print(f'[PART 2]: sumToDelete: {sumToDelete2}')


import pandas as pd

from catalyst.test_algorithms import (
    ExceptionAlgorithm,
    DivByZeroAlgorithm,
    SetPortfolioAlgorithm,
)
from catalyst.testing.fixtures import (
    WithDataPortal,
    WithSimParams,
    CatalystTestCase,
)

DEFAULT_TIMEOUT = 15  # seconds
EXTENDED_TIMEOUT = 90

class ExceptionTestCase(WithDataPortal, WithSimParams, CatalystTestCase):
    START_DATE = pd.Timestamp('2006-01-03', tz='utc')
    START_DATE = pd.Timestamp('2006-01-07', tz='utc')

    sid, = ASSET_FINDER_EQUITY_SIDS = 133,

    def _test_exception_in_handle_data(self):
        algo = ExceptionAlgorithm('handle_data',
                                  self.sid,
                                  sim_params=self.sim_params,
                                  env=self.env)

        with self.assertRaises(Exception) as ctx:
            algo.run(self.data_portal)

        self.assertEqual(str(ctx.exception), 'Algo exception in handle_data')

    def _test_zerodivision_exception_in_handle_data(self):
        algo = DivByZeroAlgorithm(self.sid,
                                  sim_params=self.sim_params,
                                  env=self.env)

        with self.assertRaises(ZeroDivisionError):
            algo.run(self.data_portal)

    def _test_set_portfolio(self):
        """
        Are we protected against overwriting an algo's portfolio?
        """
        algo = SetPortfolioAlgorithm(self.sid,
                                     sim_params=self.sim_params,
                                     env=self.env)

        with self.assertRaises(AttributeError):
            algo.run(self.data_portal)


#Visualization Engine

#Parse The Trace files and collect Block Information and Time Stamps

import os.path
import sys
import shutil

runno=sys.argv[1:]
runno=map(str,runno)
runno=''.join(runno)

ftApploc="/home/tasu/Downloads/pin-3.0-76991-gcc-linux/Results/appTest/Traces"
ftOrLoc="/home/tasu/Downloads/pin-3.0-76991-gcc-linux/Results/Oracle/Traces"

deslocation="/home/tasu/Downloads/pin-3.0-76991-gcc-linux/Runs/Traces/TestFuzzer/Trace"+runno
if not os.path.exists(deslocation):
    os.makedirs(deslocation)

#Get the Total count of files in the folders and parse them

traceAppfileNames=[]
traceAppfilelocations=[]
traceOracleFileNames=[]
traceOracleFileLocations=[]

#Get All Traces generated by Pin for the Application under test
for name in os.listdir(ftApploc):
    traceAppfileNames.append(name)
    traceAppfilelocations.append(os.path.join(ftApploc,name))

#Get All Traces for oracle

for name in os.listdir(ftOrLoc):
    traceOracleFileNames.append(name)
    traceOracleFileLocations.append(os.path.join(ftOrLoc,name))

#Open Each Trace file for Ananlysis

##### For Application Under Test#########

for i in range(0, len(traceAppfileNames)):
    fttest=open(traceAppfilelocations[i], "r+")
    currfilename=traceAppfileNames[i]
    testarr=[]
    dictRes={}
    diccount={}
    countBlk=0
    for i in fttest.readlines():
        testarr.append(i)

    for i in range(0, len(testarr)):
        if "Block" in testarr[i]:
          currblk=testarr[i-1].strip("\n")
          currtime=testarr[i].split(" ")[1].strip("\n")
          dictRes[currblk]=currtime
          if currblk in diccount:
              #Update Value
              tempval=diccount[currblk]+1
              diccount[currblk]=tempval
          else:
              #Blk is not present
              countBlk+=1
              diccount[currblk]=countBlk

    firsttime=int(dictRes[str(1)])

    for key in dictRes:
        tempval=firsttime
        temptime=dictRes[key]
        actualtime=int(temptime)-tempval
        #update the Array
        dictRes[key]=actualtime

    #Write to a File
    FappTest=open("BlkTime"+currfilename, "w+")
    FappTest.write("BlkNumber,Time in Milliseconds,TimesAppeared")
    FappTest.write("\n")
    for key in dictRes:
        FappTest.write(key+","+str(dictRes[key])+","+str(diccount[key]))
        FappTest.write("\n")

    shutil.move("BlkTime"+currfilename, deslocation)

    FappTest.close()


import openai
import json
import ast
from sklearn.model_selection import train_test_split
import os
import time

def main():
    openai.api_key = open("ID/my_api_key.txt").read().strip()

    data_list = create_data_list("data/original_data.json")
    training_question_list = []
    testing_question_list = []

    for data in data_list:
        qna_string = get_questions(data)
        if qna_string == -1:
            continue
        try:
            qna_list = extract_qa(qna_string)
            if len(qna_list) == 1:
                training_question_list += qna_list
            else:
                training_question_list += qna_list[:-1]
                testing_question_list.append(qna_list[-1])
            print(training_question_list)
            print(testing_question_list)
        except:
            continue

    model_ID = train(training_question_list, testing_question_list)
    #model_ID = create_finetune_model(model='curie', batch_size=8, n_epochs=20, training_file="data/training_data.jsonl", validation_file="data/testing_data.jsonl")
    model_ID_file = "ID/my_fine-tuned_model_ID.txt"
    with open(model_ID_file, "w") as f:
        f.write(model_ID)
    f.close()

    return 0

def create_data_list(original_json_file):
    f = open(original_json_file)
    data = json.load(f)
    data_list = []
    for title in data:
        for command in data[title]:
            description = data[title][command]
            data_list.append([title, command, description])
    f.close()
    print(data_list)
    return data_list

def get_questions(data):
    category, command, function = data[0], data[1], data[2]
    context = f"{category}: {command}\nFunction: {function}"
    content = f"Please write at least five question-answer pairs based on the text below, in the format of a nested python list. Each inner list should contain one question and one answer.\n\n{context}"
    example_context = "command: p4 add\nFunction: to add new files"
    example_content = f"Example:\nPlease write at least five question-answer pairs based on the text below, in the format of a nested python list. Each inner list should contain one question and one answer.\n\n{example_context}"

    try:
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are good at generating question-answer pairs based on a given text."},
                {"role": "user", "content": example_content},
                {"role": "assistant", "content": "qa_list = [\n['What is the p4 command to add a new file?', 'p4 add'],\n['What is the purpose of p4 add?', 'to add a new file'],\n['When do you use p4 add?', 'when you want to add a new file'],\n['What command should you use when you want to add a new file?', 'p4 add'],\n['What is the function of p4 add?','to add new files']\n]"},
                {"role": "user", "content": content}
            ]
        )
    except openai.error.ServiceUnavailableError:
        return -1

    msg = response['choices'][0]['message']['content']

    print("This is the response:\n")
    print(msg)
    return msg

def extract_qa(data_string):
    if '->' in data_string:
        data_string = data_string.replace('->', 'implies')
    if '\n' in data_string:
        data_string = data_string.replace('\n', ' ')

    # Extract the content inside the square brackets using literal_eval
    qa_pairs = ast.literal_eval(data_string.split('=')[-1])
    print(qa_pairs)

    return qa_pairs

# train model, returns the ID of the trained model
def train(train_df, test_df):
    print(train_df)
    print(test_df)
    with open("data/training_data.jsonl", "w") as f:
        for qa_pair in train_df:
            prompt_completion_pair = {"prompt": qa_pair[0] + " ->", "completion": " " + qa_pair[1] + "\n"}
            json.dump(prompt_completion_pair, f)
            f.write("\n")
    f.close()
    with open("data/testing_data.jsonl", "w") as f:
        for qa_pair in test_df:
            prompt_completion_pair = {"prompt": qa_pair[0] + " ->", "completion": " " + qa_pair[1] + "\n"}
            json.dump(prompt_completion_pair, f)
            f.write("\n")
    f.close()

    fine_tuned_model_id = create_finetune_model(model='curie', batch_size=len(train_df), n_epochs=20, training_file="data/training_data.jsonl", validation_file="data/testing_data.jsonl")
    return fine_tuned_model_id

def create_file(file_name):
    upload_response = openai.File.create(
        file=open(file_name, "rb"),
        purpose='fine-tune'
    )
    file_id = upload_response.id
    return file_id

def create_finetune_model(model, batch_size, n_epochs, training_file, validation_file):
    fine_tune_response = openai.FineTune.create(
        model=model,
        batch_size=batch_size,
        n_epochs=n_epochs,
        training_file=create_file(training_file),
        validation_file=create_file(validation_file)
    )

    job_id = fine_tune_response["id"]
    print(f"Fine_tuning job created with ID: {job_id}")

    return job_id

if __name__ == "__main__":
    main()


#
# Task 4: estimate alpha & beta values.
#

import argparse
import math
import numpy as np
from sklearn.linear_model import LinearRegression

def get_tensor_size(size_str):
    if size_str.endswith("MB"):
        return float(size_str[:-2])
    if size_str.endswith("KB"):
        return float(size_str[:-2]) / 1024
    if size_str.endswith("B"):
        return float(size_str[:-1]) / (1024 * 1024)
    return float(size_str)

def read_task2(csv):
    result = {
        'vsizes': [],
        'ring': [],
        'recur_hd': []
    }

    with open(csv, 'r') as fcsv:
        curr_run = []

        for line in fcsv.readlines():
            line = line.strip()
            segs = line.split(', ')
            assert len(segs) == 6
            assert segs[0] == "task2-tag"

            size = get_tensor_size(segs[1])
            alg = segs[3]
            time = float(segs[5])

            if len(result['vsizes']) == 0 or size != result['vsizes'][-1]:
                result['vsizes'].append(size)
            curr_run.append(time)

            num_nodes = int(segs[2])
            node_id = int(segs[4])
            if node_id == num_nodes - 1:
                avg = sum(curr_run) / len(curr_run)
                result[alg].append(avg)
                curr_run = []

    return result

def solve_linear_regression(xs, ys):
    xs, ys = np.array(xs), np.array(ys)
    xs = xs.reshape((-1, 1))    # requires 2D X column vector
    model = LinearRegression().fit(xs, ys)
    assert len(model.coef_) == 1

    slope = model.coef_[0]
    intercept = model.intercept_
    r_squared = model.score(xs, ys)
    return slope, intercept, r_squared

def calculate_params_for_alg(alg, num_nodes, slope, intercept):
    if alg == 'ring':
        alpha = intercept / (num_nodes - 1)
        beta = slope / ((num_nodes - 1) / num_nodes)
        return alpha, beta
    else:
        alpha = intercept / math.log(num_nodes, 2)
        beta = slope / math.log(num_nodes, 2)
        return alpha, beta

def estimate_params(result):
    """
    Use linear regression to get estimated values for alpha & beta.

      ring:     T = (p-1) * alpha + ((p-1)/p) * n * beta
                  = ((p-1)/p) * beta * n + (p-1) * alpha
                    ------ a ------- * x + ----- b -----

      recur_hd: T = log(p) * (alpha + n * beta)
                  = log(p) * beta * n + log(p) * alpha
                    ----- a ----- * x + ----- b ------

    number of nodes p = 16 in task2, vector size n measured in MB

    We assume that doing the reduction operation (vector add) is cheap
    enough to be negligible.
    """
    print("alg, alpha, beta_in_MB, r_squared")
    for alg in ('ring', 'recur_hd'):
        xs = result['vsizes']
        ys = result[alg]

        slope, intercept, r_squared = solve_linear_regression(xs, ys)
        alpha, beta = calculate_params_for_alg(alg, 16, slope, intercept)
        print(f"{alg}, {alpha:.6f}, {beta:.6f}, {r_squared:.6f}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--task2_csv", required=True, type=str)
    args = parser.parse_args()

    result = read_task2(args.task2_csv)
    estimate_params(result)


import time

from engine.F3F4.package import create_package, print_frame
from engine.F3F4.protocol import create_frame

import engine.F0F7
import engine.F0F7.protocol
import engine.F0F7.process
import link.commu_uart
import link.p_link

from device.table_halocode import table_halocode_tag

class adapter_mbuild():
    def __init__(self, port, bauadrate = 115200):
        self.port = port
        self.bauadrate = 115200

    # not used
    def create_key(self, table_tag):
    	pass

    def start(self):
        start_heart_package = True
        port_device = link.p_link.get_available_port()[0]
        if not port_device.is_open():
            self.link_obj = link.commu_uart.uart_link(["COM0", 115200])

            self.link_obj.config([self.port, str(self.bauadrate)])
            self.link_obj.open()
            self.link_obj.start_listening()
            port_device.status = 1

            port_device.link_obj = self.link_obj
            start_heart_package = True
        else:
            start_heart_package = False
            self.link_obj = port_device.link_obj

        self.protocol_obj = engine.F0F7.protocol.F0F7_frame()

        self.process = engine.F0F7.process.neurons_process_c()
        self.protocol_obj.register_frame_process(self.process)

        self.link_obj.rigister_protocol_parse_handle(self.protocol_obj)

        engine.F0F7.neurons_engine.neuron_request_bind_phy(self.protocol_obj.send_protocol)
        self.process.start_engine(start_heart_package)

        # if mbuild modules are connected to halo, then set halo passthrough mode
        # even halo not available, send these commands either
        self.link_obj.write(create_frame(create_package("import communication", 0x00, 0x04)))
        time.sleep(0.1)
        self.link_obj.write(create_frame(create_package("halo.led.show_all(10,10,0)", 0x00, 0x04)))
        time.sleep(0.1)
        self.link_obj.write(create_frame(create_package("communication.bind_passthrough_channels(\"uart0\", \"uart1\")", 0x00, 0x04)))


def resources(ctx, gpu):
    """Get build job resources.

    Uses [Caching](/references/polyaxon-cli/#caching)

    Examples:

    \b
    ```bash
    $ polyaxon build -b 2 resources
    ```

    For GPU resources

    \b
    ```bash
    $ polyaxon build -b 2 resources --gpu
    ```
    """
    user, project_name, _build = get_build_or_local(ctx.obj.get('project'), ctx.obj.get('build'))
    try:
        message_handler = Printer.gpu_resources if gpu else Printer.resources
        PolyaxonClient().build_job.resources(user,
                                             project_name,
                                             _build,
                                             message_handler=message_handler)
    except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
        Printer.print_error('Could not get resources for build job `{}`.'.format(_build))
        Printer.print_error('Error message `{}`.'.format(e))
        sys.exit(1)


import numpy
# import tensorflow.compat.v1 as tf
# tf.disable_v2_behavior()
import tensorflow as tf

import skeletalModel
import pose2Dto3D

def backpropagationBasedFiltering_v2(
  lines0_values, # initial (logarithm of) bones lenghts
  rootsx0_values, # head position
  rootsy0_values,
  rootsz0_values,
  anglesx0_values, # angles of limbs
  anglesy0_values,
  anglesz0_values,
  tarx_values, # target
  tary_values,
  w_values, # weights of estimated points (likelihood of estimation)
  structure,
  dtype,
  learningRate=0.1,
  nCycles=1000,
  regulatorRates=[0.001, 0.1],
):

  T = rootsx0_values.shape[0]
  nBones, nPoints = skeletalModel.structureStats(structure)
  nLimbs = len(structure)

  # vector of (logarithm of) bones length
  #   shape: (nLines,)
  lines = tf.Variable(lines0_values, dtype=dtype)
  # x cooordinates of head
  #   shape: (T, 1)
  rootsx = tf.Variable(rootsx0_values, dtype=dtype)
  # y cooordinates of head
  rootsy = tf.Variable(rootsy0_values, dtype=dtype)
  # z cooordinates of head
  rootsz = tf.Variable(rootsz0_values, dtype=dtype)
  # x coordinate of angles
  #   shape: (T, nLimbs)
  anglesx = tf.Variable(anglesx0_values, dtype=dtype)
  # y coordinate of angles
  anglesy = tf.Variable(anglesy0_values, dtype=dtype)
  # z coordinate of angles
  anglesz = tf.Variable(anglesz0_values, dtype=dtype)

  # target
  #   shape: (T, nPoints)
  ##tarx = tf.compat.v1.placeholder(dtype=dtype)
  ##tary = tf.compat.v1.placeholder(dtype=dtype)
  # likelihood from previous pose estimator
  #   shape: (T, nPoints)
  ##w = tf.compat.v1.placeholder(dtype=dtype)

  # resultant coordinates. It's a list for now. It will be concatenated into a matrix later
  #   shape: (T, nPoints)
  x = [None for i in range(nPoints)]
  y = [None for i in range(nPoints)]
  z = [None for i in range(nPoints)]

  # head first
  x[0] = rootsx
  y[0] = rootsy
  z[0] = rootsz

  # now other limbs
  i = 0
  # for numerical stability of angles normalization
  epsilon = 1e-10
  for a, b, l, _ in structure:
    # limb length
    L = tf.exp(lines[l])
    # angle
    Ax = anglesx[0:T, i:(i + 1)]
    Ay = anglesy[0:T, i:(i + 1)]
    Az = anglesz[0:T, i:(i + 1)]
    # angle norm
    normA = tf.sqrt(tf.square(Ax) + tf.square(Ay) + tf.square(Az)) + epsilon
    # new joint position
    x[b] = x[a] + L * Ax / normA
    y[b] = y[a] + L * Ay / normA
    z[b] = z[a] + L * Az / normA
    i = i + 1

  # making a matrix from the list
  x = tf.Variable(tf.concat(x, axis=1))
  y = tf.Variable(tf.concat(y, axis=1))
  z = tf.Variable(tf.concat(z, axis=1))

  @tf.function()
  def loss():
    return tf.math.reduce_sum(input_tensor=w_values * tf.square(x - tarx_values) + w_values * tf.square(y - tary_values)) / (T * nPoints) \
         + tf.reduce_sum(input_tensor=tf.square(x[0:(T - 1), 0:nPoints] - x[1:T, 0:nPoints]) \
                                                    + tf.square(y[0:(T - 1), 0:nPoints] - y[1:T, 0:nPoints]) \
                                                    + tf.square(z[0:(T - 1), 0:nPoints] - z[1:T, 0:nPoints])) / ((T - 1) * nPoints) \
         + tf.reduce_sum(input_tensor=tf.exp(lines))  # ?¿?¿ right now that's a constant!

  # the backpropagation
  opt = tf.keras.optimizers.SGD(learning_rate=learningRate)
  for iCycle in range(nCycles):
    opt.minimize(loss, var_list=[x, y, z])
    if (iCycle+1) == nCycles:
      print("iCycle = %3d, loss = %e" % (iCycle, loss()), flush=True)

  # returning final coordinates
  return x.numpy(), y.numpy(), z.numpy()

# retrieves the bone length
# the length of a bone is calculated as the average across all frames and clips
def get_bone_length(kp_3d, structure, dtype="float32"):
  lines = numpy.zeros((len(structure), ), dtype=dtype)
  Ls = {}
  for i in range(len(kp_3d)):
    Yx = kp_3d[i][0:kp_3d[i].shape[0], 0:(kp_3d[i].shape[1]):3]
    Yy = kp_3d[i][0:kp_3d[i].shape[0], 1:(kp_3d[i].shape[1]):3]
    Yz = kp_3d[i][0:kp_3d[i].shape[0], 2:(kp_3d[i].shape[1]):3]
    T = kp_3d[i].shape[0]
    for iBone in range(len(structure)):
      a, b, _, _ = structure[iBone]
      line = iBone
      if not line in Ls:
        Ls[line] = []
      for t in range(T):
        ax = Yx[t, a]
        ay = Yy[t, a]
        az = Yz[t, a]
        bx = Yx[t, b]
        by = Yy[t, b]
        bz = Yz[t, b]
        L = pose2Dto3D.norm([ax - bx, ay - by, az - bz])
        Ls[line].append(L)
  for i in range(len(structure)):
    #lines[i] = pose2Dto3D.perc(Ls[i], 0.5)
    lines[i] = numpy.mean(Ls[i])
  return lines

if __name__ == "__main__":
  # debug - don't run it

  #
  #             (0)
  #              |
  #              |
  #              0
  #              |
  #              |
  #     (2)--1--(1)--1--(3)
  #
  structure = (
    (0, 1, 0),
    (1, 2, 1),
    (1, 3, 1),
  )

  T = 3
  nBones, nPoints = skeletalModel.structureStats(structure)
  nLimbs = len(structure)

  dtype = "float32"

  lines0_values = numpy.zeros((nBones, ), dtype=dtype)
  rootsx0_values = numpy.ones((T, 1), dtype=dtype)
  rootsy0_values = numpy.ones((T, 1), dtype=dtype)
  rootsz0_values = numpy.ones((T, 1), dtype=dtype)
  anglesx0_values = numpy.ones((T, nLimbs), dtype=dtype)
  anglesy0_values = numpy.ones((T, nLimbs), dtype=dtype)
  anglesz0_values = numpy.ones((T, nLimbs), dtype=dtype)

  w_values = numpy.ones((T, nPoints), dtype=dtype)

  tarx_values = numpy.ones((T, nPoints), dtype=dtype)
  tary_values = numpy.ones((T, nPoints), dtype=dtype)

  x_values, y_values, z_values = backpropagationBasedFiltering(
    lines0_values,
    rootsx0_values,
    rootsy0_values,
    rootsz0_values,
    anglesx0_values,
    anglesy0_values,
    anglesz0_values,
    tarx_values,
    tary_values,
    w_values,
    structure,
    dtype,
  )