#!/usr/bin/env python3

import sys
import numpy as np
from edfwriter import EDFwriter

if sys.version_info[0] != 3 or sys.version_info[1] < 5:
  print("Must be using Python version >= 3.5.0")
  sys.exit()

if np.__version__ < "1.17.0":
  print("Must be using NumPy version >= 1.17.0")
  sys.exit()

sf1 = 1000  # samplerate signal 1
sf2 = 1500  # samplerate signal 2
edfsignals = 2
datrecs = 20  # recording length 20 seconds
sine_17 = np.pi * 2.0
sine_17 /= (sf1 / 1.7)
sine_26 = np.pi * 2.0
sine_26 /= (sf2 / 2.6)
q1 = 0.0
q2 = 0.0

hdl = EDFwriter("sinewave.edf", EDFwriter.EDFLIB_FILETYPE_EDFPLUS, edfsignals)

for chan in range(0, edfsignals):
  if hdl.setPhysicalMaximum(chan, 3000) != 0:
    print("setPhysicalMaximum() returned an error")
    sys.exit()
  if hdl.setPhysicalMinimum(chan, -3000) != 0:
    print("setPhysicalMinimum() returned an error")
    sys.exit()
  if hdl.setDigitalMaximum(chan, 32767) != 0:
    print("setDigitalMaximum() returned an error")
    sys.exit()
  if hdl.setDigitalMinimum(chan, -32768) != 0:
    print("setDigitalMinimum() returned an error")
    sys.exit()
  if hdl.setPhysicalDimension(chan, "uV") != 0:
    print("setPhysicalDimension() returned an error")
    sys.exit()
if hdl.setSampleFrequency(0, sf1) != 0:
  print("setSampleFrequency() returned an error")
  sys.exit()
if hdl.setSampleFrequency(1, sf2) != 0:
  print("setSampleFrequency() returned an error")
  sys.exit()
if hdl.setSignalLabel(0, "sine 1.7Hz") != 0:
  print("setSignalLabel() returned an error")
  sys.exit()
if hdl.setSignalLabel(1, "sine 2.6Hz") != 0:
  print("setSignalLabel() returned an error")
  sys.exit()

if hdl.setPreFilter(0, "HP:0.05Hz LP:250Hz N:60Hz") != 0:
  print("setPreFilter() returned an error")
  sys.exit()
if hdl.setPreFilter(1, "HP:0.05Hz LP:250Hz N:60Hz") != 0:
  print("setPreFilter() returned an error")
  sys.exit()
if hdl.setTransducer(0, "AgAgCl cup electrode") != 0:
  print("setTransducer() returned an error")
  sys.exit()
if hdl.setTransducer(1, "AgAgCl cup electrode") != 0:
  print("setTransducer() returned an error")
  sys.exit()

if hdl.setPatientCode("1234567890") != 0:
  print("setPatientCode() returned an error")
  sys.exit()
if hdl.setPatientBirthDate(1913, 4, 7) != 0:
  print("setPatientBirthDate() returned an error")
  sys.exit()
if hdl.setPatientName("Smith J.") != 0:
  print("setPatientName() returned an error")
  sys.exit()
if hdl.setAdditionalPatientInfo("normal condition") != 0:
  print("setAdditionalPatientInfo() returned an error")
  sys.exit()
if hdl.setAdministrationCode("1234567890") != 0:
  print("setAdministrationCode() returned an error")
  sys.exit()
if hdl.setTechnician("Black Jack") != 0:
  print("setTechnician() returned an error")
  sys.exit()
if hdl.setEquipment("recorder") != 0:
  print("setEquipment() returned an error")
  sys.exit()
if hdl.setAdditionalRecordingInfo("nothing special") != 0:
  print("setAdditionalRecordingInfo() returned an error")
  sys.exit()

buf1 = np.empty(sf1, np.float64, "C")
buf2 = np.empty(sf2, np.float64, "C")

for i in range(0, datrecs):
  for j in range(0, sf1):
    q1 += sine_17
    buf1[j] = 2000.0 * np.sin(q1)

  err = hdl.writeSamples(buf1)
  if err != 0:
    print("writeSamples() returned error: %d" %(err))
    break;

  for j in range(0, sf2):
    q2 += sine_26
    buf2[j] = 2000.0 * np.sin(q2)

  err = hdl.writeSamples(buf2)
  if err != 0:
    print("writeSamples() returned error: %d" %(err))
    break;

if hdl.writeAnnotation(0, -1, "Recording starts") != 0:
  print("writeAnnotation() returned an error")
if hdl.writeAnnotation(40000, 20000, "Test annotation") != 0:
  print("writeAnnotation() returned an error")

hdl.close()


from lebai import LebaiRobot
from lebai_msgs.srv import SetAO, SetAOResponse, SetAORequest
from lebai_msgs.srv import  SetDO, SetDOResponse, SetDORequest
from lebai_msgs.srv import   SetAMode, SetAModeResponse, SetAModeRequest
from lebai_msgs.srv import   SetGripper, SetGripperResponse, SetGripperRequest
import rospy
from industrial_msgs.msg import ServiceReturnCode

class IOServiceInterface:
    def __init__(self, ip):
        self.lebai_robot_ = LebaiRobot(ip, False)
        self.srv_set_robot_do_ = rospy.Service(rospy.resolve_name('~set_robot_do'), SetDO, self.cmd_set_robot_do)
        self.srv_set_robot_ao_ = rospy.Service(rospy.resolve_name('~set_robot_ao'), SetAO, self.cmd_set_robot_ao)
        self.srv_set_robot_ao_mode_ = rospy.Service(rospy.resolve_name('~set_robot_ao_mode'), SetAMode, self.cmd_set_robot_ao_mode)
        self.srv_set_robot_ai_mode_ = rospy.Service(rospy.resolve_name('~set_robot_ai_mode'), SetAMode, self.cmd_set_robot_ai_mode)
        self.srv_set_flange_do_ = rospy.Service(rospy.resolve_name('~set_flange_do'), SetDO, self.cmd_set_flange_do)
        self.srv_set_gripper_position_ = rospy.Service(rospy.resolve_name('~set_gripper_position'), SetGripper, self.cmd_set_gripper_position)
        self.srv_set_gripper_force_ = rospy.Service(rospy.resolve_name('~set_gripper_force'), SetGripper, self.cmd_set_gripper_force)

    def cmd_set_robot_do(self, req):
        res = SetDOResponse()
        self.lebai_robot_.set_do(req.pin, req.value)
        res.code.val  = ServiceReturnCode.SUCCESS
        return res

    def cmd_set_robot_ao(self, req):
        res = SetAOResponse()
        self.lebai_robot_.set_ao(req.pin, req.value)
        res.code.val  = ServiceReturnCode.SUCCESS
        return res

    def cmd_set_robot_ao_mode(self, req):
        res = SetAModeResponse()
        self.lebai_robot_.set_ao_mode(req.pin, req.mode)
        res.code.val  = ServiceReturnCode.SUCCESS
        return res

    def cmd_set_robot_ai_mode(self, req):
        res = SetAModeResponse()
        self.lebai_robot_.set_ai_mode(req.pin, req.mode)
        res.code.val  = ServiceReturnCode.SUCCESS
        return res

    def cmd_set_flange_do(self, req):
        res = SetDOResponse()
        self.lebai_robot_.set_flange_do(req.pin, req.value)
        res.code.val  = ServiceReturnCode.SUCCESS
        return res

    def cmd_set_gripper_position(self, req):
        res = SetGripperResponse()
        self.lebai_robot_.set_claw(amplitude = req.val)
        res.ret = True
        return res

    def cmd_set_gripper_force(self, req):
        res = SetGripperResponse()
        self.lebai_robot_.set_claw(force = req.val)
        res.ret = True
        return res


#!/usr/bin/python3
"""Defines a base model class"""
import json
import csv

class Base:
    """Base class for all other classes in this project.
    Args:
        id (int): The identity of the new Base instance.
    Attributes:
        __nb_objects (int): The number of instantiated Bases.
    """

    __nb_objects = 0

    def __init__(self, id=None):
        """Initialize a new Base.
        Args:
            id (int): The identity of the new Base.
        """
        if id is not None:
            self.id = id
        else:
            Base.__nb_objects += 1
            self.id = Base.__nb_objects

    @staticmethod
    def to_json_string(list_dictionaries):
        """Return serializable representation of list of dicts.
        Args:
            list_dictionaries (list): A list of dictionaries.
        """
        if not list_dictionaries:
            return "[]"
        return json.dumps(list_dictionaries)

    @classmethod
    def save_to_file(cls, list_objs):
        """Write the JSON serialization of a list of objects
        to a file.
        Args:
            list_objs (list): A list of inherited Base instances.
        """
        with open(cls.__name__ + ".json", "w") as jsonfile:
            if not list_objs:
                jsonfile.write("[]")
            else:
                list_dicts = [o.to_dictionary() for o in list_objs]
                jsonfile.write(Base.to_json_string(list_dicts))

    @staticmethod
    def from_json_string(json_string):
        """Return the list represented by a JSON string.
        Args:
            json_string (str): A JSON str representation of a list of dicts.
        """
        if not json_string:
            return []
        return json.loads(json_string)

    @classmethod
    def create(cls, **dictionary):
        """
        Return an instance with all attributes already set.
        Args:
            **dictionary (dict): Key/value pairs of attributes to initialize.
        """
        if dictionary:
            if cls.__name__ == "Rectangle":
                new = cls(100, 100)
            else:
                new = cls(100)
            new.update(**dictionary)
            return new

    @classmethod
    def load_from_file(cls):
        """
        Return a list of classes instantiated from a file of JSON strings.
        Reads from `<cls.__name__>.json`.
        """
        try:
            with open(str(cls.__name__) + ".json", "r") as jsonfile:
                return [cls.create(**d)
                        for d in Base.from_json_string(jsonfile.read())]
        except IOError:
            return []

    @classmethod
    def save_to_file_csv(cls, list_objs):
        """Write the CSV serialization of a list of objects to a file.
        Args:
            list_objs (list): A list of inherited Base instances.
        """
        with open(cls.__name__ + ".csv", "w", newline="") as csv_file:
            if not list_objs:
                csv_file.write("[]")
            else:
                if cls.__name__ == "Rectangle":
                    head = ["id", "width", "height", "x", "y"]
                else:
                    head = ["id", "size", "x", "y"]
                writer = csv.DictWriter(csv_file, fieldnames=head)
                for obj in list_objs:
                    writer.writerow(obj.to_dictionary())

    @classmethod
    def load_from_file_csv(cls):
        """Return a list of classes instantiated from a CSV file.
        Reads from `<cls.__name__>.csv`.
        """
        try:
            with open(cls.__name__ + ".csv", "r", newline="") as csvfile:
                if cls.__name__ == "Rectangle":
                    head = ["id", "width", "height", "x", "y"]
                else:
                    head = ["id", "size", "x", "y"]
                list_dicts = csv.DictReader(csvfile, fieldnames=head)
                list_dicts = [
                    dict([key, int(value)] for key, value in dict_.items())
                    for dict_ in list_dicts
                ]
                return [cls.create(**dict_) for dict_ in list_dicts]
        except IOError:
            return []


import matplotlib.pyplot as plt
import matplotlib.patches as patches
from PIL import Image
import numpy as np
import json
from collections import OrderedDict
import torch
import json

