import threading
import xml.etree.ElementTree as X
import unittest

array = []

def partition(array, left, right):
    #first element pivot
    pivot = array[left]
    i = left + 1
    for j in range(left+1, right+1):
        if array[j] < pivot:
            array[j],array[i] = array[i], array[j]
            i += 1
    array[left], array[i-1] = array[i-1], array[left]
    #print('array:\t\t', array)
    return i-1

def quicksort(array, left, right):

    if left <= right:
        print("thead {0} is sorting {1}".format(threading.current_thread(), array[left:right]))
        q = partition(array, left, right)

        lthread = None
        rthread = None

        if (left < q-1):
            lthread = threading.Thread(target = lambda: quicksort(array,left,q-1))
            lthread.start()

        if (q+1 < right):
            rthread = threading.Thread(target=lambda: quicksort(array,q+1,right))
            rthread.start()

        if lthread is not None:
            lthread.join()
        if rthread is not None:
            rthread.join()

        '''
        thread_1 = threading.Thread(target=quicksort, args=(array, left, q-1))
        thread_2 = threading.Thread(target=quicksort, args=(array, q+1, right))
        thread_1.start()
        thread_2.start()
        thread_1.join()
        thread_2.join()
        '''

def dummy_quicksort(array):
    quicksort(array, 0, len(array)-1)
    return array

class UnitTesting(unittest.TestCase):

    def test_assert_equal(self):
        self.assertEqual(dummy_quicksort(array), [1, 2, 3, 5, 7, 9, 11, 12, 22, 24, 33, 34, 36, 44, 45, 48, 55, 60, 66, 77, 88, 90, 99, 115, 118, 557, 664, 776, 887, 998, 999])

if __name__ == "__main__":
    root = X.parse("input.xml").getroot()
    print('array: ', root.text)

    array = list(map(int, root.text.split()))
    print('array: ', array)

    print("testing..")
    unittest.main()

'''
ignore this.
array = []
fi = open("data.txt", "r")
lines = fi.readlines()
count = 0
for line in lines:
    if count > 50000:
        break
    count += 1
    array.append(int(line))

print("numbers count: ", len(array))

for _ in range(100000):
    fi.write(random.randint(1, 1000))

start = time.time()
quicksort(array, 0, len(array)-1)
end = time.time()

print('time needed: ', end-start)
'''


# -*- coding: utf-8 -*-
# @Author: Niccolò Bonacchi
# @Date:   2018-02-02 17:19:09
# @Last Modified by:   Niccolò Bonacchi
# @Last Modified time: 2018-02-26 16:07:42
import os
import datetime
import numpy as np
import scipy.stats as st
from pythonosc import udp_client
import json
import glob

class sounds():
    """Software solution for playing sounds"""
    def configure_sounddevice(SD=None):
        if SD is None:
            import sounddevice as SD
        SD.default.latency = 'low'
        SD.default.channels = 2
        return SD

    def make_sound(frequency=10000, duration=0.1, amplitude=1, fade_in=0.01):
        """builds sound to feed to sounddevice lib
        if frequency is set to -1 will produce white noise"""
        FsOut = 44100  # sample rate, depend on the sound card
        toneDuration = duration  # sec
        amplitude = amplitude  # [0->1]
        frequency = frequency  # Hz
        onsetDur = fade_in  # sec

        tvec = np.linspace(0, toneDuration, toneDuration * FsOut)
        sound = amplitude * np.sin(2 * np.pi * frequency * tvec)  # sound vec
        size = FsOut * onsetDur / 2  #
        dist = st.expon(0., size)  # distribution object provided by scipy
        F = dist.cdf  # cumulative density function
        ker = F(range(int(FsOut * toneDuration)))
        sound = sound * ker
        if frequency == -1:
            sound = amplitude * np.random.rand(sound.size)
        return sound

    def play_sound(sound):
        pass

class rotary_encoder(object):  # TODO: SAVE THIS IN SETTINGS FILE ALSO

    def __init__(self, port, stim_positions, quiescence_thresholds, gain):
        self.port = port
        self.wheel_perim = 31 * 2 * np.pi  # = 194,778744523
        self.wheel_deg_mm = 360 / self.wheel_perim
        self.factor = self.wheel_deg_mm / gain
        self.all_thresholds = stim_positions + quiescence_thresholds
        self.SET_THRESHOLDS = [x * self.factor for x in self.all_thresholds]
        self.ENABLE_THRESHOLDS = [(True if x != 0
                                   else False) for x in self.SET_THRESHOLDS]
        # ENABLE_THRESHOLDS needs 8 bools even if only 2 thresholds are set
        while len(self.ENABLE_THRESHOLDS) < 8:
            self.ENABLE_THRESHOLDS.append(False)

    def configure(self, RotaryEncoderModule):
        m = RotaryEncoderModule(self.port)
        m.set_zero_position()  # Not necessarily needed
        m.set_thresholds(self.SET_THRESHOLDS)
        m.enable_thresholds(self.ENABLE_THRESHOLDS)
        m.close()

class session_param_handler(object):
    """Session object copies settings parameters and calculates other secondary
    session parameters, saves all params in a settings file.json"""

    def __init__(self, task_settings):
        tsp = {i: task_settings.__dict__[i]
               for i in [x for x in dir(task_settings) if '__' not in x]}
        self.__dict__.update(tsp)

        self.VALVE_TIME = self.CALIBRATION_VALUE * self.TARGET_REWARD

        self.GO_TONE = sounds.make_sound(frequency=self.GO_TONE_FREQUENCY,
                                         duration=self.GO_TONE_DURATION,
                                         amplitude=self.GO_TONE_AMPLITUDE)
        self.WHITE_NOISE = sounds.make_sound(
            frequency=-1,
            duration=self.WHITE_NOISE_DURATION,
            amplitude=self.WHITE_NOISE_AMPLITUDE)
        self.SD = sounds.configure_sounddevice()
        self.OSC_CLIENT = self.osc_client_init()

        self.ALL_THRESHOLDS = (self.STIM_POSITIONS +
                               self.QUIESCENCE_THRESHOLDS)
        # Names of the RE events generated by Bpod
        self.ENCODER_EVENTS = ['RotaryEncoder{}_{}'.format(
            self.ROTARY_ENCODER_SERIAL_PORT_NUM, x) for x in
            list(range(1, len(self.ALL_THRESHOLDS) + 1))]
        # Dict mapping threshold crossings with name ov RE event
        self.THRESHOLD_EVENTS = dict(zip(self.ALL_THRESHOLDS,
                                         self.ENCODER_EVENTS))

        self.SESSION_NAME = datetime.datetime.now().isoformat().replace(':',
                                                                        '_')
        self.TASK_NAME = '{}_{}'.format('pycw', self.TASK.strip('ChoiceWorld'))

        self.SESSION_ID = '{}_{}_{}'.format(self.MOUSE_NAME,
                                            self.SESSION_NAME,
                                            self.TASK_NAME)

        self.ROOT_DATA_FOLDER = path_helper.root_data_folder(
            self.ROOT_DATA_FOLDER)
        self.MOUSE_DATA_FOLDER = path_helper.mouse_data_folder(self)
        self.PREVIOUS_DATA_FILE = path_helper.previous_data_file(self)
        self.SESSION_DATA_FOLDER = path_helper.session_data_folder(self)
        self.SETTINGS_FILE_PATH = path_helper.settings_file_path(self)
        self.DATA_FILE_PATH = path_helper.data_file_path(self)

        self.STATE_AFTER_START = ('stim_on' if self.QUIESCENT_PERIOD == 0
                                  else 'quiescent_period')

        self.save_session_settings()

    def reprJSON(self):
        d = self.__dict__.copy()
        d['GO_TONE'] = 'sounds.make_sound(frequency={}, duration={}, \
amplitude={})'.format(self.GO_TONE_FREQUENCY, self.GO_TONE_DURATION,
                      self.GO_TONE_AMPLITUDE)
        d['WHITE_NOISE'] = 'sounds.make_sound(frequency=-1, duration={}, \
amplitude={})'.format(self.WHITE_NOISE_DURATION, self.WHITE_NOISE_AMPLITUDE)
        d['SD'] = str(d['SD'])
        d['OSC_CLIENT'] = str(d['OSC_CLIENT'])
        return d

    def save_session_settings(self):
        with open(self.SETTINGS_FILE_PATH, 'a') as f:
            f.write(json.dumps(self.reprJSON()))
            f.write('\n')
        return

    def osc_client_init(self):
        osc_client = udp_client.SimpleUDPClient(self.OSC_CLIENT_IP,
                                                self.OSC_CLIENT_PORT)
        return osc_client

class path_helper:

    def root_data_folder(rdf):
        # if running as main
        if __name__ == '__main__' and os.name == 'nt':
            return 'C:\\IBL_root\\pybpod_projects\\IBL\\data/'
        elif __name__ == '__main__' and os.name == 'posix':
            return '/home/nico/Projects/IBL/IBL-github/pybpod_projects/IBL/\
data/'

        # If no data folder was defined in settings file use default folder
        if rdf is None:
            out = 'C:/IBL_root/pybpod_data/'  # '../pybpod_projects/IBL/data/'
        else:
            # If folder was defined in settings check if endswith '/'
            out = rdf if rdf.endswith('/') else rdf + '/'

        if not os.path.exists(out):
            os.mkdir(out)
        return out

    def mouse_data_folder(sph):
        mdf = sph.ROOT_DATA_FOLDER + sph.MOUSE_NAME + '/'
        if not os.path.exists(mdf):
            os.mkdir(mdf)
        return mdf

    def session_data_folder(sph):
        sdf = sph.MOUSE_DATA_FOLDER + sph.SESSION_NAME + '/'
        if not os.path.exists(sdf):
            os.mkdir(sdf)
        return sdf

    def settings_file_path(sph):
        return (sph.SESSION_DATA_FOLDER + sph.TASK_NAME + '.settings.json')

    def data_file_path(sph):
        return (sph.SESSION_DATA_FOLDER + sph.TASK_NAME + '.data.json')

    def previous_data_file(sph):
        session_list = glob.glob(sph.MOUSE_DATA_FOLDER + '*')
        if not session_list:
            return None
        latest_session = max(session_list, key=os.path.getctime)
        prev_session_files = glob.glob(latest_session + '/*')
        prev_data_file = [x for x in prev_session_files if 'data.' in x]
        if prev_data_file:
            return prev_data_file[0]
        else:
            # Alternatively could call myself again after deleting session...
            del_file = open(latest_session + '/NO_DATA_FOUND_DELETE_SESSION',
                            'a')
            del_file.close()
            return None

        return prev_data_file

