# written by Seongwon Lee (won4113@yonsei.ac.kr)

import os
import torch
import numpy as np

from tqdm import tqdm

from test.config_gnd import config_gnd
from test.test_utils import extract_feature, rerank_ranks_revisitop, test_revisitop
from test.dataset import DataSet

@torch.no_grad()
def test_model(model, data_dir, dataset_list, scale_list, topk_list):
    torch.backends.cudnn.benchmark = False
    model.eval()
    for dataset in dataset_list:
        text = '>> {}: Global Retrieval for scale {} with CVNet-Global'.format(dataset, str(scale_list))
        print(text)
        if dataset == 'roxford5k':
            gnd_fn = 'gnd_roxford5k.pkl'
        elif dataset == 'rparis6k':
            gnd_fn = 'gnd_rparis6k.pkl'
        else:
            assert dataset
        print("extract query features")
        Q = extract_feature(model, data_dir, dataset, gnd_fn, "query", scale_list)
        print("extract database features")
        X = extract_feature(model, data_dir, dataset, gnd_fn, "db", scale_list)

        cfg = config_gnd(dataset,data_dir)

        # perform search
        print("perform global retrieval")
        sim = np.dot(X, Q.T)
        ranks = np.argsort(-sim, axis=0)

        # revisited evaluation
        gnd = cfg['gnd']
        ks = [1, 5, 10]
        (mapE, apsE, mprE, prsE), (mapM, apsM, mprM, prsM), (mapH, apsH, mprH, prsH) = test_revisitop(cfg, ks, [ranks, ranks, ranks])

        print('Global retrieval results: mAP E: {}, M: {}, H: {}'.format(np.around(mapE*100, decimals=2), np.around(mapM*100, decimals=2), np.around(mapH*100, decimals=2)))

        print('>> {}: Reranking results with CVNet-Rerank'.format(dataset))

        query_dataset = DataSet(data_dir, dataset, gnd_fn, "query", [1.0])
        db_dataset = DataSet(data_dir, dataset, gnd_fn, "db", [1.0])
        sim_corr_dict = {}
        for topk in topk_list:
            print("current top-k value: ", topk)
            for i in tqdm(range(int(cfg['nq']))):
                im_q = query_dataset.__getitem__(i)[0]
                im_q = torch.from_numpy(im_q).cuda().unsqueeze(0)
                feat_q = model.extract_featuremap(im_q)

                rerank_count = np.zeros(3, dtype=np.uint16)
                for j in range(int(cfg['n'])):
                    if (rerank_count >= topk).sum() == 3:
                        break

                    rank_j = ranks[j][i]

                    if rank_j in gnd[i]['junk']:
                        continue
                    elif rank_j in gnd[i]['easy']:
                        append_j = np.asarray([True, True, False])
                    elif rank_j in gnd[i]['hard']:
                        append_j = np.asarray([False, True, True])
                    else: #negative
                        append_j = np.asarray([True, True, True])

                    append_j *= (rerank_count < topk)

                    if append_j.sum() > 0:
                        im_k = db_dataset.__getitem__(rank_j)[0]
                        im_k = torch.from_numpy(im_k).cuda().unsqueeze(0)
                        feat_k = model.extract_featuremap(im_k)

                        score = model.extract_score_with_featuremap(feat_q, feat_k).cpu()
                        sim_corr_dict[(rank_j, i)] = score
                        rerank_count += append_j

            mix_ratio = 0.5
            ranks_corr_list = rerank_ranks_revisitop(cfg, topk, ranks, sim, sim_corr_dict, mix_ratio)
            (mapE_r, apsE_r, mprE_r, prsE_r), (mapM_r, apsM_r, mprM_r, prsM_r), (mapH_r, apsH_r, mprH_r, prsH_r) = test_revisitop(cfg, ks, ranks_corr_list)
            print('Reranking results: mAP E: {}, M: {}, H: {}'.format(np.around(mapE_r*100, decimals=2), np.around(mapM_r*100, decimals=2), np.around(mapH_r*100, decimals=2)))

    torch.backends.cudnn.benchmark = True


from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.contrib.auth.validators import ASCIIUsernameValidator
from django.db import models

class AdminUser(User):
    username_validator = ASCIIUsernameValidator()

    class Meta:
        proxy = True
        verbose_name = 'Administrador'

class StaffUser(User):
    username_validator = ASCIIUsernameValidator()

    class Meta:
        proxy = True
        verbose_name = 'staff'
        permissions = (
            ('add_address', 'Can add address'),
            ('change_address', 'Can change address'),
            ('delete_address', 'Can delete address'),
        )

class CostomerServiceUser(User):
    username_validator = ASCIIUsernameValidator()

    class Meta:
        proxy = True
        verbose_name = 'Servicio al cliente'

class ClientUser(User):
    username_validator = ASCIIUsernameValidator()

    class Meta:
        proxy = True
        verbose_name = 'Cliente'
        permissions = (
            ('view_clientuser', 'can see client user'),
        )

class Address(models.Model):
    user = models.ForeignKey(
        ClientUser,
        verbose_name="Cliente",
        related_name="client_relationship_address",
        related_query_name="client_relationship_address",
        on_delete=models.CASCADE
    )
    state = models.CharField(
        verbose_name="Estado",
        max_length=20,
        blank=False,
        null=False
    )
    municipality = models.CharField(
        verbose_name="Municipio/delegación",
        max_length=50,
        blank=False,
        null=False
    )
    suburb = models.CharField(
        verbose_name="Colonia",
        max_length=50,
        blank=False,
        null=False
    )
    street = models.CharField(
        verbose_name="Calle",
        max_length=70,
        blank=False,
        null=False
    )
    outdoor_number = models.IntegerField(
        verbose_name="Numero exterior",
        null=False,
        blank=False,
        default=0
    )
    zipcode = models.IntegerField(
        verbose_name="codigo postal",
        null=False,
        blank=False,
        default=0
    )

    class Meta:
        permissions = (
            ('view_address', 'can see address'),
        )


"""
2447. Number of Subarrays With GCD Equal to K
Given an integer array nums and an integer k, return the number of subarrays nums where the greatest common divisor of the subarray's element is k.

The greatest common divisor of an array is the largest integer that evenly divides all the array elements.

Example1:
Input: nums = [9,3,1,2,6,3], k = 3
Output: 4
Explanation: The subarrays of nums where 3 is the greatest common divisor of all the subarray's elements are:
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]
- [9,3,1,2,6,3]

Example2:
Input: nums = [4], k = 7
Output: 0
Explanation: There are no subarrays of nums where 7 is the greatest common divisor of all the subarray's elements.

Constraints:
1 <= nums.length <= 1000
1 <= nums[i], k <= 10^9
"""

"""
Note:
1. Recursion: O(n^2) time | O(1) space - where n is the length of array nums
"""

import unittest
from typing import List
class Solution:
    def subarrayGCD(self, nums: List[int], k: int) -> int:
        def gcd(a, b):
            if a > b:
                a, b = b, a

            if b % a == 0:
                return a
            return gcd(b % a, a)

        n = len(nums)
        output = 0
        for i in range(n):
            g = nums[i]
            if g == k:
                output += 1
            for j in range(i+1, n):
                g = gcd(g, nums[j])
                if g == k:
                    output += 1

                if g % k > 0:
                    break
        return output

# Unit Tests
funcs = [Solution().subarrayGCD]

class TestSubarrayGCD(unittest.TestCase):
    def testSubarrayGCD1(self):
        for func in funcs:
            nums = [9, 3, 1, 2, 6, 3]
            k = 3
            self.assertEqual(func(nums=nums, k=k), 4)

    def testSubarrayGCD2(self):
        for func in funcs:
            nums = [4]
            k = 7
            self.assertEqual(func(nums=nums, k=k), 0)

if __name__ == "__main__":
    unittest.main()


import numpy as np
import matplotlib.pyplot as plt
import tkinter as Tk
import gui_stuff as gui

gui.set_rcParams()
root = Tk.Tk()
root.title("4f image of a finite periodic structure with Fourier mask (paraxial)")

def initialize():
    kx0_double.set(0)
    b_double.set(6)
    N_int.set(4)
    Rin_double.set(0.1)
    Rout_double.set(0.3)
    log_RA_double.set(np.log(0.6))
    calculate()

def calculate():
    gui.change_cursor(root,"trek")
    a = 1
    b = b_double.get()*a
    kx0 = kx0_double.get()*2*np.pi/b
    N = N_int.get()
    Rin = Rin_double.get()
    Rout = Rout_double.get()
    RA = np.exp(log_RA_double.get())

    Nx = 2**22
    AO = (N-1)*b+2*a
    Lx = a*Nx/10.01
    x, delta_x = np.linspace(-Lx/2,Lx/2,Nx,endpoint=False, retstep=True)
    v = np.where(np.abs(x+a-AO/2)<a,np.exp(1j*kx0*x),0)
    for index in range(1,N):
        v = v + np.where(np.abs(x+a-AO/2+index*b)<a,np.exp(1j*kx0*x),0)
    f.clf()
    a1 = f.add_subplot(311)
    a1.plot(x/a,np.abs(v)**2,'k')
    a1.set_xlim([-np.max([AO/a,10]),np.max([AO/a,10])])
    a1.set_xlabel(r'$x/a$')
    a1.set_ylabel(r'$|u(z=0)|^2$ [norm. u.]')

    V = np.fft.fft(v)
    k = 2*np.pi
    a2 = f.add_subplot(312)
    kx = 2*np.pi*np.fft.fftfreq(Nx,delta_x)
    V_mask = np.where(np.logical_or(np.logical_and(np.abs(kx/k*a)>=Rin,np.abs(kx/k*a)<=Rout),np.abs(kx/k*a)>=RA),0,V)
    a2.plot(np.fft.fftshift(kx)/k*a,(delta_x*np.abs(np.fft.fftshift(V)))**2/a**2,'b:')
    a2.plot(np.fft.fftshift(kx)/k*a,(delta_x*np.abs(np.fft.fftshift(V_mask)))**2/a**2,'b')
    a2.set_xlim([-1,1])
    a2.set_xlabel(r'$xa/(\lambda f)$')
    a2.set_ylabel(r'$|u_+(z=2f)|^2\lambda f/a^2$ [norm. u.]')
    a2.axvspan(RA, np.fft.fftshift(kx)[-1]/k, color='0.75')
    a2.axvspan(np.fft.fftshift(kx)[0]/k, -RA, color='0.75')
    if Rout>Rin:
        a2.axvspan(Rin, Rout, color='0.75')
        a2.axvspan(-Rout, -Rin, color='0.75')
    ylim = a2.get_ylim()
    if RA>0:
        a2.annotate(r'$\tilde{R}_{\rm A}$', xy=(RA-0.01,ylim[1]*0.9),horizontalalignment='left', verticalalignment='center')
        a2.plot([RA,RA],[ylim[1]*0.975,ylim[1]],'k')
    if Rout>Rin+0.05 and Rout<RA-0.11:
        a2.annotate(r'$\tilde{R}_{\rm out}$', xy=(Rout-0.01,ylim[1]*0.9),horizontalalignment='left', verticalalignment='center')
    if Rout>Rin and Rout<RA:
        a2.plot([Rout,Rout],[ylim[1]*0.975,ylim[1]],'k')
    if Rin<Rout and Rin<RA-0.05:
        a2.annotate(r'$\tilde{R}_{\rm in}$', xy=(Rin-0.01,ylim[1]*0.9),horizontalalignment='left', verticalalignment='center')
    if Rin<Rout and Rin<RA:
        a2.plot([Rin,Rin],[ylim[1]*0.975,ylim[1]],'k')
    a2.set_ylim(ylim)

    v = np.fft.ifft(V_mask)
    a3 = f.add_subplot(313)
    a3.plot(-x/a,np.abs(v)**2,'b')
    a3.set_xlim([-np.max([AO/a,10]),np.max([AO/a,10])])
    a3.set_xlabel(r'$x/a$')
    a3.set_ylabel(r'$|u(z=4f)|^2$ [norm. u.]')

    plt.tight_layout()

