def test_instance(dirname, images): start = time() run(dirname, images, True, False, method=method_one) time_passed = time() - start print('{0}set: {1}\t\ttime: {2:0.3f}{3}'.format(INFO, dirname, time_passed, ENDC)) return time_passed
def init(): main.run(C3F32_fullDataset) # notify Windows that all tasks are done toaster = ToastNotifier() toaster.show_toast("Facial Expression Recognition", "All tasks completed!")
def main(): args.data_to_repeat = 1 args.set = 'MNISTPerm' args.multigpu = [0] args.model = 'FC1024' args.conv_type = 'FastMultitaskMaskConv' args.conv_init = 'signed_constant' args.eval_ckpts = [10, 50, 100, 150, 200] args.num_tasks = 250 args.adaptor = "se_oneshot_entropy_minimization" args.output_size = 500 args.name = f'id=supsup_h_fc_mnistperm' args.lr = 1e-4 args.optimizer = 'rmsprop' args.iter_lim = 1000 args.epochs = 3 args.save = True args.no_scheduler = True args.unshared_labels = True args.data_to_repeat = 1 args.data = '~/data' args.log_dir = "~/checkpoints/test" run()
def doTask(task): task_id =task[0] task_uuid = task[1] task_parameter = task[2] task_type = task[3] task_status = task[4] task_stra_id = task[5] task_user_id = task[6] t=task_parameter.split(',') print task_stra_id userCode=getUserCode(task_stra_id) #print userCode prepareCodeFile(userCode) prepare_data(t[0],t[1],t[2]) try: # to be running status updateTaskStatus(task_id, 3) main.run(t, task_id) except Exception as e: saveComplieError(task_id,e) # the task status is error updateTaskStatus(task_id, 2) return # the task is succesful updateTaskStatus(task_id,1)
def test_precondition_true_executes_task(self): def do_execute(): return True task = {'op': "ls", 'args': ["-l"], 'pre_condition': {'func': do_execute}} main.run([task], logger=logger) self.assertTrue('result' in task) self.assertEquals(task['result'], 0)
def new_game(self): os.system("clear") name = raw_input(color.DARKCYAN + "What is your name? " + color.END) # THIS SHOULD BE REMOVED BEFORE THE GAME IS RELEASED # you can skip the choosing character stuff if you just press enter when it asks for a name, and it'll automatically make you a knight if name == "": main.run(characters.Developer("Developer", None, 1, 1)) print(color.DARKCYAN + "Hi " + color.END + name + color.DARKCYAN + "!\n" + color.END) print(color.BLUE + "What class are you? " + color.END) for i in range(len(characters.charlist)): print(color.BLUE + str(i + 1) + ": " + characters.charlist[i] + color.END) inn = None while inn == None: inn = getch.__call__() print(inn) print("") print(color.BLUE + "You are a " + characters.charlist[int(inn) - 1] + "! Doot doot" + color.END) a = raw_input() if inn == "1": main.run(characters.Knight(name, None, 1, 1)) elif inn == "2": main.run(characters.Wizard(name, None, 1, 1)) elif inn == "3": main.run(characters.Gunner(name, None, 1, 1)) elif inn == "4": main.run(characters.Rogue(name, None, 1, 1))
def test_run_with_sizes(self): self.setup_prompts('5', '4 medium') main.run(self.mock_read, self.mock_print) self.assertEqual('5 people with 4 pizzas', self.outputs[0]) self.assertEqual( 'Each person gets 4 pieces of pizza.', self.outputs[1]) self.assertEqual('There are 4 leftover pieces.', self.outputs[2])
def __click(self): path = "temp.txt" file = open(path, "w+") file.write(self.__thisTextArea.get(1.0, END)) file.close() run(path) os.remove(path)
def run(pins: bool, fullscreen: bool) -> None: os.environ['USE_PINS'] = "true" if pins else "false" os.environ['FULLSCREEN'] = "true" if fullscreen else "false" import main main.run()
def main(): parser = argparse.ArgumentParser( description='Even Simpler Client - Team SharkiShark') parser.add_argument('--host', type=str, help='The host the client should connect to.', default='127.0.0.1') parser.add_argument('--port', type=int, help='The port the client should connect to.', default=13050) parser.add_argument( '--reservation', type=str, help='The reservation code of the game it should enter.', default=None) args = parser.parse_args() with open('args.txt', 'w') as file: file.write("sys.argv: %s\n" % sys.argv) file.write("\n\n parser:\n") file.write("\thost: %s (%s)\n" % (repr(args.host), type(args.host))) file.write("\tport: %s (%s)\n" % (repr(args.port), type(args.port))) file.write("\treservation code: %s (%s)\n" % (repr(args.reservation), type(args.reservation))) run(args.host, args.port)
def test_run(self): self.setup_prompts('8', '2') main.run(self.mock_read, self.mock_print) self.assertEqual('8 people with 2 pizzas', self.outputs[0]) self.assertEqual( 'Each person gets 2 pieces of pizza.', self.outputs[1]) self.assertEqual('There are 0 leftover pieces.', self.outputs[2])
def test_replay(self): root = os.environ.get("RECORD_SANDBOX_BUFFERS_DIR") if not root: self.skipTest("RECORD_SANDBOX_BUFFERS_DIR not set") for dirpath, dirnames, filenames in os.walk(root): if "input" not in filenames: continue print("Checking " + dirpath) input_path = os.path.join(dirpath, "input") output_path = os.path.join(dirpath, "output") new_output_path = os.path.join(dirpath, "new_output") with open(input_path, "rb") as external_input: with open(new_output_path, "wb") as external_output: sandbox = Sandbox(external_input, external_output) run(sandbox) original_output = marshal_load_all(output_path) # _send_to_js does two layers of marshalling, # and NSandbox._onSandboxData parses one of those layers before writing, # hence original_output is 'more parsed' than marshal_load_all(new_output_path) new_output = [ marshal.loads(b) for b in marshal_load_all(new_output_path) ] # It's usually not worth asserting a match, see comments at the top of the file print("Match:", original_output == new_output)
def trainable(config, name_fmt, envname, trainingconfig, evaluate_mean_n): # Parse arguments trial_dir = Path(tune.get_trial_dir()) if tune.get_trial_dir( ) is not None else Path.cwd() adv_force = config["adv_force"] name = name_fmt.format(adv_force=adv_force) cmd_args = [ '--name', name, '--env', envname, '--log', '--trainingconfig', str(trainingconfig), '--root', str(trial_dir), '--monitor-dir', str(monitor_dir_name(envname, adv_force)) ] cmd_args += ['--adv_force', str(adv_force)] args = parse_args(cmd_args) # Add adversarial force logging.info(f'Running {name=} with {args=}') def evaluate(prot, ts): # reward = get_mean_reward_last_n_steps(evaluate_mean_n, args.monitor_dir) # logging.info(f'{name} {reward=:.2f} {ts=}') # tune.report(reward=reward) robustness = eval_robustness(args, prot, envname, trainingconfig, name) logging.info(f'{name} {robustness=:.2f} {ts=}') tune.report(robustness=robustness) run(args, evaluate_fn=evaluate)
def run(self): """ Method runs in the daemon. """ try: #monit.sh to restart agent if it is killed self.monit_pid = subprocess.Popen([ exe_path + 'bin/monit.sh', unicode(os.getpid()), '%d' % self.monit_interval ], preexec_fn=os.setpgrp).pid except Exception as e: _log.error('Failed to open monitoring script; %s' % unicode(e)) self.set_procname('sealiond') #set process name for display purpose is_update_only_mode = False crash_dump_details = self.get_crash_dump_details( ) #get crash dump details helper.terminatehook = self.termination_hook #set the termination hook called whenever agent shutdown disgracefully if crash_dump_details[1] > 0: #start thread to send crash dump _log.info('Found %d dumps' % crash_dump_details[1]) ThreadEx(target=self.send_crash_dumps, name='CrashDumpSender').start() if crash_dump_details[ 0] == True: #crash loop detected. start agent in update only mode _log.info( 'Crash loop detected; Starting agent in update-only mode') is_update_only_mode = True import main main.run(is_update_only_mode) #start executing agent
def run(): """Select type of PunnetSet for questions :return: string (user response) """ window = gui.SimpleWindow(title=BOX_TITLE, msg=('Which type of punnet square problems ' 'would you like to practice?'), buttons=[ 'One trait', 'Two trait', 'One and two trait', 'Main Menu', 'Exit Program' ]) window.run() user_choice = window.clicked if user_choice == 'One trait': ask_questions('1') elif user_choice == 'Two trait': ask_questions('2') elif user_choice == 'One and two trait': ask_questions('both') elif user_choice == 'Main Menus': main.run() return user_choice
def main(): args.set = 'RotatingMNIST' args.num_tasks = 36 args.multigpu = [0] args.model = 'FC1024' args.conv_type = 'VectorizedBatchEnsembles' args.conv_init = 'kaiming_normal' args.adaptor = 'gt' args.no_scheduler = True args.iter_lim = 1000 args.epochs = 3 args.eval_ckpts = [2, 5, 10, 15, 20, 25, 30, 35] args.output_size = 10 args.name = f'id=batche_mnistrotate' args.lr = 1e-2 args.train_weight_lr = 1e-4 args.optimizer = 'adam' args.train_weight_tasks = 1 args.data = '~/data' args.log_dir = "~/checkpoints/test" run()
def run(self): """ Method runs in the daemon. """ self.set_procname(self.daemon_name + ('d' if self.daemon_name[-1] != 'd' else '')) #set process name for display purpose crash_dump_details = self.get_crash_dump_details( ) #get crash dump details helper.terminatehook = self.termination_hook #set the termination hook called whenever agent shutdown disgracefully if crash_dump_details[1] > 0: #start thread to send crash dump _log.info('Found %d dumps' % crash_dump_details[1]) ThreadEx(target=self.send_crash_dumps, name='CrashDumpSender').start() if crash_dump_details[ 0] == True: #crash loop detected. start agent in update only mode _log.info( 'Crash loop detected; Starting agent in update-only mode') universal.Universal().is_update_only_mode = True import main main.stop_stream_logging() #stop logging on stdout/stderr main.run() #start executing agent
def main(): args.set = 'MNISTPerm' args.multigpu = [0] args.model = 'LeNet' args.conv_type = 'VectorizedBatchEnsembles' args.conv_init = 'kaiming_normal' args.name = 'id=batche_lenet_mnistperm' args.epochs = 3 args.adapt_lrs = [0] args.eval_ckpts = [10, 50, 100, 150, 200] args.num_tasks = 250 args.adaptor = "gt" args.output_size = 10 args.lr = 1e-2 args.train_weight_lr = 1e-4 args.optimizer = 'adam' args.no_scheduler = True args.iter_lim = 1000 args.train_weight_tasks = 1 args.save = True args.data = '~/data' args.log_dir = "~/checkpoints/test" run()
def run(self): """ Method runs in the daemon. """ try: #monit.sh to restart agent if it is killed self.monit_pid = subprocess.Popen([exe_path + 'bin/monit.sh', unicode(os.getpid()), '%d' % self.monit_interval], preexec_fn = os.setpgrp).pid except Exception as e: _log.error('Failed to open monitoring script; %s' % unicode(e)) self.set_procname('sealiond') #set process name for display purpose is_update_only_mode = False crash_dump_details = self.get_crash_dump_details() #get crash dump details helper.terminatehook = self.termination_hook #set the termination hook called whenever agent shutdown disgracefully if crash_dump_details[1] > 0: #start thread to send crash dump _log.info('Found %d dumps' % crash_dump_details[1]) ThreadEx(target = self.send_crash_dumps, name = 'CrashDumpSender').start() if crash_dump_details[0] == True: #crash loop detected. start agent in update only mode _log.info('Crash loop detected; Starting agent in update-only mode') is_update_only_mode = True import main main.run(is_update_only_mode) #start executing agent
def test_no_max_sessions_week(self): self.configuration.maxSessionsWeek = None self.get_counters_value = (0, 0, 4) main.run(self.configuration, "monday") self.assertEqual(self.count['pauta'], 2) self.assertEqual(self.count['update_config'], 2) self.assertEqual(self.count['get_counters'], 1)
def main(): args.set = 'MNISTPerm' args.multigpu = [0] args.model = 'LeNet' args.conv_type = 'PSPRotation' args.conv_init = 'xavier_normal' args.name = f'id=psprot_lenet_mnistperm' args.adapt_lrs = [0] args.eval_ckpts = [10, 50, 100, 150, 200] args.num_tasks = 250 args.adaptor = "gt" args.hard_alphas = True args.output_size = 10 args.train_weight_tasks = -1 args.train_weight_lr = 1e-4 args.lr = 1e-4 args.momentum = 0.5 args.optimizer = 'rmsprop' args.no_scheduler = True args.iter_lim = 1000 args.epochs = 3 args.ortho_group = True args.save = True args.data = '~/data' args.log_dir = "~/checkpoints/test" run()
def main(): args.set = 'RotatingMNIST' args.num_tasks = 36 args.multigpu = [0] args.model = 'FC1024' args.conv_type = 'FastMultitaskMaskConv' args.conv_init = 'signed_constant' args.eval_ckpts = [2, 5, 10, 15, 20, 25, 30, 35] args.name = f'id=supsup_mnistrotate' args.adaptor = "se_binary_entropy_minimization" args.lr = 1e-4 args.optimizer = 'rmsprop' args.iter_lim = 1000 args.epochs = 3 args.data_to_repeat = 128 args.output_size = 200 args.save = True args.no_scheduler = True args.unshared_labels = True args.data = '~/data' args.log_dir = "~/checkpoints/test" run()
def main(): args.set = 'RandSplitCIFAR100' args.seed = 1996 args.multigpu = [0] args.model = 'GEMResNet18' args.conv_type = 'MultitaskMaskConv' args.bn_type = 'NonAffineNoStatsBN' args.conv_init = 'signed_constant' args.epochs = 5 args.output_size = 5 args.er_sparsity = True args.sparsity = 32 args.adaptor = "gt" args.hard_alphas = True args.batch_size = 128 args.test_batch_size = 128 args.num_tasks = 3 args.save = True args.optimizer = 'adam' args.lr = 0.001 args.eval_ckpts = [] args.name = f"id=rn18" # TODO: Change these paths! #args.data = '/home/mitchnw/data' #args.log_dir = "/home/mitchnw/ssd/checkpoints/supsup_test" args.data = '/scratch/db4045/data/' args.log_dir = "/scratch/db4045/scratch/test_bn_orig" run()
def home_view(request): if request.user.is_authenticated: context = {'isim': 'Serhat', 'soyisim': 'Arslan'} else: context = {'isim': 'Misafir', 'soyisim': 'Kullanıcı'} if request.method == 'POST': import main myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) start_time = time.time() main.run() end_time = time.time() - start_time print(round(end_time, 2)) dir_path = os.path.abspath('../..') no_face = dir_path + '/static/no_face' has_face = dir_path + '/static/has_face' content = { 'noface': os.listdir(no_face), 'hasface': os.listdir(has_face), 'noface_zip': '/media/result/noface.zip', 'hasface_zip': '/media/result/hasface.zip', } return render(request, 'result.html', content) return render(request, 'home.html', context)
def test_simple_include_collection(self): root_collection = "/humgen/asclepius_testing" config = "/lustre/scratch115/teams/hgi/lustre-usage/tools/pyrodstest/asclepius/test/test_config_1.yaml" main.run(root_collection, config, include_collections=True, overwrite=True) filepath = "/humgen/asclepius_testing/new-test/test/bar" # expected_metadata = [(pi, ch12, None), (group, hgi, None)] changed_metadata = irods_wrapper.get_metadata(self.session, filepath) self.assertEqual(changed_metadata['pi'].value, "ch12") self.assertEqual(changed_metadata['group'].value, "hgi") filepath = "/humgen/asclepius_testing/new-test/test" changed_metadata = irods_wrapper.get_metadata(self.session, filepath, True) print(f"Final_avus: {changed_metadata.items()}") self.assertEqual(changed_metadata['pi'].value, "ch12") self.assertEqual(changed_metadata['group'].value, "hgi") filepath = "/humgen/asclepius_testing/new-test" changed_metadata = irods_wrapper.get_metadata(self.session, filepath, True) print(f"Final_avus: {changed_metadata.items()}") self.assertEqual(changed_metadata['pi'].value, "ch12") self.assertEqual(changed_metadata['group'].value, "hgi")
def main(): args.set = 'RotatingMNIST' args.num_tasks = 36 args.multigpu = [0] args.model = 'FC1024' args.conv_type = 'PSPRotation' args.conv_init = 'xavier_normal' args.adaptor = "gt" args.epochs = 3 args.no_scheduler = True args.iter_lim = 1000 args.eval_ckpts = [2, 5, 10, 15, 20, 25, 30, 35] args.name = f'id=psp_mnistrotate' args.output_size = 10 args.train_weight_tasks = -1 args.train_weight_lr = 1e-4 args.lr = 1e-4 args.momentum = 0.5 args.optimizer = 'rmsprop' args.ortho_group = True args.data = '~/data' args.log_dir = "~/checkpoints/test" run()
def test_no_load_bad_tablenmae(client): run('member_eligibilit.20200101.psv') with db_session_handler() as db_session: records = db_session.query(MemberEligibility).all() assert len(records) == 0 manifest = db_session.query(Manifest).all() assert len(manifest) == 0
def translate(ds_name, model_name, ass2s_data_dir, voc_size=None): pathlib.Path(ASS2S_PRED_DIR).mkdir(parents=True, exist_ok=True) model_dir = f"{ASS2S_DIR}/store_model/{model_name}" params = opt( model_dir, ass2s_data_dir, "infer", pred_path=f"{ASS2S_PRED_DIR}/{ds_name}_preds.txt", voc_size=voc_size, batch_size=args.batch_size ) run(params)
def startup(): import sys if mypath not in sys.path: sys.path.append(mypath) sys.modules.clear() import main print "go!" main.run(globals())
def startup(): tornado.options.parse_command_line() print 'port: %s' % (options.port) if options.daemonize: from daemonize import become_daemon become_daemon(our_home_dir=options.workdir) run(options)
def on_any_event(event): try: if event.event_type == 'created' and not event.is_directory: pathAndFilename = event.src_path h.logger(f"File {h.removePath( pathAndFilename )} has been added.") main.run( pathAndFilename ) except Exception as e: h.logger(f"Something wrong on watcher. Erro: {str(e)}")
def test_prehook_vars_do_not_match_func_return_values(self): def exec_before_task(a,b,c): return a,b,c task = {'op': "echo", 'args': ['prehook.0', 'prehook.1'], 'pre_hook': {'func': exec_before_task, 'args': ["how", "are", "ya"]}} main.run([task], logger=logger) self.assertEquals(task['args'], ['prehook.0', 'prehook.1']) self.assertTrue('result' not in task)
def parse_config(file): """ Checks the config values and brings them in :param file: The config.yml file :return: """ yaml_file = yaml.load(open(file)) main.run(yaml_file)
def test_small_gan_run(self): self.skipTest('too long') args = '--data=fake-mnist --imsize=32 ' \ '--model=gan --hdim=32 --zdim=32 --encoder=affine --synthesis=affine ' \ '--bsz=8 --disc-lr=4e-4 --gen-lr=1e-4 --epochs=1 ' args = utils.parser.parse_args(args.split()) print(args) main.run(args)
def test_running_main(test_dir_in, test_dir_out): run(test_dir_in, test_dir_out) expected_file = test_dir_out / "out.example01.txt" assert expected_file.exists() is True with open(expected_file) as f: assert list(f.read().splitlines()) == ["AS1a2b", "BL2a", "AS2a1b"]
def test_proc_error(self, m_Backuper): # XXX: required for tests to pass in python <3.8 open.return_value.name = "whatever" m_Backuper.return_value.run.side_effect = WhateverException with self.assertRaises(SystemExit) as ctx: module.run(self.args) self.assertEqual(ctx.exception.args, (1, ))
def test_runner(self): printer = TestPrinter() counter = CountDown(datetime(1, 1, 1, 10, 0, 0), 1) run(counter, printer) # Prints 11 timestamps (10 - 0, inclusive) and end of time statement self.assertEqual(len(printer.outputs), 12) self.assertEqual(printer.outputs[-2], 'Time is %s' % counter.format()) self.assertEqual(printer.outputs[-1], 'You have reached the beginning of the common era')
def run_for_loop(action, pointer, stack, functions, global_vars): from main import run if str(action.iterations).isnumeric(): iterations = int(action.iterations) else: iterations = sum(run(action.iterations, global_vars=global_vars, functions=functions)) for _ in range(iterations): stack[:] = run(action.command, stack=stack[:], global_vars=global_vars, functions=functions)
def runPcaOnly(self): print("Running PCA Only...") inputFilepath = self.dataPath + "/" + self.ui.dataSet.currentText() inputTrainingFilepath = self.dataPath + "/" + self.ui.trainingSet.currentText() outputFilepath = QtCore.QString(inputFilepath).replace("_colmat.pkl", "_result_pca.pkl") outputDirpath = QtCore.QString(outputFilepath).replace(".pkl", "") QtCore.QDir().mkdir(outputDirpath) PCA.run( str(inputFilepath), str(inputTrainingFilepath), str(outputFilepath), str(outputDirpath), 1, self.ui.pcaNumComp.value() ) self.updateResults()
def runCombination(self): print("Running Combination...") inputFilepath = self.dataPath + "/" + self.ui.dataSet.currentText() inputTrainingFilepath = self.dataPath + "/" + self.ui.trainingSet.currentText() outputFilepath = QtCore.QString(inputFilepath).replace("_colmat.pkl", "_result_combination.pkl") outputDirpath = QtCore.QString(outputFilepath).replace(".pkl", "") QtCore.QDir().mkdir(outputDirpath) PCA.run( str(inputFilepath), str(inputTrainingFilepath), str(outputFilepath), str(outputDirpath), self.ui.kmeansNumClust.value(), self.ui.pcaNumComp.value() ) self.updateResults()
def startup(): import sys path = "D:\\ELECTIVES\\SELF_ORGA\\new_code\\" if path not in sys.path: sys.path.append(path) sys.modules.clear() import main print "go!" main.run(globals())
def test_prehook_func_substitutes_vars(self): def exec_before_task(a,b,c): return a,b,c task = {'op': "echo", 'args': ['hello', 'prehook.1', 'prehook.0', 'prehook.2'], 'pre_hook': {'func': exec_before_task, 'args': ["how", "are", "ya"]}} main.run([task], logger=logger) self.assertEquals(task['args'], ["hello", "are", "how", "ya"]) self.assertTrue('result' in task) self.assertEquals(task['result'], 0)
def monitor(path_to_watch): fits_list = glob.glob(path_to_watch+"*.fits") reduced_list = glob.glob(path_to_watch+"reduced/*.fits") if len(fits_list) == len(reduced_list): time.sleep(10) main.run() else: print "No new files"
def debug(config_id): program.load_cache() config = models.OlderConfig.get(config_id) monday = program.week_start_date() config.warnings = [] monday = datetime.combine(monday, datetime.min.time()) program.run(config, monday) config.save()
def test_run(self): main.run() actual = True try: main.run(infile="") actual = False except Exception: actual = True expected = True self.assertEqual(actual, expected)
def run_variable(action, pointer, stack, functions, global_vars): from main import run if isinstance(action.val, str): if any(x in global_vars for x in action.val) or len(action.val) != 1: global_vars[action.name] = sum(run(action.val, functions=functions, global_vars=global_vars)) else: global_vars[action.name] = sum( run(action.val, stack=stack[:], functions=functions, global_vars=global_vars) ) else: global_vars[action.name] = int(action.val)
def main(grammar_file, test_images_dir): """ Run main optimization function from command line. :param grammar_file: Name of augmented CFDG file to start from :param test_images_dir: Name of directory where test images for exemplar scoring can be found """ click.echo( "Optimizing grammar '{0}' using the " "images in directory '{1}'...".format(grammar_file, test_images_dir) ) main.run(grammar_file, test_images_dir)
def inner_run(self, *args, **options): threading = options.get("use_threading") shutdown_message = options.get("shutdown_message", "") quit_command = (sys.platform == "win32") and "CTRL-BREAK" or "CONTROL-C" try: # fire up the app from main import run run() except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0)
def run(self): """ """ if not self.skip_build: self.run_command('build') # If we built for any other platform, we can't install. build_plat = self.distribution.get_command_obj('build').plat_name # check warn_dir - it is a clue that the 'install' is happening # internally, and not to sys.path, so we don't check the platform # matches what we are running. if self.warn_dir and build_plat != get_platform(): raise DistutilsPlatformError("Can't test when " "cross-compiling") sys.path.insert(0, os.path.join(os.getcwd(), 'test')) import main if self.build_lib is None: if os.path.exists(self.build_purelib): self.build_lib = self.build_purelib elif os.path.exists(self.build_platlib): self.build_lib = self.build_platlib link = os.path.join(self.build_scripts, "blast2seqids.py") os.symlink("blast2seqids", link) test_res = main.run(self.build_scripts, [], verbosity = self.verbosity) res_path = os.path.join("build", ".tests_results") os.unlink(link) with open(res_path, 'w') as _file: print >> _file, int(test_res.wasSuccessful()) if not test_res.wasSuccessful(): sys.exit("some tests fails. Run python setup.py test -vv to have more details")
def parse_list(instructions, pointer): from main import run # We have to do it this way to avoid circular imports. pointer += 1 list_end = instructions[pointer:].find(LIST_END) + pointer[:] list_body = instructions[pointer:list_end] pointer += len(list_body) + 1 list_val = run(list_body) return pointer, List(list_val)
def test_history(self): self.get_counters_value = (0, 0, 0) mocks.MockPatternHistory.list_mocks = [] self.configuration.pattern = models_tests.generate_pattern() self.configuration.block = models_tests.generate_block() self.configuration.level = 2 self.configuration.older = models.Older() self.configuration.warnings = [mocks.MockWarning(), mocks.MockWarning()] main.run(self.configuration, "monday") self.assertEqual(len(mocks.MockPatternHistory.list_mocks), 1) historic = mocks.MockPatternHistory.list_mocks[0] self.assertEqual(self.configuration.pattern, historic.pattern) self.assertEqual(self.configuration.block, historic.block) self.assertEqual(self.configuration.level, historic.level) self.assertEqual(self.configuration.older, historic.older) self.assertEqual(self.configuration.warnings, historic.warnings) self.assertEqual(len(historic.sessions), 2)
def run_getter(action, pointer, stack, functions, global_vars): from main import run from .stack_ops import is_int if is_int(action.location): stack.append(stack[action.location]) else: loc = sum(run(action.location, functions=functions, global_vars=global_vars)) stack.append(stack[loc])
def run_jump(action, pointer, stack, functions, global_vars): from main import run # Certain jump types require an empty stack, others need the current value of the stack if action.clear_stack: _stack = [] else: _stack = stack if stack[-1] == sum(run(action.condition, stack=_stack[:], functions=functions, global_vars=global_vars)): pointer += 2 # We skip the jump command and the next one.
def processInput(): url = request.form['url'] domain = request.form['domain'] if url != "" and url is not None: root=run(url,domain)#this run from main.py not run.py pages = spellCheckTree(root) #arr = processSpellCheck(pages) return render_template('validation.html',title="validation",elems=pages) else: return "You entered nothing"
def post(self): self.response.write('<!doctype html><html><body>Running simulation.<pre>') num_trials = int(cgi.escape(self.request.get('numTrials'))) price, volatility, option_data = main.run(num_trials) template = JINJA_ENVIRONMENT.get_template('results.html') template_values = { 'option_data': option_data, 'price': price, 'volatility': volatility} self.response.write(template.render(template_values))
def main(): grrr.set_parameter('B0', B0) grrr.set_parameter('E0', E0) grrr.set_emfield_func('const') EB = -linspace(4, 25, 16) * co.kilo / co.centi L = empty_like(EB) for i, iEB in enumerate(EB): grrr.set_parameter('EB', iEB) run(init_hooks=[init], inner_hooks=[track], finish_hooks=[]) t, z, n = (array(x) for x in (lt, lz, ln)) a, b = simple_regression(z, log(n)) L[i] = 1 / a print(("L = {} m".format(1 / a))) savetxt("avalanche_lengths.dat", c_[-EB / (co.kilo / co.centi), L]) pylab.plot(-EB / (co.kilo / co.centi), L, 'o') pylab.show()
def test(): if request.method == 'GET': return render_template('test.html') else: name = request.form['name'] code = request.form['code'] from main import run, loadBettingFunctions bfs = loadBettingFunctions() errors = [] def catchErrors(bf): def bf2(*args): try: result = bf(*args) if result is None or not isinstance(result, tuple) or len(result) != 2: raise Exception("Bad value returned: %r" % result) return result except Exception as ex: errors.append(ex) raise ex return bf2 from random import randint filename = 'temp_test_%d.py' % randint(0,1000000) with open(filename, 'w') as f: f.write(code) f.close() try: bfs[name] = catchErrors(__import__(filename[:-3]).bet) from state import State state = State.load() bets, converged = run(state, bfs, max_iterations = 100) if errors: raise errors[0] return render_template('test.html', name=name, code=code, run=True, bets=bets, converged=converged) except Exception as ex: print repr(ex) return render_template('test.html', name=name, code=code, error=repr(ex)) finally: import os os.remove(filename)