if __name__ == '__main__':
    import task_settings
    sph = session_param_handler(task_settings)

    # session_settings = []
    # with open(sph.SETTINGS_FILE_PATH, 'r') as f:
    #     for line in f:
    #         dict_obj = json.loads(line)
    #         session_settings.append(dict_obj)
    # print(dict_obj)

    # f = open(sph.SETTINGS_FILE_PATH + 'dump', 'w')
    # json.dump(sph.reprJSON(), f)
    # f.close()

    # f = open(sph.SETTINGS_FILE_PATH + 'dump', 'r')
    # bla = json.load(f)
    # f.close()
    # print(bla)


from tkinter import *

wn = Tk()
wn.title('KeyDetect')

m = 0

def down(e):
    global m
    if m == 0:
        print(e.char)
        #print('Down\n', e.char, '\n', e)
        m = 1

def up(e):
    global m
    if m == 1:
        print(e.char)
        #print('Up\n', e.char, '\n', e)
        m = 0

wn.bind('<KeyPress>', down)
wn.bind('<KeyRelease>', up)

wn.mainloop()


# uncompyle6 version 3.7.4
# Python bytecode 2.6 (62161)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/pysvnmanager/hooks/plugins/EolStyleCheck.py
# Compiled at: 2010-06-08 22:36:02
from pysvnmanager.hooks.plugins import *
from pysvnmanager.hooks.plugins import _

class EolStyleCheck(PluginBase):
    name = _('mime-type and eol-style check')
    description = _('New file must provide svn:eol-style if not binary file.')
    detail = ''
    type = T_PRE_COMMIT
    key_switch = 'eol_style_check'
    key_force = 'eol_style_check_force'
    section = 'pre_commit'

    def enabled(self):
        """
        Return True, if this plugin has been installed.
        Simply call 'has_config()'.
        """
        return self.has_config(self.key_switch)

    def install_info(self):
        """
        Show configurations if plugin is already installed.

        return reStructuredText.
        reST reference: http://docutils.sourceforge.net/docs/user/rst/quickref.html
        """
        result = self.description
        if self.enabled():
            result += '\n\n'
            result += '**' + _('Current configuration') + '**\n\n'
            force = self.get_config(self.key_force)
            if force == 'no':
                result += '- ' + _('Loose mode: permit checkin without svn:eol-style properity if no CRLF in text file.')
            else:
                result += '- ' + _('Strict mode: must have svn:eol-style even if not CRLF in text file.')
        return result

    def install_config_form(self):
        """
        This method will be called to build setup configuration form.
        If this plugin needs parameters, provides form fields here.
        Any html and javascript are welcome.
        """
        if self.get_config(self.key_force) == 'no':
            enable_checked = ''
            disable_checked = 'checked'
        else:
            enable_checked = 'checked'
            disable_checked = ''
        result = ''
        result += '
%s
' % _('Fill this form')
        result += '
'
        result += '
'
        result += '\n
'
        result += "<input type='radio' name='force' value='yes' " + enable_checked + '>' + _('Strict mode') + ' '
        result += '\n
'
        result += _('Must set svn:eol-style even if CRLF not in text file (in Unix format).')
        result += '\n
'
        result += "<input type='radio' name='force' value='no' " + disable_checked + '>' + _('Loose mode') + '
'
        result += '\n
'
        result += _('Permit checkin without svn:eol-style properity if is in Unix file format (no crlf in text file).')
        result += '\n
'
        result += '
'
        return result

    def uninstall(self):
        """
        Uninstall hooks-plugin from repository.
        Simply call 'unset_config()' and 'save()'.
        """
        self.unset_config(self.key_switch)
        self.unset_config(self.key_force)
        self.save()

    def install(self, params=None):
        """
        Install hooks-plugin from repository.
        Simply call 'set_config()' and 'save()'.

        Form fields in setup_config() will pass as params.
        """
        force = params.get('force', 'no')
        if force != 'no':
            force = 'yes'
        self.set_config(self.key_switch, 'yes')
        self.set_config(self.key_force, force)
        self.save()

def execute(repospath=''):
    """
    Generate and return a hooks plugin object

    @param request: repos full path
    @rtype: Plugin
    @return: Plugin object
    """
    return EolStyleCheck(repospath)


from .agreementr import Agreementr

ar = None

def predict(text):
    global ar
    if ar is None:
        try:
            ar = Agreementr()
        except Exception as e:
            print("Failed to initialize Agreementr")
            print(e)

    return ar.predict(text)


class PrimeNumbers():
    def __init__(self,treshold):
        self.treshold = treshold
        self.prime_map = [False]+[False]+[True]*(self.treshold-2)
        self.pointer = 2
        self.prime_num_set = set()
        self.prime_num_list = []

    def generate(self):
        while self.pointer < self.treshold:
            for i in xrange(self.pointer*2,self.treshold,self.pointer):
                self.prime_map[i] = False
            for i in xrange(self.pointer+1,self.treshold):
                if self.prime_map[i]:
                    self.pointer = i
                    break
                self.pointer=self.treshold
        return self.prime_map

    def get_set(self):
        self.generate()
        for i,item in enumerate(self.prime_map):
            if item: self.prime_num_set.add(i)
        return self.prime_num_set

    def get_list(self):
        self.generate()
        for i,item in enumerate(self.prime_map):
            if item: self.prime_num_list.append(i)
        return self.prime_num_list


def sum13(nums):
    sum = 0
    i = 0
    while i < len(nums):
        if nums[i] == 13:
            i += 2
            continue
        sum += nums[i]
        i += 1

    return sum

print(sum13([13, 1, 2, 13, 2, 1, 13]))


# -*- coding:utf-8 -*-
__author__ = 'Threedog'
__Date__ = '2018/7/30 20:59'

import socket
import threading
import json

from PyQt5.QtWidgets import QLabel,QMessageBox,QWidget,QLineEdit,QVBoxLayout,QHBoxLayout,QPushButton,QListWidget,QListWidgetItem
from PyQt5.QtGui import QMouseEvent,QPixmap,QIcon,QCloseEvent
from PyQt5.QtCore import QPoint,pyqtSignal,Qt
import pygame

from Base import Chessman,is_win,trans_pos
from Base import BasePlayer

from TDWidgets import TDPushButton
import Base

# addr = ("www.threedog.top",3003)
addr = ('127.0.0.1',3003)
chessboard = Base.chessboard
# 列表记录走棋坐标，用于悔棋操作
history = []

pygame.mixer.init()
pygame.mixer.music.load("source/luozisheng.wav")
sound = pygame.mixer.Sound("source/cuicu.wav")

def recv_sockdata(the_socket):
    '''从网络接收数据'''
    total_data = ""
    while True:
        data = the_socket.recv(1024).decode()
        if "END" in data:
            # 注意这里不去掉末尾的END，直接转发给另一端
            total_data += data[:data.index("END")]
            break
        total_data += data
    # print("total data:" , total_data)
    return total_data

class NetworkConfig(QWidget):
    '''
    配置网络信息的窗体
    '''

    # 传输数据的信号
    dataSignal = pyqtSignal(dict, name='data')
    #  连接中断的信号
    disconnectSignal = pyqtSignal()

    def __init__(self,main_window,parent=None):
        super().__init__(parent)
        self.setWindowTitle('网络配置')
        self.setWindowIcon(QIcon('source/icon.ico'))
        self.main_window = main_window

        self.game_window = None
        self.is_join = False
        self.keep_recv = True

        # 启动网络
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.connect(addr)
            self.is_connected = True
            threading.Thread(target=self.recv_data).start()
            self.dataSignal.connect(self.deal_data)
        except ConnectionRefusedError as e:
            QMessageBox.information(self,"消息","连接服务器失败，程序即将退出")
            raise e

        # 显示自己的昵称
        self.layout_h = QHBoxLayout()  # 水平布局1
        self.label_name = QLabel("昵称：",self)
        self.name_edit = QLineEdit(self)
        self.name_edit.setText("未命名")
        self.layout_h.addWidget(self.label_name,1)
        self.layout_h.addWidget(self.name_edit,3)

        # 玩家列表文字：
        self.layout_h1 = QHBoxLayout()  # 水平布局1
        self.label_players = QLabel("玩家列表：",self)
        self.refresh_btn = QPushButton("刷新",self)
        self.refresh_btn.clicked.connect(self.refresh)
        self.layout_h1.addWidget(self.label_players)
        self.layout_h1.addWidget(self.refresh_btn)

        # 加载玩家列表
        self.layout_h2 = QHBoxLayout()  # 水平布局1
        self.list_widget = QListWidget()
        self.refresh()  # 发送消息刷新用户列表
        self.list_widget.itemDoubleClicked.connect(self.item_double_clicked)
        self.layout_h2.addWidget(self.list_widget)

        self.layout_h3 = QHBoxLayout()  # 水平布局2
        self.join_btn = QPushButton("加入房间",self)
        self.join_btn.clicked.connect(self.join)
        self.battle_btn = QPushButton("选择对战",self)
        self.battle_btn.clicked.connect(self.battle)
        self.battle_btn.setEnabled(False)
        self.layout_h3.addWidget(self.join_btn)
        self.layout_h3.addWidget(self.battle_btn)

        self.layout_main = QVBoxLayout()  # 整体垂直布局
        self.layout_main.addLayout(self.layout_h)
        self.layout_main.addLayout(self.layout_h1)
        self.layout_main.addLayout(self.layout_h2)
        self.layout_main.addLayout(self.layout_h3)
        self.setLayout(self.layout_main)
        self.disconnectSignal.connect(self.dis_connect)

    def item_double_clicked(self,item):
        if not self.is_join:
            return  # 如果没有加入房间， 双击无效
        # print(item)
        # print(item.text())
        data = {
            "target": "server",
            "msg": "battle",
            "data": item.text()
        }
        self.sock.sendall((json.dumps(data) + " END").encode())

    def refresh(self):
        data = {
            "target":"server",
            "msg":"refresh",
            "data":""
        }
        self.sock.sendall((json.dumps(data)+" END").encode())

    def join(self):
        '''加入房间'''
        if not self.is_join:
            # listwidget_item = QListWidgetItem(self.name_edit.text(),self.list_widget)
            # self.list_widget.addItem(listwidget_item)
            data = {
                "target": "server",
                "msg": "join",
                "data": self.name_edit.text().strip()
            }
            # print(self.name_edit.text())
            self.sock.sendall((json.dumps(data) + " END").encode())
            self.battle_btn.setEnabled(True)
            self.name_edit.setEnabled(False)
            self.join_btn.setText("退出房间")
            self.is_join = True
        else:
            # 退出房间
            data = {
                "target": "server",
                "msg": "quit"
                # "data": self.name_edit.text()
            }
            self.sock.sendall((json.dumps(data) + " END").encode())
            self.battle_btn.setEnabled(False)
            self.name_edit.setEnabled(True)
            self.is_join = False
            self.join_btn.setText("加入房间")

    def battle(self):
        '''选择对战'''
        data = {
            "target": "server",
            "msg": "battle",
            "data": self.list_widget.currentItem().text()
        }
        self.sock.sendall((json.dumps(data) + " END").encode())

    def deal_data(self,json_data):
        '''数据处理'''
        if json_data['msg'] == 'player_list':
            # print(json_data['data'])
            self.list_widget.clear()
            for name in json_data['data']:
                self.widget_item = QListWidgetItem(name, self.list_widget)
                self.list_widget.addItem(self.widget_item)

        elif json_data['msg'] == 'get_name':  # 收到服务器分配的用户名
            self.name_edit.setText(json_data['data'])

        elif json_data['msg'] == "replay":
            if json_data['type'] == 'join':  # 加入游戏失败
                QMessageBox.information(self,"消息",json_data['data'])
                self.battle_btn.setEnabled(False)
                self.name_edit.setEnabled(True)
                self.is_join = False
                self.join_btn.setText("加入房间")

            if json_data['type'] == 'battle':  # 对战
                if json_data['data'] == True:
                    # 进入对战模式
                    self.game_window = NetworkPlayer(sock=self.sock,name=json_data['name'])
                    self.game_window.backSignal.connect(self.main_window.show)  # 点击后退按钮触发的信号
                    self.game_window.exitSignal.connect(self.main_window.game_over)  # 如果程序退出，触发的信号
                    self.game_window.show()
                    self.close()
                else :
                    QMessageBox.information(self,"提示",json_data['info'])

    def dis_connect(self):
        QMessageBox.information(self,"提示","与服务器断开连接，即将返回主界面")
        self.is_connected = False
        self.close()

    def recv_data(self):
        while self.keep_recv:
            try:
                res_data = recv_sockdata(self.sock)     # 本地收到数据
                json_data = json.loads(res_data)        # json转成字典
                # 在线程处理函数中不能直接进行界面的相关操作，所以用一个信号把数据发送出来
                self.dataSignal.emit(json_data)
                # self.deal_data(json_data,parent)

            except (ConnectionAbortedError,ConnectionResetError):
                # print("与服务器断开连接")
                self.disconnectSignal.emit()
                break  # 退出循环，线程结束

            except json.JSONDecodeError:
                # print("数据解析错误")
                print("Error Data:",res_data)

    def closeEvent(self, a0: QCloseEvent):
        if self.is_connected:
            data = {
                "target": "server",
                "msg": "quit"
            }
            self.keep_recv = False # 结束接收线程
            self.sock.sendall((json.dumps(data) + " END").encode())
        else:
            self.main_window.show()
        super().closeEvent(a0)

