def run(self): logging.basicConfig(filename="/home/rubin/sms_gateway/sms_xmpp.log", level=logging.INFO) server = ('pi.xurubin.com', 5222) logging.info("Starting up: " + str(server)) peer.init(server) #Nonblocking start_recv_loop() #Nonblocking controller.run(server) #Block
def make_point(): global b x = float(request.args.get('x')) y = float(request.args.get('y')) with lock: min = 99999999999 min_blob = None print b for blob in b: n = np.linalg.norm(np.array([x-blob[0],y-blob[1]])) if n<min: min_blob = blob min = n print min_blob min_x = min_blob[0]*min_blob[2] l = [blob[0] for blob in b] sum = 0 for blob in b: sum += blob[0]*blob[2] ave_x = sum/len(b) if min_x<ave_x: print "LEFT" run(left=True) else: print "RIGHT" run(left=False) return "worked"
def run(self): """Enter the polling loop. The default poller (returned by select.poll) can also be replaced with any object implementing the methods required by libusb1: This function exits if stop() is called. If stop was passed an exception, it indicates an unrecoverable error that means the main program must exit, and that exception is raised by the run() method. If stop() had no arguments, the run() method returns normally. """ controller.run(driver=self)
def main(argv=None): """Start Simulator Main Function""" if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_version = "v%s" % __version__ program_version_message = '%%(prog)s %s ' % (program_version) program_shortdesc = ''' --- IBM POWER Functional Simulator --- Configures and starts the IBM POWER8 and POWER9 Functional Simulator ''' try: parser = ArgumentParser(description=program_shortdesc, formatter_class=RawTextHelpFormatter) group = parser.add_mutually_exclusive_group() group.add_argument('-V', '--version', action='version', version=program_version_message) group.add_argument('-i', '--install', dest="install", action='store_true', help='install the simulator and its dependencies\n') group.add_argument( '-s', '--start', dest="start", default=None, choices=['power8', 'power9'], help='start the a selected version of the simulator\n') # Process arguments args = parser.parse_args() if not (args.install or args.start): parser.error( 'no action set, select either -i/--install or -s/--start.\ \ne.g: mambo -i/--install\ \n mambo -s/--start [power8 or power9]') parser.print_help() else: controller.run(args) except KeyboardInterrupt: return 1
def run(is_update_only_mode = False): """ Function that starts the agent execution. Args: is_update_only_mode: whether to run the agent in update only mode """ univ.is_update_only_mode = is_update_only_mode _log.info('Agent starting up') _log.info('Using python binary at %s' % sys.executable) _log.info('Python version : %s' % univ.details['pythonVersion']) _log.info('Agent version : %s' % univ.config.agent.agentVersion) controller.run() #call the run method controller module to start the controller _log.info('Agent shutting down with status code 0') _log.debug('Took %f seconds to shutdown' % (univ.get_stoppage_time())) _log.info('Ran for %s hours' % univ.get_run_time_str()) helper.notify_terminate() #send terminate event so that modules listening on the event will get a chance to cleanup sys.exit(0)
def test_run(self): pos = (0, 0, 0) attitude = [0, 0, np.pi / 6] quad = Quadcopter(pos, attitude) time = 0.0 des_state = trajGen.genLine(time) F, M = controller.run(quad, des_state) print "des_state", des_state print "F", F print "M", M
def run(*args): """ Function that starts the agent execution. """ _log.info('Agent starting up%s' % (' in update only mode' if univ.is_update_only_mode else '')) _log.info('Using python binary at %s' % sys.executable) _log.info('Python version : %s' % univ.details['pythonVersion']) _log.info('Agent user : %s' % univ.details['user']) _log.info('Agent version : %s' % univ.config.agent.agentVersion) controller.run( ) #call the run method controller module to start the controller _log.info('Agent shutting down with status code 0') _log.debug('Took %f seconds to shutdown' % (univ.get_stoppage_time())) _log.info('Ran for %s hours' % univ.get_run_time_str()) helper.notify_terminate( ) #send terminate event so that modules listening on the event will get a chance to cleanup sys.exit(exit_status.AGENT_ERR_SUCCESS)
def predict(): which = request.get_json().get('input.1') if not which: return "InvalidData" try: number = int(which) + 1 prediction = controller.run(number) out = json.dumps({'NextNumber': prediction}) except ValueError: out = json.dumps({'NextNumber': 'WooHooo!!!'}) return out
def handleController(self): """Change the state of a controller. Returns: The controller state that it was changed to become. """ try: # Run the controller run function to modify the GPIO pin logic return controller.run(controllers[self.options['key']], self.options) except AttributeError: print(AttributeError)
def run_update(i): for _ in range(params.num_of_iters_in_batch): des_state = generate_trajectory(time[0], 1.2, waypoints, coeff_x, coeff_y, coeff_z) F, M = controller.run(quad, des_state) quad.update(params.dt, F, M) time[0] += params.dt frame = quad.get_quad_motor_xyz_pos() lines = ax.get_lines() lines_data = [frame[[0, 2], :], frame[[1, 3], :], frame[[4, 5], :]] lines = ax.get_lines() for line, line_data in zip(lines[:3], lines_data): line_data = np.array(line_data) x, y, z = line_data.T line.set_data(x, y) line.set_3d_properties(z) return lines
def run_and_get_error_only(iterations, time, controller, mytrack, mycar, speed): sq_cte_sum = 0 for i in range(iterations): #sensing line_sensed, CTE, abs_pt, true_cte = mycar.sense(mytrack) if not line_sensed: true_cte = mycar.sensor_width * 0.6667 sq_cte_sum += true_cte**2 #control steering = controller.run(CTE) # update the car's position mycar = mycar.move(steering, speed*time) return sq_cte_sum
def run_live(action, dates, ground_truth_str, horizon_str, recent, method): ''' Input: action: string which identifies the action to be taken values: live/check/return recent: integer which identifies how many recent days to predict. If it is a values larger than 0 it will overwrite the dates parameter values: 1 ''' # get time period for recent days if recent >= 1: curr_date = datetime.date.today() prev_date = curr_date - datetime.timedelta(days=recent - 1) dates = datetime.datetime.strftime( prev_date, '%Y-%m-%d') + "::" + datetime.datetime.strftime( curr_date, '%Y-%m-%d') #live testing if action == "live": live(dates, method, ground_truth_str, horizon_str) #live check for generation of file elif action == "check": model = '_'.join(method.split('_')[:-1]) method = method.split('_')[-1] rerun_for_file(model, method, ground_truth_str.split(','), [int(i) for i in horizon_str.split(',')], "" if model not in ["ensemble", 'pp_sub'] else dates) #return dataframe elif action == "return": final_df = pd.DataFrame() for gt in ground_truth_str.split(','): for step in horizon_str.split(','): df = run("predict", gt, step, "NExT", "Filter", "post_process/Filter", "True", dates) print(df) df.columns = [gt + step] final_df = pd.concat([final_df, df], axis=1) print(final_df) return final_df
def run(iterations, time, controller, mytrack, mycar, speed): pos_out = [] sense_out = [] filt = filters.single_pole_IIR(.1, 0.1) past_points = numpy.zeros([5,2]) shift_down = numpy.matrix('[0 0 0 0 0, 1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0, 0 0 0 0 1]') for i in range(iterations): #sensing line_sensed, CTE, abs_pt, true_cte = mycar.sense(mytrack) #past_points = shift_down * past_points #past_points[0,0] = abs_pt[0,0] #past_points[0,1] = abs_pt[0,1] if line_sensed: sense_out.append("%f, %f" % (abs_pt[0,0], abs_pt[0,1])) #control steering = controller.run(CTE) # update the car's position mycar = mycar.move(steering, speed*time) #output the position of the sensor (the front of the car pos = mycar.get_sensor_pos() pos_out.append("%f, %f, %f, %f, %f, %f" % (pos[0], pos[1], mycar.orientation, speed, steering, mycar.steering_angle)) return (pos_out, sense_out)
def volverController(channel): # /home/pi/Downloads/Trivia/controller.py print "VOLVER A CONTROLLER" controller.run()
def run(): controller.run()
import controller controller.run("info")
def main(argv=None): """MA main function""" if argv is None: argv = sys.argv else: sys.argv.extend(argv) program_version = "v%s" % __version__ program_version_message = '%%(prog)s %s ' % (program_version) program_shortdesc = ''' --- Migration Advisor (MA) --- Migrates C/C++ applications to POWER ''' try: parser = ArgumentParser(description=program_shortdesc, formatter_class=RawTextHelpFormatter) parser.add_argument('-V', '--version', action='version', version=program_version_message) subparsers = parser.add_subparsers(help='\nMA commands\n\n') # Arguments for the run subcommand parser_run = subparsers.add_parser( 'run', formatter_class=RawTextHelpFormatter, help='analyze a given directory or file for possible C/C++\n' 'migration problems from x86_64 to Power\n' 'see ma run --help\n\n') parser_run.add_argument( dest='location', metavar='LOCATION', help='directory or file which will be analyzed\n\n', nargs=1) parser_run.add_argument( '-m', '--mode', dest='execution_mode', type=str, choices=['full', 'lightweight'], default='lightweight', help='specify the execution mode of MA which can be \'full\' or\n' '\'lightweight\'. The \'full\' mode looks for problems in all files\n' 'located in a given directory. This option may take several minutes\n' 'to complete. On the other hand the \'lightweight\' mode minimize\n' 'the amount of files where the search for problems is executed by\n' 'best guessing whether a file should or not be verified.\n' ' e.g: ma run --mode=full <location>\n\n') parser_run.add_argument( '-s', '--stat', dest='statistics', type=str, choices=['project', 'file'], default='', help='display migration statistics by project or per file and' '\nsuppresses the migraton report\n\n') parser_run.add_argument( '-c', '--checkers', dest='checkers', metavar='checker_1,...,checher_n', default=core.get_supported_checkers(), help='allows selecting a group of checkers which will be used to\n' 'identify potential migration problems. By default MA will look for\n' 'all problems. By activating this option you will be able to select\n' 'a unique checker or a subset of checkers from the following list:\n' ' api: Linux/x86-specific API\n' ' asm: x86-specific assembly\n' ' builtins: x86-specific compiler built-in\n' ' char: Char usage\n' ' double: Long double usage\n' ' htm: Hardware Transaction Memory\n' ' performance: Performance degradation\n' ' pthread: Non-portable Pthreads implementation\n' ' syscall: Syscall not available for Linux on Power\n\n' ' Usage: ma run -c/--checkers <checkers> <location>\n' ' e.g: ma run -c/--checker htm <location>\n' ' e.g: ma run -c/--checker api,char,syscall <location>\n\n' ) # Arguments for the info subcommand parser_info = subparsers.add_parser( 'info', formatter_class=RawTextHelpFormatter, help='show information about supported migration checkers\n' 'see ma info --help\n\n') parser_info.add_argument( '-c', required=True, dest='checker_info', type=str, choices=core.get_supported_checkers(), help= '\ndisplay information about the set of checkers that Migration\n' 'Advisor uses to identify potential migration problems.\n\n' 'The available checkers are:\n' ' api: Linux/x86-specific API\n' ' asm: x86-specific assembly\n' ' builtins: x86-specific compiler built-in\n' ' char: Char usage\n' ' double: Long double usage\n' ' htm: Hardware Transaction Memory\n' ' performance: Performance degradation\n' ' pthread: Non-portable Pthreads implementation\n' ' syscall: Syscall not available for Linux on Power\n\n' ' Usage: ma info -c <checker>\n' ' e.g: ma info -c asm\n\n') # Process arguments args = parser.parse_args() controller.run(args) except KeyboardInterrupt: return 1
def run(self): c.run(self)
import controller if __name__ == "__main__": controller.run(playlist)
def main(): controller.run()
state_0 = init_state(np.array([0.5, 0, 0]), yaw=0.0) quad = Quadcopter(state_0, params.L, params.H) waypoints = calculate_helix_waypoints(0, 9) coeff_x, coeff_y, coeff_z = calculate_MST_coeffs(waypoints) fig = plt.figure() ax = plt.axes(projection='3d') ax.set_xlim(-0.5, 0.5) ax.set_ylim(-0.5, 0.5) ax.set_zlim(-0.5, 7) for i,_ in enumerate(waypoints[:, 0]): ax.plot3D([waypoints[i, 0]], [waypoints[i, 1]], [waypoints[i, 2]], '*') time = 0 yaws = [] yaws_d = [] for i in range(300): for _ in range(params.num_of_iters_in_batch): des_state = generate_trajectory(time, 1.2, waypoints, coeff_x, coeff_y, coeff_z) F, M = controller.run(quad, des_state) quad.update(params.dt, F, M) time += params.dt quad_frame = quad.get_quad_motor_xyz_pos() res = quad_frame[5, :] a = ax.plot3D([res[0]], [res[1]], [res[2]], 'r*') # ax.plot3D([quad_frame[0, 0], quad_frame[2, 0]], [quad_frame[0, 1], quad_frame[2, 1]], [quad_frame[0, 2], quad_frame[2, 2]]) # ax.plot3D([quad_frame[1, 0], quad_frame[3, 0]], [quad_frame[1, 1], quad_frame[3, 1]], [quad_frame[1, 2], quad_frame[3, 2]]) plt.pause(params.dt) plt.savefig('simulation.png')
if fnum > -1: socket_pub.send_multipart( [config.topic_main_telem, pickle.dumps(telem, -1)]) cnt += 1 await asyncio.sleep(0.05) #~20hz control def is_joy_override(joy_axes): if joy_axes is None: return False tr = 0.1 return abs(joy_axes[J.ud]) > tr or abs(joy_axes[J.fb]) > tr or abs( joy_axes[J.lr]) > tr or abs(joy_axes[J.yaw]) > tr def init(): controller.init() if __name__ == '__main__': init() loop = asyncio.get_event_loop() loop.run_until_complete( asyncio.gather( controller.run(socket_pub), get_zmq_events(), control(), )) loop.close()
def attitudeControl(quad, time, waypoints, coeff_x, coeff_y, coeff_z): desired_state = trajGen3D.generate_trajectory(time[0], 1.2, waypoints, coeff_x, coeff_y, coeff_z) F, M = controller.run(quad, desired_state) quad.update(dt, F, M) time[0] += dt
def Location(): controller.run()
# -*- coding: utf-8 -*- """ EOTF and Gamut controller """ import os import controller if __name__ == '__main__': os.chdir(os.path.dirname(os.path.abspath(__file__))) controller.run()
#!/usr/bin/python3 from args import parse_arguments import controller if __name__ == '__main__': args = parse_arguments() controller.run(exchange_after=args.exchange, generations=args.generations, cities=args.cities, population_size=args.chromosomes, elite_size=args.elite, mutation_probability=args.mprobability, independent_populations=args.populations, number_workers=args.workers, verbose=args.verbose, latex=args.latex)
import controller # Adding command handling modules manually #from motor.motor import DummyMotor #controller.add(DummyMotor()) # Importing and running a full configured collection of command handling modules from configexample import config controller.run(33583635, config) # Alternative syntax #controller.add(config) #controller.run(33583635)
self.last_enqueue_frame_number = frame_number #self.log("*** Transmitted %s, (En %s, De %s), %s in queue." % \ # (details.last_transmitted_frame, details.last_enqueued_frame, \ # details.last_dequeued_frame, details.frames_in_queue)) def _get_exception_completed(self, details): print "Exception Details: %s" % details self.host.stop() def inputs_changed(self, inputs): self.input_count += 1 self.log("* Inputs Changed (currently %s, %s changes)" % \ (hex(inputs), self.input_count)) if self.input_count % 100 == 0: self.log("* Inputs Changed (currently %s, %s changes)" % \ (hex(inputs), self.input_count)) if __name__ == "__main__": source = Source() driver = Driver(source) # Enter the polling loop. The default poller (returned by select.poll) can # also be replaced with any object implementing the methods required by libusb1: controller.run(driver=driver)
import motor import pyb import utime ## A motor object pinENA = pyb.Pin(pyb.Pin.board.PA10, pyb.Pin.OUT_PP) pinIN1A = pyb.Pin(pyb.Pin.board.PB4, pyb.Pin.OUT_PP) pinIN2A = pyb.Pin(pyb.Pin.board.PB5, pyb.Pin.OUT_PP) motor = motor.MotorDriver([pinIN1A, pinIN2A, pinENA], 3, [1, 2]) ## An encoder object encoder = encoder.Encoder([pyb.Pin.board.PB6, pyb.Pin.board.PB7], 4, [1, 2]) ## A controller object controller = controller.Controller(K_p=0.10) # # Positioner # while(True): # motor.set_duty_cycle(controller.run(encoder.read())) # utime.sleep_ms(10) # Step repsonse while (True): controller.clear_data() input('Press "enter" to run a step response test!') controller.set_setpoint(4000) encoder.zero() stop = utime.ticks_add(utime.ticks_ms(), 1000) while (utime.ticks_diff(stop, utime.ticks_ms()) > 0): motor.set_duty_cycle(controller.run(encoder.read())) utime.sleep_ms(10) motor.set_duty_cycle(0) controller.get_data()
self.last_enqueue_frame_number = frame_number #self.log("*** Transmitted %s, (En %s, De %s), %s in queue." % \ # (details.last_transmitted_frame, details.last_enqueued_frame, \ # details.last_dequeued_frame, details.frames_in_queue)) def _get_exception_completed(self, details): print "Exception Details: %s" % details self.host.stop() def inputs_changed(self, inputs): self.input_count += 1 self.log("* Inputs Changed (currently %s, %s changes)" % \ (hex(inputs), self.input_count)) if self.input_count % 100 == 0: self.log("* Inputs Changed (currently %s, %s changes)" % \ (hex(inputs), self.input_count)) if __name__ == "__main__": source = Source() driver = Driver(source) # Enter the polling loop. The default poller (returned by select.poll) can # also be replaced with any object implementing the methods required by libusb1: controller.run(driver = driver)
logger = logger_create('dpa_pred_sales_' + sector, BASE_DIR) logger.debug("[PID.{}] Begin - {}({}).".format(os.getpid(), now, sys.argv[0])) settings = Settings() print('Sarimax prediction for the {sector} sector.'.format( sector=sector)) settings.sector = sector if args.parallel: settings.parallel = args.parallel print('[I] Into the controller.') logger.info('Into the controller.') controller.run(rootpath=BASE_DIR, logger=logger, settings=settings, verbose=args.verbose) logger.debug("[PID.{}] End - {}({}).".format(os.getpid(), now, sys.argv[0])) else: print( '[I] It necessary to pass an acceptable parameter. Look the help with {./service.py -h}.' ) now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print("[I][PID.{}] End - {} ({}).".format(os.getpid(), now, sys.argv[0])) sys.exit(0)
from selenium import webdriver import sys from login import login from controller import run from restart import restart_program # If this is the first file called, run if __name__ == "__main__": print("Go Selenium!") # Start webdriver try: browser = webdriver.Chrome() except BaseException as e: print("Error: Selenium Webdriver could not be started") print(f"Specific Error {e}") sys.exit() # Initiate the login process login(browser) # Run the automator in a loop while True: # Make sure to update the dictioanry in the Controller object when changes run planets run(browser, 1, 249, 1000000216225) run(browser, 3, 200, 1000000201099) run(browser, 4, 133, 1000000033163) run(browser, 9, 440, 1000000029519)
cur.copy_from(ifp, 'ReceptorModels', columns = ('receptor_id', 'model_id', 'pdb_fn')) cur.execute('select count(*) from ReceptorModels') print cur.fetchone()[0], 'receptor models added' with open(trajectories_fn, 'r') as ifp: cur.copy_from(ifp, 'Trajectories', columns = ('receptormodel_id', 'expsolv', 'bilayer', 'trj_dir')) cur.execute('select count(*) from Trajectories') print cur.fetchone()[0], 'trajectories added' with open(frames_fn, 'r') as ifp: cur.copy_from(ifp, 'Frames', columns = ('trj_id', 't', 'fred_fn', 'dock6_fn', 'pdb_fn')) cur.execute('select count(*) from Frames') print cur.fetchone()[0], 'frames added' cur.close conn.commit() conn.close() if __name__ == '__main__': if LDDBController.check_user(): controller = LDDBController() controller.run()
if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-d', '--depth', help='set the color depth of the output image', type=int, choices=[15, 18, 24], default=15) parser.add_argument('-t', '--threshold', help='set the threshold for color similarity', type=int, default=200) parser.add_argument('-v', '--verbose', help='increase output verbosity', action='store_true') parser.add_argument('--no-save', help='don\'t save output file', action='store_false') args = parser.parse_args() config = presets[args.depth] config['verbose'] = args.verbose config['threshold'] = args.threshold config['save_output'] = args.no_save run(config)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ System sterowania komfortem auta poprzez interfejs głosowy """ from controller import run if __name__ == "__main__": run()
def attitudeControl(quad, time): desired_state = trajGen.genLine(time[0]) F, M = controller.run(quad, desired_state) reward_fcn(np.concatenate((quad.position(), quad.velocity()),axis=0),np.concatenate((desired_state.pos, desired_state.vel),axis=0),F,M) quad.update(dt, F, M) time[0] += dt