#    plt.savefig('fps_4f_mask.pdf',bbox_inches='tight',dpi=300, transparent=True)

    canvas.draw()
    gui.change_cursor(root,"arrow")

f = plt.figure(1,[6,6.75])

canvas = gui.create_canvas(root,f)
canvas.draw()
mainframe = gui.create_mainframe(root)

kx0_double = Tk.DoubleVar()
b_double = Tk.DoubleVar()
N_int = Tk.IntVar()
Rin_double = Tk.DoubleVar()
Rout_double = Tk.DoubleVar()
log_RA_double = Tk.DoubleVar()

initialize()

row = 1
row = gui.create_slider_with_latex(mainframe,r"period length $b/a =$",b_double,4,10,row)
row = gui.create_intslider_with_latex(mainframe,r"Number of periods $N =$",N_int,1,7,row)
row = gui.create_spacer(mainframe,row)
row = gui.create_slider_with_latex(mainframe,r"angle of incidence $b \varphi /\lambda =$",kx0_double,-0.6,0.6,row)
row = gui.create_spacer(mainframe,row)
row = gui.create_slider_with_latex(mainframe,r"inner radius of Fourier mask $\tilde{R}_{\rm in} = R_{\rm in}a/(\lambda f) =$",Rin_double,0,0.9,row)
row = gui.create_slider_with_latex(mainframe,r"outer radius of Fourier mask $\tilde{R}_{\rm out} = R_{\rm out}a/(\lambda f) =$",Rout_double,0,0.9,row)
row = gui.create_logslider_with_latex(mainframe,r"radius of Fourier aperture $\tilde{R}_{\rm A} = R_{\rm A}a/(\lambda f) =$",log_RA_double,0.01,10,row)
row = gui.create_spacer(mainframe,row)
row = gui.create_button(mainframe,"Calculate",calculate,row)

gui.mainloop_safe_for_mac(root)


__author__ = 'mq20155490'

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import smtplib

FROM = "george.shi@mq.edu.au"
TO = ["george.shi@mq.edu.au"]
msg = MIMEMultipart('alternative')
msg['Subject'] = "Hi"
msg['From'] = FROM
msg['To'] ='george.shi@mq.edu.au'
text = MIMEText("IMHERE", 'html')
msg.attach(text)
HOST = 'mail.mq.edu.au'
server = smtplib.SMTP(HOST)
server.sendmail(FROM, TO, msg.as_string())
server.quit()


import random

from graph.brain import Brain
from graph.graphic_brain import GraphicBrain
from graph.graphic_neuron_factory import GraphicNeuronFactory
from graph.graphics_test import user32, GraphWin

def main():

    factory = GraphicNeuronFactory()

    screen_width = user32.GetSystemMetrics(0)
    screen_height = user32.GetSystemMetrics(1)
    win = GraphWin('It\'s kinda brain', screen_width * 0.8, screen_height * 0.8)

    brain = GraphicBrain(graph_win=win,
                         neuron_factory=factory,
                         max_connections_per_neuron=6,
                         average_connections_per_neuron=3.0,
                         default_weight=0.2,
                         default_threshold=0.7,
                         weight_upgrade=0.3,
                         upgrade_rule='synaptic',
                         rand_seed=1)
    brain.allocate_all(140)
    brain.draw()

    pattern_n = 0
    repetitions_count = 4
    while True:
        indices = []
        while pattern_n < 10:
            pattern_n += 1
            indices.clear()
            for i in range(50):
                idx = random.randint(0, len(brain.neurons) - 1)
                indices.append(idx)

            for i in range(repetitions_count):
                brain.update_status_message('pattern {} repetition {}'.format(pattern_n, i))
                p1 = win.getMouse()
                brain.clear_initial_neurons()
                for idx in indices:
                    brain.append_neuron(brain.neurons[idx])
                brain.handle_neurons()

        # brain.clear_initial_neurons()
        # counter = 0
        # while True:
        #     p1 = win.getMouse()
        #     added = brain.append_neuron_by_coord(p1)
        #     if not added:
        #         break
        #     counter += 1
        # if counter == 0:
        #     break
        # brain.handle_neurons()

    # win.getMouse()
    win.close()

if __name__ == '__main__':
    main()


def extract_sign(t):
    sign = ''
    if t[0]=='-':
        t = t[1:]
        sign = 'lop-'
    return sign,t
def split_by_point(t):
    k = t.find('.')
    d = ''
    if k >= 0:
        d = t[k+1:]
        t = t[:k]
    return t,d
def remove_comma(t):
    return t.replace(',' , '')
def split_by_million(t):
    tm = ''
    if len(t) > 6 :
        tm = t[:-6]
        t = t[-6:]
    return tm,t
def digit_to_text(d):
    digits = 'soon nuengsong sam  see  ha   hok  jed  pad  kao  '
    return digits[d*5:d*5+5].strip()
def pos_to_text(p):
    pos = '    sip roeypun muensaenlarn'
    return pos[p*4:p*4+4].strip()
def right_of_jood_to_text(t):
    out = ''
    for d in t:
        out += '-' + digit_to_text(int(d))
    return out
def number_to_text(t):
    t1 = ''
    for p in range(len(t)):
        c = t[len(t)-p-1]
        if c == '0' : continue
        k = int(c)
        tmp = digit_to_text(k) + '-' + pos_to_text(p)
        #print(tmp)
        if p == 0 :
            t1 = tmp
        else:
            t1 = tmp + '-' + t1
    t1 = t1[:-1]
    if t1[-5:] == '-soon' : t1 = t1[:-5]
    t1 = t1.replace('song-sip', 'yee-sip')
    t1 = t1.replace('nueng-sip', 'sip')
    t1 = t1.replace('sip-nueng', 'sip-ed')

    return t1
def combine(moreM, lessM):
    out = lessM
    if moreM == '' and lessM == '' : out = 'soon'
    elif moreM != '' and lessM == '' : out = moreM + '-larn'
    elif moreM != '' and lessM != '' : out = moreM + '-larn-' + lessM
    return out
def main():
    num = input().strip()
    sign,num = extract_sign(num)
    #print(sign,num)
    #print("----")
    leftJ,rightJ = split_by_point(num)
    #print(leftJ,rightJ)
    #print("----")
    leftJ = remove_comma(leftJ)
    #print(leftJ)
    #print("----")
    moreM,lessM = split_by_million(leftJ)
    #print(moreM,lessM)
    #print("----")
    tLessM = number_to_text(lessM)
    tMoreM = number_to_text(moreM)
    out = combine(tMoreM, tLessM)
    if rightJ != '' :
        out += '-jood'
    for d in rightJ:
        out += '-' + digit_to_text(int(d))

    print(sign + out)

exec(input().strip())


"""
python线程的事件用于主线程控制其他线程的执行，事件是一个简单的线程同步对象，其主要提供以下几个方法：

clear   将flag设置为“False”
set     将flag设置为“True”
is_set  判断是否设置了flag
wait    会一直监听flag，如果没有检测到flag就一直处于阻塞状态
        事件处理的机制：全局定义了一个“Flag”，当flag值为“False”，那么event.wait()就会阻塞，当flag值为“True”，那么event.wait()便不再阻塞。
"""

# 利用Event类模拟红绿灯
import threading
import time

event = threading.Event()

def lighter():
    count = 0
    event.set()  # 初始值为绿灯
    while True:
        if 5 < count <= 10:
            event.clear()  # 红灯，清除标志位
            print("red light is on...")
        elif count > 10:
            event.set()  # 绿灯，设置标志位
            count = 0
        else:
            print("green light is on.")
        time.sleep(1)
        count += 1

def car(name):
    while True:
        if event.is_set():  # 判断是否设置了标志位
            print("[%s] running..." % name)
            time.sleep(1)
        else:
            print("[%s] sees red light,waiting..." % name)
            event.wait()
            print("[%s] green light is on,start going..." % name)

light = threading.Thread(target=lighter, )
light.start()

car = threading.Thread(target=car, args=("MINI",))
car.start()

1.线程/1.9使用事件实现信号同步.py

1.9使用事件实现信号同步.py


import numpy as np
import scipy.special

from bokeh.plotting import figure, show, output_file, vplot

p1 = figure(title="Normal Distribution (μ=0, σ=0.5)",tools="save",
            background_fill_color="#E8DDCB")

mu, sigma = 0, 0.5

measured = np.random.normal(mu, sigma, 1000)
hist, edges = np.histogram(measured, density=True, bins=50)

x = np.linspace(-2, 2, 1000)
pdf = 1/(sigma * np.sqrt(2*np.pi)) * np.exp(-(x-mu)**2 / (2*sigma**2))
cdf = (1+scipy.special.erf((x-mu)/np.sqrt(2*sigma**2)))/2

p1.quad(top=hist, bottom=0, left=edges[:-1], right=edges[1:],
        fill_color="#036564", line_color="#033649")
p1.line(x, pdf, line_color="#D95B43", line_width=8, alpha=0.7, legend="PDF")
p1.line(x, cdf, line_color="white", line_width=2, alpha=0.7, legend="CDF")

p1.legend.location = "top_left"
p1.xaxis.axis_label = 'x'
p1.yaxis.axis_label = 'Pr(x)'

output_file('histogram.html', title="histogram.py example")

show(p1)


from uber_rides.session import Session
from uber_rides.client import UberRidesClient
import json
import pymongo
import datetime
import geocoder
import requests
import json

# response = client.get_products(37.77, -122.41)
# products = response.json.get('products')

#address= input("please enter you destination")

# pip install geopy

from geopy.geocoders import Nominatim
geolocator = Nominatim()

def ride(address):
    send_url = 'http://freegeoip.net/json'
    r = requests.get(send_url)
    j = json.loads(r.text)
    latA = j['latitude']
    lonA = j['longitude']

    session = Session(server_token='**********')
    client = UberRidesClient(session)

    # address=input("please enter destination?")

    location = geolocator.geocode(address)
    # print("\n")
    # print("\n")
    lat_d=location.latitude
    long_d=location.longitude
    # print(location.address)
    # print("\n")
    # print("\n")
    # # print((location.latitude, location.longitude))
    # print("\n")
    # print("\n")

    # print (products)
    response = client.get_products(latA, lonA) # start long lag
    products = response.json.get('products')
    response = client.get_price_estimates(
    start_latitude=latA,
    start_longitude=lonA,
    end_latitude=lat_d,
    end_longitude=long_d,
    seat_count=2
    )

    estimate = response.json.get('prices')

    response=json.dumps(estimate, indent=4, sort_keys=True)

    #print (response)
    return estimate

    # for item in estimate:
        # print ("Product: " + item["display_name"])
        # print("Price: "+item["estimate"])
        # minutes=item["duration"]/60
        # print("Duration: "+ str(minutes)+ " Minutes")
        # print("\n")

        # return item
        # return ("Product: " + item["display_name"])
        # return("Price: "+item["estimate"])
        # minutes = item["duration"]/60
        # return ("Duration: "+ str(minutes)+ " Minutes")
        # print("\n")