class NetworkPlayer(BasePlayer):
    dataSignal = pyqtSignal(dict,name='data')
    disconnectSignal = pyqtSignal()

    # 网络对战窗体
    def __init__(self,name,sock,parent=None):
        super().__init__(parent)
        self.name = name # 对方的昵称
        self.setWindowTitle('与 {} 对战中'.format(name))

        self.label_statu = QLabel("游戏状态：",self)
        self.label_statu.resize(100,20)
        self.label_statuvalue = QLabel("点击开始",self)
        self.label_statuvalue.resize(200,30)
        self.label_statuvalue.setAlignment(Qt.AlignTop)
        self.label_statu.move(630,200)
        self.label_statuvalue.move(690,204)

        # 清空棋盘
        global chessboard
        chessboard = [[None for i in range(0,19)] for i in range(0,19)]
        # 默认情况下游戏是结束状态， 通过开始按钮才可以触发
        self.is_over = True
        # 标识黑旗白旗
        self.color = 'w'
        # 是否是我的回合
        self.my_turn = False
        # 保持连接
        self.keep_connect = True
        # 三个按钮点击触发的函数
        self.restart_button.click_signal.connect(self.restart)
        self.huiqi_button.click_signal.connect(self.goback)
        self.renshu_button.click_signal.connect(self.lose)
        self.win_label = None

        self.cuicu_button = TDPushButton(self,"source/催促按钮_normal.png","source/催促按钮_hover.png","source/催促按钮_press.png",parent=self)
        self.cuicu_button.move(640,450)
        self.cuicu_button.click_signal.connect(self.cuicu)
        self.chess_pos.hide()  # 这个位置标识隐藏起来

        # 网络模块启动
        self.is_connected = True  # 默认情况下有连接
        self.is_listening = True  # 默认情况下启动了监听
        self.tcp_socket = sock
        self.label_statuvalue.setText("连接成功,\n点击开始")
        threading.Thread(target=self.recv_data, args=(self.tcp_socket, '')).start()

        self.dataSignal.connect(self.deal_data)
        self.disconnectSignal.connect(self.dis_connect)

    def dis_connect(self):
        QMessageBox.information(self,"提示","与服务器断开连接，即将返回主界面")
        self.back()

    def deal_data(self,data):
        '''
        对收到的数据进行处理
        '''
        print(data)
        if data['msg'] == 'action':

            if data['data'] == 'restart':
                result = QMessageBox.information(self,"消息","对方请求(重新)开始游戏，是否同意？",QMessageBox.Yes | QMessageBox.No)
                if result == QMessageBox.Yes:
                    data = {"msg": "replay", "data": True, "type":"restart","target":"player"}
                    self.tcp_socket.sendall((json.dumps(data) + " END").encode())
                    self.restart_func()
                    self.is_over = False
                    self.my_turn = True
                    if self.my_turn:
                        self.label_statuvalue.setText("己方回合")
                    else:
                        self.label_statuvalue.setText("对方回合")
                else:
                    data = {"msg": "replay", "data": False, "type": "restart","target":"player"}
                    self.tcp_socket.sendall((json.dumps(data) + " END").encode())
                    self.label_statuvalue.setText("点击开始")

            if data['data'] == 'lose':
                QMessageBox.information(self,"消息","对方认输")
                if self.my_turn:
                    self.win(color=self.color)
                else:
                    self.change_color()
                    self.win(color=self.color)

            if data['data'] == 'goback':
                result = QMessageBox.information(self, "消息", "对方请求悔棋，是否同意？", QMessageBox.Yes | QMessageBox.No)
                if result == QMessageBox.Yes:
                    data = {"msg": "replay", "data": True, "type": "goback","target":"player"}
                    self.tcp_socket.sendall((json.dumps(data) + " END").encode())
                    self.goback_func()
                    # self.is_over = False
                    if self.my_turn:
                        self.label_statuvalue.setText("己方回合")
                    else:
                        self.label_statuvalue.setText("对方回合")
                else:
                    data = {"msg": "replay", "data": False, "type": "goback","target":"player"}
                    self.tcp_socket.sendall((json.dumps(data) + " END").encode())
                    # self.label_statuvalue.setText("等待开始")

            if data['data'] == 'cuicu':
                # print(self.is_connected)
                if not self.is_connected:
                    return
                if self.is_over :
                    return
                # print("cuicu")
                sound.play()
                # pygame.mixer.music.load("source/luozisheng.wav")

            if data['data'] == 'ready':
                pass

            if data['data'] == 'exit':
                # 对方退出游戏  回到游戏大厅
                print("receive exit!!!")
                self.keep_connect = False
                QMessageBox.information(self,"消息","对方退出游戏对局，即将返回游戏主界面")
                self.back()
                # self.is_connected = False
                # self.is_listening = False
                # self.tcp_socket.close()
                # self.tcp_socket = None
            # print(data)

        elif data['msg'] == 'position':
            # print(data['data'])
            # 在对应位置落子
            pos = data['data']
            if chessboard[pos[1]][pos[0]] is not None:
                return  # 如果对应位置不为空，说明有棋子，则直接返回

            self.chess = Chessman(self.color, self)
            self.chess.move(QPoint(pos[0] * 30 + 50, pos[1] * 30 + 50))
            self.chess.show()
            pygame.mixer.music.play() # 播放声音
            self.logo_move()  # 移动小标
            self.change_color()

            # 在棋盘的对应位置放上棋子
            chessboard[pos[1]][pos[0]] = self.chess
            # 并且在列表中记录坐标
            history.append((pos[1], pos[0], self.chess.color))
            # 每次落子后，都判断一下胜负
            res = is_win(chessboard)
            if res:
                self.win(res) # 通过颜色，显示胜利的图片
                return
            self.my_turn = True
            self.label_statuvalue.setText("己方回合")

        elif data['msg'] == 'replay':
            if data['type'] == 'restart': # 重开回执
                if data['data'] == True:
                    self.restart_func()
                else:
                    QMessageBox.information(self,"消息","对方拒绝了你的请求")
                    self.label_statuvalue.setText("点击开始")
                    return
                if self.my_turn:
                    self.label_statuvalue.setText("己方回合")
                else:
                    self.label_statuvalue.setText("对方回合")
            if data['type'] == 'goback': # 悔棋回执

                if data['data'] == True:
                    self.is_over = False
                    self.goback_func()
                else:
                    QMessageBox.information(self,'消息','对方拒绝了你的请求')
                if self.my_turn:
                    self.label_statuvalue.setText("己方回合")
                else:
                    self.label_statuvalue.setText("对方回合")
                self.is_over = False

        elif data['msg'] == 'name':
            self.setWindowTitle('与 {} 对战中'.format(data['data']))

    def restart_func(self):
        # 清空所有棋子
        for j in range(0, 19):
            for i in range(0, 19):
                if chessboard[i][j] is not None:
                    chessboard[i][j].close()
                    chessboard[i][j] = None
        history.clear()  # 清空历史数组
        if self.is_over:  # 如果游戏已经结束
            if self.win_label is not None:
                self.win_label.close()
            self.win_label = None
            self.is_over = False
        self.chess_pos.hide()  # 这个位置标识隐藏起来

    def recv_data(self,sock,addr):
        self.is_connected = True  # 连接状态
        # print("start receiving data ...")
        while self.keep_connect:
            # print("start receiving data ...")
            try:
                res_data = recv_sockdata(sock)
            except (ConnectionAbortedError,ConnectionResetError):
                if self.keep_connect == False:
                    break
                # print("与服务器连接断开")
                # QMessageBox.information(self, "消息", "与服务器断开连接，即将退回到主界面")
                # QMessageBox.information(self,"提示","对方已经断开连接")
                self.is_connected = False
                # 连接断开
                # self.label_statuvalue.setText("对方断线,\n点击开始重试")
                self.disconnectSignal.emit()
                break
            try:
                data = json.loads(res_data)
                # print(type(data))
                # 在线程处理函数中不能直接进行界面的相关操作，所以用一个信号把数据发送出来
                self.dataSignal.emit(data)
            except json.decoder.JSONDecodeError as e:
                print(e)
                print("error data:\n"+res_data)
                continue
            # self.deal_data(data,parent)
        self.is_connected = False  # 连接断开
        self.tcp_socket.close()
        # self.back()

    def closeEvent(self, a0: QCloseEvent):
        self.keep_connect = False
        if self.tcp_socket is not None and self.is_connected == True:
            print("???")
            self.tcp_socket.sendall((json.dumps({"msg":"action","data":"exit","target":"player"})+" END").encode())
            self.tcp_socket.close()

        return super().closeEvent(a0)

    def win(self,color):
        '''
        黑旗胜利或者白棋胜利了
        '''
        if color == 'b':
            win_pic = QPixmap('source/黑棋胜利.png')
            self.label_statuvalue.setText("黑旗胜利")
        else:
            win_pic = QPixmap('source/白棋胜利.png')
            self.label_statuvalue.setText("白棋胜利")
        self.win_label = QLabel(parent=self)
        self.win_label.setPixmap(win_pic)
        self.win_label.resize(win_pic.size())
        self.win_label.move(50, 50)  # 显示游戏结束的图片
        self.win_label.show()
        self.is_over = True  # 游戏结束

    def mouseReleaseEvent(self, a0: QMouseEvent):
        if self.is_over: # 如果游戏已经结束，点击失效
            return
        if not self.my_turn:
            # print("not my turn")
            return
        # 如果点击在棋盘区域
        if a0.x() >= 50 and a0.x() <= 50+30*19 and a0.y() >= 50 and a0.y() <= 50+30*19:

            # 讲像素坐标转化成棋盘坐标，判断棋盘此位置是否为空
            pos = trans_pos(a0)
            if chessboard[pos[1]][pos[0]] is not None:
                return # 如果对应位置不为空，说明有棋子，则直接返回

            # 不为空，则生成棋子并显示
            self.chess = Chessman(self.color,self)
            self.chess.move(a0.pos())
            self.chess.show()
            pygame.mixer.music.play()  # 播放声音
            self.logo_move() # 移动小标
            self.change_color()

            # 在棋盘的对应位置放上棋子
            chessboard[pos[1]][pos[0]] = self.chess
            # 并且在列表中记录坐标
            history.append((pos[1], pos[0],self.chess.color))
            # 将坐标发送给另一方
            if self.tcp_socket is not None:
                data={"msg":"position","data":pos,"target":"player"}
                self.tcp_socket.sendall((json.dumps(data)+" END").encode())

            # 每次落子后，都判断一下胜负
            res = is_win(chessboard)
            if res:
                self.win(res) # 通过颜色，显示胜利的图片
                return
            self.my_turn = False
            self.label_statuvalue.setText("对方回合")

    def change_color(self):
        if self.color == 'w':
            self.color = 'b'
        else:
            self.color = 'w'

    def restart(self):
        '''
        重新开始游戏
        '''
        data = {"msg": "action", "data": "restart","target":"player"}
        self.tcp_socket.sendall((json.dumps(data) + " END").encode())
        self.label_statuvalue.setText("请求(重新)开始")
        self.my_turn = False

    def goback(self):
        '''
        悔棋按钮
        '''
        if self.my_turn is False:
            return # 如果是对方回合，不能悔棋
        if self.is_over:
            return
        if not self.is_connected:
            return
        else :
            data = {"msg": "action", "data": "goback","target":"player"}
            self.tcp_socket.sendall((json.dumps(data) + " END").encode())
            self.label_statuvalue.setText("请求悔棋")
            self.is_over = True

    def goback_func(self):
        if self.is_over:
            return None  # 如果游戏已经结束了
        if len(history) == 0:
            return None  # 没有落子，不能悔棋
        chess = history.pop(-1)
        chessboard[chess[0]][chess[1]].close()
        chessboard[chess[0]][chess[1]] = None
        # self.change_color()
        if len(history) == 0:
            return None  # 没有落子，不能悔棋
        chess = history.pop(-1)
        chessboard[chess[0]][chess[1]].close()
        chessboard[chess[0]][chess[1]] = None
        # self.change_color()
        self.chess_pos.hide()  # 这个位置标识隐藏起来

    def lose(self):
        '''
        认输按钮
        '''
        if self.is_over:
            return
        if not self.is_connected:
            return
        else :
            data = {"msg": "action", "data": "lose","target":"player"}
            self.tcp_socket.sendall((json.dumps(data) + " END").encode())
            self.label_statuvalue.setText("对方胜利")
            if self.my_turn:
                self.change_color()
                self.win(color=self.color)
            else:
                self.win(color=self.color)

    def cuicu(self):
        '''
        催促按钮
        '''
        if self.my_turn:
            return
        if self.is_over:
            return
        if not self.is_connected:
            return
        else:
            data = {"msg": "action", "data": "cuicu","target":"player"}
            self.tcp_socket.sendall((json.dumps(data) + " END").encode())
            # self.label_statuvalue.setText("请求(重新)开始")

    def logo_move(self):
        self.chess_pos.show()
        self.chess_pos.move(self.chess.pos())
        self.chess_pos.raise_()

    def __del__(self):
        # print("析构函数被执行")
        pass