#plot bbox for prediction result, bbox_data includes the dictionary of pred_bboxes with confidence score
def plot_bbox(image, bbox_data, result_path="somewhere"):
    # image = np.array(Image.open(img_path), dtype=np.uint8)
    try:
        fig, ax = plt.subplots(1)
        ax.imshow(image)

        for bbox in bbox_data:
            x1 = bbox['xmin']
            y1 = bbox['ymin']
            x2 = bbox['xmax']
            y2 = bbox['ymax']
            score = bbox['confidence_score']
            rect = patches.Rectangle((x1, y1), x2-x1+1, y2-y1+1, linewidth=1, edgecolor='b', facecolor='none')
            ax.add_patch(rect)
            plt.text(x1, y1, score, color='red', verticalalignment='top')

        # plt.show()
        plt.axis('off')
        plt.savefig(result_path, dpi=200, bbox_inches='tight', pad_inches=0.0)
        plt.close()
    except:
        pass

def compute_IoU(boxA, boxB):
    # determine the (x, y)-coordinates of the intersection rectangle
    xA = max(boxA[0], boxB[0])
    yA = max(boxA[1], boxB[1])
    xB = min(boxA[2], boxB[2])
    yB = min(boxA[3], boxB[3])

    # compute the area of intersection rectangle
    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)

    # compute the area of both the prediction and ground-truth
    # rectangles
    boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
    boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)

    # compute the intersection over union by taking the intersection
    # area and dividing it by the sum of prediction + ground-truth
    # areas - the interesection area
    iou = interArea / (boxAArea + boxBArea - interArea)

    # return the intersection over union value
    return iou

def visualize_both_detection(img_path, gt_bboxs, pred_bboxs):
    img = Image.open(img_path)
    pixdata = img.load()
    (w, h) = img.size

    for bbox in gt_bboxs:
        [xmin, ymin, xmax, ymax] = bbox[1]
        xmin, ymin = max(0, xmin), max(0, ymin)
        xmax, ymax = min(w, xmax), min(h, ymax)
        xmax -= 1
        ymax -= 1
        for i in range(xmin, xmax + 1):
            for j in range(3):
                pixdata[i, ymin+j] = RED
                pixdata[i, ymax-j] = RED

        for i in range(3):
            for j in range(ymin, ymax + 1):
                pixdata[xmin+i, j] = RED
                pixdata[xmax-i, j] = RED

    for bbox in pred_bboxs:
        [xmin, ymin, xmax, ymax] = bbox[1]
        xmin, ymin = max(0, xmin), max(0, ymin)
        xmax, ymax = min(w, xmax), min(h, ymax)
        xmax -= 1
        ymax -= 1
        for i in range(xmin, xmax + 1):
            for j in range(3):
                pixdata[i, ymin+j] = BLUE
                pixdata[i, ymax-j] = BLUE

        for i in range(3):
            for j in range(ymin, ymax + 1):
                pixdata[xmin+i, j] = BLUE
                pixdata[xmax-i, j] = BLUE

    return img

def verify(x, w):
    return min(max(int(x), 0), w-1)

def get_gt_bbox(label_path):
    bboxes = list(open(label_path, 'r'))
    gt_bboxes = []
    for bbox in bboxes:
        bbox = bbox.strip().split(' ')
        bbox = [int(item) for item in bbox]

        gt_bboxes.append(bbox[:-1])

    return gt_bboxes

def visualize_bbox(image, bboxes):
    RED = (255, 0, 0)
    pixdata = image.load()
    (w, h) = image.size

    for bbox in bboxes:
        [xmin, ymin, xmax, ymax] = bbox

        for i in range(xmin, xmax + 1):
            for j in range(3):
                pixdata[i, ymin+j] = RED
                pixdata[i, ymax-j] = RED

        for i in range(3):
            for j in range(ymin, ymax + 1):
                pixdata[xmin+i, j] = RED
                pixdata[xmax-i, j] = RED

    return image

def visualize_bboxes(sk_image, bboxes, color):
    def relocate(x, t):
        x = max(0, x)
        x = min(t-1, x)
        return x
    color = np.array(color)
    (height, width, _) = sk_image.shape
    for bbox in bboxes:
        x1 = bbox['x']
        y1 = bbox['y']
        x2 = x1 + bbox['w'] - 1
        y2 = y1 + bbox['h'] - 1
        sk_image[y1:y2, relocate(x1-3, width):relocate(x1+3, width)] = color
        sk_image[y1:y2, relocate(x2-3, width):relocate(x2+3, width)] = color

        sk_image[relocate(y1-3, height):relocate(y1+3, height), x1:x2] = color
        sk_image[relocate(y2-3, height):relocate(y2+3, height), x1:x2] = color

    return sk_image

class KeepAspect(object):
    def __init__(self):
        pass

    def __call__(self, sample):
        image = sample['image']

        h, w, _ = image.shape
        dim_diff = np.abs(h - w)
        # Upper (left) and lower (right) padding
        pad1, pad2 = dim_diff // 2, dim_diff - dim_diff // 2
        # Determine padding
        pad = ((pad1, pad2), (0, 0), (0, 0)) if h <= w else ((0, 0), (pad1, pad2), (0, 0))
        # Add padding
        image_new = np.pad(image, pad, 'constant', constant_values=128)

        return {'image': image_new, 'padding': pad}

def bbox_iou(box1, box2, x1y1x2y2=True):
    """
    Returns the IoU of two bounding boxes
    """
    if not x1y1x2y2:
        # Transform from center and width to exact coordinates
        b1_x1, b1_x2 = box1[:, 0] - box1[:, 2] / 2, box1[:, 0] + box1[:, 2] / 2
        b1_y1, b1_y2 = box1[:, 1] - box1[:, 3] / 2, box1[:, 1] + box1[:, 3] / 2
        b2_x1, b2_x2 = box2[:, 0] - box2[:, 2] / 2, box2[:, 0] + box2[:, 2] / 2
        b2_y1, b2_y2 = box2[:, 1] - box2[:, 3] / 2, box2[:, 1] + box2[:, 3] / 2
    else:
        # Get the coordinates of bounding boxes
        b1_x1, b1_y1, b1_x2, b1_y2 = box1[:,0], box1[:,1], box1[:,2], box1[:,3]
        b2_x1, b2_y1, b2_x2, b2_y2 = box2[:,0], box2[:,1], box2[:,2], box2[:,3]

    # get the corrdinates of the intersection rectangle
    inter_rect_x1 =  torch.max(b1_x1, b2_x1)
    inter_rect_y1 =  torch.max(b1_y1, b2_y1)
    inter_rect_x2 =  torch.min(b1_x2, b2_x2)
    inter_rect_y2 =  torch.min(b1_y2, b2_y2)
    # Intersection area
    inter_area =    torch.clamp(inter_rect_x2 - inter_rect_x1 + 1, min=0) * \
                    torch.clamp(inter_rect_y2 - inter_rect_y1 + 1, min=0)
    # Union Area
    b1_area = (b1_x2 - b1_x1 + 1) * (b1_y2 - b1_y1 + 1)
    b2_area = (b2_x2 - b2_x1 + 1) * (b2_y2 - b2_y1 + 1)

    iou = inter_area / (b1_area + b2_area - inter_area + 1e-16)

    return iou

def non_max_suppression(prediction, num_classes, conf_thres=0.5, nms_thres=0.4):
    """
    Removes detections with lower object confidence score than 'conf_thres' and performs
    Non-Maximum Suppression to further filter detections.
    Returns detections with shape:
        (x1, y1, x2, y2, object_conf, class_score, class_pred)
    """

    # From (center x, center y, width, height) to (x1, y1, x2, y2)
    box_corner = prediction.new(prediction.shape)
    box_corner[:, :, 0] = prediction[:, :, 0] - prediction[:, :, 2] / 2
    box_corner[:, :, 1] = prediction[:, :, 1] - prediction[:, :, 3] / 2
    box_corner[:, :, 2] = prediction[:, :, 0] + prediction[:, :, 2] / 2
    box_corner[:, :, 3] = prediction[:, :, 1] + prediction[:, :, 3] / 2
    prediction[:, :, :4] = box_corner[:, :, :4]

    output = [None for _ in range(len(prediction))]
    for image_i, image_pred in enumerate(prediction):
        # Filter out confidence scores below threshold
        conf_mask = (image_pred[:, 4] >= conf_thres).squeeze()
        image_pred = image_pred[conf_mask]
        # If none are remaining => process next image
        if not image_pred.size(0):
            continue
        # Get score and class with highest confidence
        class_conf, class_pred = torch.max(image_pred[:, 5:5 + num_classes], 1,  keepdim=True)
        # Detections ordered as (x1, y1, x2, y2, obj_conf, class_conf, class_pred)
        detections = torch.cat((image_pred[:, :5], class_conf.float(), class_pred.float()), 1)
        # Iterate through all predicted classes
        unique_labels = detections[:, -1].cpu().unique()
        if prediction.is_cuda:
            unique_labels = unique_labels.cuda()
        for c in unique_labels:
            # Get the detections with the particular class
            detections_class = detections[detections[:, -1] == c]
            # Sort the detections by maximum objectness confidence
            _, conf_sort_index = torch.sort(detections_class[:, 4], descending=True)
            detections_class = detections_class[conf_sort_index]
            # Perform non-maximum suppression
            max_detections = []
            while detections_class.size(0):
                # Get detection with highest confidence and save as max detection
                max_detections.append(detections_class[0].unsqueeze(0))
                # Stop if we're at the last detection
                if len(detections_class) == 1:
                    break
                # Get the IOUs for all boxes with lower confidence
                ious = bbox_iou(max_detections[-1], detections_class[1:])
                # Remove detections with IoU >= NMS threshold
                detections_class = detections_class[1:][ious < nms_thres]

            max_detections = torch.cat(max_detections).data
            # Add max detections to outputs
            output[image_i] = max_detections if output[image_i] is None else torch.cat((output[image_i], max_detections))

    return output

def get_bbox_data(pred_bboxes_data):
    """
    input: prediction bbox list
    output: pred_bboxes, json_bboxes
    """
    pred_bboxes = pred_bboxes_data.bbox
    pred_confidences = pred_bboxes_data.extra_fields['scores']
    num_pred_bboxes = pred_bboxes.size(0)

    pred_bboxes_list = [[] for _ in range(num_pred_bboxes)]
    for i in range(num_pred_bboxes):
        pred_bbox = []
        for j in range(4):
            pred_bbox.append(int(pred_bboxes[i][j]))
        pred_bboxes_list[i] = pred_bbox
    pred_bboxes = pred_bboxes_list

    json_bboxes = {"bboxes": []}
    for pred_id, [x1, y1, x2, y2] in enumerate(pred_bboxes):
        json_bbox = OrderedDict()
        json_bbox['x1'] = x1
        json_bbox['y1'] = y1
        json_bbox['x2'] = x2
        json_bbox['y2'] = y2
        json_bbox['confidence'] = pred_confidences[pred_id].item()

        json_bboxes["bboxes"].append(json_bbox)

    return pred_bboxes, json_bboxes


from pwn import *

context.log_level = 'INFO'

conn = remote('jh2i.com', 50031)
log.info(conn.recvuntil('>').decode())
conn.sendline('6')
conn.sendline('1')
while True:
    log.info(conn.recv().decode())
    for i in range(4):
        conn.sendline('6')
        conn.sendline(str(i+1))
        log.info(str(i+1))
        for _ in range(1000 if i != 3 else 3000 ):
            log.info(conn.recvuntil('>').decode())
            conn.sendline(str(5-i))
            log.info(str(5-i))
    conn.interactive()


import urllib.request, urllib.parse, http.client
import json
import hmac, hashlib
import sys

import pwned.competitions

