def find_lin_reg(): x = np.array(column1) y = np.array(column2) A = np.vstack([x, np.ones(len(x))]).T soln = np.linalg.lstsq(A,y) m, c = soln[0] residual= soln[1] print type(residual) r = 1 - residual/(y.size * y.var()) print r print m, c # Now I need to actually find the start and end points of the best fit line # newM and newC are calculated based on how the data points are # stretched in the javascript newM = m*(float(10)/float(100)) newC = (c)*float(10) y1 = float(600) y2 = float(0) # the width of my current svg x1 = (y1-newC)/newM x2 = (float(-1)*newC)/newM line_file = "line.csv" line_header = ["x1", "y1", "x2", "y2", "col1", "col2", "r"] rows_list_of_lists = [[x1, y1, x2, y2, column_name1, column_name2, r]] # write a new csv file that contains the information about the best # fit line for the data gd.write_data(line_file, line_header, rows_list_of_lists)
def finish(self): global lastMode global lastPID lastMode = 0 data = get_data.read_data() print("data[0]:", len(data[0])) if data[0] != "K": os.kill(lastPID, signal.SIGKILL) lastPID = None get_data.write_data(str("K"), str(lastMode)) print("disconnected\tIP:" + self.ip + "\tPort:" + str(self.port))
def find_lin_reg(): col1a = column1[3:20] col1b = column1[38:82] for i in col1b: col1a.append(i) col2a = column2[3:20] col2b = column2[38:82] for j in col2b: col2a.append(j) x = np.array(col1a) y = np.array(col2a) A = np.vstack([x, np.ones(len(x))]).T m, c = np.linalg.lstsq(A,y)[0] print m, c # Now I need to actually find the start and end points of the best fit line # newM and newC are calculated based on how the data points are # stretched in the javascript newM = m*(float(1)/float(20000)) newC = c + 300 y1 = float(600) y2 = float(0) # the width of my current svg x1 = (y1-newC)/newM x2 = (float(-1)*newC)/newM line_file = "line.csv" line_header = ["x1", "y1", "x2", "y2", "col1", "col2", "r"] rows_list_of_lists = [[x1, y1, x2, y2, column_name1, column_name2, "-0.73"]] # write a new csv file that contains the information about the best # fit line for the data gd.write_data(line_file, line_header, rows_list_of_lists)
final = final else: final = final + i print "entry: " + final new_headers.append(final) return new_headers def change_to_list_of_lists(list_of_dicts): headers = gd.get_headers() final = [] for x in range(len(list_of_dicts)): final.append([]) for entry in headers: col = gd.get_data_slice(entry, list_of_dicts) for y in range(len(list_of_dicts)): final[y].append(col[y]) return final filename = "cleaned_headers.csv" list_of_dicts = gd.get_data_list_of_dicts() new_headers = cleaned_headers() rows_list_of_lists = change_to_list_of_lists(list_of_dicts) gd.write_data(filename, new_headers, rows_list_of_lists)
def handle(self): global lastMode global lastPID Flag = True while Flag: try: recv = self.request.recv(128) # 接收数据v if recv == b'': Flag = False # 空则推出 else: self.buf += recv.decode() # 解码 #print(self.buf) self.buf = re.sub(r'333333', '', self.buf, 10) # 约定客户端通过发送'3'来进行心跳, 删除字符串中的3 s = re.search(r'mode=\d{1,2}', self.buf, re.I) # 查找字符串中的 MODE=数字 格式的字串 if s: self.buf = "" # 只要找到一个就将所有的缓存清除 Mode = int(s.group()[5:]) # 从字串中获取mode的数值 print(Mode) data = get_data.read_data() if data[1] == "0": lastMode = 0 # 根据Mode的数值 向 对于的子进程发送继续运行信号,对应的子进程运行,产生效果 if Mode == 0: lastMode = Mode try: os.kill(lastPID, signal.SIGKILL) except: pass self.request.sendall("OK".encode()) # 向客户端发送“OK" elif Mode == 1: if lastMode != Mode: lastMode = Mode if lastPID is not None and get_data.read_data( )[0] != 'K': os.kill(lastPID, signal.SIGKILL) ChildCvFindStream = subprocess.Popen([ "python3", "/home/pi/human_code/cv_find_stream.py" ]) # 自动射门 lastPID = ChildCvFindStream.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 2: if lastMode != Mode: lastMode = Mode if lastPID is not None and get_data.read_data( )[0] != 'K': os.kill(lastPID, signal.SIGKILL) ChildColorStream = subprocess.Popen([ "python3", "/home/pi/human_code/cv_color_stream.py" ]) # 颜色识别 lastPID = ChildColorStream.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 3: if lastMode != Mode: lastMode = Mode if lastPID is not None and get_data.read_data( )[0] != 'K': os.kill(lastPID, signal.SIGKILL) ChildCvFindHand = subprocess.Popen([ "python3", "/home/pi/human_code/cv_find_hand.py" ]) # 手势识别 lastPID = ChildCvFindHand.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 4: if lastMode != Mode: lastMode = Mode if lastPID is not None and get_data.read_data( )[0] != 'K': os.kill(lastPID, signal.SIGKILL) ChildCvLinePatrol = subprocess.Popen([ "python3", "/home/pi/human_code/cv_line_patrol.py" ]) # 寻线 lastPID = ChildCvLinePatrol.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 5: if lastMode != Mode: lastMode = Mode if lastPID is not None and get_data.read_data( )[0] != 'K': os.kill(lastPID, signal.SIGKILL) ChildCvTrackStream = subprocess.Popen([ "python3", "/home/pi/human_code/cv_track_stream.py" ]) # 云台跟踪 lastPID = ChildCvTrackStream.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) else: lastMode = 0 if lastPID is not None and get_data.read_data( )[0] != 'K': os.kill(lastPID, signal.SIGKILL) lastPID = None self.request.sendall("Failed".encode()) pass except Exception as e: print(e) Flag = False
rows_lol[j].append(column[j]) elif i ==8: rows_lol[j].append(column[j]) elif i==18: rows_lol[j].append(column[j]) """ for i in range(len(headers)): column = gd.get_data_slice(headers[i], dicts) for j in range(len(column)): if i-1 in rows_with_cadences: rows_lol[j].append(column[j]) else: print "no cadence" """ new_headers = ["id","start_measure","cadence_alter","cadence_final_tone","stop_measure","cadence","cadence_kind"] gd.write_data("test1.csv", new_headers, rows_lol) sp_col = 5; old_data = rows_lol new_data = [] """ for i in range(len(gd.get_data_slice(headers[0], dicts))): new_data.append([]) """ for j in range(column_length): if (old_data[j][sp_col] == "True" or old_data[j][sp_col] == "Yes"): new_data.append(old_data[j]) gd.write_data("test2.csv", new_headers, new_data) changing_csv = new_data
headers = gd.get_headers() dicts1000 = gd.get_data_list_of_dicts_for_scale(1000) #print headers #print dicts[0] g_active = gd.get_data_slice('Global_active_power', dicts) g_intensity = gd.get_data_slice('Global_intensity', dicts) g_active1000 = gd.get_data_slice('Global_active_power', dicts1000) g_intensity1000 = gd.get_data_slice('Global_intensity', dicts1000) #print g_active print len(g_active) rows_list_of_lists = [] for i in range(len(g_active1000)): rows_list_of_lists.append([g_active1000[i], g_intensity1000[i]]) gd.write_data('test2.csv', ['column1', 'column2'], rows_list_of_lists) #print hello array = np.vstack([g_active, np.ones(len(g_active))]).T #print array m, c = np.linalg.lstsq(array, g_intensity)[0] print m, c residual = 0 for i in range(len(g_active)): residual = residual + (m*float(g_active[i]) + c - float(g_intensity[i]))**2 print residual
def handle(self): global action_num, action_times, inf_flag conn = self.request recv_data = b'' Flag = True while Flag: try: buf = conn.recv(1024) if buf == b'': Flag = False else: recv_data = recv_data + buf # Send the command to the serial port until receiving the complete command to prevent error while True: try: index = recv_data.index( b'\x55\x55') # Search 0x55 0x55 in the data if len( recv_data ) >= index + 3: # Whether the length of the data in the cache is sufficient recv_data = recv_data[index:] if recv_data[2] + 2 <= len( recv_data ): # Whether the length of the data in the cache is enough cmd = recv_data[0:(recv_data[2] + 2)] # Take the command recv_data = recv_data[( recv_data[2] + 3):] # Remove the taken command if cmd[0] and cmd[1] is 0x55: if cmd[2] == 0x08 and cmd[ 3] == 0x03: # Data length and control single servo command print('id', cmd[7]) id = cmd[7] pos = 0xffff & cmd[ 8] | 0xff00 & cmd[9] << 8 print('pos', pos) if id == 19: PWMServo.setServo(1, pos, 20) elif id == 20: PWMServo.setServo(2, pos, 20) else: pass elif cmd[2] == 0x05 and cmd[3] == 0x06: action_num = cmd[4] action_times = 0xffff & cmd[ 5] | 0xff00 & cmd[6] << 8 print('action', action_num) print('times', action_times) if action_times == 0: # Infinite imes print('action_times:', action_times) SSR.change_action_value( str(action_num), action_times) inf_flag = True else: if inf_flag: SSR.stop_action_group() inf_flag = False else: SSR.change_action_value( str(action_num), action_times) elif cmd[2] == 0x0b and cmd[3] == 0x03: PWMServo.setServo(1, 1500, 100) PWMServo.setServo(2, 1500, 100) time.sleep(0.1) data = get_data.read_data() print(int(data[0])) os.kill(int(data[0]), signal.SIGKILL) get_data.write_data("K", "0") if DEBUG is True: for i in cmd: print(hex(i)) print('*' * 30) else: break else: break except Exception as e: # The '\x55\x55' substring cannot be found in recv_data break recv_data = b'' action_times = None action_num = None except Exception as e: print(e) Flag = False break
def clean_headers(headers): all_headers = gd.get_headers() new_headers = [] for entry in headers: final = "" for i in entry: if (i == " "): final = final else: final = final + i print "entry: " + final new_headers.append(final) print new_headers return new_headers #remove_dup_cols() 32 [0,1,3,4,5,6,7,8,9,15,23,24,25,26] filename = "cleaned_3.csv" list_of_dicts = gd.get_data_list_of_dicts() new_headers = get_headers_with_cols([0,1,3,4,5,6,7,8,9]) final_headers = clean_headers(new_headers) rows_list_of_lists = create_rows_list_of_lists_with_cols(list_of_dicts, [0,1,3,4,5,6,7,8,9]) final_headers.insert(0,"id") gd.write_data(filename, final_headers, rows_list_of_lists)
def handle(self): global action_num, action_times, inf_flag conn = self.request recv_data = b'' Flag = True stop = False t2 = 0 while Flag: try: buf = conn.recv(128) if buf == b'': Flag = False else: recv_data = recv_data + buf if len(recv_data) <= 13: # 解决断包问题,接收到完整命令后才发送到串口,防止出错 while True: try: index = recv_data.index( b'\x55\x55') # 搜索数据中的0x55 0x55 if len(recv_data) >= index + 3: # 缓存中的数据长度是否足够 recv_data = recv_data[index:] if recv_data[2] + 2 <= len( recv_data): # 缓存中的数据长度是否足够 cmd = recv_data[0:(recv_data[2] + 2)] # 取出命令 #print(cmd) recv_data = recv_data[( recv_data[2] + 3):] # 去除已经取出的命令 if cmd[0] and cmd[1] is 0x55: if cmd[2] == 0x08 and cmd[ 3] == 0x03: # 数据长度和控制单舵机命令 id = cmd[7] pos = 0xffff & cmd[ 8] | 0xff00 & (cmd[9] << 8) print('id:', cmd[7], 'pos:', pos) if id == 7: if 1900 < pos: pos = 1900 elif pos < 1200: pos = 1200 PWMServo.setServo( 1, 3000 - pos, 20) elif id == 6: PWMServo.setServo( 2, 3000 - pos, 20) else: pass elif cmd[2] == 0x05 and cmd[ 3] == 0x06: action_num = cmd[4] action_times = 0xffff & cmd[ 5] | 0xff00 & cmd[6] << 8 if action_num == 0: SSR.stop_action_group() SSR.change_action_value( 'stand_slow', 1) try: data = get_data.read_data( ) if data[0] != 'K': os.system( 'sudo kill -9 ' + str(data[0])) PWMServo.setServo( 1, 1500, 300) PWMServo.setServo( 2, 1500, 300) get_data.write_data( "K", "0") except BaseException as e: print(e) elif action_times == 0: # 无限次 print( 'action', action_num, 'times', action_times) SSR.change_action_value( str(action_num), action_times) stop = True else: print( 'action', action_num, 'times', action_times) if stop: SSR.stop_action_group() SSR.change_action_value( 'stand_slow', 1) stop = False else: print( 'action', action_num, 'times', action_times) SSR.change_action_value( str(action_num), action_times) elif cmd[2] == 0x0b and cmd[ 3] == 0x03: PWMServo.setServo(1, 1500, 100) PWMServo.setServo(2, 1500, 100) time.sleep(0.1) elif cmd[2] == 0x02 and cmd[ 3] == 0x0F: if SSR.action_finish(): try: time.sleep(0.05) v = math.ceil( serial_servo_read_vin( 1)) buf = [ 0x55, 0x55, 0x04, 0x0F, 0x00, 0x00 ] buf[4] = v & 0xFF buf[5] = ( v >> 8) & 0xFF conn.sendall( bytearray(buf)) except BaseException as e: print(e) if DEBUG is True: for i in cmd: print(hex(i)) print('*' * 30) else: break else: break except Exception as e: # 在recv_data 中搜不到 '\x55\x55'子串 break recv_data = b'' action_times = None action_num = None else: recv_data = b'' pass except Exception as e: print(e) Flag = False break
def handle(self): global lastMode global lastPID Flag = True while Flag: try: recv = self.request.recv(128) # Receive datav if recv == b'': Flag = False # Exit if it is empty else: self.buf += recv.decode() # Decode #print(self.buf) self.buf = re.sub( r'333333', '', self.buf, 10 ) # Appoint the client sends '3' to perform the heartbeat and remove the 3 from the character string s = re.search( r'mode=\d{1,2}', self.buf, re.I ) # Find the MODE= number character string in the formatted string if s: self.buf = "" # Clear all caches as long as find one Mode = int( s.group()[5:] ) # Get the value of mode from the character string print(Mode) data = get_data.read_data() if data[1] == "0": lastMode = 0 # According to the value of Mode, continue sending running signal to the corresponding subprocess, and the corresponding subprocess will run if Mode == 0: if lastMode != Mode: # Only if the last time mode is different from the current mode, the mode should convert lastMode = Mode if lastPID is not None: os.kill(lastPID, signal.SIGKILL) self.request.sendall( "OK".encode()) # Send "OK" to the client elif Mode == 1: if lastMode != Mode: lastMode = Mode if lastPID is not None: os.kill(lastPID, signal.SIGKILL) ChildCvColor = subprocess.Popen([ "python2", "/home/pi/hexapod/color.py" ]) # Colour identification lastPID = ChildCvColor.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 2: if lastMode != Mode: lastMode = Mode if lastPID is not None: os.kill(lastPID, signal.SIGKILL) ChildCvColorFollow = subprocess.Popen([ "python2", "/home/pi/hexapod/color_follow.py" ]) # Colour tracking lastPID = ChildCvColorFollow.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 3: if lastMode != Mode: lastMode = Mode if lastPID is not None: os.kill(lastPID, signal.SIGKILL) ChildCvColorFollowMove = subprocess.Popen([ "python2", "/home/pi/hexapod/color_follow_move.py" ]) # Ogranism colour tracking lastPID = ChildCvColorFollowMove.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 4: if lastMode != Mode: lastMode = Mode if lastPID is not None: os.kill(lastPID, signal.SIGKILL) ChildBalance = subprocess.Popen([ "python2", "/home/pi/hexapod/balance.py" ]) # Self balance lastPID = ChildBalance.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 5: if lastMode != Mode: lastMode = Mode if lastPID is not None: os.kill(lastPID, signal.SIGKILL) ChildCvFind = subprocess.Popen([ "python2", "/home/pi/hexapod/sonar.py" ]) # Ultrasonic aviodance lastPID = ChildCvFind.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) elif Mode == 6: if lastMode != Mode: lastMode = Mode if lastPID is not None: os.kill(lastPID, signal.SIGKILL) ChildCvLineFollow = subprocess.Popen([ "python2", "/home/pi/hexapod/linefollow.py" ]) # Line following lastPID = ChildCvLineFollow.pid get_data.write_data(str(lastPID), str(lastMode)) print("lastPID:", lastPID) self.request.sendall("OK".encode()) else: lastMode = 0 if lastPID is not None: os.kill(lastPID, signal.SIGKILL) lastPID = None self.request.sendall("Failed".encode()) pass except Exception as e: print(e) Flag = False
def judge_one(id, question_id, data_num, time_limit, mem_limit, language, dblock): """评测一组数据""" # low_level() # 写入数据 write_data(id, question_id) input_path = os.path.join(config.data_dir, str(question_id), 'data%s.in' % data_num) # print('use %s' % input_path) output_path = os.path.join(config.work_dir, str(id), 'out%s.txt' % data_num) try: input_data = open(input_path) # print('open input data') # print('success w') except: # print("False111") return False temp_out_data = open(output_path, 'w+') if language == 'java': cmd = 'java -cp %s Main' % (os.path.join(config.work_dir, str(id))) main_exe = shlex.split(cmd) elif language == 'python2': cmd = 'python2 %s' % (os.path.join(config.work_dir, str(id), 'main.pyc')) main_exe = shlex.split(cmd) elif language == 'python3': # print('python3') cmd = 'python3 %s' % (os.path.join(config.work_dir, str(id), '__pycache__/main.cpython-36.pyc')) main_exe = shlex.split(cmd) elif language == 'lua': cmd = "lua %s" % (os.path.join(config.work_dir, str(id), "main")) main_exe = shlex.split(cmd) elif language == "ruby": cmd = "ruby %s" % (os.path.join(config.work_dir, str(id), "main.rb")) main_exe = shlex.split(cmd) elif language == "perl": cmd = "perl %s" % (os.path.join(config.work_dir, str(id), "main.pl")) main_exe = shlex.split(cmd) else: main_exe = [ os.path.join(config.work_dir, str(id), 'main'), ] # main_exe = shlex.split(main_exe) # in_path = os.path.join('/home/bri/project_oj/Judge/testdata', '4', 'data1.in') # out_path = os.path.join('/home/bri/project_oj/Judge/testdata', '4', 'data1.out') # fin = open(in_path) # ftemp = open('temp.out', 'w') # print('my input path:', input_path) # print('other input path:', in_path) # print("main_exe", main_exe) runcfg = { 'args': main_exe, # 'args': ['cd', main_exe, '&&', 'java', 'Main'], 'fd_in': input_data.fileno(), 'fd_out': temp_out_data.fileno(), # 'fd_in':fin.fileno(), # 'fd_out':ftemp.fileno(), 'timelimit': time_limit, # in MS 'memorylimit': mem_limit, # in KB } # low_level() rst = lorun.run(runcfg) # print('lorun') input_data.close() temp_out_data.close() logging.debug(rst) # print(rst) # print('result', end=': ') # print(judge_result(id, question_id, data_num)) return rst
col2.append(float(column2[entry])) column1 = col1 column2 = col2 filename = "test.csv" # I am naming them column1 and column2 so that in my javascript I don't # have to worry about finding which different datatypes I am comparing and # just refer to them by their column new_headers = ["column1","column2"] rows_list_of_lists = [] for i in range(len(column1)): rows_list_of_lists.append([column1[i], column2[i]]) gd.write_data(filename, new_headers, rows_list_of_lists) viz_file = "visual_points.csv" # this section selects a random variety of point to display random_points_to_plot = [] for i in range(len(column1)): x = r.randrange(1, 99) if x == 42: random_points_to_plot.append([column1[i],column2[i]]) gd.write_data(viz_file, new_headers, random_points_to_plot) def find_lin_reg(): x = np.array(column1)
def check_high(self): if self.current > self.high: self.high = self.current self.text = "High Score: "+ str(self.high) write_data(self.file, str(self.high))
# I am naming them column1 and column2 so that in my javascript I don't # have to worry about finding which different datatypes I am comparing and # just refer to them by their column new_headers = ["column1","column2"] rows_list_of_lists = [] for i in range(len(column1)): rows_list_of_lists.append([column1[i], column2[i]]) rows1 = rows_list_of_lists[0:20] rows2 = rows_list_of_lists[36:82] rows_final = rows1 for i in rows2: rows_final.append(i) gd.write_data(filename, new_headers, rows1) # this section selects a random variety of point to display def find_lin_reg(): col1a = column1[3:20] col1b = column1[38:82] for i in col1b: col1a.append(i) col2a = column2[3:20] col2b = column2[38:82] for j in col2b: col2a.append(j) x = np.array(col1a) y = np.array(col2a)