import os.path
import sys
import json
import urllib2
import base64
import time
import md5

working_dir = os.path.dirname(sys.argv[0])
update_only = len(sys.argv) > 1 and 'only' in str(sys.argv[1]).lower()

class PatreonAPI(object):
    def __init__(self, access_token):
        super(PatreonAPI, self).__init__()
        self.access_token = access_token

    def fetch_user(self):
        return self.__get_json('current_user')

    def fetch_campaign_and_patrons(self):
        return self.__get_json('current_user/campaigns?include=rewards,creator,goals,pledges')

    def __get_json(self, suffix):
        url = "https://api.patreon.com/oauth2/api/{}".format(suffix)
        headers = {'Authorization': "Bearer {}".format(self.access_token)}
        request = urllib2.Request(url, headers=headers)
        contents = urllib2.urlopen(request).read()
        return json.loads(contents)

class MailChimpAPI(object):
    def __init__(self, api_key, list_id):
        super(MailChimpAPI, self).__init__()
        self.api_key = api_key
        self.list_id = list_id

    def create_tags_and_update_emails(self, email_map):
        tags_result = self.create_tags()
        emails_result = self.update_emails(email_map)
        return [tags_result, emails_result]

    def create_tags(self):
        create_operations = [self.craft_single_mergevar_creation('PTR_AMT', 'Patreon - Pledge Amount (Cents)', 'number'),
                             self.craft_single_mergevar_creation('PTR_NAME', 'Patreon - Full Name', 'text'),
                             self.craft_single_mergevar_creation('PTR_EXISTS', 'Patreon - Is Patron', 'radio')]
        return self.__batch_operations(create_operations)

    def craft_single_mergevar_creation(self, key, name, type_):
        single_tag_creation_body = {
            'tag': key,
            'type': type_,
            'name': name,
            'required': False,
            'public': False
        }
        if type_ == 'radio':
            single_tag_creation_body['options'] = {
                'choices': ['true', '']
            }
        return {
            'method': 'POST',
            'path': '/lists/{}/merge-fields'.format(self.list_id),
            'operation_id': 'create mergevar {}'.format(key),
            'body': json.dumps(single_tag_creation_body)
        }

    def update_emails(self, email_map):
        update_operations = [self.craft_single_email_update(email, patronage_amount_and_full_name['amount_cents'],
                                                              patronage_amount_and_full_name['full_name'])
                             for email, patronage_amount_and_full_name in email_map.items()]
        update_result = self.__batch_operations(update_operations)
        # TODO: we could http-GET update_result['response_body_url'], un-gzip & un-tar it, iterate over the responses, and retry any operation_id that had a non-200 status_code
        # ... or, we could just issue create requests for all the emails, and trust that the intersection of failures for the updates and failures for the creations is size 0
        creation_result = None
        if not update_only and update_result['errored_operations'] != 0:
            create_operations = [self.craft_single_email_creation(email, patronage_amount_and_full_name['amount_cents'],
                                                                  patronage_amount_and_full_name['full_name'])
                                 for email, patronage_amount_and_full_name in email_map.items()]
            creation_result = self.__batch_operations(create_operations)
        return [update_result, creation_result]

    def craft_single_email_update(self, email, patronage_amount, full_name):
        single_email_update_body = {
            'email_address': email,
            'merge_fields': {
                'PTR_EXISTS': 'true' if (patronage_amount > 0) else '',
                'PTR_AMT': patronage_amount,
                'PTR_NAME': full_name
            }
        }
        return {
            'method': 'PATCH',
            'path': self.path_for_email(email),
            'operation_id': 'update {}'.format(email),
            'body': json.dumps(single_email_update_body)
        }

    def craft_single_email_creation(self, email, patronage_amount, full_name):
        single_email_create_body = {
            'email_address': email,
            'status': 'subscribed',
            'merge_fields': {
                'PTR_EXISTS': 'true' if (patronage_amount > 0) else '',
                'PTR_AMT': patronage_amount,
                'PTR_NAME': full_name
            }
        }
        return {
            'method': 'POST',
            'path': self.path_for_email(email, is_create=True),
            'operation_id': 'update {}'.format(email),
            'body': json.dumps(single_email_create_body)
        }

    def datacenter(self):
        return "us{}".format(self.api_key.split('us')[-1])

    def path_for_email(self, email, is_create=False):
        basic_path = '/lists/{}/members'.format(self.list_id)
        if is_create:
            return basic_path
        else:
            email_md5 = md5.new(email.lower())
            return '{}/{}'.format(basic_path, email_md5.hexdigest())

    def __mailchimp_request(self, suffix, json_payload):
        url = "https://{}.api.mailchimp.com/3.0/{}".format(self.datacenter(), suffix)
        print('url',url)
        basic_auth = base64.encodestring('{}:{}'.format('user', self.api_key)).replace('\n', '')
        headers = {'Authorization': "Basic {}".format(basic_auth)}
        if json_payload:
            payload = json.dumps(json_payload)
            request = urllib2.Request(url, data=payload, headers=headers)
        else:
            request = urllib2.Request(url, headers=headers)
        try:
            contents = urllib2.urlopen(request).read()
            return json.loads(contents)
        except urllib2.HTTPError as e:
            print('http error',e.read())
            raise e

    def __batch_operations(self, operations):
        batch_request_state = self.__mailchimp_request('batches', {'operations': operations})
        batch_request_id = batch_request_state['id']
        while batch_request_state['status'] != 'finished':
            time.sleep(3)
            batch_request_state = self.__mailchimp_request('batches/{}'.format(batch_request_id), None)
        return batch_request_state