class Pwned:
    __version = '0'

    def __init__(self, base_url, public_key, private_key):
        if not base_url.endswith('/'):
            base_url = base_url + '/'

        self.base_url = base_url
        self.public_key = public_key
        self.private_key = private_key

    def create_tournament(self, tournament):
        response = self._request('tournaments', 'POST', tournament.get_api_dict())

        if response:
            return pwned.competitions.Tournament.from_api_call(response, client=self)

    def create_league(self, league):
        response = self._request('leagues', 'POST', league.get_api_dict())

        if response:
            return pwned.competitions.League.from_api_call(response, client=self)

    def get(self, type, id):
        if hasattr(self, 'get_' + str(type)):
            return getattr(self, 'get_' + str(type))(id)

        raise PwnedAPIException('Unknown type for get: ' + str(type))

    def get_league(self, id):
        response = self._get_competition('league', id)

        if response:
            return pwned.competitions.League.from_api_call(response, client=self)

    def get_tournament(self, id):
        response = self._get_competition('tournament', id)

        if response:
            return pwned.competitions.Tournament.from_api_call(response, client=self)

    def get_tournament_templates(self):
        response = self._request('tournaments/templates')

        if not response is None:
            templates = []

            for template in response:
                templates.append(pwned.support.TournamentTemplate.from_api_call(template))

            return templates

    def update(self, type, id, competition):
        return self._request(type + 's/' + str(id), 'POST', competition.get_api_dict())

    def start(self, type, id):
        return self._request(type + 's/' + str(id), 'POST', {'status': 'live'})

    def add_signups(self, type, competition_id, signups):
        data = []

        for signup in signups:
            data.append(signup.get_api_dict())

        return self._request(type + 's/' + str(competition_id) + '/signups', 'POST', data)

    def get_signups(self, type, competition_id):
        response = self._request(type + 's/' + str(competition_id) + '/signups')

        if not response is None:
            signups = []

            for el in response:
                signups.append(pwned.support.Signup.from_api_call(el))

            return signups

    def remove_signup(self, type, competition_id, signup_id):
        return self._request(type + 's/' + str(competition_id) + '/signups/' + str(signup_id), 'DELETE')

    def get_round(self, type, competition_id, round_index):
        response = self._request(type + 's/' + str(competition_id) + '/rounds/' + str(round_index))

        if not response is None:
            return pwned.support.Round.from_api_call(response)

    def get_rounds(self, type, competition_id):
        response = self._request(type + 's/' + str(competition_id) + '/rounds')

        if not response is None:
            rounds = []

            for el in response:
                rounds.append(pwned.support.Round.from_api_call(el))

            return rounds

    def get_match(self, type, competition_id, match_id):
        response = self._request(type + 's/' + str(competition_id) + '/matches/' + str(match_id))

        if not response is None:
            return pwned.support.Match.from_api_call(response)

    def update_match(self, type, competition_id, match):
        return self._request(type + 's/' + str(competition_id) + '/matches/' + str(match.id), 'POST', match.get_api_dict())

    def update_round(self, type, competition_id, round):
        return self._request(type + 's/' + str(competition_id) + '/rounds/' + round.round_number, 'POST', round.get_api_dict())

    def get_league_table(self, league_id):
        response = self._request('leagues/' + str(league_id) + '/table')

        if not response is None:
            table = []

            for position in response:
                table.append(pwned.support.LeagueTablePosition.from_api_call(position))

            return table

    def get_league_scoring_models(self, type=None):
        if type:
            response = self._request('leagues/scoringmodels/' + type)
        else:
            response = self._request('leagues/scoringmodels', 'GET')

        if not response is None:
            scoring_models = []

            for scoring_model in response:
                scoring_models.append(pwned.support.LeagueScoringModel.from_api_call(scoring_model))

            return scoring_models

    def get_league_scoring_model(self, id):
        response = self._request('leagues/scoringmodels/' + str(id), 'GET')

        if not response is None:
            return pwned.support.LeagueScoringModel.from_api_call(response)

    def create_league_scoring_model(self, scoring_model):
        response = self._request('leagues/scoringmodels/', 'POST', scoring_model.get_api_dict())

        if not response is None:
            return pwned.support.LeagueScoringModel.from_api_call(response)

    def update_league_scoring_model(self, scoring_model):
        return self._request('leagues/scoringmodels/' + str(scoring_model.id), 'POST', scoring_model.get_api_dict())

    def delete_league_scoring_model(self, scoring_model_id):
        return self._request('leagues/scoringmodels/' + str(scoring_model_id), 'DELETE')

    def league_set_championship_round_results(self, league_id, round_number, results):
        data = []

        for result in results:
            val = result.get_api_dict()
            val['signupId'] = val['signup']['id']
            data.append(val)

        return self._request('leagues/' + str(league_id) + '/rounds/' + str(round_number) + '/results', 'POST', data)

    def get_games(self):
        response = self._request('games')

        if not response is None:
            games = []

            for game in response:
                games.append(pwned.support.Game.from_api_call(game))

            return games

    def get_countries(self):
        response = self._request('countries')

        if not response is None:
            countries = []

            for country in response:
                countries.append(pwned.support.Country.from_api_call(country))

            return countries

    def _get_competition(self, type, id):
        return self._request(type + 's/' + str(id))

    def _request(self, resource, request_method = 'GET', data = None):
        if data:
            data = json.dumps(data)
        else:
            data = ''

        url = self.base_url + resource + self._url_query_string(resource, request_method, data)
        headers = {'Content-Type': 'application/json', 'User-Agent': self._user_agent(), }
        response = None

        try:
            if data:
                data = bytes(data.encode("utf-8"))
            else:
                data = None

            if request_method in ('GET', 'POST'):
                request = urllib.request.Request(url, data=data, headers=headers)
                response = urllib.request.urlopen(request).read()
            else:
                url_info = urllib.parse.urlparse(url)
                path = url_info.path

                if url_info.query:
                    path = path + '?' + url_info.query

                connection = http.client.HTTPConnection(url_info.netloc)
                connection.request(request_method, path, body=data, headers=headers)

                response = connection.getresponse().read()
                connection.close()
        except urllib.error.HTTPError as e:
            response = e.read()

        try:
            response = json.loads(response.decode("utf-8"))
        except ValueError:
            print(response)
            raise PwnedAPIException('Invalid JSON returned from server.', response)

        if ('error' in response) and response['error']:
            raise PwnedAPIException(response['error']['reason'])

        if 'result' in response:
            return response['result']

        return response

    def _url_query_string(self, resource, request_method, data):
        return '?' + urllib.parse.urlencode({
            'publicKey': self.public_key,
            'signature': self._signature(resource, request_method, data)
        })

    def _signature(self, resource, request_method, data):
        return hmac.new(self.private_key.encode('ascii'), bytes((self.public_key + '|' + request_method + '|' + resource + '|' + data).encode("utf-8")), hashlib.sha256).hexdigest()

    def _user_agent(self):
        return 'python-pwned-api/' + self.__version + '/' + '.'.join(str(x) for x in sys.version_info[0:3])

class PwnedAPIException(Exception):
    def __init__(self, message, raw_response = None):
        Exception.__init__(self, message)

        if raw_response:
            self.raw_response = raw_response
        else:
            self.raw_response = None

    def __repr__(self):
        if self.raw_response:
            return self.message + "\n\n" + raw_response

        return self.message


'''
Madhur Jaripatke
Roll No. 55
SE A Computer
RMDSSOE, Warje, Pune
'''
'''Consider telephone book database of N clients. Make use of a hash table
implementation to quickly look up client's telephone number. Make use of
two collision handling techniques and compare them using number of comparisons
required to find a set of telephone numbers'''
from Record import Record
from DoubleHash import doubleHashTable
def input_record():
	record=Record()
	name=input('Enter Name ')
	number=int(input('Enter Number '))
	record.set_name(name)
	record.set_number(number)
	return record
class HashTable:
	def __init__(self):
		self.size=int(input('Enter size of contact book '))
		self.elementcount=0
		self.comparisons=0
		self.table=list(None for i in range(self.size))

	def isFull(self):
		if (self.elementcount==self.size):
			return True
		else:
			return False

	def display(self):
		print('\n')
		for i in range(self.size):
			print('Hash Value ',str(i)+'\t\t',str(self.table[i]))
		print('\nThe total number of contacts are ',self.elementcount,'\n\n')

	def hashfun(self,record):
		return record % self.size

	def insert(self,record):
		if self.isFull()==True:
			print('Table full')
			return False
		isStored=False
		position=self.hashfun(record.get_number())
		if self.table[position]==None:
			self.table[position]=record
			print('Phone number of',record.get_name(),'is at Hash Value ',str(position))
			isStored=True
			self.elementcount+=1
		else:
			print('Collision encountered for %s\'s number at position %s.\nFinding new position.'%(record.get_name(),str(position)))
			while self.table[position]!=None:
				position+=1
				if position>=self.size:
					position=0
			self.table[position]=record
			print('Phone number of',record.get_name(),'is at ',str(position))
			isStored=True
			self.elementcount+=1
		return isStored

	def search(self,record):
		isFound=False
		position=self.hashfun(record.get_number())
		self.comparisons+=1
		if (self.table[position].get_name()==record.get_name() and self.table[position].get_number()==record.get_number()):
			isFound==True
			print(record,' found at position {}'.format(position),' total comparisons made are',str(1))
			return position
		else:
			position+=1
			if (position>=self.size-1):
				position=0
			while (self.table[position]!=None):
				if (self.table[position].get_name()==record.get_name() and self.table[position].get_number()==record.get_number()):
					isFound==True
					i=self.comparisons+1
					print(record,' found at position {}'.format(position),' total comparisons made are',str(i))
					return position
				position+=1
				if position>=self.size-1:
					position=0
				self.comparisons+=1
			if isFound==False:
				print('Record not found')
				return False

#Main
while(True):
		ch=int(input('Please Enter Your Choice\n1.Linear Probing\t2.Double Hashing\n3.Exit '))
		if (ch==1):
			o1=HashTable()
			while(True):
				ch1=int(input('Please Enter Your Choice\n1. Add Contact\t\t2. Search Contact\n3. Display Contacts\t4. Go Back\n5. Exit '))
				if (ch1==1):
					record=input_record()
					o1.insert(record)
				elif (ch1==2):
					record=input_record()
					o1.search(record)
				elif (ch1==3):
					o1.display()
				elif (ch1==4):
					break
				elif (ch1==5):
					exit()
				else:
					print('Invalid Choice, Please Try Again')
		elif (ch==2):
			o2=doubleHashTable()
			while(True):
				ch2=int(input('Please Enter Your Choice\n1. Add Contact\t\t2. Search Contact\n3. Display Contacts\t4. Go Back\n5. Exit '))
				if (ch2==1):
					record=input_record()
					o2.insert(record)
				elif (ch2==2):
					record=input_record()
					o2.search(record)
				elif (ch2==3):
					o2.display()
				elif (ch2==4):
					break
				elif (ch2==5):
					exit()
				else:
					print('Invalid Choice, Please Try Again')
		elif (ch==3):
			exit()
		else:
			print('Invalid Choice, Please Try Again')


# -*- coding: utf-8 -*-
# BMS  dlg_draw  show the voltage of battery;

import sys
import random
import numpy as np
import array
import random
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication, QLabel, QWidget, QPushButton, QVBoxLayout,QGridLayout,QCheckBox,QLineEdit
from PyQt5.QtWidgets import QLayout
from PyQt5.QtCore import QTimer