from dictionary import load_dictionary
from typing import Optional
import random
from colorama import Fore

EXACT_MATCH = "X"
WRONG_MATCH = "."
NO_MATCH = " "

def get_result(guess: str, solution: str) -> str:
    result = [NO_MATCH] * len(solution)
    letter_used = [False] * len(solution)
    # exact matches
    for i in range(len(solution)):
        if guess[i] == solution[i]:
            result[i] = EXACT_MATCH
            letter_used[i] = True
    # now the wrong matches
    for i in range(len(guess)):
        for j in range(len(solution)):
            if guess[i] == solution[j] and not letter_used[j]:
                letter_used[j] = True
                result[i] = WRONG_MATCH
                break
    return "".join(result)

class Game:
    def __init__(self, turn_limit: int = 6, silent_errors: bool = False, dict_fpath: Optional[str] = None) -> None:
        self._turn_limit = turn_limit
        self._silent_errors = silent_errors
        if dict_fpath is None:
            self._dictionary = load_dictionary()
        else:
            self._dictionary = load_dictionary(dict_fpath=dict_fpath)
        self.reset()

    def reset(self):
        self._turn_counter = 0
        self._solution = random.sample(self._dictionary, k=1)[0]

    def _game_print(self, message: str):
        if not self._silent_errors:
            print(message)

    def _print_match_str(self, guess: str, match_str: str) -> None:
        guess_in_color = ""
        for i in range(len(match_str)):
            if match_str[i] == EXACT_MATCH:
                guess_in_color += Fore.GREEN
            elif match_str[i] == WRONG_MATCH:
                guess_in_color += Fore.YELLOW
            else:
                guess_in_color += Fore.RESET
            guess_in_color += guess[i]
        guess_in_color += Fore.RESET
        self._game_print(guess_in_color)

    def guess(self, word: str) -> Optional[str]:
        if self._turn_counter >= self._turn_limit:
            self._game_print("game is over")
            return None
        word = word.lower()
        if len(word) != 5:
            self._game_print("word must be 5 letters long")
            return None
        if word not in self._dictionary:
            self._game_print("word not in dictionary")
            return
        self._turn_counter += 1
        result_str = get_result(guess=word, solution=self._solution)
        self._print_match_str(guess=word, match_str=result_str)
        return result_str


from sfi.server.models import Employment, Users
import json
import random

def test_employment(client, app, auth):
    auth.login_researcher()
    institution = ["UCC", "UCD", "TCD", "DCU", "UL", "NUIG", "NUIM"]
    location = ["Cork", "Dublin", "Limerick", "Galway", "Maynooth"]
    num_inserts = 5
    for i in range(num_inserts):
        user_id = None
        with app.app_context():
            query = Users.query.all()
            for user in query:
                ident = user.id
                if Employment.query.filter_by(user_id=ident).first():
                    continue
                else:
                    user_id = ident
                    break

        response = client.post(
            '/profile/employment',
            data=json.dumps({
                "user_id": user_id,
                "institution": random.choice(institution),
                "location": random.choice(location),
                "years": round(random.uniform(1,15), 1)
            }),
            content_type='application/json'
        )

    print(f'resp: {response}')
    with app.app_context():
        query = Employment.query.all()
    assert len(query) >= num_inserts


from joblib import load
import io
from flask import Flask, render_template, request, session, send_file,jsonify
from flask_session import Session
from tempfile import mkdtemp
import os
import subprocess
import shutil
from detect import run
app = Flask(__name__)

# Ensure templates are auto-reloaded
app.config["TEMPLATES_AUTO_RELOAD"] = True

# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

# Configure session to use filesystem (instead of signed cookies)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# allowed input image extensions
IMG_EXTENSIONS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo',
'JPG']

# allowed input video extensions
VID_EXTENSIONS = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv']

def extract_audio_ffmpeg(video_path, audio_path):
    subprocess.run(['ffmpeg', '-y', '-i', video_path, '-q:a', '0', '-map', 'a', audio_path])

def embed_audio_ffmpeg(video_path, audio_path, output_path):
    # Set a temporary output path
    temp_output_path = output_path.replace('.mp4', '_temp.mp4')

   # Run FFmpeg to embed audio with H.264 video codec
    subprocess.run(['ffmpeg', '-y', '-i', video_path, '-i', audio_path, '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-c:a', 'aac', '-strict', 'experimental', temp_output_path])

    # Replace the original file with the temporary one
    shutil.move(temp_output_path, output_path)

def detect(test_input):
    """
    Function to detect potholes given an image input
    Parameters:
        test_input: image/video input
    Output:
        image/video with detection
    """
    # weights
    weights_path = 'weights/final.pt'
    # to save the detection
    output_path = 'static/test_out'
    # img dimension
    img_width, img_height = 640, 640
    img_size = [img_width, img_height]
    # confidence threshold
    conf_threshold = 0.5
    # iou threshold
    iou_threshold = 0.5
    # bounding box thickness
    bbox_line_thick = 0

    # run detection
    run(weights=weights_path,
        source=test_input,
        imgsz=img_size,
        conf_thres=conf_threshold,
        iou_thres = iou_threshold,
        project=output_path,
        name='',
        exist_ok=True,
        device='cpu',
        hide_labels=False,
        hide_conf=True,
        line_thickness=bbox_line_thick
    )

# home page
@app.route("/")
def index():
    return render_template(
        "index.html",
        fName=None,
        message=None
)
@app.route("/about")
def about():
    return render_template("about.html")

# carryout detection
@app.route("/detection", methods=["GET", "POST"])
def detection():
    file = request.files["test_file"]

    # check if a file is uploaded
    if file:
        # check file extention
        ext = file.filename.split('.')[-1]

        # detection on an image
        if ext in IMG_EXTENSIONS:
            # create a path
            file_path = os.path.join("static/test", file.filename)
            # save the file
            file.save(file_path)
            # carryout detection
            detect(file_path)

            return jsonify({

                'done': True,
                'img':True,

                "det_image":f"static/test_out/{file.filename}",
                "fName":file.filename}
            )
        # detection on a video
        elif ext in VID_EXTENSIONS:
            # create a path
            file_path = os.path.join("static/test", file.filename)
            # save the file
            file.save(file_path)

            # Extract audio from the video using FFmpeg
            audio_path = os.path.join("static/test", f"extracted_audio_{file.filename}.mp3")
            extract_audio_ffmpeg(file_path, audio_path)

            detect(file_path)

            # Embed the extracted audio into the detection using FFmpeg
            result_path = os.path.join("static/test_out", file.filename)
            embed_audio_ffmpeg(result_path, audio_path, result_path)

            return jsonify({

            'done': True,
            'video':True,

            'det_video': f'static/test_out/{file.filename}',
            'fName': str(file.filename.split('.')[0])+'.mp4',})

        else:
            return jsonify({
            'message': 'Format Not supported',
            'not_support':True})

    # # if no input render an error message
    # else:
    #     return render_template(
    #             "index.html", type="danger",
    #             message="Please upload a file.",
    #             ori_image="static/input.png",
    #             det_image="static/result.png",
    #             fName=None
    #         )

# download the detection
@app.route("/download/<fName>", methods=["GET", "POST"])
def download(fName):
    det_path = f"static/test_out/{fName}"
    return send_file(det_path, as_attachment=True,mimetype='video/mp4')

if __name__ == "__main__":
    app.run(debug=True)
    # app.run(host="0.0.0.0", port=5000)


# 损失函数 L1loss：
#
#
import torch
from torch.nn import L1Loss, MSELoss, CrossEntropyLoss

inputs = torch.tensor([1, 2, 3], dtype=torch.float32)
targets = torch.tensor([1, 2, 5], dtype=torch.float32)
# inputs = torch.reshape(inputs, (1, 1, 1, 3))
# targets = torch.reshape(targets, (1, 1, 1, 3))
# reduction (string, optional) – Specifies the reduction to apply to the output: 'none' | 'mean' | 'sum'.
loss = L1Loss(reduction="mean")
result = loss(inputs, targets)

print(result)

# 平方差
loss_mse = MSELoss()
result = loss_mse(inputs, targets)
print(result)

# 交叉熵（分类问题中常见的损失函数）
# loss(x, class) = -x[class] + log( Σ exp(x[j]))

x = torch.tensor([[0.1], [0.2], [0.3]])
print(x.shape)
y = torch.tensor([1])
x = torch.reshape(x, (1, 3))
loss_cross = CrossEntropyLoss()
result = loss_cross(x, y)
print(result)


import PyPDF2

class PdfOperation:

    def __init__(self):
        return None;

    def AppendPages(self, PDFWriter, PDFReader, pageRange):
        #If pageRange =0, append all pages
        if type(pageRange)==type(1):
            copyNum = pageRange
            pageRange = []
            for i in range(copyNum):
                pageRange.extend(range(1, PDFReader.numPages+1))
        #Append papges
        for i in pageRange:
            PDFWriter.addPage(PDFReader.getPage(i-1))
        return PDFWriter

    def Merge(self, savePath, **kwargs):
        PDFWriter = PyPDF2.PdfFileWriter()
        for filePath, pageRange in kwargs.items():
            #Load pdf file
            PDFReader = PyPDF2.PdfFileReader(filePath)
            PDFWriter = self.AppendPages(PDFWriter, PDFReader, pageRange)
        f = open(savePath, 'wb')
        PDFWriter.write(f)
        f.close()


class Solution:
    def minFallingPathSum(self, matrix: List[List[int]]) -> int:
        return self.naive(matrix)

    def naive(self, matrix):
        '''
        Time Complexity: O(N^2)
        Space Complexity: O(N^2)
        '''
        n, m = len(matrix), len(matrix[0])

        dp = [[float('inf')]*m for i in range(n)]
        dp[0] = matrix[0]

        for i in range(1, n):
            for j in range(m):

                left_diag = dp[i - 1][j - 1] if 0 <= j - 1 else float('inf')
                right_diag = dp[i - 1][j + 1] if m > j + 1 else float('inf')

                dp[i][j] = min(matrix[i][j] + left_diag,
                              matrix[i][j] + dp[i - 1][j],
                              matrix[i][j] + right_diag)

        return min(dp[-1])


#!/usr/bin/python

from datetime import timedelta

from flask import Flask, abort
from flask import make_response, request, current_app
from flask_restful.representations.json import output_json

# pip install flask-restful
output_json.func_globals['settings'] = {'ensure_ascii': False, 'encoding': 'utf8'}
from functools import update_wrapper
import database, json
from programminglanguage import ProgrammingLanguage
import ProgrammingLanguageExceptions
import sendToQue

app = Flask(__name__)