with open("{}/Resources/Config/config.csv".format(working_dir), 'r') as config_file:
    access_token, mailchimp_api_key, mailchimp_list_id = config_file.read().split(',')
    access_token = access_token.strip()
    mailchimp_api_key = mailchimp_api_key.strip()
    mailchimp_list_id = mailchimp_list_id.strip()
    results = [access_token, mailchimp_api_key, mailchimp_list_id]

    # # GET from Patreon
    patreon_api_client = PatreonAPI(access_token)
    response = patreon_api_client.fetch_campaign_and_patrons()
    main_campaign = response['data'][0]
    creator_id = main_campaign['relationships']['creator']['data']['id']
    included = response.get('included')
    pledges = [obj for obj in included
               if obj['type'] == 'pledge' and obj['relationships']['creator']['data']['id'] == creator_id]
    patron_ids = [pledge['relationships']['patron']['data']['id'] for pledge in pledges]
    patrons = [obj for obj in included
               if obj['type'] == 'user' and obj['id'] in patron_ids]
    patron_attributes_map = {patron['id']: patron['attributes']
                             for patron in patrons
                             if 'email' in patron['attributes']}
    patronage_map = {}
    for pledge in pledges:
        if pledge['relationships']['patron']['data']['id'] in patron_attributes_map:
            patron_attributes = patron_attributes_map[pledge['relationships']['patron']['data']['id']]
            if 'email' in patron_attributes and 'amount_cents' in pledge['attributes']:
                relevant_info = {
                    'amount_cents': pledge['attributes']['amount_cents']
                }
                if 'full_name' in patron_attributes:
                    relevant_info['full_name'] = patron_attributes['full_name']
                patronage_map[patron_attributes['email']] = relevant_info

    # POST and PATCH to MailChimp
    mailchimp_api_client = MailChimpAPI(api_key=mailchimp_api_key,
                                        list_id=mailchimp_list_id)
    email, amt_and_name = patronage_map.items()[0]
    # results = mailchimp_api_client.update_one_email(email, amt_and_name['amount_cents'], amt_and_name['full_name'])
    # results = mailchimp_api_client.create_tags()
    results = mailchimp_api_client.create_tags_and_update_emails(patronage_map)


# This program determines the quantity of ones in a binary number.

# From https://open.kattis.com/problems/bits

"""
Title: Bits
As we all know, it takes more energy to store binary numbers with lots of ones in them. Yraglac’s calculator has some batteries that are almost dead, and he’s concerned that the battery may run out as he types in a number.

The way the calculator processes numbers being entered is as follows. Initially, the calculator stores the number zero in a 32-bit internal register. As Yraglac types in each digit of his number, the register updates to store the number entered thus far. For example, when Yraglac enters the number 94, the register stores the number 9 (binary 1001) after the first key is pressed. When he presses the second key, the register clears itself and stores the number 94 (binary 1011110). What is the maximum number of one-bits in the register as Yraglac enters a number digit-by-digit?

Input
The first line contains a single integer 𝑇≤1000 giving the number of test cases. Each test case consists of a line with a single integer 𝑋 (0≤𝑋<231), the number Yraglac wants to enter.

Output
For each test case, output a single line containing the maximum number of one-bits in the storage register as the number 𝑋 is entered, digit by digit.

Sample Input 1:
6
1
2
3
4
10
94

Sample Output 1:
1
1
2
1
2
5
"""

caseQuantity = int(input())

results = []
for i in range(caseQuantity):
    onesPerDigit = []
    numChars = input()
    digitQuantity = len(numChars)

    for j in range(digitQuantity):
        num = numChars[0:j + 1]
        binStr = bin(int(num))
        result = 0

        for i in range(2, len(binStr)):
            if binStr[i] == '1':
                result += 1
        onesPerDigit.append(result)

    results.append(max(onesPerDigit))

for result in results:
    print(result)


import os
import json
import settings

_config = None

def config():
    if os.path.isfile(r'%s\env.json' % settings.BASE_DIR):
        with open(r'%s\env.json' % settings.BASE_DIR) as file:
            global _config
            _config = json.load(file)
            return _config
    else:
        raise NameError('Config-file is not found')

if __name__ == '__main__':
    config()


import socket
import sys
import math

def D(x):
    x = float(x)
    return str(math.log10(x))

def run_server(host="localhost", port=8884):

    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    server_address = (host, port)

    print >> sys.stderr, 'starting up server D on %s port %s' % server_address

    sock.bind(server_address)
    sock.listen(1)

    while True:
        print >> sys.stderr, 'server D: waiting for a connection'

        connection, client_address = sock.accept()
        try:
            print >> sys.stderr, 'client connected:', client_address
            while True:
                x = connection.recv(16)
                print >> sys.stderr, 'received "%s"' % x
                if x:
                    result = D(x)
                    connection.sendall(result)
                else:
                    break
        finally:
            connection.close()

if __name__ == "__main__":
    run_server()


# script meant to extract features from curated training data and put features into an input vector for ANN as well as create
# a target vector for labels

import os
import sys

import MusEEG
from MusEEG import eegData
import pandas as pandas
import numpy as np

sizeYes = 160*2
sizeNo = 160

def createTargetVector(objarray, *argv):
    labels = []
    targets = [0 for row in range(0, sizeYes+sizeNo)]
    index = 0
    for i in range(0, len(objarray)):
        print(objarray[i][0].filename)
        for j in range(0, len(objarray[i])):
            labels.append(objarray[i][j].filename)
            for arg in argv:
                if arg in objarray[i][j].filename:
                    targets[index] = i
                    index = index + 1
    return targets

# create object lists.  They are lists, not arrays
nogesture = [eegData() for i in range(0, sizeNo)]
gesture = [eegData() for i in range(0, sizeYes)]

splitsies = int(len(gesture)/5)

# load chunks
for i in range(0, len(nogesture)):
    nogesture[i].loadChunkFromTraining(os.path.join('trainbatch1', 'smallChunks', 'hugo_facialgestures'), 'neutral_' + str(i) + '.csv')

for j in range(0, splitsies):
    for i in range(0, int(160 / 5)):
         gesture[j].loadChunkFromTraining(os.path.join('trainbatch1','bigChunks'), 'smile_' + str(i) + '.csv')

for j in range(2*splitsies, 3*splitsies):
    for i in range(0, int(160 / 5)):
         gesture[j].loadChunkFromTraining(os.path.join('trainbatch1','bigChunks'), 'lookleft_' + str(i) + '.csv')

for j in range(3 * splitsies, 4 * splitsies):
    for i in range(0, int(160 / 5)):
         gesture[j].loadChunkFromTraining(os.path.join('trainbatch1','bigChunks'), 'lookright_' + str(i) + '.csv')

for j in range(4 * splitsies, 5 * splitsies):
    for i in range(0, int(160 / 5)):
         gesture[j].loadChunkFromTraining(os.path.join('trainbatch1','bigChunks'), 'scrunch_' + str(i) + '.csv')

for j in range( splitsies, 2 * splitsies):
    for i in range(0, int(160 / 5)):
         gesture[j].loadChunkFromTraining(os.path.join('trainbatch1','bigChunks'), 'hardblink_' + str(i) + '.csv')

gestures = [nogesture, gesture]

for i in range(0, len(gestures)):
    for j in range(0, len(gestures[i])):
        if i == 1:
            gestures[i][j].filename = 'yesgesture'
        elif i == 0:
            gestures[i][j].filename = 'nogesture'

targets = createTargetVector(gestures, 'nogesture', 'yesgesture')

##for smallchunks only. smallchunks are 1/8 of bigChunks (comment if you're working with big chunks)
for i in range(0, len(gestures)):
    gesture[i].cutChunk(eegData.smallchunkSize)

inputs = np.ndarray([sizeYes + sizeNo, 350])
inputindex = 0
for i in range(0, len(gestures)):
    for j in range(0, len(gestures[i])):
        gestures[i][j].wavelet()
        gestures[i][j].extractStatsFromWavelets()
        gestures[i][j].flattenIntoVector()
        inputs[inputindex][:] = gestures[i][j].inputVector
        inputindex = inputindex + 1

print(targets)

inputs = pandas.DataFrame(inputs)
targets = pandas.DataFrame(targets)

inputs.to_csv(os.path.join(MusEEG.parentDir, 'data', 'training', 'smallChunks_v5', 'inputs.csv'))
targets.to_csv(os.path.join(MusEEG.parentDir, 'data', 'training', 'smallChunks_v5', 'targets.csv'))


def maxSubArr(A):
    if not A:
        return 0
    curMax = A[0]
    res = A[0]
    for i in range(1, len(A)):
        curMax = max(A[i], curMax + A[i])
        res = max(res, curMax)
    return res

def minSubArr(A):
    if not A:
        return 0
    curMin = A[0]
    res = A[0]
    for i in range(1, len(A)):
        curMin = min(A[i], curMin + A[i])
        res = min(res, curMin)
    return res

A = [10, -5, 3, -2, -4, 8, 6, -6, 7, -10, -2, 5]
print(maxSubArr(A))


# -*- coding: utf-8 -*-
#
# Copyright 2012-2015 Spotify AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

import logging
from helpers import unittest

import luigi.notifications
import luigi.worker
from luigi import Parameter, RemoteScheduler, Task
from luigi.worker import Worker
from mock import Mock

luigi.notifications.DEBUG = True

class DummyTask(Task):
    param = Parameter()

    def __init__(self, *args, **kwargs):
        super(DummyTask, self).__init__(*args, **kwargs)
        self.has_run = False

    def complete(self):
        old_value = self.has_run
        self.has_run = True
        return old_value

    def run(self):
        logging.debug("%s - setting has_run", self.task_id)
        self.has_run = True

class MultiprocessWorkerTest(unittest.TestCase):

    def setUp(self):
        self.scheduler = RemoteScheduler()
        self.scheduler.add_worker = Mock()
        self.scheduler.add_task = Mock()
        self.worker = Worker(scheduler=self.scheduler, worker_id='X', worker_processes=2)

    def tearDown(self):
        self.worker.stop()

    def gw_res(self, pending, task_id):
        return dict(n_pending_tasks=pending,
                    task_id=task_id,
                    running_tasks=0, n_unique_pending=0)

    def test_positive_path(self):
        a = DummyTask("a")
        b = DummyTask("b")

        class MultipleRequirementTask(DummyTask):

            def requires(self):
                return [a, b]

        c = MultipleRequirementTask("C")

        self.assertTrue(self.worker.add(c))

        self.scheduler.get_work = Mock(side_effect=[self.gw_res(3, str(a)),
                                                    self.gw_res(2, str(b)),
                                                    self.gw_res(1, str(c)),
                                                    self.gw_res(0, None),
                                                    self.gw_res(0, None)])

        self.assertTrue(self.worker.run())
        self.assertTrue(c.has_run)

    def test_path_with_task_failures(self):
        class FailingTask(DummyTask):

            def run(self):
                raise Exception("I am failing")

        a = FailingTask("a")
        b = FailingTask("b")

        class MultipleRequirementTask(DummyTask):

            def requires(self):
                return [a, b]

        c = MultipleRequirementTask("C")

        self.assertTrue(self.worker.add(c))

        self.scheduler.get_work = Mock(side_effect=[self.gw_res(3, str(a)),
                                                    self.gw_res(2, str(b)),
                                                    self.gw_res(1, str(c)),
                                                    self.gw_res(0, None),
                                                    self.gw_res(0, None)])

        self.assertFalse(self.worker.run())

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


from __future__ import print_function
from scores import get_all_scores
from odds import get_spread

from datetime import datetime
import httplib2
import os

from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools

try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None

# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/sheets.googleapis.com-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/spreadsheets'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Google Sheets API Python Quickstart'