#idx=0
rand1=random.randint(0,800)
rand2=random.randint(0,100)
vol=[3.5, 3.8, 3.6, 3.7,3.9,3.6,3.8,3.5]
checked=[True,True,True,True,True,True,True,True]
class dlg_qt_draw(QWidget):
    def __init__(self,parent=None):
        super(dlg_qt_draw, self).__init__()
        self.draw2()
        self.initui()

    def draw2(self):
        self.plt2=pg.PlotWidget()
        self.tim1=QTimer()
        self.tim1.timeout.connect(self.update)
        self.tim1.start(100)

        self.x=500
        self.plt2.setRange(xRange=[0,self.x],yRange=[0,5],padding=0)
        self.dat0=[array.array('d'),array.array('d'),array.array('d'),array.array('d'),array.array('d'),array.array('d'),array.array('d'),array.array('d')]
        self.curve0=self.plt2.plot(pen='y')
        self.curve1=self.plt2.plot(pen='r')
        self.curve2=self.plt2.plot(pen='b')
        self.curve3=self.plt2.plot(pen='g')
        self.curve4=self.plt2.plot(pen='y')
        self.curve5=self.plt2.plot(pen='r')
        self.curve6=self.plt2.plot(pen='b')
        self.curve7=self.plt2.plot(pen='g')

    def update(self):
        #global idx
        global rand1,rand2
        global vol
        if rand1%10==0:
            tmp=rand1%8
            if rand2>50:      vol[tmp]=vol[tmp]+0.01
            if rand2<5:      vol[tmp]=vol[tmp]-0.01
            if vol[tmp]>4.1:  vol[tmp]=4.1
            #if vol[tmp]<3.4:  vol[tmp]=3.4
        rand1 = random.randint(0, 1800)
        rand2 = random.randint(0, 100)

        for i in range(8):
            if len(self.dat0[i])<self.x:
                self.dat0[i].append(vol[i])
            else:
                self.dat0[i][:-1]=self.dat0[i][1:]
                self.dat0[i][-1]=vol[i]

        self.curve0.setData(self.dat0[0])
        self.curve1.setData(self.dat0[1])
        self.curve2.setData(self.dat0[2])
        self.curve3.setData(self.dat0[3])
        self.curve4.setData(self.dat0[4])
        self.curve5.setData(self.dat0[5])
        self.curve6.setData(self.dat0[6])
        self.curve7.setData(self.dat0[7])
        #idx+=1;

    def initui(self):
        self.gridlayout = QGridLayout(self)
        self.gridlayout.addWidget(self.plt2, 0, 0, 16, 9)
        self.checkb = [QCheckBox("通道1"),QCheckBox("通道2"),QCheckBox("通道3"), QCheckBox("通道4"),\
            QCheckBox("通道5"), QCheckBox("通道6"), QCheckBox("通道7"), QCheckBox("通道8"),\
                QCheckBox("通道9"),QCheckBox("通道10"),QCheckBox("通道11"), QCheckBox("通道12"),\
                    QCheckBox("通道13"), QCheckBox("通道14"), QCheckBox("通道15"), QCheckBox("通道16")]
        for i in range(16):
            self.gridlayout.addWidget(self.checkb[i], i,10)
            self.checkb[i].stateChanged.connect(self.check_change)
        self.setLayout(self.gridlayout)

    def check_change(self):
        global checked
        for i in range(16):
            checked[i]=self.checkb[i].isChecked()
            #print(i,checked[i])

if __name__ == '__main__':
    app = QApplication(sys.argv)
    win= dlg_qt_draw()
    win.show()
    sys.exit(app.exec_())


import tensorflow as tf
import os
import numpy as np
from matplotlib import pylab as  plt

os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
#产生训练数据集
train_X=np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,
                   7.042,10.791,5.313,7.997,5.654,9.27,3.1])
train_Y=np.asarray([1.7,2.76,2.09,3.19,1.694,1.573,3.366,2.596,2.53,1.221,
                    2.827,3.465,1.65,2.904,2.42,2.94,1.3])
n_train_sample=train_X.shape[0]
print('训练样本数量为:',n_train_sample)

test_X=np.asarray([6.83,4.668,8.9,7.91,5.7,8.7,3.1,2.1])
test_Y=np.asarray([1.84,2.273,3.2,2.831,2.92,3.24,1.35,1.03])
n_test_sample=test_X.shape[0]
print('测试样本数量为:',n_test_sample)

plt.scatter(train_X,train_Y)
plt.scatter(test_X,test_Y)
plt.show()

with tf.Graph().as_default():
    with tf.name_scope('Input'):
        X=tf.placeholder(tf.float32,name='X')
        Y_true=tf.placeholder(tf.float32,name='Y_true')
    with tf.name_scope('Inference'):
        w=tf.Variable(tf.zeros([1]),name='weight')
        b=tf.Variable(tf.zeros([1]),name='Bias')
        Y_pred=tf.add(tf.multiply(X,w),b)
    with tf.name_scope('Loss'):
        TrainLoss=tf.reduce_mean(tf.pow(Y_true-Y_pred,2))/2
    with tf.name_scope('Train'):
        Optimizer=tf.train.GradientDescentOptimizer(learning_rate=0.01)
        TrainOp=Optimizer.minimize(TrainLoss)
    with tf.name_scope('Evaluate'):
        EvalLoss=tf.reduce_mean(tf.pow(Y_true-Y_pred,2))/2

    initOp=tf.global_variables_initializer()

    writer=tf.summary.FileWriter(logdir='Log_linear_regression',graph=tf.get_default_graph())
    writer.flush()

    print('开启会话，运行计算图，训练模型！')

    with tf.Session() as sess:
        sess.run(initOp)
        for step in range(1000):         #训练1000次
            for tx,ty in zip(train_X,train_Y):
                _,train_loss,train_w,train_b=sess.run([TrainOp,TrainLoss,w,b],feed_dict={X:tx,Y_true:ty})

            if(step+1)%5==0:
                print('step:','%04d'%(step+1),'train_loss=','{:.9f}'.format(train_loss),'w=',train_w,'b=',train_b)
            if (step+1)%10==0:
                test_loss=sess.run(EvalLoss,feed_dict={X:test_X,Y_true:test_Y})
                print('step:','%04d'%(step+1),'test_loss=','{:.9f}'.format(test_loss),
                      'w=',train_w,'b=',train_b)

        print('训练完毕！！')
        w,b=sess.run([w,b])
        print('模型参数:','w=',w,'b=',b)
        train_loss=sess.run(TrainLoss,feed_dict={X:train_X,Y_true:train_Y})
        print('训练集上的损失:',train_loss)
        test_loss=sess.run(EvalLoss,feed_dict={X:test_X,Y_true:test_Y})
        print('测试集上面的损失:',test_loss)

        plt.plot(train_X, train_Y, 'ro', label='Origin Train Points')
        plt.plot(test_X, test_Y, 'b*', label='Origin Test Points')
        plt.plot(train_X, w * train_X + b, label='Fitted Line')
        plt.legend()
        plt.show()


from mne.time_frequency import psd_welch
import numpy as np
import pandas as pd
import torch
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import itertools

# https://mne.tools/dev/auto_tutorials/sample-datasets/plot_sleep.html#sphx-glr-auto-tutorials-sample-datasets-plot-sleep-py%00
def eeg_power_band(epochs):
    """EEG relative power band feature extraction.

    This function takes an ``mne.Epochs`` object and creates EEG features based
    on relative power in specific frequency bands that are compatible with
    scikit-learn.

    Parameters
    ----------
    epochs : Epochs
        The data.

    Returns
    -------
    X : numpy array of shape [n_samples, 5]
        Transformed data.
    """
    # specific frequency bands
    FREQ_BANDS = {"delta": [0.5, 4.5],
                  "theta": [4.5, 8.5],
                  "alpha": [8.5, 11.5],
                  "sigma": [11.5, 15.5],
                  "beta": [15.5, 30]}

    psds, freqs = psd_welch(epochs, picks='eeg', fmin=0.5, fmax=30.)
    # Normalize the PSDs
    psds /= np.sum(psds, axis=-1, keepdims=True)

    X = []
    for fmin, fmax in FREQ_BANDS.values():
        psds_band = psds[:, :, (freqs >= fmin) & (freqs < fmax)].mean(axis=-1)
        X.append(psds_band.reshape(len(psds), -1))

    return np.concatenate(X, axis=1)

def get_series_and_features(epochs, channels):
    """
    this is to extract label, raw signal and calcuate time domain feature from decrypted edf data
    """
    epoch_dfs = []
    time_features = {"time_min": [], "time_max": [], "time_std": [], "time_kurtosis": [], "time_median": []}
    labels = np.ones(len(epochs))
    for i in range(len(epochs)):
        print("{}th epoch started to be processed.".format(i))
        epoch = epochs[i]
        epoch_df = epoch.to_data_frame()
        epoch_df = epoch_df[channels]
        epoch_dfs.append(epoch_df)
        time_features["time_min"].append(epoch_df.min())
        time_features["time_max"].append(epoch_df.max())
        time_features["time_std"].append(epoch_df.std())
        time_features["time_kurtosis"].append(epoch_df.kurtosis())
        time_features["time_median"].append(epoch_df.median())
        label = list(epoch.event_id.values())[0]
        labels[i] = label
    for key, value in time_features.items():
        new_df = pd.concat(time_features[key], axis=1).transpose()
        new_df.reset_index(drop=True, inplace=True)
        orig_columns = list(new_df.columns)
        new_columns = [column + "_" + key for column in orig_columns]
        new_df.columns = new_columns
        time_features[key] = new_df
    dfs = list(time_features.values())
    time_feature_df = pd.concat(dfs, axis=1)
    return epoch_dfs, time_feature_df, labels

def to_tensor(list_data, device, type="float"):
    """
    function to change from a list to corresponding tenor
    """
    if type == "float":
        return torch.from_numpy(list_data).float().to(device, non_blocking=True)
    elif type == "int":
        return torch.from_numpy(list_data).int().to(device, non_blocking=True)
    elif type == "long":
        return torch.from_numpy(list_data).long().to(device, non_blocking=True)

def plot_confusion_matrix(true_y_label, pred_y_label, class_names, tag, dataset):
    """
    function to plot confusion matrix
    """
    internalMatrixFunction = confusion_matrix(true_y_label, pred_y_label)
    filename = "plot/confusion_" + tag + "_" + str(dataset) + ".png"
    cm = internalMatrixFunction.astype('float') / internalMatrixFunction.sum(axis=1)[:, np.newaxis]
    fig = plt.figure(figsize=(12, 8), tight_layout=True)
    ax = fig.add_subplot(111)
    cax = plt.imshow(cm, interpolation='nearest', cmap=plt.get_cmap('Blues'))
    format_type = '.2f'
    max_limit = cm.max() / 2.
    for x, y in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(y, x, format(cm[x, y], format_type), horizontalalignment="center",
                 color="white" if cm[x, y] > max_limit else "black")
    plt.title('Confusion matrix of the classifier')
    fig.colorbar(cax)
    checkered_boxes = np.arange(len(class_names))
    plt.xticks(checkered_boxes, class_names)
    plt.yticks(checkered_boxes, class_names)
    plt.xlabel('Predicted')
    plt.ylabel('True')
    fig.savefig(filename, dpi=fig.dpi)
    pass


from collections import Counter,defaultdict,deque
try:
    from gurobipy import*
except:
    from mypulp import*

def packingCG(cap,cargo):
    if max(cargo)>cap:
        raise ValueError("maximum value is more than cap")
    if min(cargo)<0:
        raise ValueError("minimum value is less than 0")

    num=len(cargo)
    m=Model("a")
    try:
        m.setParam('OutputFlag', 0)
    except:
        pass

    cargo.sort()
    dp=defaultdict(list)
    dp[0]=[set()]

    for i,j in enumerate(cargo):
        for k,v in dp.copy().items():
            if k+j<=cap:
                for r in dp[k]:
                    if i not in r:
                        dp[k+j].append(r|{i})

    ret=tuple(itertools.chain.from_iterable(dp.values()))

    cmbidx={}
    for i in range(len(ret)):
        cmbidx[i]=m.addVar(vtype="B")

    m.update()
    for i in range(num):
        m.addConstr( quicksum(cmbidx[j] for j,v in enumerate(ret)if i in v) == 1 )

    m.setObjective( quicksum(cmbidx.values()) ,GRB.MINIMIZE)
    m.optimize()

    if m.Status == GRB.Status.OPTIMAL:
        return sorted([[cargo[idx]for idx in ret[k]]for k,v in cmbidx.items()if round(v.X)>0],key=lambda x:sum(x),reverse=1)