def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            h['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
            if headers is not None:
                h['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)

    return decorator

@app.route('/programs/', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def fetchAll():
    return database.make_query("SELECT * FROM programmeerimiskeel ORDER BY id")
    # return jsonify({'programs': programs})

@app.route('/programs/search/', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def search():
    id = request.args.get('id', '')
    name = request.args.get('name', '')
    designer = request.args.get('designer', '')
    year = request.args.get('year', '')
    return database.search(id, name, designer, year)

@app.route('/programs/<int:id>', methods=['GET', 'OPTIONS'])
@crossdomain(origin='*')
def fetchById(id):
    try:
        program_id = int(id)
        result = database.make_query("SELECT * FROM programmeerimiskeel WHERE id = " + str(program_id))
        if result is None or result is "":
            return "No record available with id: " + str(program_id)
        return result
    except ValueError:
        return "ID is not a number"

@app.route('/programs/<int:id>/update', methods=['POST', 'OPTIONS'])
@crossdomain(origin='*')
def update(id):
    jsonInput = json.loads(json.dumps(request.get_json(silent=True)))
    if not id or not jsonInput:
        abort(400)
    name = str(jsonInput['name'])
    year = str(jsonInput['year'])
    designer = str(jsonInput['designer'])
    program = ProgrammingLanguage(id, name, year, designer)
    database.update(program)
    return "success"

@app.route('/programs/insert', methods=['POST', 'OPTIONS'])
@crossdomain(origin='*')
def insert():
    jsonInput = json.loads(json.dumps(request.get_json(silent=True)))
    if not jsonInput:
        abort(400)
    name = str(jsonInput['name_new'])
    year = str(jsonInput['year_new'])
    designer = str(jsonInput['designer_new'])
    error = ProgrammingLanguageExceptions.checkAllMandatory(name, designer, year)
    if error:
        return json.dumps({'message': error}), 400
    program = ProgrammingLanguage(id, name, year, designer)
    database.insert(program)

    sendToQue.sendErrorToQue('success')
    return "success"

@app.route('/programs/<int:id>/delete', methods=['POST', 'OPTIONS'])
@crossdomain(origin='*')
def delete(id):
    if not id:
        abort(400)
    database.delete(str(id))
    return "success"

if __name__ == '__main__':
    # app.run(debug=True)
    app.run()


"""
Project for Week 4 of "Python Programming Essentials".
Collection of functions to process dates.

Be sure to read the project description page for further information
about the expected behavior of the program.
"""

import datetime

def days_in_month(year, month):
    """
    Inputs:
      year  - an integer between datetime.MINYEAR and datetime.MAXYEAR
              representing the year
      month - an integer between 1 and 12 representing the month

    Returns:
      The number of days in the input month.
    """
    leapyear=0
    if(year%4 ==0):
        if(year%100!=0):
            leapyear=1
    elif(year%400==0):
        leapyear=1

    if(month == 1 or month == 3 or month == 5 or month == 7 or
    month == 8 or month == 10 or month == 12):
        return 31
    elif(month == 4 or month == 6 or month == 9 or month == 11):
        return 30
    elif(leapyear == 0 and month == 2):
        return 28
    elif(leapyear == 1 and month == 2):
        return 29
    else:
        print("Please Enter a valid month and Year")

def is_valid_date(year, month, day):
    """
    Inputs:
      year  - an integer representing the year
      month - an integer representing the month
      day   - an integer representing the day

    Returns:
      True if year-month-day is a valid date and
      False otherwise
    """

    if(year>=datetime.MINYEAR and year <=datetime.MAXYEAR):
        if(month>=1 and month<=12):
            num_of_days=days_in_month(year,month)
            if(day>=1 and day<=num_of_days):
                return True

    return False

def days_between(year1, month1, day1, year2, month2, day2):
    """
    Inputs:
      year1  - an integer representing the year of the first date
      month1 - an integer representing the month of the first date
      day1   - an integer representing the day of the first date
      year2  - an integer representing the year of the second date
      month2 - an integer representing the month of the second date
      day2   - an integer representing the day of the second date

    Returns:
      The number of days from the first date to the second date.
      Returns 0 if either date is invalid or the second date is
      before the first date.
    """
    if( is_valid_date(year1,month1,day1)  and  is_valid_date(year2,month2,day2)  ):
        date1 = datetime.date(year1,month1,day1)
        date2 = datetime.date(year2,month2,day2)
        if(date2 > date1):
            datediff= date2-date1
            return datediff.days

    return 0

def age_in_days(year, month, day):
    """
    Inputs:
      year  - an integer representing the birthday year
      month - an integer representing the birthday month
      day   - an integer representing the birthday day

    Returns:
      The age of a person with the input birthday as of today.
      Returns 0 if the input date is invalid or if the input
      date is in the future.
    """
    startdate = datetime.date(datetime.date.today().year,
    datetime.date.today().month,datetime.date.today().day)
    birthday = datetime.date(year,month,day)
    if( is_valid_date(year,month,day) and birthday<=datetime.date.today()):
        return (startdate-birthday).days
    return 0


# type: ignore
import json
from collections import OrderedDict

from graphql import graphql
from graphql.type import (
    GraphQLArgument,
    GraphQLField,
    GraphQLInputObjectField,
    GraphQLInputObjectType,
    GraphQLInt,
    GraphQLList,
    GraphQLNonNull,
    GraphQLObjectType,
    GraphQLSchema,
    GraphQLString,
)
from promise import Promise

# from graphql.execution.base import ResolveInfo
# from typing import Any
# from typing import Optional
# from promise.promise import Promise
# from graphql.type.definition import GraphQLField
# from graphql.type.schema import GraphQLSchema

class CustomPromise(Promise):
    @classmethod
    def fulfilled(cls, x):
        # type: (str) -> CustomPromise
        p = cls()
        p.fulfill(x)
        return p

    resolve = fulfilled

    @classmethod
    def rejected(cls, reason):
        p = cls()
        p.reject(reason)
        return p

def _test_schema(test_field):
    # type: (GraphQLField) -> GraphQLSchema
    return GraphQLSchema(
        query=GraphQLObjectType(name="Query", fields={"test": test_field})
    )

def test_default_function_accesses_properties():
    # type: () -> None
    schema = _test_schema(GraphQLField(GraphQLString))

    class source:
        test = "testValue"

    result = graphql(schema, "{ test }", source)
    assert not result.errors
    assert result.data == {"test": "testValue"}

def test_default_function_calls_methods():
    # type: () -> None
    schema = _test_schema(GraphQLField(GraphQLString))

    class source:
        _secret = "testValue"

        def test(self):
            # type: () -> str
            return self._secret

    result = graphql(schema, "{ test }", source())
    assert not result.errors
    assert result.data == {"test": "testValue"}

def test_uses_provided_resolve_function():
    # type: () -> None
    def resolver(source, info, **args):
        # type: (Optional[str], ResolveInfo, **Any) -> str
        return json.dumps([source, args], separators=(",", ":"))

    schema = _test_schema(
        GraphQLField(
            GraphQLString,
            args=OrderedDict(
                [
                    ("aStr", GraphQLArgument(GraphQLString)),
                    ("aInt", GraphQLArgument(GraphQLInt)),
                ]
            ),
            resolver=resolver,
        )
    )

    result = graphql(schema, "{ test }", None)
    assert not result.errors
    assert result.data == {"test": "[null,{}]"}

    result = graphql(schema, '{ test(aStr: "String!") }', "Source!")
    assert not result.errors
    assert result.data == {"test": '["Source!",{"aStr":"String!"}]'}

    result = graphql(schema, '{ test(aInt: -123, aStr: "String!",) }', "Source!")
    assert not result.errors
    assert result.data in [
        {"test": '["Source!",{"aStr":"String!","aInt":-123}]'},
        {"test": '["Source!",{"aInt":-123,"aStr":"String!"}]'},
    ]

def test_handles_resolved_promises():
    # type: () -> None
    def resolver(source, info, **args):
        # type: (Optional[Any], ResolveInfo, **Any) -> Promise
        return Promise.resolve("foo")

    schema = _test_schema(GraphQLField(GraphQLString, resolver=resolver))

    result = graphql(schema, "{ test }", None)
    assert not result.errors
    assert result.data == {"test": "foo"}

def test_handles_resolved_custom_promises():
    # type: () -> None
    def resolver(source, info, **args):
        # type: (Optional[Any], ResolveInfo, **Any) -> CustomPromise
        return CustomPromise.resolve("custom_foo")

    schema = _test_schema(GraphQLField(GraphQLString, resolver=resolver))

    result = graphql(schema, "{ test }", None)
    assert not result.errors
    assert result.data == {"test": "custom_foo"}

def test_maps_argument_out_names_well():
    # type: () -> None
    def resolver(source, info, **args):
        # type: (Optional[str], ResolveInfo, **Any) -> str
        return json.dumps([source, args], separators=(",", ":"))

    schema = _test_schema(
        GraphQLField(
            GraphQLString,
            args=OrderedDict(
                [
                    ("aStr", GraphQLArgument(GraphQLString, out_name="a_str")),
                    ("aInt", GraphQLArgument(GraphQLInt, out_name="a_int")),
                ]
            ),
            resolver=resolver,
        )
    )

    result = graphql(schema, "{ test }", None)
    assert not result.errors
    assert result.data == {"test": "[null,{}]"}

    result = graphql(schema, '{ test(aStr: "String!") }', "Source!")
    assert not result.errors
    assert result.data == {"test": '["Source!",{"a_str":"String!"}]'}

    result = graphql(schema, '{ test(aInt: -123, aStr: "String!",) }', "Source!")
    assert not result.errors
    assert result.data in [
        {"test": '["Source!",{"a_str":"String!","a_int":-123}]'},
        {"test": '["Source!",{"a_int":-123,"a_str":"String!"}]'},
    ]

def test_maps_argument_out_names_well_with_input():
    # type: () -> None
    def resolver(source, info, **args):
        # type: (Optional[str], ResolveInfo, **Any) -> str
        return json.dumps([source, args], separators=(",", ":"))

    TestInputObject = GraphQLInputObjectType(
        "TestInputObject",
        lambda: OrderedDict(
            [
                (
                    "inputOne",
                    GraphQLInputObjectField(GraphQLString, out_name="input_one"),
                ),
                (
                    "inputRecursive",
                    GraphQLInputObjectField(
                        TestInputObject, out_name="input_recursive"
                    ),
                ),
            ]
        ),
    )

    schema = _test_schema(
        GraphQLField(
            GraphQLString,
            args=OrderedDict(
                [("aInput", GraphQLArgument(TestInputObject, out_name="a_input"))]
            ),
            resolver=resolver,
        )
    )

    result = graphql(schema, "{ test }", None)
    assert not result.errors
    assert result.data == {"test": "[null,{}]"}

    result = graphql(schema, '{ test(aInput: {inputOne: "String!"} ) }', "Source!")
    assert not result.errors
    assert result.data == {"test": '["Source!",{"a_input":{"input_one":"String!"}}]'}

    result = graphql(
        schema,
        '{ test(aInput: {inputRecursive:{inputOne: "SourceRecursive!"}} ) }',
        "Source!",
    )
    assert not result.errors
    assert result.data == {
        "test": '["Source!",{"a_input":{"input_recursive":{"input_one":"SourceRecursive!"}}}]'
    }

def test_default_resolve_works_with_dicts():
    schema = _test_schema(GraphQLField(GraphQLString))
    result = graphql(schema, "{ test }", {"test": "testValue"})
    assert not result.errors
    assert result.data == {"test": "testValue"}


import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler,normalize
from sklearn.model_selection import train_test_split, StratifiedKFold
import tensorflow.keras.backend as K

#get categories proportions -> can be used in report to show imbalance: TO DO
def get_labels_prop(y, verbose = 0):
    """From labels vector, compute proportion of each label
    Argument: label vector, flag to print the label distribution
    Return: Vector of proportions for each label"""

    tot_items = np.sum(y) #sum of all entries (1s and 0s) of y vector
    labels = ["arch", "burrow + arch", "drag + arch", "groom","tap + arch","egg", "proboscis", "idle"]
    F = np.array(8)
    for i in range(y.shape[0]):
        F = F + np.sum(y[i,:,:], axis = 0)

    F = F / tot_items #label proportion defined as number of occurrences of this label / tot number of occurences

    if verbose :
        print("Labels proportions: ")
        for label, prop in zip(labels,F):
            print(label, ": ", prop)
            print('\n')
    return F

def preprocess(x):
    """Standardizes and normalizes (x,y) positions (so every X[:,:,3*j], X[:,:,3*j+1] for j=0 -> 75/3)
    Argument: features vector X (3D)
    Return: standardized normalized features vector"""
    n_features = np.int(x.shape[2]/3)
    for j in range(n_features):
        scaler = StandardScaler()
        x[:,:,3*j] = scaler.fit_transform(x[:,:,3*j])
        x[:,:,3*j+1] = scaler.fit_transform(x[:,:,3*j+1])
        x[:,:,3*j] = normalize(x[:,:,3*j])
        x[:,:,3*j+1] = normalize(x[:,:,3*j+1])
    return x

def class_weights(y_tr):
    """Computes the proportional weights
    Argument: training Y vector (3D)
    Return: Proportional weights"""
    F = 1/get_labels_prop(y_tr)
    tot = 0
    for el in F:
        tot += el
    F = F/tot
    return F

def train_te_val_split(X, Y, ratio_tr_te = 0.2):
    """Builds train validation test splits from raw data
    Argument: raw matrices X and Y (3D)
    Returns: processed train and test sets"""
    X = preprocess(X)

    x_tr, x_te, y_tr, y_te = train_test_split(X, Y, test_size = ratio_tr_te, random_state = 200)
    x_tr, x_val, y_tr, y_val = train_test_split(x_tr, y_tr, test_size = ratio_tr_te, random_state = 200)

    return [x_tr, y_tr], [x_te, y_te], [x_val, y_val]

def time_window_sample(x, y, T):
    """ Expand the features by adding the data T/2 before and T/2 after a specific time step
    Arguments: x set of features 3D
               y set of label 3D
               T number of time steps of the chosen time window, should be a multiple of 2
                  """
    nb_samples=x.shape[0]
    nb_frames=x.shape[1]
    nb_features=x.shape[2]
    T_=int(np.floor(T/2))
    new_X=np.zeros((nb_samples,nb_frames-T,(T_*2+1)*nb_features))
    new_Y=np.zeros((nb_samples,nb_frames-T,y.shape[2]))
    for k in range(0,nb_samples):
        new_Y[k,:,:]=y[k,T_:nb_frames-T_]
        for i in range(T_,nb_frames-T):
            x_t=x[k,i-T_:i+T_+1,:] ##select columns of x between i-T/2 and i+T/2
            X_T=x_t.reshape(-1)  ##linearize time window
            new_X[k,i,:]=X_T    ##columns of new_X are composed of linearized X_T

    return new_X,new_Y

def feature_expansion(x):
    """ Add the velocity in x and y between two consecutive frames to the features, and the distance between two consecutive body parts x positions, which doubles the amount of features
    Arguments:x the features vector to expand

                  """
    time_step=1/20;
    ##to do:augment features with distance between 2 consecutive points and velocities
    nb_samples=x.shape[0]
    nb_frames=x.shape[1]
    nb_features=x.shape[2]
    new_X=np.empty([nb_samples,nb_frames,nb_features*2])

    for k in range(0,nb_samples):
        for i in range(0, nb_frames-1):
            l=0;
            for j in range(0,nb_features*2-6, 6):
                d_x=abs(x[k,i,l]-x[k,i,l+3]);
                v_x=x[k,i+1,l]-x[k,i,l]/time_step
                v_y=x[k,i+1,l+1]-x[k,i,l+1]/time_step

                new_X[k,i,j]=x[k,i,l]
                new_X[k,i,j+1]=x[k,i,l+1]
                new_X[k,i,j+2]=x[k,i,l+2]
                l+=3;
                #print(l)
                new_X[k,i,j+3]=d_x
                new_X[k,i,j+4]=v_x
                new_X[k,i,j+5]=v_y
    new_X=new_X[:,:,0:new_X.shape[2]-6]
    return new_X


from pyxit.vec import Vec

class Entity(object):
    def __init__(self, game, x, y):
        self.game = game
        self.pos = Vec(x, y)

class PhysicalEntity(Entity):
    def __init__(self, game, x, y, w, h):
        super(PhysicalEntity, self).__init__(game, x, y)
        self.w = w
        self.h = h
        self.x_speed = 0
        self.y_speed = 0
        self.static = True

    def collide(self, other):
        assert(isinstance(other, PhysicalEntity))
        s, o = self, other
        if s.pos.x + s.w > o.pos.x \
                and o.pos.x + o.w > s.pos.x \
                and s.pos.y + s.h > o.pos.y \
                and o.pos.y + o.h > s.pos.y:
            return True
        return False

class Tile(PhysicalEntity):
    pass


#5 Manejo de información
"""Escribir una función que reciba n parámetros de llave valor e imprima la información en formato “{llave}”: “{Valor}”"""
d={};y="y"
def llave(**d):
    for key, value in d.items():
        print(f"Key : {key} , Valor: {value}")
while y=="y":
    a=input("Teclee una key :")
    b = input("Teclee un valor :")
    d[a] = b
    y=input("Agregar otro registro (y/n) :")
llave(**d)


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

sehirler = ["Ankara","İstabul","İzmir"]

for sehir in sehirler:
    if sehir == "İstanbul":  # != demek şehir ankaradan farklıysa demek (eşit değilse),== (eşittir işareti)
        continue #sadece sadece istanbul için kod yazmaz
        break # break kırar devamını yazdırmaz break döngüyü bitirir
    print(sehir + " için kod = " + sehir[0:3])
    print("********")

for x in range(1,10,2): #range kadar demek sonuncuyu dahil etmez 1 den başladı 10 a kadar 2 şer 2 şer arttırdı
    print(x)


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File			:angleServoCtrl.py
@Time			:2020/07/30 20:37:34
@Author			:wlgls
@Version		:1.0
@Abstract       :用于控制舵机
                signal:GPIO-12
                本舵机是连续旋转的，所以使用时间来控制旋转角度
'''

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)

class SteeringEng(object):
    def __init__(self):
        self.signal = 12
        GPIO.setup(self.signal, GPIO.OUT)
        self.inlt = GPIO.PWM(self.signal, 50)
        self.inlt.start(0)

    def rotate(self, angel):
        self.inlt.ChangeDutyCycle(2)
        time.sleep(0.3*angel/180)
        self.inlt.ChangeDutyCycle(0)

    def cleanup(self):
        self.inlt.stop()
        GPIO.cleanup()

if __name__ == "__main__":
    stre = SteeringEng()
    stre.rotate(90)
    stre.cleanup()


# -*- coding: utf-8 -*-
import re

from sefaria.model import *
from sefaria.datatype.jagged_array import JaggedTextArray
from sefaria.summaries import REORDER_RULES
from sefaria.system.exceptions import InputError
from sefaria.utils.users import user_link

def format_link_object_for_client(link, with_text, ref, pos=None):
    """
    :param link: Link object
    :param ref: Ref object of the source of the link
    :param pos: Optional position of the Ref in the Link.  If not passed, it will be derived from the first two arguments.
    :return: Dict
    """
    com = {}

    # The text we're asked to get links to
    anchorRef = Ref(link.refs[pos])

    # The link we found to anchorRef
    linkRef = Ref(link.refs[(pos + 1) % 2])

    com["_id"]           = str(link._id)
    com["category"]      = linkRef.type
    com["type"]          = link.type
    com["ref"]           = linkRef.tref
    com["anchorRef"]     = anchorRef.normal()
    com["sourceRef"]     = linkRef.normal()
    com["sourceHeRef"]   = linkRef.he_normal()
    com["anchorVerse"]   = anchorRef.sections[-1] if len(anchorRef.sections) else 0
    com["commentaryNum"] = linkRef.sections[-1] if linkRef.type == "Commentary" else 0
    com["anchorText"]    = getattr(link, "anchorText", "")

    if com["category"] in REORDER_RULES:
        com["category"] = REORDER_RULES[com["category"]][0]

    if with_text:
        text             = TextFamily(linkRef, context=0, commentary=False)
        com["text"]      = JaggedTextArray(text.text).flatten_to_array()
        com["he"]        = JaggedTextArray(text.he).flatten_to_array()

    # if the the link is commentary, strip redundant info (e.g. "Rashi on Genesis 4:2" -> "Rashi")
    if com["type"] == "commentary":
        com["commentator"]   = linkRef.book.split(" on ")[0]
        com["heCommentator"] = linkRef.he_book().split(u" על ")[0]
    else:
        if com["category"] == "Commentary":
            com["category"] = "Quoting Commentary"
        com["commentator"] = linkRef.book
        com["heCommentator"] = linkRef.index_node.primary_title("he") if linkRef.index_node.primary_title("he") else com["commentator"]

    if linkRef.index_node.primary_title("he"):
        com["heTitle"] = linkRef.index_node.primary_title("he")

    return com

def format_object_for_client(obj, with_text=True, ref=None, pos=None):
    """
    Assumption here is that if obj is a Link, and ref and pos are not specified, then position 0 is the root ref.
    :param obj:
    :param ref:
    :param pos:
    :return:
    """
    if isinstance(obj, Note):
        return format_note_object_for_client(obj)
    elif isinstance(obj, Link):
        if not ref and not pos:
            ref = obj.refs[0]
            pos = 0
        return format_link_object_for_client(obj, with_text, ref, pos)
    else:
        raise InputError("{} not valid for format_object_for_client".format(obj.__class__.__name__))

def format_note_object_for_client(note):
    """
    Returns an object that represents note in the format expected by the reader client,
    matching the format of links, which are currently handled together.
    """
    com = {}
    anchor_oref = Ref(note.ref).padded_ref()

    com["category"]    = "Notes"
    com["type"]        = "note"
    com["owner"]       = note.owner
    com["_id"]         = str(note._id)
    com["anchorRef"]   = note.ref
    com["anchorVerse"] = anchor_oref.sections[-1]
    com["anchorText"]  = getattr(note, "anchorText", "")
    com["public"]      = getattr(note, "public", False)
    com["commentator"] = user_link(note.owner)
    com["text"]        = note.text
    com["title"]       = note.title
#    com["text"]        = note.title + " - " + note.text if getattr(note, "title", None) else note.text

    return com

#this previously had signature: get_notes(tref, public=True, uid=None, pad=True, context=0)
#but all usages used: get_notes(tref, uid=request.user.id, context=1)
def get_notes(oref, public=True, uid=None, context=1):
    """
    Returns a list of notes related to ref.
    If public, include any public note.
    If uid is set, return private notes of uid.
    """
    notes = []

    noteset = oref.padded_ref().context_ref(context).noteset(public, uid)

    for note in noteset:
        com = format_note_object_for_client(note)
        notes.append(com)

    return notes

def get_links(tref, with_text=True):
    """
    Return a list of links tied to 'ref' in client format.
    If with_text, retrieve texts for each link.
    """
    links = []
    oref = Ref(tref)
    nRef = oref.normal()
    reRef = oref.regex()

    # for storing all the section level texts that need to be looked up
    texts = {}

    linkset = LinkSet({"refs": {"$regex": reRef}})
    # For all links that mention ref (in any position)
    for link in linkset:
        # each link contins 2 refs in a list
        # find the position (0 or 1) of "anchor", the one we're getting links for
        pos = 0 if re.match(reRef, link.refs[0]) else 1
        try:
            com = format_link_object_for_client(link, False, nRef, pos)
        except InputError:
            # logger.warning("Bad link: {} - {}".format(link.refs[0], link.refs[1]))
            continue

        # Rather than getting text with each link, walk through all links here,
        # caching text so that redundant DB calls can be minimized
        # If link is spanning, split into section refs and rejoin
        if with_text:
            original_com_oref = Ref(com["ref"])
            com_orefs = original_com_oref.split_spanning_ref()
            for com_oref in com_orefs:
                top_oref = com_oref.top_section_ref()

                # Lookup and save top level text, only if we haven't already
                top_nref = top_oref.normal()
                if top_nref not in texts:
                    texts[top_nref] = TextFamily(top_oref, context=0, commentary=False, pad=False).contents()
                    for t in ["text", "he"]:
                        texts[top_nref][t] = JaggedTextArray(texts[top_nref][t])

                sections, toSections = com_oref.sections[1:], com_oref.toSections[1:]
                for t in ["text", "he"]:
                    res = texts[top_nref][t].subarray(
                        [i - 1 for i in sections],
                        [i - 1 for i in toSections]
                    ).array()
                    if t not in com:
                        com[t] = res
                    else:
                        com[t] += res
                    '''
                    next_section = grab_section_from_text(sections, texts[top_nref][t], toSections)
                    if t not in com:
                        com[t] = next_section
                    elif isinstance(com[t], list):
                        if isinstance(next_section, list):
                            com[t] += next_section
                        else:
                            com[t] += [next_section]
                    else: #com[t] is string
                        if isinstance(next_section, list):
                            com[t] = [com[t]] + next_section
                        else:
                            com[t] += u" " + next_section
                    '''
        links.append(com)

    return links


# -*- coding: utf-8 -*-
"""
Created on Tue Jun 28 15:17:22 2022

@author: Gerardo A. Rivera Tello
@handle: DangoMelon
"""

BASE_WAGE = 20
EXTRA_WAGE = 25

wk_hours = eval(input("Ingrese las horas trabajadas: "))
wk_minutes = eval(input("Ingrese los minutos trabajados: "))

if wk_hours < 0 or wk_minutes < 0:
    raise ValueError("Las horas y minutos deben ser positivos")
elif wk_minutes > 60:
    raise ValueError("Los minutos no pueden ser mayores a 60")

_tot_hours = wk_hours + (wk_minutes / 60)
minute_wage = 0
_wk_hours = wk_hours

if _tot_hours <= 40:
    extra_hours = 0
    minute_wage = BASE_WAGE / 60
elif _tot_hours > 40:
    if wk_minutes != 0:
        _wk_hours += 1
    extra_hours = _wk_hours - 40
    _wk_hours = 40

base = BASE_WAGE * _wk_hours + minute_wage * wk_minutes
extra = EXTRA_WAGE * extra_hours
pago = base + extra

print(
    f"El pago total por trabajar {wk_hours} horas "
    f"y {wk_minutes} minutos es: ${pago:2.2f}"
)


import os
from datetime import datetime

def tictoc():
    return datetime.now().minute + datetime.now().second + datetime.now().microsecond * (10 ** -6)

def vConv(filename):
    """
    use memechip
    :param InputFile: fasta file
    :return:
    """
    DataRoot = "../../../data/chip-seqFa/"

    tmp_cmd = "python vConv-basedmotifdiscovery.py "+DataRoot+filename
    print(tmp_cmd)
    os.system(tmp_cmd)

def mkdir(path):
    isExists = os.path.exists(path)
    if not isExists:
        os.makedirs(path)
        return (True)
    else:
        return False

if __name__ == '__main__':

    import glob

    files = open("./fastause.txt").readlines()

    for filename in files:
        filename = filename.replace("\n","")
        vConv(filename)


from rest_framework import viewsets, permissions
from rest_framework.response import Response
from rest_framework import status
from rest_framework.parsers import MultiPartParser
from rest_framework.decorators import action
from drf_yasg.utils import swagger_auto_schema

from mysite.parsers import ImageParser
from .models import Project
from .serializers import ProjectSerializer, ProjectCreationSerializer, ProjectImageSerializer

# Create your views here.
class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    permission_classes = [
        permissions.AllowAny
    ]
    serializer_classes = {'create': ProjectCreationSerializer,
                          'update': ProjectCreationSerializer,
                          'partial_update': ProjectCreationSerializer,
                          'image': ProjectImageSerializer}
    default_serializer_class = ProjectSerializer

    def get_serializer_class(self):
        return self.serializer_classes.get(self.action, self.default_serializer_class)

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(is_approved=True)

    @swagger_auto_schema(method='post', operation_description="Set the image for a project.")
    @action(detail=True, methods=['post'], parser_classes=(MultiPartParser, ImageParser))
    def image(self, request, pk):
        try:
            project = Project.objects.get(pk=pk)
        except:
            return Response({"error": "Project Not Found"}, status=status.HTTP_404_NOT_FOUND)

        try:
            serializer = ProjectImageSerializer(project, data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response(status=status.HTTP_201_CREATED)
            return Response({"error": "Unsupported Media Type"}, status=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE)
        except:
            return Response(status=status.HTTP_400_BAD_REQUEST)


from authentication_and_parameters import (
    client,
    story_bucket,
    edges,
    initial_state,
)
import pandas as pd

RAJK_ZORK_edges_from_AWS_server = client.get_object(
    Bucket=story_bucket, Key=edges
)

edge_data_session_state = pd.read_csv(
    RAJK_ZORK_edges_from_AWS_server["Body"]
).set_index(["FROM", "OPTION_NUM"])

class SessionState:
    def __init__(self) -> None:
        self.initial_state = initial_state
        self.current_state = self.initial_state

    def decide(self, option_num):
        self.current_state = edge_data_session_state.loc[
            (self.current_state, option_num), "TO"
        ]


import glob
print(glob.glob("*"))

import random
x=random.sample(range(200),15)
print(x)

from datetime import date
now=date.today()
birthday=date(1998,9,27)
age=now-birthday
print(age.days)

def average(values):
    """Computes the arithmetic mean of a list of numbers.

    >>> print(average([20, 30, 70]))
    40.0
    """
    return sum(values) / len(values)

import doctest
print(doctest.testmod())


#Palindrome Checker
def reverse(s):
    if len(s) <= 1:
        return s
    else:
        return reverse(s[1:]) + s[0]

def removeWhite(s):
    newStr = ""
    for ch in s:
        if ch != " " and ch != "\'": #特殊文字の扱い
            newStr = newStr + ch
    return newStr

def isPal(s):
    s = removeWhite(s)
    if s == reverse(s):
        return True
    else:
        return False

test = "radar"
print (isPal(test))


class Color:
    """Класс Color, который выводит ● в заданном цвете RGB"""
    END = "\033[0"
    START = "\033[1;38;2"
    MOD = "m"

    def __init__(self, r, g, b):
        self.red_level = r
        self.green_level = g
        self.blue_level = b

    def __repr__(self):
        return f"{self.START};{self.red_level};{self.green_level};{self.blue_level}{self.MOD}●{self.END}{self.MOD}"

    @staticmethod
    def _is_correct_ch(channel):
        if not isinstance(channel, int):
            raise ValueError(f"{type(channel)} != int")

        if not 0 <= channel <= 255:
            raise ValueError("Channel > 255 or Channel < 0")

    @property
    def red_level(self):
        return self.red_level_

    @property
    def green_level(self):
        return self.green_level_

    @property
    def blue_level(self):
        return self.blue_level_

    @red_level.setter
    def red_level(self, channel):
        Color._is_correct_ch(channel)
        self.red_level_ = channel

    @blue_level.setter
    def blue_level(self, channel):
        Color._is_correct_ch(channel)
        self.blue_level_ = channel

    @green_level.setter
    def green_level(self, channel):
        Color._is_correct_ch(channel)
        self.green_level_ = channel

    def __eq__(self, other):
        """Сравнение цветов"""
        if self is other:
            return True
        return (self.red_level == other.red_level) and (self.green_level == other.green_level) \
            and (self.blue_level == other.blue_level)

    def __add__(self, other):
        """Смешение цветов"""
        return Color(self.red_level + other.red_level, self.green_level + other.green_level,
                     self.blue_level + other.blue_level)

    def __hash__(self):
        """Вывод уникальных цветов из списка"""
        return hash((self.red_level, self.green_level, self.blue_level))

    def __mul__(self, other):
        """Уменьшение контраста цвета"""
        if other < 0 or other > 1:
            raise ValueError("Contrast constant must be between 0 and 1")
        cl = -256 * (1 - other)
        f = 259 * (cl + 255) / (255 * (259 - cl))
        r = int(f * (self.red_level - 128) + 128)
        g = int(f * (self.green_level - 128) + 128)
        b = int(f * (self.blue_level - 128) + 128)
        return Color(r, g, b)

    def __rmul__(self, other):
        return self.__mul__(other)

if __name__ == '__main__':
    red = Color(255, 0, 0)
    green = Color(0, 255, 0)
    orange1 = Color(255, 165, 0)
    orange2 = Color(255, 165, 0)
    color_list = [orange1, red, green, orange2]
    print(red)
    print(red == green)
    print(red + green)
    print(set(color_list))
    print(0.5 * red)
    print(red * 0.8)


import numpy as np
from PIL import Image
import glob
import os

from scipy.ndimage import gaussian_filter
from skimage.transform import resize
import pandas as pd
import glob
from scipy.ndimage import rotate

import sys, getopt

def open_image(filename, rotation, offset1, offset2, imwidth, flip_image=False):

    imarray = np.array(Image.open(filename))

    imarray = imarray[:2052,:2052]

    if flip_image:
        imarray = np.fliplr(imarray)

    imarray = rotate(imarray, rotation, reshape=False, cval=200)

    xoffset = 300 - offset1
    yoffset = 300 - offset2
    imarray = imarray[xoffset:xoffset + imwidth, yoffset:yoffset + imwidth]

    imarray = resize(imarray, (1024, 1024)) * pow(2,8)

    return imarray

def process_image(imarray, limit1, limit2):

    distance = limit2 - limit1

    imarray[imarray < limit1] = limit1 # lower bound
    imarray[imarray > limit2] = limit2 # upper bound
    imarray = imarray - (limit1) # set min to 0
    imarray = imarray / (distance) # normalize between zero and one
    imarray = 1 - imarray # invert
    imarray = imarray * 255 # scale to 8-bit
    imarray = gaussian_filter(imarray,2) # smooth
    imarray = imarray.astype('uint8') # convert to unsigned int

    return imarray

def resize_volume(volume):

    volume2 = np.zeros((1024,1024,1023), dtype='uint8')

    for horzslice in range(1024):

        imslice = volume[horzslice,:,:]
        imslice = resize(imslice, (1024, 1024))
        imslice = imslice*255
        imslice = imslice.astype('uint8')

        volume2[horzslice,:,:] = imslice[:,:1023]

    return volume2

def create_header():

    Z = [3, 0, 0]
    X = [0, 4, 0, 0]
    Y = [0, 4, 0, 0]

    header = [0, 255]
    header.extend(Z)
    header.extend(X)
    header.extend(Y)

    header = np.array(header).astype('uint8')

    return header

def transpose_volume(volume):

    V = np.transpose(volume[:,:,:])

    for i in range(0, V.shape[0]):
        V[i,:,:] = V[i,:,:].T

    return V

def add_header(volume):

    volume_flat = volume.flatten()
    full_dataset = np.concatenate((create_header(), volume_flat))

    return full_dataset

def loadVolume(fname, _dtype='u1', num_slices=1023):

    dtype = np.dtype(_dtype)

    volume = np.fromfile(fname, dtype) # read it in

    z_size = np.sum([volume[1], volume[2] << pow(2,3)])
    x_size = np.sum([(val << pow(2,i+1)) for i, val in enumerate(volume[8:4:-1])])
    y_size = np.sum([(val << pow(2,i+1)) for i, val in enumerate(volume[12:8:-1])])

    fsize = np.array([z_size, x_size, y_size]).astype('int')

    volume = np.reshape(volume[13:], fsize) # remove 13-byte header and reshape

    return volume

def save_volume(volume, mouse, data_directory, image_type):

    flattened = add_header(volume)

    if not os.path.exists(data_directory):
        os.mkdir(data_directory)

    fname = data_directory + '/' + mouse + '_' + image_type + '.pvl.nc'

    flattened.tofile(fname + '.001')

    nc_file_string = """<!DOCTYPE Drishti_Header>
    <PvlDotNcFileHeader>
      <rawfile></rawfile>
      <voxeltype>unsigned char</voxeltype>
      <pvlvoxeltype>unsigned char</pvlvoxeltype>
      <gridsize>1023 1024 1024</gridsize>
      <voxelunit>micron</voxelunit>
      <voxelsize>10 10 10</voxelsize>
      <description></description>
      <slabsize>1024</slabsize>
      <rawmap>0 255 </rawmap>
      <pvlmap>0 255 </pvlmap>
    </PvlDotNcFileHeader>"""

    print(nc_file_string, file=open(fname, 'w+'))

def find_histogram_bounds(imarray, threshold = 3.0):

    h,b = np.histogram(imarray.flatten(), bins=range(1,255))

    print(h)

    logH = np.log10(h)
    a = np.where(logH > threshold)

    peak = b[np.argmax(logH)]

    limit1 = b[np.min(a)]
    limit2 = b[np.max(a)]

    return peak, limit1, limit2

# %%

def process_volume(input_directory,
                   output_directory,
                   mouse,
                   rot1, rot2, rot3, offset1, offset2,
                   flip_image=False,
                   imwidth=1488):

    print(input_directory)
    print(output_directory)
    image_types = ('fluor','trans')

    for type_index, image_type in enumerate(image_types):

        print(image_type)

        search_string = os.path.join(input_directory,
                                     image_type,
                                     'native',
                                     'recon', 'imgRot__rec*.tif')

        images = glob.glob(search_string)
        images.sort()

        print(len(images))

        volume_data = np.zeros((1024, 1024, imwidth), dtype='uint8')

        print(images[500])

        imarray = open_image(images[500], rot1, offset1, offset2, imwidth)

        peak, limit1, limit2 = find_histogram_bounds(imarray)
        print('  Peak of histogram: ' + str(peak))

        print('  Loading images...')

        for slice_idx, filename in enumerate(images[:imwidth]):

            imarray = open_image(filename, rot1, offset1, offset2, imwidth, flip_image)

            volume_data[:,:,slice_idx] = process_image(imarray, limit1, limit2)

        print("   Resizing volume...")
        volume = resize_volume(volume_data)

        print("   Transposing volume...")
        volumeT = transpose_volume(volume)

        print("   Saving volume...")
        save_volume(volumeT, 'mouse' + str(mouse),
                    os.path.join(output_directory, str(mouse)), image_type)

    # implement rotation 2

    for type_index, image_type in enumerate(image_types):

        print('  ' + image_type)

        print('   Applying second rotation')

        fname = os.path.join(output_directory,  str(mouse), 'mouse' + str(mouse) + '_' + image_type + '.pvl.nc.001')

        volume = loadVolume(fname)

        new_volume = np.zeros((volume.shape),dtype='u1')

        for i in range(1024):
            new_volume[:,i,:] = rotate(volume[:,i,:], rot2, reshape=False, cval=200)

        save_volume(new_volume, 'mouse' + str(mouse),
                    os.path.join(output_directory, str(mouse)),
                    image_type)

    # implement rotation 3

    for type_index, image_type in enumerate(image_types):

        print('  ' + image_type)

        print('   Applying third rotation')

        fname = os.path.join(output_directory,  str(mouse), 'mouse' + str(mouse) + '_' + image_type + '.pvl.nc.001')

        volume = loadVolume(fname)

        new_volume = np.zeros((volume.shape),dtype='u1')

        for i in range(1024):
            new_volume[:,:,i] = rotate(volume[:,:,i], rot3, reshape=False, cval=200)

        save_volume(new_volume, 'mouse' + str(mouse),
                    os.path.join(output_directory, str(mouse)),
                    image_type)

    print('DONE.')

# %%

def main(argv):

   if len(argv) > 1:
       print('ERROR: Only one input argument allowed (path to transforms.json file)')
   elif len(argv) < 1:
       print('ERROR: Required input argument (path to transforms.json file)')
   else:

       import json

       dictionary = json.load(open(argv[0]))

       if len(dictionary['output_directory']) == 0:
           dictionary['output_directory'] = dictionary['location']

       if 'flip_image' in dictionary.keys():
         flip_image = dictionary['flip_image']
         print("Flipping images along L/R axis")
       else:
         flip_image = False
         print("NOT flipping images along L/R axis")

       process_volume(dictionary['location'],
                   dictionary['output_directory'],
                   dictionary['mouse'],
                   dictionary['rot1'],
                   dictionary['rot2'],
                   dictionary['rot3'],
                   dictionary['offset1'],
                   dictionary['offset2'],
                   flip_image)

if __name__ == "__main__":
   main(sys.argv[1:])


import time

from libvirt import libvirtError

from libvirttestapi.src import sharedmod
from libvirttestapi.utils import utils

required_params = ('guestname',)
optional_params = {}

def reboot(params):
    """Reboot virtual machine
       Return 0 on SUCCESS or 1 on FAILURE
    """
    # Initiate and check parameters
    global logger
    logger = params['logger']
    params.pop('logger')
    domain_name = params['guestname']

    # Connect to local hypervisor connection URI
    hypervisor = utils.get_hypervisor()
    if hypervisor == "kvm":
        logger.info("kvm hypervisor doesn't support the funtion now")
        return 0

    conn = sharedmod.libvirtobj['conn']
    domobj = conn.lookupByName(domain_name)

    # Get domain ip
    logger.info("get the mac address of vm %s" % domain_name)
    mac = utils.get_dom_mac_addr(domain_name)
    logger.info("the mac address of vm %s is %s" % (domain_name, mac))
    logger.info("get ip by mac address")
    ip = utils.mac_to_ip(mac, 180)
    logger.info("the ip address of vm %s is %s" % (domain_name, ip))
    timeout = 600
    logger.info('reboot vm %s now' % domain_name)

    # Reboot domain
    try:
        domobj = reboot(0)
    except libvirtError as e:
        logger.error("API error message: %s, error code is %s"
                     % (e.get_error_message(), e.get_error_code()))
        logger.error("fail to reboot domain")
        return 1

    logger.info("the vm %s is power off" % domain_name)

    # Check domain status by ping ip
    while timeout:
        time.sleep(10)
        timeout -= 10
        if utils.do_ping(ip, 0):
            logger.info(str(timeout) + "s left")
        else:
            logger.info("vm %s power off successfully" % domain_name)
            break
        if timeout == 0:
            logger.info("fail to power off %s" % domain_name)
            return 1

    timeout = 600
    logger.info("the vm %s is power on" % domain_name)

    while timeout:
        time.sleep(10)
        timeout -= 10
        if not utils.do_ping(ip, 0):
            logger.info(str(timeout) + "s left")
        else:
            logger.info("vm %s power on successfully")
            break

        if timeout == 0:
            logger.info("fail to power on vm %s" % domain_name)
            return 1

    return 0


import pytest
from app.asgi import app
from app.db import Session, User
from fastapi.testclient import TestClient

@pytest.fixture
def client() -> TestClient:
    """Instance of application client for tests"""
    return TestClient(app)

@pytest.fixture
def clean_test_data() -> None:
    """Applies db cleaning before tests (if anything left) and after"""
    clean_db()
    yield
    clean_db()

def clean_db():
    """Cleans test data from database"""
    s = Session()
    s.query(User).filter(User.email == "test@assignit.com").delete()
    s.query(User).filter(User.email == "test-repeat@assignit.com").delete()
    s.commit()


import numpy as np

from defenses.detection.frequency.spectrum.utils import f_utils
from scaling.ScalingApproach import ScalingApproach

from .AdaptiveFourierAttackStrategy import AdaptiveFourierAttackStrategy

class AddFrequencyPeakStrategy(AdaptiveFourierAttackStrategy):
    """
    Attack strategy where an already existing attack instance is given and some frequencies
    in spectrogram are added far away from main peaks in each excerpt to prevent detection
    from Fourier detection mechanism.

    Excerpts are tiles in target_shape, starting from the center
    .   .   .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .   .   .
    .   .   .   .   .   x   .   .   .   .   .
    .   .   ---------   .   .   .   .   .   .
    .   .   |   .   |   .   .   .   .   .   .
    .   .   ---------   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .   .   .
    .   .   .   .   .   .   .   .   .   .   .

    Note that we use the symmetry of the fourier transform to add peaks. We add peaks in the corners + 5 in each
    dimension. This causes peaks in the other corner in excerpts on the opposite. See the spectrum as example.
    """

    def __init__(self,
                 verbose: bool,
                 scaler_approach: ScalingApproach,
                 frequency_modification_factor: int = 0):
        super().__init__(verbose=verbose, scaler_approach=scaler_approach)
        self.frequency_modification_factor = frequency_modification_factor

    # @Overwrite
    def _strategy(self, f_img: np.ndarray) -> np.ndarray:
        """
        Add a bright pixel to distract peak finding algorithm from center of excerpt

        :param f_img: spectrogram to manipulate
        :return: manipulated spectrogram
        """
        peaks = f_utils.get_main_peaks(f_img.shape, self.target_shape)

        center = (int(f_img.shape[0] / 2), int(f_img.shape[1] / 2))

        for p in peaks:

            y_start = p[0] - self.target_shape[0] // 2
            y_end = p[0] + self.target_shape[0] // 2
            x_start = p[1] - self.target_shape[1] // 2
            x_end = p[1] + self.target_shape[1] // 2

            fake_peak_coordinates = np.array([y_start, x_start])  # default: just increase the intensity at upper left pixel
            if y_start < center[0]:  # correct if excerpt might be cropped in axis 0
                fake_peak_coordinates[0] = y_end
            if x_start < center[1]:  # correct if excerpt might be cropped in axis 1
                fake_peak_coordinates[1] = x_end

            f_img[fake_peak_coordinates[0] + 5,
                  fake_peak_coordinates[1] + 5] = np.max(f_img) / self.frequency_modification_factor

        return f_img

    def describe(self):
        print("AdaptiveAttackStrategy={}:\n"
              "\ttarget_shape={},\n"
              "\tpeak_finding_method={}".format(self.__class__.__name__,
                                                self.target_shape,
                                                self.frequency_modification_factor))


#!/usr/bin/env python3

#Rahman ve Rahim olan Allah'in Adıyla - 2022
#Rahman ve Rahim Olan Allah'in Adiyla - 2023 Bismillah
import pybullet as p
import time

import rospy
from GammaSwarm.msg import FullCommand
from GammaSwarm.msg import FullState
from GammaSwarm.msg import UavState
from GammaSwarm.msg import FullTrajectoryCommand

from gym_pybullet_drones.utils.utils import sync
from environment import *
import numpy as np
from ControllerUtils import *

"""

In this code simulation execution done. Simulation execution have:

    Manage all in coming data and out data. This means simulation manager publish current telemetry data of drones
    and subscribe command coming from mainSystem, pls look at mainSystem code for more information.

    And using command data gives commands to drone using gym_pybullet env.step() function with action List matrix.
    For more information pls look at gym_pybullet repository : https://github.com/utiasDSL/gym-pybullet-drones

    @Author: Muhammed Emin Hamamcı - hamamci19@itu.edu.tr
    @Contributor: Muhammed Emin Hamamcı, Yunus Emre Yiğit and others members of ITU-GAMMA Team 2022

"""

class SimulationManager:

    def __init__(self):
        self.command = None
        self.pub = rospy.Publisher("simulation_uav_state", FullState, queue_size = 10)

    def subscriber(self):
        rospy.Subscriber("uav_commands", FullCommand, self.call_back)
        rospy.Subscriber("uav_trajectory_commands", FullTrajectoryCommand, self.trajectory_call_back)

    def call_back(self, data): #Callback for FullCommand message.
        self.command = data

    def trajectory_call_back(self, data): #Callback for FullTrajectoryCommand message.
        self.command = data

    def publisher(self, uav_states): #Publish to FullStateMessage. Generated in Loop.
        self.pub.publish(uav_states)

if __name__ == "__main__":
    env_class = Environment()
    env = env_class.properEnv()
    manager = SimulationManager()
    mellinger = MellingerController()

    PYB_CLIENT = env.getPyBulletClient()
    DRONE_IDS = env.getDroneIds()
    actionL = {str(i): np.array([0, 0, 0, 0]) for i in range(env_class.params.num_drones)}
    print(actionL)
    target_angular_rate = {str(i): np.array([0, 0, 0]) for i in range(env_class.params.num_drones)}
    initial_obs = env._computeObs()
    #####################################Run the simulation ####################################

    START = time.time()

    manager.subscriber() #After initialization Subscribe to commands.

    freq = rospy.Rate(60)
    #TODO Emir verme 15 Hz için yapılabilir. Denenebilir.
    while not rospy.is_shutdown():

        command = manager.command

        #Manager function may be return non-value in first(0-10) loops.
        if command == None:
            #print("Command is none")
            continue

        _, _, _, _ = env.step(actionL,target_angular_rate)
        obs = env._computeObs()

        velocity_values = []
        angular_values = []
        for i in range(env_class.params.num_drones):
            #print("DRONE IDS ====="+str(DRONE_IDS))
            cmd_msg = manager.command.allcommands[i]
            virtual_drone = obs[str(i)]
            state=virtual_drone["state"]

            act_roll = state[0]
            act_pitch = state[1]
            act_yaw = state[2]

            #Defining Rotation Matrix
            row1 = [(np.cos(act_pitch)*np.cos(act_yaw)),(np.cos(act_pitch)*np.sin(act_yaw)),(-1*np.sin(act_pitch))]
            row2 = [((-1*np.cos(act_roll)*np.sin(act_yaw))+(np.sin(act_roll)*np.sin(act_pitch)*np.cos(act_yaw))),     ((np.cos(act_roll)*np.cos(act_yaw))+(np.sin(act_roll)*np.sin(act_pitch)*np.sin(act_yaw))),      (np.sin(act_roll)*np.cos(act_pitch))]
            row3 = [((np.sin(act_roll)*np.sin(act_yaw))+(np.cos(act_roll)*np.sin(act_pitch)*np.cos(act_yaw))),      ((-1*np.sin(act_roll)*np.cos(act_yaw))+(np.cos(act_roll)*np.sin(act_pitch)*np.sin(act_yaw))),     (np.cos(act_roll)*np.cos(act_pitch))]
            R_body_to_world = np.array([row1,row2,row3]).T

            msg_array = np.array([cmd_msg.twist.angular.x,cmd_msg.twist.angular.y,cmd_msg.twist.angular.z])
            angular_vel = R_body_to_world@msg_array
            angular_values.append(np.array(angular_vel))

            target_vel = np.array([cmd_msg.twist.linear.x*((60*60)/1000),cmd_msg.twist.linear.y*((60*60)/1000),(cmd_msg.twist.linear.z)*((60*60)/1000)])
            target_vel_kmh_fraction = (np.linalg.norm(target_vel)*((60*60)/1000))/30.0
            velocity_values.append(np.append(target_vel,target_vel_kmh_fraction))

        actionL = dict(list(enumerate(velocity_values)))
        target_angular_rate = dict(list(enumerate(angular_values)))

        if i % env.SIM_FREQ == 0:
            env.render()
            #### Print matrices with the images captured by each drone #
            if env_class.params.vision:
                for j in range(env_class.params.num_drones):
                    print(obs[str(j)]["rgb"].shape, np.average(obs[str(j)]["rgb"]),
                          obs[str(j)]["dep"].shape, np.average(obs[str(j)]["dep"]),
                          obs[str(j)]["seg"].shape, np.average(obs[str(j)]["seg"])
                          )

        state_msg = FullState()
        for i in range(env_class.params.num_drones):
            msg = UavState()
            virtual_drone = obs[str(i)]
            state=virtual_drone["state"]

            #In simulation drones always active! In real this is not! Look at realSystems.
            msg.active = True
            msg.id = "uav/"+str(i+1)
            msg.pose.position.x = state[0]
            msg.pose.position.y = state[1]
            msg.pose.position.z = state[2]

            msg.pose.orientation.x = state[3]
            msg.pose.orientation.y = state[4]
            msg.pose.orientation.z = state[5]
            msg.pose.orientation.w = state[6]

            msg.twist.linear.x = state[10]
            msg.twist.linear.y = state[11]
            msg.twist.linear.z = state[12]

            msg.twist.angular.x = state[13]
            msg.twist.angular.y = state[14]
            msg.twist.angular.z = state[15]
            state_msg.fullState.append(msg)

        manager.publisher(state_msg)
        freq.sleep()

        if env_class.params.gui:
            sync(i, START, env.TIMESTEP)

    env.close()

#########################################################  DEVELOPING  ###############################################################################

"In this loop try to achieve Mellinger Controller for simulation. But it took a long effort to do this. For this reason, this work has been suspended."

# for i in range(env_class.params.num_drones):
        #     #LOCK ACQUIRE YAZILABİLİR!!!
        #     #DRONE_IDS = manager.allcommands[i].id[4:]
        #     #print("DRONE IDS ====="+str(DRONE_IDS))
        #     cmd_msg = manager.command.allcommands[i]
        #     #print(cmd_msg)
        #     virtual_drone = obs[str(i)]
        #     state=virtual_drone["state"]

        #     act_roll = state[0]
        #     act_pitch = state[1]
        #     act_yaw = state[2]
        #     #Defining Rotation Matrix
        #     row1 = [(np.cos(act_pitch)*np.cos(act_yaw)),(np.cos(act_pitch)*np.sin(act_yaw)),(-1*np.sin(act_pitch))]
        #     row2 = [((-1*np.cos(act_roll)*np.sin(act_yaw))+(np.sin(act_roll)*np.sin(act_pitch)*np.cos(act_yaw))),     ((np.cos(act_roll)*np.cos(act_yaw))+(np.sin(act_roll)*np.sin(act_pitch)*np.sin(act_yaw))),      (np.sin(act_roll)*np.cos(act_pitch))]
        #     row3 = [((np.sin(act_roll)*np.sin(act_yaw))+(np.cos(act_roll)*np.sin(act_pitch)*np.cos(act_yaw))),      ((-1*np.sin(act_roll)*np.cos(act_yaw))+(np.cos(act_roll)*np.sin(act_pitch)*np.sin(act_yaw))),     (np.cos(act_roll)*np.cos(act_pitch))]
        #     R_body_to_world = np.array([row1,row2,row3]).T

        #     msg_array = np.array([cmd_msg.twist.angular.x,cmd_msg.twist.angular.y,cmd_msg.twist.angular.z])
        #     angular_vel = R_body_to_world@msg_array
        #     #print(angular_vel[2],cmd_msg.twist.angular.z)
        #     p.resetBaseVelocity(DRONE_IDS[i],
        #                         [cmd_msg.twist.linear.x,cmd_msg.twist.linear.y,cmd_msg.twist.linear.z+0.125],
        #                         [0,0,angular_vel[2]],
        #                         physicsClientId=PYB_CLIENT
        #                         )

            #mellinger.quaternion_of_drones.x = state[3]
            #mellinger.quaternion_of_drones.y = state[4]
            #mellinger.quaternion_of_drones.z = state[5]
            #mellinger.quaternion_of_drones.w = state[6]
#
            #mellinger.position_of_drones.x = state[0]
            #mellinger.position_of_drones.y = state[1]
            #mellinger.position_of_drones.z = state[2]
#
            #mellinger.position_of_drones.roll = state[0]
            #mellinger.position_of_drones.pitch = state[1]
            #mellinger.position_of_drones.yaw = state[2]
#
            #mellinger.velocity_of_drones.x = state[10]
            #mellinger.velocity_of_drones.y = state[11]
            #mellinger.velocity_of_drones.z = state[12]
            #mellinger.velocity_of_drones.wx = state[13]
            #mellinger.velocity_of_drones.wy = state[14]
            #mellinger.velocity_of_drones.wz = state[15]
#
            #target_takeoff_position = Position(initial_obs[str(i)][0],initial_obs[str(i)][1],takeoff_params.takeoff_height)
            #target_velocity = Velocity(cmd_msg.twist.linear.x,cmd_msg.twist.linear.y,cmd_msg.twist.linear.z,cmd_msg.twist.angular.x,cmd_msg.twist.angular.y,cmd_msg.twist.angular.z)
            #mellinger.compute_control(target_takeoff_position,target_velocity)