def get_credentials():
    """Gets valid user credentials from storage.

    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.

    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'sheets.googleapis.com-python-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else: # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials

def main():
    """Shows basic usage of the Sheets API.

    Creates a Sheets API service object and prints the names and majors of
    students in a sample spreadsheet:
    https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
                    'version=v4')
    service = discovery.build('sheets', 'v4', http=http,
                              discoveryServiceUrl=discoveryUrl)

    spreadsheetId = '1PELhCwHNgiirymW1kMx_-r2qOUB3cKeBUtjsAKnP_TY'
    spread = get_spread()
    if spread:
        col = get_col(spread['week'])
        rng = "'Betting Market Spread'!{}2:{}33".format(col, col)
        result = service.spreadsheets().values().update(
                spreadsheetId=spreadsheetId, range=rng,
                body={
                    'values': [spread['values']],
                     'majorDimension': "COLUMNS"
                    }, valueInputOption='RAW').execute()

    scores = get_all_scores()
    if scores:
        rng = "'Final Score Diff'!D2:T33"
        result = service.spreadsheets().values().update(
                spreadsheetId=spreadsheetId, range=rng,
                body={
                    'values': scores,
                     'majorDimension': "COLUMNS"
                    }, valueInputOption='RAW').execute()

    result = service.spreadsheets().values().update(
            spreadsheetId=spreadsheetId, range="'Betting Market Spread'!B34",
            body={
                'values': [[datetime.now().strftime('%b %d, %H:%M')]],
                }, valueInputOption='RAW').execute()

def get_col(week):
    return chr(week + 2 + ord('A'))
    return "{}2:{}33".format(col, col)

if __name__ == '__main__':
    main()


"""
Capstone project.  Code to run on LAPTOP (not EV3 robot).

Contains special functions

Author: Jack Wilson
"""
from tkinter import ttk
import rosebot
import time

def color_sensor_frame(window, mqtt_sender):
    frame = ttk.Frame(window, padding=10, borderwidth=5, relief="ridge")
    frame.grid()

    frame_label = ttk.Label(frame, text="Color sensor frame")
    follow_line_button = ttk.Button(frame, text="Follow the black line")
    speed_label = ttk.Label(frame, text="Input desired speed here")
    speed_entry = ttk.Entry(frame, width=4)
    frame_label.grid(row=0, column=1)
    speed_label.grid(row=1, column=1)
    speed_entry.grid(row=2, column=1)
    follow_line_button["command"] = lambda: follow_line(speed_entry.get(), mqtt_sender)
    follow_line_button.grid(row=3, column=1)
    return frame

def follow_line(speed, mqtt_sender):
    color_sensor = rosebot.ColorSensor("3")
    original = color_sensor.get_reflected_light_intensity()
    error = color_sensor.get_reflected_light_intensity() - original
    print("forward")
    mqtt_sender.send_message("forward", [speed, speed])
    mistakes = 0
    if error > 0:
        if mistakes % 2 == 0:
            v = speed - error
            print("turn")
            mqtt_sender.send_message("forward", [v, speed])
        else:
            v = speed - error
            print("turn")
            mqtt_sender.send_message("forward", [speed, v])

def move_object():
    arm = rosebot.ArmAndClaw()
    arm.raise_arm()


#!/usr/bin/env python

__author__ = "Colin Reese"
__copyright__ = "Copyright 2014, Interface Innovations"
__credits__ = ["Colin Reese"]
__license__ = "Apache 2.0"
__version__ = "1.0"
__maintainer__ = "Colin Reese"
__email__ = "support@interfaceinnovations.org"
__status__ = "Development"

# This library is for control functions

#######################################################
## Control Functions
#######################################################

def runalgorithm(controldatabase, recipedatabase, channelname):
    from pilib import sqlitequery, datarowtodict, gettimestring, timestringtoseconds
    import time

    message = ''

    # get our details of our channel
    channeldata = sqlitequery(controldatabase, 'select * from channels where name=' + "'" + channelname + "'")[0]
    channeldict = datarowtodict(controldatabase, 'channels', channeldata)
    # check to see if we are running a recipe

    controlrecipename = channeldict['controlrecipe']
    if controlrecipename and controlrecipename != 'none':

        # Get recipe details
        # If recipes get too big, we'll just get
        # a couple stages. For now, we make a
        # dictionary array

        #print('we are in recipe ' + controlrecipename)
        #print(recipedatabase)

        recipedata = sqlitequery(recipedatabase, 'select * from \'' + controlrecipename + '\'')
        recipedictarray = []

        for stage in recipedata:
            recipedict = datarowtodict(recipedatabase, controlrecipename, stage)
            recipedictarray.append(recipedict)

        # get current stage
        currentstagenumber = int(channeldict['recipestage'])
        #print('current stage is ' + str(currentstagenumber) )

        # Get data for current stage
        stagefound = False
        for stage in recipedictarray:
            if int(stage['stagenumber']) == currentstagenumber:
                currentstage = stage
                stagefound = True
                break
        if stagefound:
            #print("stage found")
            pass
        else:
            print('error. stage not found.')

        # Check to see if we need to move to next stage
        currenttime = time.time()
        #print('Time')
        #print(currenttime)
        #print(gettimestring(currenttime))

        if currentstagenumber == 0 or currenttime - timestringtoseconds(channeldict['recipestagestarttime']) > int(
                currentstage['stagelength']):
            print('stage time expired for stage ' + str(currentstagenumber) + '. Checking on stage advance. ')

            # Advance stage if there is another stage. Otherwise
            # update channel to be off a recipe. We assume explicitly
            # that the stages are sequential integers.

            nextstagenumber = currentstagenumber + 1

            # look for next stage

            stagefound = False
            for stage in recipedictarray:
                if int(stage['stagenumber']) == nextstagenumber:
                    nextstage = stage
                    stagefound = True
                    break

            if stagefound:
                print(' Next stage was found. Setting next stage. ')
                if currentstagenumber == 0:
                    print("Stagenumber is 0. Setting recipe start time. ")

                    # Set recipe start time
                    sqlitequery(controldatabase, 'update channels set recipestarttime=\'' + gettimestring(
                        currenttime) + '\' where name=\'' + channelname + '\'')

                # Set stage to new stage number
                sqlitequery(controldatabase, 'update channels set recipestage=\'' + str(
                    nextstagenumber) + '\' where name=\'' + channelname + '\'')

                # Set setpointvalue
                sqlitequery(controldatabase, 'update channels set setpointvalue=\'' + str(
                    nextstage['setpointvalue']) + '\' where name=\'' + channelname + '\'')

                # Set stage start time to now
                sqlitequery(controldatabase, 'update channels set recipestagestarttime=\'' + gettimestring(
                    currenttime) + '\' where name=\'' + channelname + '\'')

                # Set new controlalgorithm
                sqlitequery(controldatabase, 'update channels set controlalgorithm=\'' + nextstage[
                    'controlalgorithm'] + '\' where name=\'' + channelname + '\'')

            else:

                # Take channel off recipe
                sqlitequery(controldatabase,
                            'update channels set controlrecipe=\'none\' where name=\'' + channelname + '\'')
                sqlitequery(controldatabase, 'update channels set recipestate=\'0\' where name=\'' + channelname + '\'')

                sqlitequery(controldatabase,
                            'update channels set recipestage=\'0\' where name=\'' + channelname + '\'')

                # if lengthmode is setpoint

                # get current stage

                # check stage start against stage length
                # and current time

                # move to next stage if time and revise setpoint

                # adjust setpoint based on stage

                # set action based on setpoint

    else:
        # make sure we're not on recipe and on stage 0
        sqlitequery(controldatabase,
                    'update channels set controlrecipe=\'none\' where name=\'' + channelname + '\'')
        sqlitequery(controldatabase, 'update channels set recipestate=\'0\' where name=\'' + channelname + '\'')

        sqlitequery(controldatabase,
                    'update channels set recipestage=\'0\' where name=\'' + channelname + '\'')

    algorithm = channeldict['controlalgorithm']
    setpointvalue = float(channeldict['setpointvalue'])
    controlvalue = float(channeldict['controlvalue'])

    algorithmrows = sqlitequery(controldatabase, 'select * from controlalgorithms where name=' + "'" + algorithm + "'")
    algorithmrow = algorithmrows[0]
    algorithm = datarowtodict(controldatabase, 'controlalgorithms', algorithmrow)
    type = algorithm['type']

    if type == 'on/off with deadband':
        #print(type)
        deadbandhigh = algorithm['deadbandhigh']
        deadbandlow = algorithm['deadbandlow']
        if setpointvalue > (controlvalue + deadbandhigh):
            action = 100
        elif setpointvalue < (controlvalue - deadbandlow):
            action = -100
        else:
            action = 0
    #print('setpoint' + str(setpoint))
    #print('controlvalue' + str(controlvalue))
    #print(action)
    #print(message)
    return [action, message]

# I think we need a channel class here. Not used yet, but in development.

class channel:
    def __init__(self,propertydict):
        for key,value in propertydict.items():
            setattr(self,key,value)

    def setsetpoint(self,setpointvalue):
        from pilib import controldatabase, sqlitequery
        sqlitequery(controldatabase, 'update channels set setpointvalue=\'' + str(setpointvalue) + '\' where name=\'' + channel.name + '\'')

    def setaction(self,action):
         from pilib import controldatabase, sqlitequery
         sqlitequery(controldatabase,
            'update channels set action = \'' + str(action) + '\' where name = \'' + channel.name + '\'')

    def setcontrolinput(self,inputid):
        from pilib import controldatabase, sqlitequery
        sqlitequery(controldatabase,
                'update channels set controlinput = \'' + inputid + '\' where name = \'' + channel.name + '\'')

    def getaction(self):
        from pilib import controldatabase, sqlitedatumquery
        self.action = sqlitedatumquery(controldatabase,'select action from channels where name=\'' + channel.name + '\'')

    def getsetpointvalue(self):
        from pilib import controldatabase, sqlitedatumquery
        self.setpointvalue = sqlitedatumquery(controldatabase, 'select setpointvalue from channels where name=\'' + channel.name + '\'')

    def incsetpoint(self):
        self.getsetpointvalue()
        self.setsetpoint(self.setpointvalue+1)

    def decsetpoint(self):
        self.getsetpointvalue()
        self.setsetpoint(self.setpointvalue-1)

    def getmode(self):
        from pilib import controldatabase, sqlitedatumquery
        self.mode = sqlitedatumquery(controldatabase, 'select mode from channels where name=\'' + channel.name + '\'')

    def setmode(self,mode):
        from pilib import controldatabase, sqlitequery
        sqlitequery(controldatabase, 'update channels set mode=\'' + str(mode) + '\' where name=\'' + channel.name + '\'')

    def togglemode(self,mode):
        from pilib import controldatabase, sqlitedatumquery
        self.getmode()
        if self.mode == 'manual':
            self.mode = 'auto'
        else:
            self.mode = 'manual'

# This works fine, for now.