import unittest

from mock import patch

from app.config import WHITE_LIST, RESOURCE_MAX_SIZE
from app.offline import _is_validated_url, _is_validated_response, download

class ObjectDict(dict):
    def __getattr__(self, key):
        if key in self:
            return self[key]
        return None

    def __setattr__(self, key, value):
        self[key] = value

class TestDownloader(unittest.TestCase):
    @patch('app.offline._download')
    @patch('app.offline._is_validated_url')
    def test_download(self, _is_validated_url, _download):
        _is_validated_url.return_value = False
        download('{"url": "http://fan.xyz/a.jpg"}')
        _download.assert_not_called()

    @patch('app.offline.set_task_fail')
    @patch('app.offline.is_duplicated_task')
    @patch('app.offline.is_blacklisted')
    def test__is_validated_url(self, is_blacklisted, is_duplicated_task, set_task_fail):
        url = 'http://fan.com/a.jpg'
        is_blacklisted.return_value = False
        is_duplicated_task.return_value = True
        self.assertFalse(_is_validated_url(url))
        set_task_fail.assert_not_called()
        is_blacklisted.return_value = True
        is_duplicated_task.return_value = False
        self.assertFalse(_is_validated_url(url))
        set_task_fail.assert_called_with(url)
        is_blacklisted.return_value = True
        is_duplicated_task.return_value = True
        self.assertFalse(_is_validated_url(url))
        is_blacklisted.return_value = False
        is_duplicated_task.return_value = False
        self.assertTrue(_is_validated_url(url))

    @patch('app.offline.set_task_fail')
    @patch('app.offline.set_blacklist_domain')
    def test__is_validated_response(self, set_blacklist_domain, set_task_fail):
        url = 'http://fan.com/a.jpg'
        res = ObjectDict({
            'status_code': 403,
            'headers': {
                'Content-Type': WHITE_LIST[0],
                'Content-Length': RESOURCE_MAX_SIZE
            }
        })
        _is_validated_response(url, res)
        set_blacklist_domain.assert_called_with('fan.com')
        set_task_fail.assert_called_with(url)
        res = ObjectDict({
            'status_code': 200,
            'headers': {
                'Content-Type': WHITE_LIST[0],
                'Content-Length': RESOURCE_MAX_SIZE + 1
            }
        })
        self.assertFalse(_is_validated_response(url, res))
        res = ObjectDict({
            'status_code': 200,
            'headers': {
                'Content-Type': 'fake/jpg',
                'Content-Length': RESOURCE_MAX_SIZE
            }
        })
        self.assertFalse(_is_validated_response(url, res))
        res = ObjectDict({
            'status_code': 200,
            'headers': {
                'Content-Type': WHITE_LIST[0],
                'Content-Length': RESOURCE_MAX_SIZE
            }
        })
        self.assertTrue(_is_validated_response(url, res))

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


#!/usr/bin/python3

import numpy as np

import argparse
import logging
import os

import models
import utils

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

POSTURES_TRAINING_DATA = './data/postures/D_train.csv'
POSTURES_TEST_DATA = './data/postures/D_test.csv'

LOGGER = logging.getLogger('main')
LOGGER.setLevel(logging.INFO)
LOGGER_CH = logging.StreamHandler()
LOGGER_CH.setFormatter(logging.Formatter('[%(asctime)s] [%(levelname)s] [%(name)s] %(message)s'))
LOGGER_CH.setLevel(logging.INFO)
LOGGER.addHandler(LOGGER_CH)

def main(clf):
    x_train, y_train = utils.load_csv(POSTURES_TRAINING_DATA, feature_idx = range(2, 39), label_idx = 1)
    x_test, y_test = utils.load_csv(POSTURES_TEST_DATA, feature_idx = range(2, 39), label_idx = 1)
    model = models.PosturesEstimator(clf, aggregation = True, knn_n_neighbors = 9, \
        svm_c = 10 ** 0.6, svm_gamma = 10 ** -2.0, \
        nn_validation = True)

    assert len(x_train) == len(y_train) and len(x_test) == len(y_test), 'Data size not match'

    model.fit(x_train, y_train)
    acc_train = model.evaluate(x_train, y_train, cm = 'training.png')
    LOGGER.info('Training Accuracy: %.6f' % acc_train)

    acc_cv = model.cross_validate(x_train, y_train)
    if acc_cv is not None:
        LOGGER.info('Cross Validation Accuracy: %.6f ± %.6f' % (np.mean(acc_cv), np.std(acc_cv)))

    acc_test = model.evaluate(x_test, y_test, cm = 'test.png')
    LOGGER.info('Test Accuracy: %.6f' % acc_test)

if (__name__ == '__main__'):
    parser = argparse.ArgumentParser()
    parser.add_argument('--clf', help = 'Classifier')
    args = parser.parse_args()

    try:
        main(args.clf)
    except RuntimeError as e:
        print('RuntimeError raised\n', e.args)
        exit(1)
    exit(0)


"""
    Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final mostre
        - Quantas vezes apareceu o valor 9
        - Em que posição foi digitado o primeiro valor 3.
        - Quais foram os números pares.
"""
v1 = int(input('Digite o 1º valor: '))
v2 = int(input('Digite o 2º valor: '))
v3 = int(input('Digite o 3º valor: '))
v4 = int(input('Digite o 4º valor: '))

tupla = (v1, v2, v3, v4)
print(f'O número 9 apareceu {tupla.count(9)} vezes.')
if 3 in tupla:
    print(tupla.index(3)+1)
else:
    print('O valor 3 não foi digitado em nenhuma posição')

print('Números pares:')
for i in range(0, 4):
    if (tupla[i] % 2 == 0):
        print(tupla[i])


class Node:
	def __init__(self,data):
		self.data=data
		self.next = None
		self.prev = None

class DoubleLinkedList:

	def __init__(self):
		self.head = None

	def append(self,data):
		'''
		new_node = Node(data)
		new_node.next = self.head
		new_node.prev = None
		if self.head is not None:
			self.head.prev = new_node
		self.head = new_node

		'''
		newNode = Node(data)
		if self.head is None:
			self.haed = newNode
			return

		newNode.next = self.head
		newNode.prev = None

		if self.head is not None:
			self.head.prev = newNode
		self.head = newNode

	def push(self,data):
		newNode = Node(data)

		if self.head is None:
			self.head = newNode
			return

		head = self.head
		temp = head
		while temp.next != None:
			temp = temp.next
		temp.next = newNode
		newNode.prev = temp

	def printList(self):
		temp = self.head
		if temp is None:
			print("None")
		while temp:
			print(temp.data)
			temp = temp.next

if __name__ == '__main__':

	dlist = DoubleLinkedList()
	dlist.push(1)
	dlist.push(2)
	dlist.push(3)
	dlist.append(0)
	dlist.printList()


import socket

IP = "10.108.33.5 "
PORT = 8097

# create an INET, STREAMing socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print(s)

try:
    s.connect((IP, PORT))
except OSError:
    print("Socket already used")
    # But first we need to disconnect
    s.close()
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((IP, PORT))
ip = s.getsockname()[0]
send_bytes = str.encode(ip)
s.send(send_bytes)

print("Read from the server: ", s.recv(2048).decode("utf-8"))
print("Read from the server: ", s.recv(2048).decode("utf-8"))
print("Read from the server: ", s.recv(2048).decode("utf-8"))


import matplotlib.pyplot as plt
import torch as th
import numpy as np

from glob import glob
from tqdm import tqdm
from time import sleep
import os

from IPython.display import clear_output
# it is needed only to refresh the losses plots by "flag_while", unnecessary.

def show(images, titles=None, cmaps=None, crops=None,
    figsize=None, fontsize=None, set_title=None):
    '''
    Makes the pleasant figure of images, optionally with custom titles, colormaps, crops.

    If the number of images to show is more than one, then "images" is supposed to be a list.
    The titles must be either a string (1 image for input) or a list of strings.
    '''
    if not isinstance(images, list):
        images = [images]

    images_recon = []
    for ind, image in enumerate(images):
        if len(image.shape) == 4:
            image = image[0]

        if not isinstance(image, np.ndarray): # assimed to be torch.Tensor
            if image.is_cuda:
                image = image.cpu()
            image = image.detach().numpy()

        if image.shape[0] == 1:
            image = image[0]

        if crops is not None:
        # assumed to be only from left-right corner
        # and only being only squared
            crop = crops[ind] if isinstance(crops, list) else crops
            image = image[..., :crop,:crop]

        images_recon.append(image)
    images = images_recon

    if fontsize is None:
        fontsize = 15

    num_images = len(images)

    if figsize is None:
        figsize = (8+num_images,8*num_images)
        if num_images == 3:
            figsize = (15,5)
        if num_images == 4:
            figsize = (20,5)

    fig, ax = plt.subplots(1, num_images, figsize=figsize)
    fig.patch.set_facecolor('white')

    if num_images == 1:
        ax = [ax]

    if cmaps is None:
        cmaps = ['depth']*num_images # Maybe, use 'gray' as default?

    elif isinstance(cmaps, str):
        cmaps = [cmaps]

    for i, (img, cmap) in enumerate(zip(images, cmaps)):
        if cmap == 'depth':
            cmap = 'jet'
        ax[i].imshow(img, cmap=cmap)
        ax[i].set_axis_off()

    # Now only titles have to be distributed.
    if titles is not None:

        if titles == 'shapes':
            titles = [str(img.shape) for img in images]

        elif isinstance(titles, str): # Title for one image
            ax[0].set_title(titles)

        if isinstance(titles, list):
            for i, title in enumerate(titles):
                ax[i].set_title(title, fontsize=fontsize)

            if len(titles) < num_images:
                for i in range(len(titles), num_images):
                    ax[i].set_title('', fontsize=fontsize)

    if set_title is not None:
        fig.suptitle(set_title, fontsize=fontsize)
    # fig.tight_layout()
    plt.subplots_adjust(wspace=0, hspace=0)
    plt.show()
    return

def show_losses(exp_name='EXP', flag_while=False, log=False, loglog=False,\
                path2folder='./saved_models/MSGNet/',\
                last_epochs=5, only_val=False):
    '''
    It is used for losses trends visulisation.
    The usage example is provided in the model_test.ipynb.
    '''

    path2folder += exp_name+'/'

    fontsize = 20
    while True:
        fig, ax = plt.subplots(1, 2, figsize=(15,5))
        train = np.load(path2folder+'train_losses.npy')
        val   = np.load(path2folder+'val_losses.npy')
        num_epochs = np.load(path2folder+'last_saved_epoch.npy')

        train_x = np.linspace(0, num_epochs, num=len(train))
        val_x   = np.linspace(0, num_epochs, num=len(val))

        train_x_last = int(len(train)/num_epochs*(num_epochs-last_epochs-1))
        val_x_last   = int(len(val)  /num_epochs*(num_epochs-last_epochs-1))

        if loglog:
            ax[0].loglog(train_x, train)
            ax[0].loglog(val_x, val)

            if not only_val:
                ax[1].loglog(train_x[train_x_last:], train[train_x_last:])
            ax[1].loglog(val_x[val_x_last:], val[val_x_last:])

        if log:
            ax[0].semilogy(train_x, train)
            ax[0].semilogy(val_x, val)

            if not only_val:
                ax[1].semilogy(train_x[train_x_last:], train[train_x_last:])
            ax[1].semilogy(val_x[val_x_last:], val[val_x_last:])

        else:
            ax[0].plot(train_x, train)
            ax[0].plot(val_x, val)

            if not only_val:
                ax[1].plot(train_x[train_x_last:], train[train_x_last:])
            ax[1].plot(val_x[val_x_last:], val[val_x_last:])

        # show only last last_epochs epochs
        ax[1].set_xlim((np.maximum(num_epochs-last_epochs, 0), num_epochs))

        if not only_val and len(val) > 0:
            min_y = np.minimum(train[train_x_last:].min(), val[val_x_last:].min())*0.9
            max_y = np.maximum(train[train_x_last:].max(), val[val_x_last:].max())*1.1
            ax[1].set_ylim(min_y, max_y)

        if min(train) > 0:
            min_val = min(val) if len(val)>0 else 0
            ax[0].set_title('min train=  {:3.3e} | min val= {:3.3e}'\
                    .format(min(train), min_val), fontsize=fontsize)
            last_val = val[-1] if len(val)>0 else 0
            ax[1].set_title('last train= {:3.3e} | last val= {:3.3e}'\
                    .format(train[-1], last_val), fontsize=fontsize)
        fig.tight_layout()
        plt.show()

        params = np.load(path2folder+'exp_params.npy').item()
        print('num images train = ', params['num_images_train'])
        print('num images val = ', params['num_images_val'])
        print('train size = {}, val size = {}'\
                .format(params['train_batchsize'], params['val_batchsize']))

        if flag_while:
            sleep(2)
            clear_output()
        else:
            break

