def main(): while (1): # 車輪回転中フラグの初期化(0:停止、1:回転中) flgMoving = 0 # ゴール到達フラグの初期化(0:未達、1:到達) flgGoal = 0 # 走行モードの初期化(0=探索,1=最短) runnninngmode = 0 #状態ステータス(0:停止、1:開始、2:走行中) runstatus = 0 mode = [0, 0, 0] mode = selectmode() print mode[0] # タクトスイッチ0が押されたら if mode[0] == 1: # LED0を点灯 mw.led([1, 0, 0, 0]) # 走行モードを探索に設定 runnninngmode = 0 # タクトスイッチ1が押されたら if mode[1] == 1: # LED1を点灯 mw.led([0, 1, 0, 0]) # 走行モードを最短に設定 runnninngmode = 1 # タクトスイッチ2が押されたら if mode[2] == 1: # LED2を点灯 mw.led([0, 0, 1, 0]) # 状態ステータスを開始に設定 runstatus = 1 # 状態ステータスが開始or走行中 while (runstatus != 0): # 走行モードが探索の場合 if runnninngmode == 0: ueoa.tmp_function_for_group_meeting() mode = selectmode() # タクトスイッチ1が押されたら if mode[1] == 1: # LED1を点灯 mw.led([0, 1, 0, 0]) flgGoal = 1 # マップを更新 # ゴールに到着したら ## if goal(): if flgGoal == 1: #if flgMoving == 0: # 状態ステータスを停止に設定 runstatus = 0 stop.stop() print "End" else: # 状態ステータスを走行中に設定 runstatus = 2
def restart(args): global options #begin by parsing command line arguments #setup the f****n parser parser = optparse.OptionParser(\ usage=bcolors.OKGREEN+"%prog start"+bcolors.ENDC) parser.add_option('-v', '--verbose', action='store_true', help='print debug data') (options, args) = parser.parse_args(args) verbose("Args are: %s " % args) print bcolors.OKBLUE, "Restarting", bcolors.ENDC stop.stop([]) ##SERVER STILL NEEDS RESTARTING HERE (FIRST CONFIG NEEDS TO BE ADVANCED TO STORE THE FILE NAME AND THE START PARAMS OF PREVIOUS START) start.start(config.readStartParams())
def control(): try: while True: frontDistance = reading(0, 11, 13) rightDistance = reading(0, 16, 18) leftDistance = reading(0, 29, 31) print("read ultrasonic distance ... {} {} {}".format( frontDistance, rightDistance, leftDistance)) if frontDistance <= 18: if rightDistance < leftDistance and rightDistance <= 10: print("go left") left.moveToLeft() elif leftDistance < rightDistance and leftDistance <= 10: print("go right") right.moveToRight() else: print("de back") back.goBack() elif frontDistance >= 18 and rightDistance >= 12 and leftDistance >= 10: print("go right2") #right45.moveToRight45() right45.test() elif frontDistance >= 18 and rightDistance >= 10 and leftDistance >= 12: print("go left2") left45.moveToLeft45() elif frontDistance >= 18 and rightDistance >= 12 and leftDistance >= 12: print("go straight") straight.moveToStraight() elif rightDistance <= leftDistance and rightDistance <= 10: print("change direction to left") left.moveToLeft() elif leftDistance <= rightDistance and leftDistance <= 10: print("change direction to right") right.moveToRight() pass except KeyboardInterrupt: print("foo") stop.stop()
def selectmode(): mode = [0,0,0] # タクトスイッチのスイッチ取得 swstate = mw.switchstate() # 走行モード for swno in [0, 1, 2]: if swstate[swno] == 0: swstatecnt[swno] += 1 stop.stop() elif swstate[swno] == 1: if swstatecnt[swno] >= 3: mode[swno] = 1 stop.stop() swstatecnt[swno] = 0 ## print swstate ## print swstatecnt return mode
def main(): conf = {} confloader.loadconf(conf) if len(sys.argv) == 2 and sys.argv[1] == "start": start.start(conf) elif len(sys.argv) == 2 and sys.argv[1] == "restart": if stop.stop(conf) == True: common.log(conf, "Daemon stopped") print "Daemon stopped" start.start(conf) elif len(sys.argv) == 2 and sys.argv[1] == "stop": if stop.stop(conf) == True: common.log(conf, "Daemon stopped") print "Daemon stopped" else: print >> sys.stderr, "Daemon isn't started" else: print >> sys.stderr, "Va te faire foutre\n"
def split(toy, k): global COUNT if type(toy) == str: if toy in opList: return call(k, ops_mapping[toy]) return call(k, toy) if type(toy) == int: return call(k, toy) if type(toy) == func: return call(k, value(toy)) if type(toy) == call: return split_call(toy, k) if type(toy) == cond: conditional = cond("of-tst", split(toy.true_expression, k), split(toy.false_expression, k)) f = func(["of-tst"], conditional) return call(receive(toy.condition), f) if type(toy) == decl: toy.rhs = value(toy.rhs) return toy if type(toy) == declSequence: new_sequence = [] for declaration in toy.sequence: new_sequence.append(split(declaration, k)) toy.sequence = new_sequence toy.expr = split(toy.expr, k) return toy if type(toy) == grab: return declSequence( [decl(toy.var, func(["x", "f"], call(k, "f"))), split(toy.rhs, k)]) if type(toy) == list: if len(toy) < 1: return k # ? else: call_arg = func(["of-rst"], call(k, "of-rst")) f = func(["of-fst"], call(receive(toy[1:]), call_arg)) return call(receive(toy[0]), f) if type(toy) == stop: return stop(receive(toy.toy))
def lambda_handler(event, context): client = boto3.client('ec2') ec2 = client.describe_instances( # filtering by tags, these will be particularly useful # for identifying multiple or single instances that # need to be brought up or shut down. Filters=[{ 'Name': 'tag:' + event["key"], 'Values': [event["value"]] }]) stopInstance = stop() # declaring external class for stopping instances startInstance = start() # declaring external class for starting instance for reservation in ec2["Reservations"]: for instance in reservation["Instances"]: print('instance id: ' + instance['InstanceId']) if (event['action'] == 'stop'): print('stopping instance:' + instance['InstanceId']) stopInstance.stop_ec2(instance['InstanceId'], client) elif (event['action'] == 'start'): print('starting instance:' + instance['InstanceId']) startInstance.start_ec2(instance['InstanceId'], client) print('\n')
def lambda_handler(event, context): print('\n') client = boto3.client('rds') stopInstance = stop() startInstance = start() status = '' for instance in event['instances']: rdsInstance = client.describe_db_instances( DBInstanceIdentifier=instance) for description in rdsInstance['DBInstances']: status = description['DBInstanceStatus'] print(instance) # depending on the event # the system is supposed to stop (at night 11pm) # or start the RDS instance (8am) if (event['action'] == 'start'): print('starting instance:' + instance) if (status == 'available'): print('rds status is available already') else: print('starting instance:' + instance) startInstance.start_rds(instance, client) elif (event['action'] == 'stop'): print('RDS instance status: ' + status) if (status == 'stopped'): print('rds status is stopped already') else: print('stopping instance:' + instance) stopInstance.stop_rds(instance, client) # LATER LEARNING: # implement a swich statement: it could actually # easier to do an if statements, but for the sake # of learning, let's implement a switch print('\n')
def parseList(jso): if len(jso) > 0: if jso[0] == "fun*": body = parse(jso[2]) return func(jso[1], body) if jso[0] == "call": params = [] for parameter in jso[2:]: params.append(parse(parameter)) c = call(parse(jso[1]), params) return c if jso[0] == "if-0": return cond(parse(jso[1]), parse(jso[2]), parse(jso[3])) if jso[0] == "let": return decl(jso[1], parse(jso[3])) # No need for infix operation checking in the list section, since it cannot happen if jso[0] == "seq*": args = [] for s in jso[1:-1]: p = parse(s) args.append(p) f = call(func(rand_stringer(len(args)), parse(jso[-1])), args[::-1]) return f if jso[0] == "grab": return grab(parse(jso[1]), parse(jso[2])) if jso[0] == "stop": return stop(parse(jso[1])) if type(jso) == list: return_array = [] for item in jso: return_array.append(parse(item)) if len(return_array) > 1 and type(return_array[0]) == decl: return declSequence(return_array) return return_array return jso
def test_cps(self): # Using the alpha_equals() for equality t_json = 1 parsed_json = parse(t_json) cps = receive(parsed_json) test = func(["k1"], call("k1", [1])) self.assertTrue(alpha_equal(cps, test)) t_json = "a" parsed_json = parse(t_json) cps = receive(parsed_json) test = func(["k2"], call("k2", ["a"])) self.assertTrue(alpha_equal(cps, test)) t_json = "+" parsed_json = parse(t_json) cps = receive(parsed_json) test = func(["k3"], call("k3", ops_mapping["+"])) self.assertTrue(alpha_equal(cps, test)) t_json = ["call", ["fun*", ["x", "y"], "y"], 1, 2] parsed_json = parse(t_json) cps = receive(parsed_json) test = func("k5", call(func("k6", call("k6", 2)), func("of-1", call(func("k7", call("k7", 1)), func("of-0", call(func(["k8"], call("k8", func(["k", "x", "y"], call("k", "y")))), func("of-f", call("of-f", ["k5", "of-0", "of-1"])))))))) self.assertTrue(alpha_equal(cps, test)) t_json = ["if-0", 0, 1, 2] parsed_json = parse(t_json) cps = receive(parsed_json) test = func(["k9"], call(func(["k10"], call("k10", [0])), func(["of-tst"], cond("of-tst", call("k9", [1]), call("k9", [2]))))) self.assertTrue(alpha_equal(cps, test)) t_json = [["let", "a", "=", 5], ["let", "b", "=", 6], "b"] parsed_json = parse(t_json) cps = receive(parsed_json) test = declSequence([decl("a", 5), decl("b", 6), func(["k11"], call("k11", ["b"]))]) self.assertTrue(alpha_equal(cps, test)) t_json = ["fun*", ["x"], "x"] parsed_json = parse(t_json) cps = receive(parsed_json) test = func(["k12"], call("k12", func(["k", "x"], call("k", ["x"])))) self.assertTrue(alpha_equal(cps, test)) # Unit tests against names we would generate t_json = ["fun*", ["kb"], "kb"] parsed_json = parse(t_json) cps = receive(parsed_json) test = func(["k12"], call("k12", func(["k", "kb"], call("k", ["kb"])))) self.assertTrue(alpha_equal(cps, test)) t_json = ["call", "+", 1, 2] parsed_json = parse(t_json) cps = receive(parsed_json) test = func("k13", call(func("k14", call("k14", 2)), func("of-1", call(func("k15", call("k15", 1)), func("of-0", call(func("k", call("k", ops_mapping["+"])), func("k", call("k", ["k13", "of-0", "of-1"])))))))) self.assertTrue(alpha_equal(cps, test)) t_json = ["grab", "x", ["call", "x", 10]] parsed_json = parse(t_json) cps = receive(parsed_json) test = func(["k"], declSequence([decl("x", func(["x", "f"], call("k", "f"))), call(func("kc", call("kc", 10)), func("fa", call(func("kd", call("kd", "x")), func("fb", call("fb", ["kb", "fa"])))))])) self.assertTrue(alpha_equal(cps, test)) t_json = ["stop", 10] parsed_json = parse(t_json) cps = receive(parsed_json) test = func("k", stop(func("kc", call("kc", 10)))) self.assertTrue(alpha_equal(cps, test)) t_json = ["call", "+", 1, ["stop", 10]] parsed_json = parse(t_json) cps = receive(parsed_json) test = func("k13", call(func("k", stop(func("kc", call("kc", 10)))), func("of-1", call(func("k15", call("k15", 1)), func("of-0", call(func("k", call("k", ops_mapping["+"])), func("k", call("k", ["k13", "of-0", "of-1"])))))))) self.assertTrue(alpha_equal(cps, test)) t_json = declSequence([decl("x", 15), "x"]) cps = receive(t_json) test = declSequence([decl("x", 15), func("ke", call("ke","x"))]) self.assertTrue(alpha_equal(cps, test))
def halt(): return stop()
def test_interpret(self): t_json = 1 parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 1) t_json = ["fun*", [], 1] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(str(result), "\"closure\"") t_json = "!" parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(str(result), "\"closure\"") t_json = ["call", "@", 1] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(str(result), "\"cell\"") t_json = "a" parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() self.assertRaises(errors.UndeclaredException, stop_catch_interpretter, call(toy, func(["x"], "x")), env, store_) t_json = ["call", "^", 1, -1] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() self.assertRaises(errors.exponentiationError, stop_catch_interpretter, call(toy, func(["x"], "x")), env, store_) t_json = ["call", "^", 1] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() self.assertRaises(errors.ArgumentParameterMismatch, stop_catch_interpretter, call(toy, func(["x"], "x")), env, store_) t_json = ["call", 1] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() self.assertRaises(errors.ClosureOrPrimopExpected, stop_catch_interpretter, call(toy, func(["x"], "x")), env, store_) t_json = ["grab", "c", ["call", ["fun*", ["v"], ["call", "v", 10]], "c"]] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 10) t_json = ["grab", "c", ["call", ["fun*", ["v"], ["call", "v", 10]], "c"]] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 10) t_json = ["call", "+", ["stop", [["let", "y", "=", 10], ["call", "^", 2, "y"]]], 10] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 1024) t_json = ["call", "*", ["call", ["fun*", [], 2]], 5] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 10) t_json = ["call", ["fun*", [], 1]] parsed_json = parse(t_json) toy = receive(parsed_json) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 1) toy = func("k13", call(func("k", stop(func("kc", call("kc", 10)))), func("of-1", call(func("k15", call("k15", 1)), func("of-0", call(func("k", call("k", ops_mapping["+"])), func("k", call("k", ["k13", "of-0", "of-1"])))))))) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 10) toy = func(["kb"], declSequence([decl("x", func(["x", "f"], call("kb", "f"))), call(func("kc", call("kc", 10)), func("fa", call(func("kd", call("kd", "x")), func("fb", call("fb", ["kb", "fa"])))))])) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 10) toy = func("k13", call(func("k14", call("k14", 2)), func("of-1", call(func("k15", call("k15", 1)), func("of-0", call(func("k", call("k", ops_mapping["+"])), func("k", call("k", ["k13", "of-0", "of-1"])))))))) env, store_ = interpret_init() result, new_store = stop_catch_interpretter(call(toy, func(["x"], "x")), env, store_) self.assertEqual(result, 3)
'sasl': options.sasl, 'whitelist': options.whitelist, 'whitelistAll': options.whitelistAll }]) writefile(os.path.join(serverdir, "zoo.cfg"), str(conf)) writefile(os.path.join(serverdir, "data", "myid"), str(sid)) writescript( "start.sh", str( start(searchList=[{ 'serverlist': serverlist, 'trace': options.trace, 'sasl': options.sasl }]))) writescript("stop.sh", str(stop(searchList=[{'serverlist': serverlist}]))) writescript("status.sh", str(status(searchList=[{ 'serverlist': serverlist }]))) writescript( "cli.sh", str(cli(searchList=[{ 'ssl': options.ssl, 'sasl': options.sasl }]))) if is_remote: writescript( "copycat.sh", str( copycat(searchList=[{
def rm_dirs(config): path = Path(BASE_DIR, config['RUNTIME_DIR']) print("removing dir '{}'".format(path)) shutil.rmtree(path, ignore_errors=True) def rm_docker_env_file(config): path = Path(BASE_DIR / ".env") print("removing '{}'".format(path)) path.unlink() if __name__ == '__main__': from argparse import ArgumentParser create_docker_env_file(overwrite=False) config = load_config() parser = ArgumentParser( description= "clean up the repository: remove xml database, remove sql database") args = parser.parse_args() from stop import stop stop(config) rm_dirs(config) rm_docker_env_file(config)
def clean(self): stop.stop(self.leader_process) self.leader_process = None
def run(toy): app_form = func(["x"], stop("x")) cps_form = call(receive(toy), app_form) interp_ast(cps_form)
def table(self, list, a, b, c): d = a+b+c if('UUU' == d):list.append(phenylalanine.phenylalanine()) if('UUC' == d):list.append(phenylalanine.phenylalanine()) if('UUA' == d):list.append(leucine.leucine()) if('UUG' == d):list.append(leucine.leucine()) if('CUU' == d):list.append(leucine.leucine()) if('CUC' == d):list.append(leucine.leucine()) if('CUA' == d):list.append(leucine.leucine()) if('CUG' == d):list.append(leucine.leucine()) if('AUU' == d):list.append(isoleucine.isoleucine()) if('AUC' == d):list.append(isoleucine.isoleucine()) if('AUA' == d):list.append(isoleucine.isoleucine()) if('AUG' == d):list.append(methionine.methionine()) if('GUU' == d):list.append(valine.valine()) if('GUC' == d):list.append(valine.valine()) if('GUA' == d):list.append(valine.valine()) if('GUG' == d):list.append(valine.valine()) if('AGU' == d):list.append(serine.serine()) if('AGC' == d):list.append(serine.serine()) if('CCU' == d):list.append(proline.proline()) if('CCC' == d):list.append(proline.proline()) if('CCG' == d):list.append(proline.proline()) if('CCA' == d):list.append(proline.proline()) if('ACU' == d):list.append(threonine.threonine()) if('ACC' == d):list.append(threonine.threonine()) if('ACA' == d):list.append(threonine.threonine()) if('ACG' == d):list.append(threonine.threonine()) if('GCU' == d):list.append(alanine.alanine()) if('GCC' == d):list.append(alanine.alanine()) if('GCA' == d):list.append(alanine.alanine()) if('GCG' == d):list.append(alanine.alanine()) if('UAU' == d):list.append(tryptophan.tryptophan()) if('UAC' == d):list.append(tryptophan.tryptophan()) if('UAA' == d):list.append(stop.stop()) # Ochre if('UAG' == d):list.append(stop.stop()) # Ambre if('CAU' == d):list.append(histidine.histidine()) if('CAC' == d):list.append(histidine.histidine()) if('CAA' == d):list.append(glutamine.glutamine()) if('CAG' == d):list.append(glutamine.glutamine()) if('AAU' == d):list.append(asparagine.asparagine()) if('AAC' == d):list.append(asparagine.asparagine()) if('AAA' == d):list.append(lysine.lysine()) if('AAG' == d):list.append(lysine.lysine()) if('GAU' == d):list.append(aspartic_acid.aspartic_acid()) if('GAC' == d):list.append(aspartic_acid.aspartic_acid()) if('GAG' == d):list.append(glutamic_acid.glutamic_acid()) if('GAA' == d):list.append(glutamic_acid.glutamic_acid()) if('UGU' == d):list.append(glutamic_acid.glutamic_acid()) if('UGC' == d):list.append(glutamic_acid.glutamic_acid()) if('UGA' == d):list.append(stop.stop()) # Opal if('UGC' == d):list.append(tryptophan.tryptophan()) if('CGA' == d):list.append(arginine.arginine()) if('CGC' == d):list.append(arginine.arginine()) if('CGG' == d):list.append(arginine.arginine()) if('CGU' == d):list.append(arginine.arginine()) if('AGU' == d):list.append(serine.serine()) if('AGC' == d):list.append(serine.serine()) if('AGA' == d):list.append(arginine.arginine()) if('AGG' == d):list.append(arginine.arginine()) if('GGU' == d):list.append(glycine.glycine()) if('GGC' == d):list.append(glycine.glycine()) if('GGA' == d):list.append(glycine.glycine()) if('GGG' == d):list.append(glycine.glycine()) return list
if arg_list[1] == "version": import version version.get_version(url="/system/v1/version") elif arg_list[1] == "system": try: if arg_list[2] == "start": import system system.start(url="/system/v1/login") print("SubwayTraffic service running") elif arg_list[2] == "status": import service_status service_status.show_status(url="/system/v1/live") elif arg_list[2] == "stop": import stop stop.stop(url="/system/v1/process") else: print("bash: command not found") except IndexError: print("bash: command not found") elif arg_list[1] == "stop": import stop stop.stop(url="/system/v1/process") elif arg_list[1] == "user": try: if arg_list[2] == "list": import user user.user_list(url="/user/v1/users") else: print("bash: command not found")
loss = loss/(area+1e-3) #smoothing loss = np.minimum(loss,LOSS_CAP) loss = cv2.GaussianBlur(loss,(LOSS_BINS+1,1),LOSS_SIGMA) loss = loss.flatten()[2:-2] # 画面端はうまくスムージングできないので使わない imin = np.argmin(loss) #steering if loss[imin]<=0: steer = 0.0 else: steer = 2*imin/(len(loss)-1)-1.0 # NOTE: -1 <= steer <= 1 steer *= math.pow(abs(steer),0.5) mean_steer = (1-STEER_R)*mean_steer+STEER_R*steer steering.direction(STEER_K*mean_steer) #move slowly before obstacle w = BRAKE_W//2 imin = max(w,min(len(loss-w-1),imin)) loss = loss[imin-w:imin+w+1] #average positive_loss = loss[loss>0] if len(positive_loss)>0: mean_loss = (1-BRAKE_R)*mean_loss+BRAKE_R*np.mean(positive_loss) if mean_loss>BRAKE_THRESH: straight.moveSlowly() break stop.stop()
from app import spawn from start import start from stop import stop import time import os if __name__ == '__main__': try: os.remove("thor.log") except: pass sys_base = "multiprocTCPBase" # sys_base = "simpleSystemBase" start(sys_base) time.sleep(20) procs = [] for i in range(0, 10): proc = Process(target=spawn, args=(sys_base, i+1)) procs.append(proc) proc.start() for proc in procs: proc.join() print("All apps finished") stop(sys_base)
def main(): maze = utl.Maze() mypos = [ 0, 0 ] nextpos = [ 0, 0 ] POS_X, POS_Y = 0, 1 safe_counter = 0 newWallInfo = 0 next_direction = TOP mydirection = TOP distance = [0, 0, 0] step = 1 # 走行モードの初期化(0=探索,1=最短) runnninngmode = 0 while(1): # 車輪回転中フラグの初期化(0:停止、1:回転中) flgMoving = 0 # ゴール到達フラグの初期化(0:未達、1:到達) flgGoal = 0 #状態ステータス(0:停止、1:開始、2:走行中) runstatus = 0 mode = [0,0,0] mode = selectmode() ## print mode[0] # タクトスイッチ0が押されたら if mode[0] == 1: # LED0を点灯 mw.led([1,0,0,0]) # 走行モードを探索に設定 runnninngmode = 0 # タクトスイッチ1が押されたら if mode[1] == 1: # LED1を点灯 mw.led([0,1,0,0]) # 走行モードを最短に設定 runnninngmode = 1 # タクトスイッチ2が押されたら if mode[2] == 1: # LED2を点灯 mw.led([0,0,1,0]) # 状態ステータスを開始に設定 runstatus = 1 ## print "runnninngmode=", runnninngmode # 走行の1回目だけは0.5マス前進する # 走行モードが探索の場合 while(runstatus == 1): # 走行モードが最短の場合 if runnninngmode == 1: # 足立方で探索2 maze.adachi_2nd_run() next_direction = TOP mydirection = TOP nextpos = [ 0, 0 ] # 現在位置を1順前の次の位置に設定 mypos = copy.copy(nextpos) # 初期位置では必ずRIGHT & LEFT & BOTTOMに壁がある newWallInfo = 13 maze.set_wallinfo( mypos, newWallInfo) # 0.5マス前進 half_step() # 状態ステータスを走行中に設定 runstatus = 2 nextpos = (0,1) # 状態ステータスが開始or走行中 while(runstatus == 2): # 走行モードが探索の場合 if runnninngmode == 0 or runnninngmode == 1: distance = rcg.get_distance() distance[FRONT_DIRECTION] = -1 ## distance[LEFT_DIRECTION] = -1 ## distance[RIGHT_DIRECTION] = -1 if act.is_running(): act.keep_order(distance[FRONT_DIRECTION],distance[LEFT_DIRECTION],distance[RIGHT_DIRECTION]) else: if mypos in utl.goal: # 周囲の壁情報の取得 newWallInfo = rcg.check_wall() newWallInfo = change_the_world(mydirection, newWallInfo) # 地図に壁情報を書き込み maze.set_wallinfo( mypos, newWallInfo) if runnninngmode == 0: # 0.5マス前進 half_step() print "1st Goal!!" elif runnninngmode == 1: # 0.5マス前進 half_step() print "2nd Goal!!" # ゴールに到着 flgGoal = 1 # LED3を点灯 mw.led([0,0,0,1]) else: # 現在位置を1順前の次の位置に設定 mypos = nextpos # 現在位置の表示 #print "mypos = ",mypos if runnninngmode == 0: # 周囲の壁情報の取得 newWallInfo = rcg.check_wall() # 周囲の壁情報の表示 #print "local wallinfo = ", newWallInfo newWallInfo = change_the_world(mydirection, newWallInfo) #print "global wallinfo = ", newWallInfo # 地図に壁情報を書き込み maze.set_wallinfo( mypos, newWallInfo) # 足立方で探索 maze.adachi() #maze.display_distinfo() elif runnninngmode == 1: print "Adachi2" ## # 足立方で探索2 ## maze.adachi_2nd_run() # 次の移動位置を取得 nextpos = maze.get_nextpos( mypos ) # 次の移動方向を取得 next_direction = maze.get_nextaction( mypos, nextpos ) #print "mydirection=",mydirection #print "next_direction=",next_direction if runnninngmode == 1: step = 1 origin_next_direction = next_direction pre_nextpos = nextpos while next_direction == mydirection: pre_nextpos = nextpos # 現在位置を1順前の次の位置に設定 mypos = nextpos # 次の移動位置を取得 nextpos = maze.get_nextpos( mypos ) # 次の移動方向を取得 next_direction = maze.get_nextaction( mypos, nextpos) step += 1 #print "pre_nextpospre_pypos=",pre_nextpos #print "step=",step if step > 1: step -= 1 next_direction = origin_next_direction nextpos = pre_nextpos print "-------------------------" # 次に進むべき方向と今自分が向いている方向から、回転角度を求め、move()を実行 if next_direction == 0: stop.stop() elif next_direction == RIGHT: if mydirection == RIGHT: act.go_straight(step,distance[FRONT_DIRECTION],distance[LEFT_DIRECTION],distance[RIGHT_DIRECTION]) elif mydirection == TOP: go_rotate_go(0.5,ROTATERIGHT) elif mydirection == LEFT: go_rotate_go(0.5,ROTATEOPPOSIT) elif mydirection == BOTTOM: go_rotate_go(0.5,ROTATELEFT) elif next_direction == TOP: if mydirection == RIGHT: go_rotate_go(0.5,ROTATELEFT) elif mydirection == TOP: act.go_straight(step,distance[FRONT_DIRECTION],distance[LEFT_DIRECTION],distance[RIGHT_DIRECTION]) elif mydirection == LEFT: go_rotate_go(0.5,ROTATERIGHT) elif mydirection == BOTTOM: go_rotate_go(0.5,ROTATEOPPOSIT) elif next_direction == LEFT: if mydirection == RIGHT: go_rotate_go(0.5,ROTATEOPPOSIT) elif mydirection == TOP: go_rotate_go(0.5,ROTATELEFT) elif mydirection == LEFT: act.go_straight(step,distance[FRONT_DIRECTION],distance[LEFT_DIRECTION],distance[RIGHT_DIRECTION]) elif mydirection == BOTTOM: go_rotate_go(0.5,ROTATERIGHT) elif next_direction == BOTTOM: if mydirection == RIGHT: go_rotate_go(0.5,ROTATERIGHT) elif mydirection == TOP: go_rotate_go(0.5,ROTATEOPPOSIT) elif mydirection == LEFT: go_rotate_go(0.5,ROTATELEFT) elif mydirection == BOTTOM: act.go_straight(step,distance[FRONT_DIRECTION],distance[LEFT_DIRECTION],distance[RIGHT_DIRECTION]) if next_direction == 0: mydirection = mydirection else: mydirection = next_direction swstate = mw.switchstate() # タクトスイッチ1が押されたら if swstate[1] == 0: # LED3を点灯 mw.led([0,0,0,1]) flgGoal = 1 # ゴールに到着したら if flgGoal == 1: #if flgMoving == 0: # 状態ステータスを停止に設定 runstatus = 0 stop.stop() ## print "End" else: # 状態ステータスを走行中に設定 runstatus = 2
from argparse import ArgumentParser parser = ArgumentParser( description= "initialize the repository: create directories, initialize xml database, initialize sql database" ) parser.add_argument( "--build", action="store_true", help="rebuild docker image from Dockerfile", ) args = parser.parse_args() # orig_config_file -> env_file: create_docker_env_file() # load env_file: config = load_config() create_dirs(config) # rebuild docker image: if args.build: run( env=config, build=True, ) stop(env=config, ) init_sqldb(config)
if __name__ == '__main__': from argparse import ArgumentParser config = load_config() parser = ArgumentParser( description="run the webserver" ) parser.add_argument( "--build", action = "store_true" ) parser.add_argument( "CMD", nargs="*" ) args = parser.parse_args() stop( env = config ) CMD= vars(args)['CMD'] run( env=config, build = args.build, cmd=CMD )
except UnstableChannel, e: syslog.syslog(syslog.LOG_CRIT, "%s\n%s" % (traceback.format_exc(), str(e))) except KeyboardInterrupt: syslog.syslog(syslog.LOG_INFO, "Interruption:\n%s" % traceback.format_exc()) sys.exit(0) except Exception, e: syslog.syslog( syslog.LOG_CRIT, "Critical exception (will shutdown everything) %s\n%s" % (traceback.format_exc(), str(e))) if hasattr(e, 'errno') and e.errno == 98: addr_attempts += 1 syslog.syslog( syslog.LOG_INFO, "Address already used (attempts %i)" % addr_attempts) if addr_attempts < ALREADY_ADDR_USED_ATTEMPTS: time.sleep(ALREADY_ADDR_USED_SLEEP) continue sys.exit(2) finally: syslog.syslog(syslog.LOG_INFO, "Shutdown 'inbound'. Stoping other processes.") time.sleep(0.1) stop.stop(head_process) driver.clean()
def stop(self): stop(self.key, self.secret, self.service, self.node_uuid, self.ssh_key)
userland_outbound_queue.push(driver.create_leader_proposal_msj()) syslog.syslog(syslog.LOG_INFO, "Connection ready. Forwarding the messages.") passage.passage_inbound_messages(previous_node, userland_inbound_queue, userland_outbound_queue, driver) except InvalidMessage, e: syslog.syslog(syslog.LOG_CRIT, "%s\n%s" % (traceback.format_exc(), str(e))) except UnstableChannel, e: syslog.syslog(syslog.LOG_CRIT, "%s\n%s" % (traceback.format_exc(), str(e))) except KeyboardInterrupt: syslog.syslog(syslog.LOG_INFO, "Interruption:\n%s" % traceback.format_exc()) sys.exit(0) except Exception, e: syslog.syslog(syslog.LOG_CRIT, "Critical exception (will shutdown everything) %s\n%s" % (traceback.format_exc(), str(e))) if hasattr(e, 'errno') and e.errno == 98: addr_attempts += 1 syslog.syslog(syslog.LOG_INFO, "Address already used (attempts %i)" % addr_attempts) if addr_attempts < ALREADY_ADDR_USED_ATTEMPTS: time.sleep(ALREADY_ADDR_USED_SLEEP) continue sys.exit(2) finally: syslog.syslog(syslog.LOG_INFO, "Shutdown 'inbound'. Stoping other processes.") time.sleep(0.1) stop.stop(head_process) driver.clean()
def emd_d(v1, v2, d): v1 = v1.astype(numpy.double) v2 = v2.astype(numpy.double) v1 /= v1.sum() v2 /= v2.sum() distances = float(pyemd.emd(v1, v2, d)) return distances d1 = readfile("test2.txt") # print(d1) d2 = readfile("test3.txt") stopword = stop.loadstop("stopword.txt") d1 = stop.stop(d1, stopword) d2 = stop.stop(d2, stopword) # print(d1) model = gensim.models.KeyedVectors.load_word2vec_format("model.txt", fvocab="vocab.vocab", binary=False) d1 = drop(d1, model) d2 = drop(d2, model) print("d1长度", len(d1)) print("d2长度", len(d2)) d1 = listtostr(d1) d2 = listtostr(d2) print(d1) print(d2) vect = CountVectorizer(token_pattern='(?u)\\b\\w+\\b').fit([d1, d2])
def run(self): finishflag = False # the current run finish flag global start_flag # flag to determine when to play sound global testfeature # data features global svm_model global current_dir #current dir start_flag = 0 senten_flag = True global Time2 global root # Time=time.strftime('%Y-%m-%d',time.localtime(time.time())) #current time # Time2=time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))# for current data file name # global p_acc_cal # numcount1=0# the number of trail in current run,start from 0 """timeout no need """ timeout = c_int(5000) bframecount = c_int(32) dframecount = c_int(98) #blocktype=0 """the statistic of the result""" totalcorrect = 0 totalincorrect = 0 classlabel = [] tempdata = [] newdata = [] newdata1 = [] # to save baseline data newdata2 = [] # to save reponde data baselinedata = [] baselinelabel = [] NIRSdata = [] datlabel = [] testfeature = [] x = [] #the data used to do the svm classification # num=0 tri = [] p_labels1 = [] #to save the feedback_predicted labels """connect the NIRS device""" numSor, numDet, numWav = initial('192.168.0.102', 45342, 5000) # print numSor[0], numDet[0], numWav[0] reqFrames = c_int(1) """the framesize of one sample""" frameSize = (c_int32 * 1)() frameSize[0] = numSor[0] * numDet[0] * numWav[0] buffersize = (c_int * 1)(reqFrames.value * frameSize[0]) # print buffersize[0] while not finishflag: #for the finish of current run # if start_flag==0: global count #the number of current RUN global numcount1 #the number of current trails if count < calibrationnum: blocktype = 0 else: blocktype = 1 """the default paramater for NIRSport""" acq = True while acq: """monitor cycle""" frameCount = (c_int * 1)() timestamps = (c_double * 1)() timingBytes = (c_char * 1)() data = (c_float * buffersize[0])() error_out = objdll.tsdk_getNFrames(reqFrames.value, timeout.value, frameCount, timestamps, timingBytes, data, buffersize) dataBufferSize = buffersize if senten_flag == True: start_flag = 1 senten_flag = False # print frameCount[0], timestamps[0], timingBytes, tempdata[:], dataBufferSize[0] # print timingBytes.value """get the trigger""" # while senten_flag: if timingBytes.value != '': tB_i = ord(timingBytes[0]) print 'the label is' + ' ' + str(tB_i) if (tB_i == baslitrig[0] or tB_i == baslitrig[1]): start = time.time() """ getdata2 """ # print numSor[0], numDet[0], numWav[0],bframecount,timeout,newdata getdata2(numSor, numDet, numWav, bframecount, timeout, newdata, Time2) newdata1.append(newdata) # print newdata bdata = np.array(newdata) #array ,single data # print type(bdata) # print ';;;;;;;;;' # print bdata.shape[0] bdata, cc_oxy1, cc_deo1 = onlineLBG2(ni, bdata) print 'done_bdata' # tempdata.append(bdata) baselinedata = bdata #2,32,40 baselinelabel.append(tB_i) newdata = [] bframecount = c_int(32) # print tempdata[:],ttimestamps[:] # tempdata=[tempdata[:]] finished = time.time() print 'Elapsed time is' + ' ' + str(finished - start) + 'seconds' # start_flag=1 elif (tB_i == datrig[0] or tB_i == datrig[1]): start = time.time() """ getdata2 """ # numcount1+=1 getdata2(numSor, numDet, numWav, dframecount, timeout, newdata, Time2) newdata2.append(newdata) tdata = np.array(newdata) #array ,single data tdata, cc_oxy2, cc_deo2 = onlineLBG2(ni, tdata) print 'done_tdata' # # tempdata.append(tdata) # # NIRSdata=tempdata datlabel.append(tB_i) for element in range(classnum): if tB_i == datrig[element]: classlabel.append(element - 1) tri += [float(element - 1)] newdata = [] dframecount = c_int(98) # print tempdata[:],ttimestamps[:] # tempdata=[tempdata[:]] testfeature = nirsfeedback(bdata, tdata, testfeature, blocktype) # features """belows are the data processing and model trained process""" if blocktype == 0 and numcount1 == 2 * self.soundNum: if count != 0: arr = [] brr = [] for i in range(1, count + 1): feature_file = Time2 + 'clisiffication' + str( i) + '.txt' fp = open(feature_file) for lines in fp.readlines(): lines = lines.replace("\n", "").split(" ") lines = [float(j) for j in lines] arr.append(lines) fp.close() label_file = Time2 + 'datalabel' + str( i) + '.txt' fp = open(label_file) for lines in fp.readlines(): lines = lines.replace("\n", "").split(" ") lines = [float(k) for k in lines] brr.extend(lines) fp.close() testfeature = testfeature + arr tri = tri + brr testfeature, model_MaxV, model_MinV = scale( testfeature) model_pra = [model_MaxV, model_MinV] a = np.array(testfeature) l1 = a.shape[0] l2 = a.shape[1] print l1, l2 """ This is used to change the data to the libsvm form """ for i in range(0, l1): dict = {} for j in range(0, l2): dict[j + 1] = float(a[i][j]) x = x + [dict] """get svm_model""" print tri, type(x) svm_model = svm_train(tri, x, ['-t', 0]) #train svm_model # svm_save_model('svm_model', svm_model) """load svm_model and predict""" # svm_model=svm_load_model('svm_model') # global p_acc_cal p_labels, p_acc_cal, p_vals = svm_predict( tri, x, svm_model) print p_acc_cal elif blocktype == 1: model_file = Time2 + 'model' + '.txt' fp = open(model_file) for lines in fp.readlines(): lines = lines.replace("\n", "").split(" ") lines = [float(j) for j in lines] model_MaxV = lines[0] model_MinV = lines[1] testfeature = scaleproj(testfeature, model_MaxV, model_MinV) # testfeature,MaxV,MinV=scale(testfeature) # """see if this is needed""" a = np.array(testfeature) l1 = a.shape[0] l2 = a.shape[1] """ This is used to change the data to the libsvm form """ for i in range(0, l1): dict = {} for j in range(0, l2): dict[j + 1] = float(a[i][j]) x = x + [dict] """load svm_model and predict""" # svm_model=svm_load_model('svm_model') print len(tri), len(x) p_labels, p_acc_feb, p_vals = svm_predict( tri, x, svm_model) # pr=open(Time2+'predictedlabels'+str(count+1)+'.txt','a') # pr.write(str(p_labels)+'\n') # # pr.write('\n') # pr.close() # p_labels1.append(p_labels) if p_labels == tri: totalcorrect += 1 print totalcorrect soundfile = current_dir + '\\Deine Antwort wurde als JA erkannt.wav' winsound.PlaySound( soundfile, winsound.SND_FILENAME | winsound.SND_ASYNC) f = wave.open(soundfile, "rb") # params = f.getparams() frames = f.getnframes() framerate = f.getframerate() timetrue = float(frames) * ( 1.0 / framerate ) #The time of true sentence time.sleep(timetrue) print 'This is right' else: totalincorrect += 1 print totalincorrect soundfile = current_dir + '\\Deine Antwort wurde als NEIN erkannt.wav' winsound.PlaySound( soundfile, winsound.SND_FILENAME | winsound.SND_ASYNC) f = wave.open(soundfile, "rb") # params = f.getparams() frames = f.getnframes() framerate = f.getframerate() timetrue = float(frames) * ( 1.0 / framerate ) #The time of true sentence time.sleep(timetrue) print 'This is wrong' finished = time.time() print 'Elapsed time is' + ' ' + str(finished - start) + 'seconds' start_flag = 1 elif tB_i == finish: acq = False stop.stop() # global p_acc_cal if blocktype == 1 and tri != 2 and numcount1 == 2 * self.soundNum: totalresult = totalcorrect / (totalincorrect + totalcorrect) * 100 print 'The total accuracy is ' + ' ' + str(p_acc_feb[0]) + '%' if blocktype == 0 and tri != 2 and numcount1 == 2 * self.soundNum: print 'The total accuracy is ' + ' ' + str(p_acc_cal[0]) + '%' #receive data #process data np.savetxt(Time2 + 'datalabel' + str(count + 1) + '.txt', tri) np.savetxt(Time2 + 'clisiffication' + str(count + 1) + '.txt', testfeature) if count == 0: np.savetxt(Time2 + 'model' + '.txt', model_pra) np.savetxt(Time2 + 'predictedlabels' + str(count + 1) + '.txt', p_labels) else: np.savetxt(Time2 + 'predictedlabels' + str(count + 1) + '.txt', p_labels) if numcount1 == 2 * self.soundNum and acq == False: if count < calibrationnum: cv.itemconfig(rt, text='The accuracy is ' + str(p_acc_cal[0]), fill='blue') cv.update() time.sleep(2) cv.itemconfig(rt, text='', fill='blue') button['state'] = 'active' button['text'] = 'Calibration' if count == calibrationnum - 1: button['text'] = 'Feedback' # blocktype=runtypes[count-1] # print blocktype elif count >= calibrationnum and count < totalrunnum: cv.itemconfig(rt, text='The accuracy is ' + str(p_acc_feb[0]), fill='blue') cv.update() time.sleep( 2) #execute it to display the text 'The accuracy is' cv.itemconfig(rt, text='', fill='blue') button['state'] = 'active' button['text'] = 'Feedback' # blocktype=runtypes[count-1] # print blocktype if count == totalrunnum - 1: button['state'] = 'disable' button['text'] = 'Finish' # button['command']=quit finishflag = True count += 1 numcount1 = 0
os.mkdir(serverdir) os.mkdir(os.path.join(serverdir, "data")) conf = zoocfg(searchList=[{'sid' : sid, 'servername' : options.servers[sid - 1], 'clientPort' : options.clientports[sid - 1], 'weights' : options.weights, 'groups' : options.groups, 'serverlist' : serverlist, 'maxClientCnxns' : options.maxclientcnxns, 'electionAlg' : options.electionalg}]) writefile(os.path.join(serverdir, "zoo.cfg"), str(conf)) writefile(os.path.join(serverdir, "data", "myid"), str(sid)) writescript("start.sh", str(start(searchList=[{'serverlist' : serverlist}]))) writescript("stop.sh", str(stop(searchList=[{'serverlist' : serverlist}]))) content = """#!/bin/bash java -cp zookeeper.jar:log4j.jar:jline.jar:. org.apache.zookeeper.ZooKeeperMain -server "$1"\n""" writescript("cli.sh", content) content = '#!/bin/bash\n' for sid in xrange(1, len(options.servers) + 1) : content += ('echo "' + options.servers[sid - 1] + ":" + str(options.clientports[sid - 1]) + ' "' + ' $(echo stat | nc ' + options.servers[sid - 1] + " " + str(options.clientports[sid - 1]) + ' | egrep "Mode: ")\n') writescript("status.sh", content) copyjar(False,
from stop import stop a = 1 b = 2 print a stop() print b