def setsetpoint(controldatabase, channelname, setpointvalue):
    from pilib import sqlitequery

    sqlitequery(controldatabase, 'update channels set setpointvalue=\'' + str(
        setpointvalue) + '\' where name=\'' + channelname + '\'')

def setaction(controldatabase, channelname, action):
    from pilib import sqlitequery

    sqlitequery(controldatabase,
                'update channels set action = \'' + str(action) + '\' where name = \'' + channelname + '\'')

def setcontrolinput(controldatabase, channelname, inputid):
    from pilib import sqlitequery

    sqlitequery(controldatabase,
                'update channels set controlinput = \'' + inputid + '\' where name = \'' + channelname + '\'')

def setcontrolvalue(controldatabase, channelname, controlvalue):
    from pilib import sqlitequery

    sqlitequery(controldatabase,
                'update channels set controlvalue = \'' + str(controlvalue) + '\' where name = \'' + channelname + '\'')

def getaction(controldatabase, channelname):
    from pilib import sqlitequery

    action = sqlitequery(controldatabase, 'select action from channels where name=\'' + channelname + '\'')[0][0]
    return action

def getsetpoint(controldatabase, channelname):
    from pilib import sqlitequery

    currentsetpoint = \
        sqlitequery(controldatabase, 'select setpointvalue from channels where name=\'' + channelname + '\'')[0][0]
    return currentsetpoint

def decsetpoint(controldatabase, channelname):
    currentsetpoint = getsetpoint(controldatabase, channelname)
    newsetpoint = currentsetpoint - 1
    setsetpoint(controldatabase, channelname, newsetpoint)

def incsetpoint(controldatabase, channelname):
    currentsetpoint = getsetpoint(controldatabase, channelname)
    newsetpoint = currentsetpoint + 1
    setsetpoint(controldatabase, channelname, newsetpoint)

def setmode(controldatabase, channelname, mode):
    from pilib import sqlitequery

    sqlitequery(controldatabase, 'update channels set mode=\'' + mode + '\' where name=\'' + channelname + '\'')

    # set action to 0 if we switch to manual
    if mode == 'manual':
        setaction(controldatabase, channelname, 0)

def getmode(controldatabase, channelname):
    from pilib import sqlitequery

    mode = sqlitequery(controldatabase, 'select mode from channels where name=\'' + channelname + '\'')[0][0]
    return mode

def togglemode(controldatabase, channelname):
    from pilib import sqlitequery
    from controllib import setaction

    curmode = getmode(controldatabase, channelname)
    if curmode == 'manual':
        newmode = 'auto'
    else:
        newmode = 'manual'
        setaction(controldatabase, channelname, 0)

    setmode(controldatabase, channelname, newmode)

def checkifenableready(outputname, outputs):
    from time import time
    from pilib import timestringtoseconds

    # Find the variables we want
    for output in outputs:
        if output['name'] == outputname:
            offtime = timestringtoseconds(output['offtime'])
            minofftime = output['minofftime']

    if time() - offtime > minofftime:
        return True
    else:
        return False

def checkifdisableready(outputname, outputs):
    from time import time
    from pilib import timestringtoseconds

    # Find the variables we want
    for output in outputs:
        if output['name'] == outputname:
            minontime = output['minontime']
            ontime = timestringtoseconds(output['ontime'])

    if time() - ontime > minontime:
        return True
    else:
        return False

def setposout(controldatabase, channelname, outputname):
    from pilib import sqlitequery

    sqlitequery(controldatabase,
                'update channels set positiveoutput=\'' + outputname + '\' where name=\'' + channelname + '\'')

def setnegout(controldatabase, channelname, outputname):
    from pilib import sqlitequery

    sqlitequery(controldatabase,
                'update channels set negativeoutput=\'' + outputname + '\' where name=\'' + channelname + '\'')

def setalgorithm(controldatabase, channelname, algorithm):
    from pilib import sqlitequery

    sqlitequery(controldatabase,
                'update channels set controlalgorithm=\'' + algorithm + '\' where name=\'' + channelname + '\'')

def setrecipe(controldatabase, channelname, recipe, startstage=0):
    from pilib import sqlitequery

    sqlitequery(controldatabase,
                'update channels set controlrecipe=\'' + recipe + '\' where name=\'' + channelname + '\'')
    sqlitequery(controldatabase,
                'update channels set recipestage=\'' + str(startstage) + '\' where name=\'' + channelname + '\'')

def setchannelenabled(controldatabase, channelname, newstatus):
    from pilib import sqlitequery

    sqlitequery(controldatabase, 'update channels set enabled=\'' + newstatus + '\' where name=\'' + channelname + '\'')

def setchanneloutputsenabled(controldatabase, channelname, newstatus):
    from pilib import sqlitequery

    sqlitequery(controldatabase,
                'update channels set outputsenabled=\'' + newstatus + '\' where name=\'' + channelname + '\'')

def disablealloutputs():
    from pilib import controldatabase, readalldbrows

    outputs = readalldbrows(controldatabase,'outputs')

    querylist=[]
    for output in outputs:
        querylist.append('update outputs set enabled=0 where name=\'' + output['name'] + '\'')

    print('all outputs disabled')

def turnoffgpios(GPIOnumberlist):
    import RPi.GPIO as GPIO

    GPIO.setmode(GPIO.BCM)

    for GPIOnumber in GPIOnumberlist:
        GPIO.setup(int(GPIOnumber), GPIO.OUT)
        GPIO.output(int(GPIOnumber), False)


from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

def simple_neurou(dataset):

    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])

    h1=tf.layers.dense(x,units=10)
    # output
    y=tf.nn.softmax(h1)
    # loss func
    loss_func = tf.reduce_mean(-tf.reduce_sum(y_ *
                                              tf.log(y), reduction_indices=[1]))
    # optimizer
    train = tf.train.GradientDescentOptimizer(0.5).minimize(loss_func)

    with tf.Session() as sess:
        # init variables
        sess.run(tf.global_variables_initializer())
        # train model
        for i in range(3000):
            batch_x, batch_y = dataset.train.next_batch(100)
            sess.run(train, feed_dict={x: batch_x, y_: batch_y})
            if i % 100 == 0:
                print(i)
        # assessment
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        accuracy=accuracy.eval({x: dataset.test.images, y_: dataset.test.labels})
        print(accuracy)

def mut_neurou(dataset):

    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])
    dropout_num = tf.placeholder(tf.float32)

    dense=tf.layers.dense(x,units=784)
    layer_1 = tf.nn.relu(dense)
    dropout = tf.nn.dropout(layer_1, dropout_num)
    dense = tf.layers.dense(dropout,units=10)
    y = tf.nn.softmax(dense)

    loss = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))
    train = tf.train.AdagradOptimizer(0.3).minimize(loss)

    with tf.Session() as sess:
        # init variables
        sess.run(tf.global_variables_initializer())
        # train model
        for i in range(3000):
            batch_x, batch_y = dataset.train.next_batch(100)
            sess.run(train, feed_dict={x: batch_x,
                                       y_: batch_y, dropout_num: 0.75})
            if i % 100 == 0:
                print(i)
        # assessment
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        accuracy = accuracy.eval({x: dataset.test.images,
                                            y_: dataset.test.labels, dropout_num: 1.0})
        print(accuracy)