def save_infer_imgs(exp_name, net, rgb, depth,
            mode='gaus', sigma=1, do_filtering=False,
            path2net_folder='./saved_models/MSGNet/', crop=None):
    '''
    Runs given [rgb, depth] through each saved model state
    and puts resultive images in the folder.
    '''

    path2folder = path2net_folder+exp_name+'/state_'
    state_paths = sorted(glob(path2folder+'*.pth'))
    state_names = [state_path[len(path2folder):-4] for state_path in state_paths]

    if not os.path.isdir(path2net_folder+exp_name+'/InferImgs_'+exp_name):
        os.mkdir(path2net_folder+exp_name+'/InferImgs_'+exp_name)

    for state_name, state_path in tqdm(zip(state_names, state_paths)):
        state = th.load(state_path, map_location=th.device('cpu'))
        net.load_state_dict(state['model_state_dict'])
        res = net.do_inference(rgb, depth, mode=mode, sigma=sigma,
                                    do_filtering=do_filtering)
        res[res < depth.min()] = depth.min()
        res[res > depth.max()] = depth.max()
        if crop is not None:
            res = res[:crop, :crop]
        plt.imsave(path2net_folder+exp_name+'/InferImgs_'+exp_name+'/'+state_name,
                    res, cmap='jet')


"""
This script produces completions from Codex, or any model that fudges the
completions API.

To run this script, create a file called model_keys.csv with the columns:

```
Label,Model,Key
My OpenAI Key,,sk-YOUR-OPENAI-KEY
A100,codegen,http://localhost:8080/v1/completions
A40,incoder,http://localhost:8080/v1/completions
```

OpenAI API keys will only work if you are in the Codex beta.

Then run:

python3 completions_codex.py --dir <TARGET_DIR> --max-samples=32

The max_samples argument should be a reasonable number. Too small, and
you won't be using your GPU very efficently. Too high, and you'll crash
a naive implementation.
"""
import csv
import pdb
from typing import Dict
import os

import openai_multimodel_multikey
import asyncio
import tqdm.asyncio
import argparse
import json
import sys
from pathlib import Path
import logging

from dataset_builder.utils import TOFILL_TOKEN, MULTI_INTERMEDIATE_GENERATION_FLAG

MAX_TO_GENERATE = 750 # 512

# problem is a dict. Relevant keys are "name" and "prompt".
async def process_problem_json(completion, problem, args, max_to_generate):
    target_dir_path = Path(args.target_dir)
    completions_path = target_dir_path / (problem["name"] + ".json")
    os.makedirs(target_dir_path, exist_ok=True)

    if completions_path.exists():
        with completions_path.open() as f:
            try:
                completion_results = json.load(f)
            except:
                print(f"json load error {f}")
    else:
        # Copy problem to completion_results
        completion_results = problem.copy()
        completion_results["completions"] = []

    # completion_results has the same keys as problem, and one extra key "completions".
    num_completions_required = args.limit_completions - len(completion_results["completions"])

    if num_completions_required < 1:
        return

    # nicer to have print message updating status of 20 beam w/ intermediate generation
    verbose = False
    if args.max_samples == 1 and isinstance(problem["translation_prompt"], list):
        verbose = True

    while num_completions_required > 0:
        num_samples = min(num_completions_required, args.max_samples)
        prompt, prompt_idx, num_incomplete_prompts = "", 0, 0
        if "translation_prompt" not in problem:
            prompt = problem["prompt"]
        elif isinstance(problem["translation_prompt"], str):
            prompt = problem["translation_prompt"] if TOFILL_TOKEN in completion_results["translation_prompt"] else completion_results["translation_prompt"]
        elif isinstance(problem["translation_prompt"], list):
            # if there are incomplete prompts, do 1 time intermedidate generation with multiple generations to
            # generate all different intermediate steps at once, then generate the rest 1 by 1
            num_incomplete_prompts = len([p for p in completion_results["translation_prompt"] if TOFILL_TOKEN in p])

            # once all intermediate steps are generated, generate the rest 1 by 1
            prompt_idx = len(completion_results["completions"]) % len(problem["translation_prompt"])
            prompt = completion_results["translation_prompt"][prompt_idx]
            if num_incomplete_prompts > 0:
                prompt = MULTI_INTERMEDIATE_GENERATION_FLAG+prompt
                num_samples = num_incomplete_prompts
            # num_samples will be number of intermediate steps needs to generate, but entire generation number will be 1
            # assert num_samples == 1, "with multi-intermediate step, can only generate 1 sample at a time"
        else:
            raise NotImplementedError("Do not recognize translation prompt data type")
        updated_prompt, completions = await completion(
            model=args.model,
            prompt=prompt,
            max_tokens=max_to_generate,
            temperature=args.temperature,
            n=num_samples,
            top_p=0.95,
            stop=[s for s in problem["stop_tokens"]] if problem["stop_tokens"] else None,
        )
        completion_results["completions"].extend(completions)
        if "translation_prompt" in problem and updated_prompt:
            if isinstance(problem["translation_prompt"], str) and TOFILL_TOKEN in completion_results["translation_prompt"]:
                # explicitely updating the translation prompt, otherwise it is only sometimes updated, weird
                completion_results["translation_prompt"] = updated_prompt
            elif isinstance(problem["translation_prompt"], list) and num_incomplete_prompts > 0:
                # if we have list of intermediate steps, only when it's not stored, we update the corresponding prompt
                completion_results["translation_prompt"][-num_incomplete_prompts:] = updated_prompt
                if verbose:
                    print(f"Finished intermediate for {problem['name']}: num_samples_required={num_completions_required}")
                num_samples = 1
        with completions_path.open("w") as f:
            f.write(json.dumps(completion_results, indent=2))

        num_completions_required -= num_samples
        if verbose:
            print(f"completed 1 for {problem['name']}: num_samples_required={num_completions_required}")

def configure_logging(args):
    format_str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    if args.log_file:
        logging.basicConfig(
            filename=args.log_file, level=args.log_level, format=format_str
        )
    else:
        logging.basicConfig(level=args.log_level, format=format_str)

def get_args():
    args = argparse.ArgumentParser()
    args.add_argument("--prompts-file", type=str, required=True, help="File of prompts")
    args.add_argument(
        "--target-dir",
        type=str,
        required=True,
        help="Directory to write completions to",
    )
    args.add_argument("--temperature", type=float, required=True)
    args.add_argument("--max-samples", type=int, required=True)
    args.add_argument("--model", type=str, required=True)
    args.add_argument("--limit-completions", type=int, default=200)
    args.add_argument("--log-file", type=str, default=None)
    args.add_argument("--log-level", type=str, default="INFO")
    args.add_argument(
        "--local-model",
        action="store_true",
        help="If set, --model is the name of a model file to load",
    )
    args = args.parse_args()
    args.process_function = process_problem_json
    return args

async def main(args):
    prompts_file = Path(args.prompts_file)
    if not prompts_file.exists():
        print("File does not exist: {}".format(prompts_file))
        sys.exit(1)

    if args.model == "davinci":
        args.model = "code-davinci-002"

    configure_logging(args)

    with prompts_file.open() as f:
        problems = json.load(f)

    if args.local_model:
        completions = __import__(args.model).completion
        for problem in problems:
            await args.process_function(
                completions, problem, args, max_to_generate=MAX_TO_GENERATE
            )
    else:
        # Load the model keys from the CSV file.
        with open("model_keys_azure.csv") as f:
            reader = csv.DictReader(f)
            rows = list(reader)
        model_keys = [
            row["Key"] for row in rows if not row["Key"].startswith("http://")
        ]
        other_models = [
            (row["Model"], row["Key"])
            for row in rows
            if row["Key"].startswith("http://")
        ]
        async with openai_multimodel_multikey.MultiModelMultiKeyCompletion(
            model_keys, other_models
        ) as completions:
            problem_completions = [
                args.process_function(
                    completions.completion,
                    problem,
                    args,
                    max_to_generate=MAX_TO_GENERATE,
                )
                for problem in problems
            ]
            # await asyncio.gather(*problem_completions)
            pbar = tqdm.tqdm(total=len(problems))
            for f in asyncio.as_completed(problem_completions):
                value = await f
                pbar.set_description(value)
                pbar.update()

if __name__ == "__main__":
    asyncio.run(main(get_args()))


from sys import stdin

arr = []

def stars(y: int, x: int, size: int):
    global arr

    if size == 3:
        arr[y][x] = '*'
        arr[y + 1][x - 1], arr[y + 1][x + 1] = '*', '*'
        for i in range(5):
            arr[y + 2][x - 2 + i] = '*'
        return

    nsize = size // 2
    stars(y, x, nsize)
    stars(y + nsize, x - nsize, nsize)
    stars(y + nsize, x + nsize, nsize)

def main():
    global arr

    n = int(stdin.readline())
    arr = [[' '] * n * 2 for _ in range(n)]
    stars(0, n - 1, n)
    for i in range(n):
        print(''.join(arr[i]))

if __name__ == "__main__":
    main()


from flask import render_template, request, abort, Blueprint, redirect, url_for
from flask_login import login_user, login_required, logout_user
from pydantic import ValidationError

from users.data.login_form import LoginData
from users.services import user_service

blueprint = Blueprint('users', __name__, template_folder='templates')

@blueprint.route('/', methods=["GET"])
def login_get():
    return render_template("login.html")

@blueprint.route('/login', methods=["POST"])
def login_post():
    try:
        data = LoginData(**request.json)
        user = user_service.login(data.username, data.password)
        if not user:
            raise abort(404)

        login_user(user)

        return redirect(url_for('transfers.list_'))

    except ValidationError as e:
        return {"form_errors": e.json()}, 400

@blueprint.route('/logout', methods=["GET"])
@login_required
def logout():
    logout_user()
    return redirect(url_for("users.login_get"))


# -*- coding: utf-8 -*-
"""
Created on Sat Sep 14 20:11:47 2019

@author: vrlpa
Part A: Calculating total amount owed after graduation (2 points)

•	Use input() to set variables float variables loan_per_year and interest_rate and int variable years.
•	You will need two other variables:
o	total_owed = 0
o	counter = 0   (This is a counter variable to count how many times the loop has been executed)
•	Construct a while loop that calculates how much you will owe by graduation.
•	Each year, you will add the loan_per_year to your total_owed and multiply by the interest_rate
•	The while loop will end when your counter is equal to your years.
Example input:
Number of years: 4

Loan amount per year: 4000

Interest rate (Ex. 0.045 for 4.5% annual): .05

Example output:
Total Owed At Graduation
$ 18102

"""
#Part A
loan_per_year = float(input('Enter your loan amount per year: '))
interest_rate = float(input('What is your interest rate? '))
years = int(input('For how many years? '))
counter = 0
total_owed = 0
while counter != years:
    counter += 1
    total_owed += loan_per_year+ ((loan_per_year + total_owed)*interest_rate)
    #Since we take a loan out each year I added loan per year to the given formula
print('Total amount owed at graduation ' + str(int(total_owed)))

"""
Part B: Determine if monthly payment is feasible (1 point)

•	Below the code for Part A, use input() to set float variable monthly_payment.
•	Use if/else logic to check if the monthly payment would be possible.
 For example, if your interest accrued each month is more than your monthly payment,
 then you would be paying off your loan forever.
 Print whether it is possible with the monthly payment entered as well as
 the minimum monthly payment needed to not have your loan grow.

(Hint: Your monthly interest rate is your annual interest rate divided by 12.)
Example input:
Name a monthly payment: 300

Name a monthly payment: 50

Example output:
A monthly payment of $300 will work!
The minimum monthly payment for this loan would be 75 dollars.

A monthly payment of $50 won’t work! You’ll be paying off your loans forever.
The minimum monthly payment for this loan would be 75 dollars.

"""
#Part B
monthly_payment = float(input('Enter your monthly payment: '))

monthly_interest_rate = (interest_rate/12) #interst rate per month
minimum_payment = monthly_interest_rate*total_owed
#minimum payment is caluculated by finding the
if minimum_payment > monthly_payment:
    print('You are going to pay your loan forever!')

else:
    print('This monthly payment will help you pay off your loan!')

print('The minimum monthly payment for this loan is '+str(int(minimum_payment))+' dollars')

"""
Part C: Determine how long it will take to pay off your student loans (2 points
•	Using your variable monthly_payment from Part B, now calculate how long it will take to
 pay off your student loans.
•	Use a while loop that will continue to run until the total_owed is less than or equal to 0.
•	You will also need an integer counter variable month that keeps track of how many months
have passed (how many times the loop is run)
•	In the loop,
o	Subtract the monthly payment
o	Add back interest accrued that month
o	Add one to the counter variable month

Print out the number of months and years it will take to pay off the loans.
 Note, you do not need to count partial months and the number of years do not
 need to be formatted.

Example output:
	It will take 70 months to pay off your student loans.
It will take 5.833333333333333 years to pay off your student loans.

"""
#Part C
counter_month = 0
while total_owed >= 0:
    counter_month += 1
    counter_year = (counter_month/12)
    total_owed = (total_owed - monthly_payment)
    total_owed = (total_owed * monthly_interest_rate)+total_owed

print('You will have to pay your loans for '+ str(counter_month)+' months')

print('Or '+ str(int(counter_year))+' years')


import tensorflow as tf
import numpy as np

# input from outside of TensorFlow
# we're learning an XOR gate
x_numpy = np.array([[0., 1.],
                    [0., 0.],
                    [1., 0.],
                    [1., 1.]])

y_numpy = np.array([[1.],
                    [0.],
                    [1.],
                    [0.]])

## setting up graph (just input & labels)
# not the way to _do_ it, but a decent way to understand what's done
# where the input data comes in
x_input = tf.placeholder(dtype=tf.float32, shape=[None, 2])
y_input = tf.placeholder(dtype=tf.float32, shape=[None,1])

# trainables input -> hidden
x_bias = tf.Variable(tf.random_normal([9]), trainable=True)
weights_01 = tf.Variable(tf.random_normal([2, 9]), trainable=True)

# hidden layer & its non linearity
hidden = tf.nn.xw_plus_b(x_input, weights_01, x_bias)
hidden_nonlin = tf.maximum(0., hidden)

# trainables hidden -> output
hidden_bias = tf.Variable(tf.random_normal([1]), trainable=True)
weights_02 = tf.Variable(tf.random_normal([9, 1]), trainable=True)

# predictions & its non linearity
pre_predictions = tf.nn.xw_plus_b(hidden_nonlin, weights_02, hidden_bias)
predictions = tf.sigmoid(pre_predictions)

# scoring and training
loss = tf.losses.sigmoid_cross_entropy(logits=pre_predictions,
                                      multi_class_labels=y_input)

train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)

# initializing variables
init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    # this is the part that would run on the graphics card
    sess.run(init_op)

    for i in range(10000):
        _, loss_as_number = sess.run([train_op, loss],
                                      feed_dict={x_input: x_numpy,
                                                 y_input: y_numpy})
        if i % 500 == 0:
            print('loss:', loss_as_number)

    out = sess.run(predictions, feed_dict={x_input: x_numpy, y_input: y_numpy})

print('predictions:\n{}'.format(out))


import cv2
import numpy as np

cap = cv2.VideoCapture(0)
bars = cv2.namedWindow("bars")

def hello(x):
    pass

cv2.createTrackbar("upper_hue","bars",130,180,hello)
cv2.createTrackbar("upper_sat","bars",255,255,hello)
cv2.createTrackbar("upper_val","bars",255,255,hello)
cv2.createTrackbar("lower_hue","bars",70,180,hello)
cv2.createTrackbar("lower_sat","bars",50,255,hello)
cv2.createTrackbar("lower_val","bars",50,255,hello)

while True:
    cv2.waitKey(1000)
    ret,init_frame = cap.read()
    if ret:
        break
while True:
    _,frame = cap.read()
    inspect = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)

    upper_hue = cv2.getTrackbarPos("upper_hue", "bars")
    upper_sat = cv2.getTrackbarPos("upper_sat", "bars")
    upper_val = cv2.getTrackbarPos("upper_val", "bars")
    lower_hue = cv2.getTrackbarPos("lower_hue", "bars")
    lower_sat = cv2.getTrackbarPos("lower_sat", "bars")
    lower_val = cv2.getTrackbarPos("lower_val", "bars")
    upper_hsv = np.array([upper_hue,upper_sat,upper_val])
    lower_hsv = np.array([lower_hue,lower_sat,lower_val])

    kernel = np.ones((3,3),np.uint8)

    mask = cv2.inRange(inspect ,lower_hsv,upper_hsv)
    mask = cv2.medianBlur(mask,3)
    mask = cv2.dilate(mask,kernel)
    mask_inv = 255-mask

    b = frame[:, :, 0]
    g = frame[:, :, 1]
    r = frame[:, :, 2]

    b = cv2.bitwise_and(mask_inv, b)
    g = cv2.bitwise_and(mask_inv, g)
    r = cv2.bitwise_and(mask_inv, r)
    frame_inv = cv2.merge((b,g,r))
    b = init_frame[:, :, 0]
    g = init_frame[:, :, 1]
    r = init_frame[:, :, 2]
    b = cv2.bitwise_and(mask, b)
    g = cv2.bitwise_and(mask, g)
    r = cv2.bitwise_and(mask, r)
    blanket_area = cv2.merge((b,g,r))
    final = cv2.bitwise_or(blanket_area,frame_inv)

    cv2.imshow("Invisble cloak",final)
    cv2.imshow("Original frame",frame)

    if (cv2.waitKey(1) == 27):
        break
cv2.destroyAllWindows()
cap.release()


import random
import torch
import torch.nn as nn
from torchtext.data import Field, TabularDataset

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

def tokin(text):
    # This is tokinizer
    text = text.split(" ")
    m = []
    for i in text:
        k = i
        for j in range(len(i)):
            if i[j].isalpha():
                break
            k = k.replace(i[j], "")
        for j in range(1, len(i)):
            if i[-j].isalpha():
                break
            k = k.replace(i[-j], "")
        if k != "":
            m.append(k)
    return m

# Create a field
rus = Field( tokenize=tokin, lower = True, init_token = "<sos>", eos_token = "<eos>")
train_data, validation_data, test_data = TabularDataset.splits(
                                        path="Final",
                                        train="train.json",
                                        validation="validation.json",
                                        test="test.json",
                                        format="json",
                                        fields = {"src" : ("src", rus), "trg" : ("trg",rus)})
# Create vocabulary
rus.build_vocab(train_data, max_size = 16384, min_freq=4)