def cnn_net(dataset):

    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])
    x_image = tf.reshape(x, [-1, 28, 28, 1])
    # layer 1
    conv1 = tf.layers.conv2d(x_image, filters=32, kernel_size=[
                             5, 5], padding='SAME', activation=tf.nn.relu)
    pool1 = tf.layers.max_pooling2d(conv1, pool_size=[2, 2], strides=2)
    # layer 2
    conv2 = tf.layers.conv2d(pool1, filters=64, kernel_size=[
                             5, 5], padding='SAME', activation=tf.nn.relu)
    pool2 = tf.layers.max_pooling2d(conv2, pool_size=[2, 2], strides=2)

    tem = tf.reshape(pool2, [-1, 7*7*64])
    # layer 3
    dense = tf.layers.dense(tem, units=1024, activation=tf.nn.relu)
    # layer 4
    dropout = tf.nn.dropout(dense, 0.5)
    # output layer
    dense = tf.layers.dense(dropout, units=10)
    y_out = tf.nn.softmax(dense)
    # loss and Optimizer
    loss = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_out),
                                         reduction_indices=[1]))
    train = tf.train.AdamOptimizer(0.0001).minimize(loss)

    with tf.Session() as sess:
        # init variables
        sess.run(tf.global_variables_initializer())
        # train model
        for i in range(10000):
            batch_x, batch_y = dataset.train.next_batch(50)
            sess.run(train, feed_dict={x: batch_x,
                                       y_: batch_y})
            if i % 100 == 0:
                print(i)
        # assessment
        correct_prediction = tf.equal(tf.argmax(y_out, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        accuracy = accuracy.eval(feed_dict={x: dataset.test.images,
                                            y_: dataset.test.labels})
        print(accuracy)

if __name__ == '__main__':
    # 1.Import data
    dir = '/home/guangxin/ubuntu_workspace/data/mnist'
    mnist = input_data.read_data_sets(dir, one_hot=True)

    # simple_neurou(mnist)
    mut_neurou(mnist)
    # cnn_net(mnist)


from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),

    # Authentication APIs
    path('api-auth/', include('rest_framework.urls')),
    path('dj-rest-auth/', include('dj_rest_auth.urls')),
    path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),

    # path('', include('task_management_app.urls')),
    path('api/', include('masters.apis.urls')),
    path('api/', include('product_management.apis.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)


import numpy as np
import random

class ReplayBuffer(object):

    def __init__(self, size, env):
        #number of samples stored total at a time
        self.size = size
        self.env = env
        #how many time steps to store a particular transition sample
        self.store_for_steps = 1
        #indices of the samples
        self.next_idx = 0
        self.num_in_buffer = 0
        #
        #storage of transition info
        self.obs_state = np.empty((self.size,self.env.state.shape[0],self.env.state.shape[1]))
        self.obs_action = np.empty((self.size),dtype=int)
        self.obs_reward = np.empty((self.size))
        #self.next_obs_state = np.empty((self.size,3))
        self.obs_done = np.empty((self.size),dtype=bool)

    #check whether the required batch size can be managed
    def can_sample(self, batch_size):
        return batch_size + 1 <= self.num_in_buffer

    def sample_n_unique(self, sampling_func, batch_size):
        #returns an array of (batch_size) unique indices to be used for sampling
        idxes =[]
        while len(idxes) < batch_size:
            a = sampling_func()
            if a not in idxes:
                idxes.append(a)
        #print('idxs',idxes)
        return idxes
    #
    #
    def sample(self, batch_size):
        #raise an error if not true
        assert self.can_sample(batch_size)

        idxes = self.sample_n_unique(
            lambda: random.randint(0, self.num_in_buffer - 2), batch_size)

        states = self.obs_state[idxes]
        actions = self.obs_action[idxes]
        next_states = [ self.obs_state[idx+1] for idx in idxes]
        rewards = self.obs_reward[idxes]
        done_vals = self.obs_done[idxes]

        return states, actions, rewards, next_states, done_vals

    def store(self, current_st, action, reward,  done, prefill):

        self.obs_state[self.next_idx] = current_st
        self.obs_action[self.next_idx] = action
        self.obs_reward[self.next_idx] = reward
        self.obs_done[self.next_idx] = done

        self.next_idx +=1

        #implementing the preriodicity of a ring buffer
        self.next_idx = self.next_idx % self.size

        #if not prefill:
         #   self.next_idx = self.next_idx + 100

        #update info on how filled is the buffer
        self.num_in_buffer = min(self.size, self.num_in_buffer + 1)

    def reset(self):
        self.next_idx = 0
        self.num_in_buffer = 0
        #
        #storage of transition info
        self.obs_state = np.empty((self.size,self.env.state.shape[0],self.env.state.shape[1]))
        self.obs_action = np.empty((self.size),dtype=int)
        self.obs_reward = np.empty((self.size))
        #self.next_obs_state = np.empty((self.size,3))
        self.obs_done = np.empty((self.size),dtype=bool)


_base_ = './retinanet_r50_fpn_1x_coco.py'
# learning policy
lr_config = dict(step=[16, 22])
total_epochs = 24
model = dict(
    roi_head=dict(
        bbox_head=dict(num_classes=2),
        mask_head=dict(num_classes=2)))
dataset_type = 'COCODataset'
classes = ('mif', 'ov')
data = dict(
    train=dict(
        img_prefix='balloon/train/',
        classes=classes,
        ann_file='balloon/train/annotation_coco.json'),
    val=dict(
        img_prefix='balloon/val/',
        classes=classes,
        ann_file='balloon/val/annotation_coco.json'),
    test=dict(
        img_prefix='balloon/val/',
        classes=classes,
        ann_file='balloon/val/annotation_coco.json'))


# coding=utf-8
import socket

client = socket.socket()
client.connect(('127.0.0.1', 8080))
while True:
    data = client.recv(1024)
    print(data)
    send_server = raw_input('client :')
    client.send(send_server)
    if send_server == 'exit':
        break


#!/usr/bin/env python
description = "> field efficiency  "
usage = "%prog   namefile]\n"

import os
import string
import dlt40
import sys
import numpy as np
import pylab as plt
from optparse import OptionParser
plt.ion()

if __name__ == "__main__":   # main program
    parser = OptionParser(usage=usage, description=description, version="%prog 1.0")

    option, args = parser.parse_args()
    if len(args) < 1:
        sys.argv.append('--help')
    option, args = parser.parse_args()

    ascifile = args[0]
    data = np.genfromtxt(ascifile,'str')
    targetid, candidateid, diff, ZP, magbest, exptime, xpos, ypos = zip(*data)

    targetid = np.array(targetid)
    candidateid =  np.array(candidateid)
    diff =         np.array(diff)
    ZP =           np.array(ZP,float)
    magbest =      np.array(magbest,float)
    exptime =      np.array(exptime)
    xpos =         np.array(xpos)
    ypos =         np.array(ypos)
    candidateid[candidateid=='NULL']=0
    candidateid[candidateid=='None']=0
    candidateid =  np.array(candidateid,float)

    mag = ZP+magbest-np.log10(60)*2.5
    mag1 = mag[candidateid>0]
    mag2 = mag[candidateid>-1]
    mag3 = mag[candidateid>-999999]

    bins=np.arange(12,23,.5)

    plt.figure()

    n1, bins, patches = plt.hist(mag1, bins, normed=0, facecolor='green', alpha=0.75)
    n2, bins, patches = plt.hist(mag2, bins, normed=0, facecolor='red', alpha=0.75)

    plt.clf()
    plt.ylabel('efficiency')
    plt.xlabel(' magnitude')

    xx = bins[0:-1]+(bins[1]-bins[0])/2
    yy = n1/n2
    plt.ylim(-0.01,1.1)
    plt.plot(xx,yy,'-r')
    plt.plot(xx,yy,'or')


# import the necessary packages
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from keras.models import Sequential
from keras.layers.core import Dense, Dropout
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.layers import Flatten
from keras.optimizers import SGD
import keras
from imutils import paths
import matplotlib.pyplot as plt
import numpy as np
import argparse
import random
import pickle
import cv2
import os

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
    help="path to input dataset of images")
ap.add_argument("-m", "--model", required=True,
    help="path to output trained model")
ap.add_argument("-l", "--label-bin", required=True,
    help="path to output label binarizer")
ap.add_argument("-p", "--plot", required=True,
    help="path to output accuracy/loss plot")
args = vars(ap.parse_args())

num_classes = 10

# initialize the data and labels
print("[INFO] loading images...")
data = []
labels = []

# grab the image paths and randomly shuffle them
imagePaths = sorted(list(paths.list_images(args["dataset"])))
random.seed(42)
random.shuffle(imagePaths)

# loop over the input images
for imagePath in imagePaths:
    print(imagePath)
    # load the image, resize the image to be 32x32 pixels (ignoring
    # aspect ratio), flatten the image into 32x32x3=3072 pixel image
    # into a list, and store the image in the data list
    image = cv2.imread(imagePath,0)
    image = cv2.resize(image, (32, 32))
    image = np.reshape(image, (32, 32, 1))
    data.append(image)

    # extract the class label from the image path and update the
    # labels list
    label = imagePath.split(os.path.sep)[-2]
    labels.append(label)

# scale the raw pixel intensities to the range [0, 1]
data = np.array(data, dtype="float") / 255.0
labels = np.array(labels)
print(labels)

# partition the data into training and testing splits using 75% of
# the data for training and the remaining 25% for testing
(trainX, testX, trainY, testY) = train_test_split(data,
    labels, test_size=0.2, random_state=42)

print(trainX.shape)
print(testX.shape)
print(trainY.shape)
print(testY.shape)

# convert the labels from integers to vectors (for 2-class, binary
# classification you should use Keras' to_categorical function
# instead as the scikit-learn's LabelBinarizer will not return a
# vector)
lb = LabelBinarizer()
trainY = lb.fit_transform(trainY)
testY = lb.transform(testY)

# Initialising the CNN
model = Sequential()

model.add(Conv2D(32, (3, 3), input_shape = (32,32,1), activation = 'relu'))

model.add(Conv2D(32, (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(Conv2D(64, (3, 3), activation = 'relu'))
model.add(MaxPooling2D(pool_size = (2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())

model.add(Dense(units = 128, activation = 'relu'))
model.add(Dropout(0.5))
model.add(Dense(units = num_classes, activation = 'softmax'))

# initialize our initial learning rate and # of epochs to train for
INIT_LR = 0.0001
EPOCHS = 50

# Compiling the CNN
opt = keras.optimizers.rmsprop(lr=INIT_LR, decay=1e-6)
model.compile(optimizer = opt, loss = 'categorical_crossentropy', metrics = ['accuracy'])

# Part 2 - Fitting the CNN to the images
H = model.fit(trainX, trainY, validation_data=(testX, testY), epochs=EPOCHS, batch_size=32)

# save the model
model.save(args["model"])
# evaluate the network
print("[INFO] evaluating network...")
predictions = model.predict(testX, batch_size=32)
print(classification_report(testY.argmax(axis=1),
    predictions.argmax(axis=1), target_names=lb.classes_))

# plot the training loss and accuracy
N = np.arange(0, EPOCHS)
plt.style.use("ggplot")
plt.figure()
plt.plot(N, H.history["loss"], label="train_loss")
plt.plot(N, H.history["val_loss"], label="val_loss")
plt.plot(N, H.history["acc"], label="train_acc")
plt.plot(N, H.history["val_acc"], label="val_acc")
plt.title("Training Loss and Accuracy (Simple NN)")
plt.xlabel("Epoch #")
plt.ylabel("Loss/Accuracy")
plt.legend()
plt.savefig(args["plot"])

# save label binarizer to disk
print("[INFO] serializing network and label binarizer...")

f = open(args["label_bin"], "wb")
f.write(pickle.dumps(lb))
f.close()


# [서로소 집합 자료구조: 경로 압축]

# 찾기(Find) 함수를 최적화하기 위한 방법으로 경로 압축(Path Compression)을 이용할 수 있습니다.
#   - 찾기(Find) 함수를 재귀적으로 호출한 뒤에 부모 테이블 값을 바로 갱신합니다.

# 특정 원소가 속한 집합을 찾기
def find_parent(parent, x):
    # 루트 노드가 아니라면, 루트 노드를 찾을 때까지 재귀적으로 호출
    if parent[x] != x:
        parent[x] = find_parent(parent, parent[x])
    return parent[x]

# 경로 압축 기법을 적용하면 각 노드에 대하여 찾기(Find) 함수를 호출한 이후에
#   해당 노드의 루트 노드가 바로 부모 노드가 됩니다.
# 동일한 예시에 대해서 모든 합집합(Union) 함수를 처리한 후 각 원소에 대하여
#   찾기(Find) 함수를 수행하면 다음과 같이 부모 테이블이 갱신됩니다.
# 기본적인 방법에 비하여 시간 복잡도가 개선됩니다.
# 노드 번호     1   2   3   4   5
# 부모          1   1   1   1   1

# [서로소 집합 자료구조 구현: 경로 압축]

# 특정 원소가 속한 집합을 찾기
def find_parent(parent, x): # parent : 부모 테이블, x : 노드 번호
    # 루트 노드를 찾을 때까지 재귀 호출
    if parent[x] != x: # 노드 번호와 노드 번호에 입력되어 있는 부모 번호가 다르면
        parent[x] = find_parent(parent, parent[x]) # 입력되어 있는 부모 번호로 재귀 호출
    return parent[x]

# 두 원소가 속한 집합을 합치기
def union_parent(parent, a, b): # 두 노드 번호에 대해서
    a = find_parent(parent, a) # 부모(루트) 노드를 찾고
    b = find_parent(parent, b)
    if a < b:
        parent[b] = a # 갱신
    else:
        parent[a] = b

# 노드의 개수와 간선(Union 연산)의 개수 입력 받기
v, e = map(int, input().split())
parent = [0] * (v+1) # 부모 테이블 초기화하기

# 부모 테이블상에서, 부모를 자기 자신으로 초기화
for i in range(1, v+1):
    parent[i] = i

# Union 연산을 각각 수행
for i in range(e):
    a, b = map(int, input().split())
    union_parent(parent, a, b)

# 각 원소가 속한 집합 출력하기
print('각 원소가 속한 집합: ', end="")
for i in range(1, v+1):
    print(find_parent(parent, i), end=" ")

print()

# 부모 테이블 내용 출력하기
print('부모 테이블: ', end="")
for i in range(1, v+1):
    print(parent[i], end=" ")

07_그래프이론/02_서로소집합_경로압축.py

02_서로소집합_경로압축.py