class Encoder(nn.Module):

    def __init__(self, input_size, embedding_size, hidden_size, num_layers, p):
        super(Encoder, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.embedding = nn.Embedding(input_size, embedding_size)
        self.rnn = nn.LSTM(embedding_size, hidden_size, num_layers, bidirectional=True)

        self.fc_hidden = nn.Linear(hidden_size * 2, hidden_size)
        self.fc_cell = nn.Linear(hidden_size * 2, hidden_size)
        self.dropout = nn.Dropout(p)

    def forward(self, x):
        # x: (seq_length, N) where N is batch size

        embedding = self.dropout(self.embedding(x))
        # embedding shape: (seq_length, N, embedding_size)

        encoder_states, (hidden, cell) = self.rnn(embedding)
        # outputs shape: (seq_length, N, hidden_size)

        # Use forward, backward cells and hidden through a linear layer
        # so that it can be input to the decoder which is not bidirectional
        # Also using index slicing ([idx:idx+1]) to keep the dimension
        hidden = self.fc_hidden(torch.cat((hidden[0:1], hidden[1:2]), dim=2))
        cell = self.fc_cell(torch.cat((cell[0:1], cell[1:2]), dim=2))

        return encoder_states, hidden, cell

class Decoder(nn.Module):
    def __init__(self, input_size, embedding_size, hidden_size,
                 output_size, num_layers, p):
        super(Decoder, self).__init__()
        self.hidden_size = hidden_size
        self.num_layers = num_layers

        self.embedding = nn.Embedding(input_size, embedding_size)
        self.rnn = nn.LSTM(hidden_size * 2 + embedding_size, hidden_size, num_layers)

        self.energy = nn.Linear(hidden_size * 3, 1)
        self.fc = nn.Linear(hidden_size, output_size)
        self.dropout = nn.Dropout(p)
        self.softmax = nn.Softmax(dim=0)
        self.relu = nn.ReLU()

    def forward(self, x, encoder_states, hidden, cell):
        x = x.unsqueeze(0)
        embedding = self.dropout(self.embedding(x))
        sequence_length = encoder_states.shape[0]
        h_reshaped = hidden.repeat(sequence_length, 1, 1)
        energy = self.relu(self.energy(torch.cat((h_reshaped, encoder_states), dim=2)))
        attention = self.softmax(energy)
        context_vector = torch.einsum("snk,snl->knl", attention, encoder_states)
        rnn_input = torch.cat((context_vector, embedding), dim=2)
        outputs, (hidden, cell) = self.rnn(rnn_input, (hidden, cell))
        # outputs shape: (1, N, hidden_size)

        predictions = self.fc(outputs).squeeze(0)
        # predictions: (N, hidden_size)

        return predictions, hidden, cell

class Seq2Seq(nn.Module):
    def __init__(self, encoder, decoder):
        super(Seq2Seq, self).__init__()
        self.encoder = encoder
        self.decoder = decoder

    def forward(self, source, target, teacher_force_ratio=0.5):
        batch_size = source.shape[1]
        target_len = target.shape[0]
        target_vocab_size = len(rus.vocab)

        outputs = torch.zeros(target_len, batch_size, target_vocab_size).to(device)
        encoder_states, hidden, cell = self.encoder(source)

        # First input will be <SOS> token
        x = target[0]

        for t in range(1, target_len):

            output, hidden, cell = self.decoder(x, encoder_states, hidden, cell)
            outputs[t] = output

            best_guess = output.argmax(1)
            x = target[t] if random.random() < teacher_force_ratio else best_guess

        return outputs


'''
利用预训练的wav2vec模型，在本数据集上做VA回归任务
'''
import torch
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from transformers import Wav2Vec2Model
from torch.nn.utils.rnn import pad_sequence
import math

import sys
sys.path.append('/data2/hzp/ABAW_VA_2022/code/')#
from models.base_model import BaseModel#
from models.networks.regressor import FcRegressor#

class Wav2vecModel(BaseModel):
    @staticmethod
    def modify_commandline_options(parser, is_train=True):
        parser.add_argument('--regress_layers', default='256', type=str,
                            help='size of classifier hidden size, split by comma')
        parser.add_argument('--dropout_rate', default=0.3, type=float, help='drop out rate')
        parser.add_argument('--loss_type', type=str, default='mse', choices=['mse', 'l1'], help='use MSEloss or L1loss')
        parser.add_argument('--task', type=str, default='v+a', choices=['v', 'a', 'v+a'], help='the task target.')
        return parser

    def __init__(self, opt, logger=None):
        """Initialize the BaselineModel class

        Parameters:
            opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
        """
        super().__init__(opt, logger)
        self.loss_names = [opt.loss_type] # get_current_losses: getattr(self, 'loss_' + name)
        self.regress_layers = list(map(lambda x: int(x), opt.regress_layers.split(',')))
        self.dropout_rate = opt.dropout_rate
        self.task = opt.task
        self.label_fps = 30 # 标签频率每秒30帧
        self.frame_rate = 0.02 # wav2vec 0.02s一帧
        self.model_names = ['_wav2vec', '_reg']
        self.pretrained_model = ['_wav2vec']
        self.net_wav2vec = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base")

        if self.task == 'v' or self.task == 'a':
            self.net_reg = FcRegressor(768, self.regress_layers, 1, dropout=self.dropout_rate)
        else:
            self.net_reg = FcRegressor(768, self.regress_layers, 2, dropout=self.dropout_rate)

        #settings
        if self.isTrain:
            if opt.loss_type == 'mse':
                self.criterion_reg = torch.nn.MSELoss(reduction='sum')
            else:
                self.criterion_reg = torch.nn.L1Loss(reduction='sum')

            # initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
            paremeters = [{'params': getattr(self, 'net'+net).parameters()} for net in self.model_names]
            self.optimizer = torch.optim.Adam(paremeters, lr=opt.lr, betas=(opt.beta1, 0.999))
            self.optimizers.append(self.optimizer)

    def set_input(self, input, load_label=True):
        """Unpack input data from the dataloader and perform necessary pre-processing steps.

        Parameters:
            input (dict): include the data itself and its metadata information.

        """
        self.len_speech = input['len_speech'].to(self.device) # (bs,)
        self.speech = input['speech'].to(self.device) # (bs, len_speech)
        if load_label:
            self.valid = input['valid'].to(self.device) # (bs, max_clip_length*30)
            if self.task == 'v':
                self.target = input['label'].permute(2, 0, 1)[0].to(self.device) # (bs, max_clip_length*30)
            elif self.task == 'a':
                self.target = input['label'].permute(2, 0, 1)[1].to(self.device) # (bs, max_clip_length*30)
            else:
                self.target = input['label'].to(self.device) # (bs, max_clip_length*30, 2)

    def run(self):
        """After feed a batch of samples, Run the model."""
        # forward
        prediction = self.forward_step() # (bs, aligned_len_speech, 2) or (bs, aligned_len_speech, 1)
        if self.task == 'v' or self.task == 'a':
            prediction = prediction.squeeze(dim=-1) # (bs, aligned_len_speech)

        # backward
        if self.isTrain:
            self.optimizer.zero_grad()
            self.backward_step(prediction, self.target, self.valid)
            self.optimizer.step()

        self.output = prediction

    def align_timestamp(self, batch_ft, num_frames):
        '''
        The wav2vec has 50 fts per second. There are 30 labels per second.
        We need to align the feature frequency to the label frequency.
        '''
        start_time_list = [i * (1.0/self.label_fps) for i in range(num_frames)]
        end_time_list = [((1.0/self.label_fps) + i * (1.0/self.label_fps)) for i in range(num_frames)]

        # 把每个时刻的值精度缩小一下，防止因为float本身有些小数最后一位不够精确导致多算一条frame
        start_time_list = [round(i, 4) for i in start_time_list]
        end_time_list = [round(i, 4) for i in end_time_list]

        # 确保 batch_ft pad到足够长
        finish_idx = math.ceil(end_time_list[-1] / self.frame_rate)
        if batch_ft.shape[1] < finish_idx:
            pad_num = finish_idx + 1 - batch_ft.shape[0]
            pad_ft = batch_ft[:, -1, :] # (bs, dim)
            pad_ft = pad_ft.unsqueeze(1).repeat(1, pad_num, 1) # (bs, pad_num, dim)
            batch_ft = torch.cat((batch_ft, pad_ft), dim=1)

        segment_ft = []
        for start, end in zip(start_time_list, end_time_list):
            start_idx = math.floor(round(start / self.frame_rate, 4)) # 同样也需要在这里缩小一下精度
            end_idx = math.ceil(round(end / self.frame_rate, 4))
            frame_ft = batch_ft[:, start_idx: end_idx, :]
            frame_ft = frame_ft.mean(dim=1)
            segment_ft.append(frame_ft)
        segment_ft = torch.stack(segment_ft, dim=1)
        assert segment_ft.shape[1] == num_frames

        return segment_ft # (bs, num_frames, dim)

    def forward_step(self):
        batch_ft = self.net_wav2vec(self.speech).last_hidden_state # (bs, len_speech, dim=768)
        aligned_len = self.target.shape[1]
        batch_ft = self.align_timestamp(batch_ft, aligned_len) # (bs, num_frames, dim=768)

        pred, _ = self.net_reg(batch_ft) # (bs, aligned_len_speech, 2) or (bs, aligned_len_speech, 1)
        return pred

    def backward_step(self, pred, target, mask):
        """Calculate the loss for back propagation"""
        if self.task == 'v+a':
            mask = mask.unsqueeze(2).repeat(1, 1, 2)

        pred = pred * mask
        target = target * mask
        valid_data_num = torch.sum(mask)
        self.loss_mse = self.criterion_reg(pred, target) / valid_data_num
        self.loss_mse.backward(retain_graph=False)

if __name__ == '__main__':
    import sys
    sys.path.append('/data8/hzp/ABAW_Expression_2022/code/utils')#
    from data import create_dataset, create_dataset_with_args

    class test:
        feature_set = 'None'
        input_dim = None
        lr = 1e-4
        beta1 = 0.5
        batch_size = 2
        epoch_count = 1
        niter = 20
        niter_decay=30
        gpu_ids = [1]
        isTrain = True
        checkpoints_dir = ''
        name = ''
        cuda_benchmark = ''
        max_read_num = 10
        max_clip_length = 10
        dataset_mode = 'audio_clip_toy'
        num_threads = 0
        max_dataset_size = float("inf")
        serial_batches = True
        lr_policy = ''
        init_type = 'kaiming'
        init_gain = 0.02
        verbose = ''

        regress_layers = '256'
        dropout_rate = 0.3
        loss_type = 'mse'
        task = 'v'

    opt = test()
    net_a = Wav2vecModel(opt)

    # dataset, val_dataset = create_dataset_with_args(opt, set_name=['train', 'val'])  # create a dataset given opt.dataset_mode and other options
    dataset = create_dataset_with_args(opt, set_name=['train'])[0]  # create a dataset given opt.dataset_mode and other options

    net_a.setup(opt)                            # regular setup: load and print networks; create schedulers

    total_iters = 0                             # the total number of training iterations

    for epoch in range(opt.epoch_count, opt.niter + opt.niter_decay + 1):    # outer loop for different epochs; we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>
        epoch_iter = 0                  # the number of training iterations in current epoch, reset to 0 every epoch
        for i, data in enumerate(dataset, 1):  # inner loop within one epoch
            total_iters += 1                # opt.batch_size
            epoch_iter += opt.batch_size
            net_a.set_input(data)           # unpack data from dataset and apply preprocessing
            net_a.run()

            print(net_a.output)
            print(net_a.output.shape)

    # for epoch in range(opt.epoch_count, opt.niter + opt.niter_decay + 1):    # outer loop for different epochs; we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>
    #     epoch_iter = 0                  # the number of training iterations in current epoch, reset to 0 every epoch
    #     for i, data in enumerate(val_dataset, 1):  # inner loop within one epoch
    #         total_iters += 1                # opt.batch_size
    #         epoch_iter += opt.batch_size
    #         net_a.set_input(data)           # unpack data from dataset and apply preprocessing
    #         net_a.run()

    #         print(net_a.output)
    #         print(net_a.output.shape) # (1, 2)


from tqdm import tqdm
from pytube import YouTube
import ffmpeg

videoUrl = input("Video URL=")
fps = input("FPS=")
hres = input("Horizontal Resolution=")
threaded = input("Run on multiple threads (y/n)=")
if(threaded.lower() == 'y'):
    threads = input("Thread count=")

print("WARNING: This will overwrite the existing file 'video.mp4' and any existing frames in 'frames'.")
continueInput = input("Continue? (y/n)=")

if continueInput != "y":
    exit()

# Download the video
if videoUrl != '':
    print("Downloading video...")
    yt = YouTube(videoUrl)
    video = yt.streams.filter(progressive=True, file_extension='mp4').first()
    video.download(filename="video-raw.mp4")

    # Convert the video to a video with the correct FPS and resolution
    print("Converting video...")
    ffmpeg.input('video-raw.mp4').output('video.mp4', vf='fps=' + fps + ',' + 'scale=' + hres + ':-2').run()

# run convert_video.py
if threaded.lower() == 'y':
    import convert_video_threaded
    convert_video_threaded.fps = fps
    convert_video_threaded.maxThreads = threads
else:
    import convert_video
    convert_video.fps = fps


import argparse, os, pickle, sys
sys.path.append('/home/om2382/vanilla-rtrl/')
from wrappers import cross_compare_analyzed_checkpoints

parser = argparse.ArgumentParser()
parser.add_argument('--name', dest='name')

args = parser.parse_args()

args_path = os.path.join('/home/om2382/learning-dynamics/args/', args.name)

with open(args_path, 'rb') as f:
    all_args = pickle.load(f)

compare_args = {k.split('compare_')[1]: all_args[k]
                for k in all_args.keys() if 'compare_' in k}

cross_compare_analyzed_checkpoints(args.name,
                                   compare_args=compare_args,
                                   notebook_dir=all_args['notebook_dir'])


import tkinter as tk
from tkinter import messagebox
x = 0
def panic():
    messagebox.showinfo('panic room','crisis averted!!!')
    global x
    x+=1
    var.set(x)
root = tk.Tk()
b = tk.Button(root,text='panic button',command=panic)
b.pack()
var = tk.StringVar()
var.set(x)
label2 = tk.Label(root,text = 'no of times panic button pressed : \n')
label2.pack()
label = tk.Message(root,textvariable=var)
label.pack()
root.mainloop()


#Reset and repeat the above, but with a deterministic greedy behavior policy: at each state st use the best
#action at 2 arg maxa Q(st; a) indicated by the current Q table. If there is a tie, prefer move.

import numpy as np
import random
# Initialize q-table values to 0

#np.zeros((state_size, action_size))
Q = np.zeros((2, 2))
curr_state = 0
alpha = 0.5
gamma = 0.9

for i in range(200):

    next_action = 0
    if Q[curr_state][0] < Q[curr_state][1]:
        next_action = 1
    elif Q[curr_state][0] > Q[curr_state][1]:
        next_action = 0
    elif Q[curr_state][0] == Q[curr_state][1]:
        if curr_state == 0:
            next_action = 1
        else:
            next_action = 0

    if curr_state == next_action:
        reward = 1
    else:
        reward = 0

    maxval = max(Q[next_action][0], Q[next_action][1])

    Q[curr_state][next_action] = (1-alpha)*Q[curr_state][next_action] + alpha*(reward + gamma*(maxval))
    curr_state = next_action

print(Q[0][0])
#print(Q[0][1])
#print(Q[1][0])
#print(Q[1][1])