Run the experiment locally.
489658
def debug(verbose, bot, proxy, exp_config=None):
    """"""
    debugger = DebugDeployment(Output(), verbose, bot, proxy, exp_config)
    log(header, chevrons=False)
    debugger.run()
1226503
def launch_experiment(args, experiment_config, mode, config_file_name, experiment_id=None):
    ''''''
    nni_config = Config(config_file_name)
    # check packages for tuner
    if experiment_config.get('tuner') and experiment_config['tuner'].get('builtinTunerName'):
        tuner_name = experiment_config['tuner']['builtinTunerName']
        module_name = ModuleName[tuner_name]
        try:
            check_call([sys.executable, '-c', 'import %s'%(module_name)])
        except ModuleNotFoundError as e:
            print_error('The tuner %s should be installed through nnictl'%(tuner_name))
            exit(1)
    log_dir = experiment_config['logDir'] if experiment_config.get('logDir') else None
    log_level = experiment_config['logLevel'] if experiment_config.get('logLevel') else None
    if log_level not in ['trace', 'debug'] and args.debug:
        log_level = 'debug'
    # start rest server
    rest_process, start_time = start_rest_server(args.port, experiment_config['trainingServicePlatform'], mode, config_file_name, experiment_id, log_dir, log_level)
    nni_config.set_config('restServerPid', rest_process.pid)
    # Deal with annotation
    if experiment_config.get('useAnnotation'):
        path = os.path.join(tempfile.gettempdir(), get_user(), 'nni', 'annotation')
        if not os.path.isdir(path):
            os.makedirs(path)
        path = tempfile.mkdtemp(dir=path)
        code_dir = expand_annotations(experiment_config['trial']['codeDir'], path)
        experiment_config['trial']['codeDir'] = code_dir
        search_space = generate_search_space(code_dir)
        experiment_config['searchSpace'] = json.dumps(search_space)
        assert search_space, ERROR_INFO % 'Generated search space is empty'
    elif experiment_config.get('searchSpacePath'):
        search_space = get_json_content(experiment_config.get('searchSpacePath'))
        experiment_config['searchSpace'] = json.dumps(search_space)
    else:
        experiment_config['searchSpace'] = json.dumps('')

    # check rest server
    running, _ = check_rest_server(args.port)
    if running:
        print_normal('Successfully started Restful server!')
    else:
        print_error('Restful server start failed!')
        print_log_content(config_file_name)
        try:
            kill_command(rest_process.pid)
        except Exception:
            raise Exception(ERROR_INFO % 'Rest server stopped!')
        exit(1)

    # set remote config
    if experiment_config['trainingServicePlatform'] == 'remote':
        print_normal('Setting remote config...')
        config_result, err_msg = set_remote_config(experiment_config, args.port, config_file_name)
        if config_result:
            print_normal('Successfully set remote config!')
        else:
            print_error('Failed! Error is: {}'.format(err_msg))
            try:
                kill_command(rest_process.pid)
            except Exception:
                raise Exception(ERROR_INFO % 'Rest server stopped!')
            exit(1)

    # set local config
    if experiment_config['trainingServicePlatform'] == 'local':
        print_normal('Setting local config...')
        if set_local_config(experiment_config, args.port, config_file_name):
            print_normal('Successfully set local config!')
        else:
            print_error('Set local config failed!')
            try:
                kill_command(rest_process.pid)
            except Exception:
                raise Exception(ERROR_INFO % 'Rest server stopped!')
            exit(1)
    
    #set pai config
    if experiment_config['trainingServicePlatform'] == 'pai':
        print_normal('Setting pai config...')
        config_result, err_msg = set_pai_config(experiment_config, args.port, config_file_name)
        if config_result:
            print_normal('Successfully set pai config!')
        else:
            if err_msg:
                print_error('Failed! Error is: {}'.format(err_msg))
            try:
                kill_command(rest_process.pid)
            except Exception:
                raise Exception(ERROR_INFO % 'Restful server stopped!')
            exit(1)
    
    #set kubeflow config
    if experiment_config['trainingServicePlatform'] == 'kubeflow':
        print_normal('Setting kubeflow config...')
        config_result, err_msg = set_kubeflow_config(experiment_config, args.port, config_file_name)
        if config_result:
            print_normal('Successfully set kubeflow config!')
        else:
            if err_msg:
                print_error('Failed! Error is: {}'.format(err_msg))
            try:
                kill_command(rest_process.pid)
            except Exception:
                raise Exception(ERROR_INFO % 'Restful server stopped!')
            exit(1)
    
        #set kubeflow config
    if experiment_config['trainingServicePlatform'] == 'frameworkcontroller':
        print_normal('Setting frameworkcontroller config...')
        config_result, err_msg = set_frameworkcontroller_config(experiment_config, args.port, config_file_name)
        if config_result:
            print_normal('Successfully set frameworkcontroller config!')
        else:
            if err_msg:
                print_error('Failed! Error is: {}'.format(err_msg))
            try:
                kill_command(rest_process.pid)
            except Exception:
                raise Exception(ERROR_INFO % 'Restful server stopped!')
            exit(1)

    # start a new experiment
    print_normal('Starting experiment...')
    # set debug configuration
    if experiment_config.get('debug') is None:
        experiment_config['debug'] = args.debug
    response = set_experiment(experiment_config, mode, args.port, config_file_name)
    if response:
        if experiment_id is None:
            experiment_id = json.loads(response.text).get('experiment_id')
        nni_config.set_config('experimentId', experiment_id)
    else:
        print_error('Start experiment failed!')
        print_log_content(config_file_name)
        try:
            kill_command(rest_process.pid)
        except Exception:
            raise Exception(ERROR_INFO % 'Restful server stopped!')
        exit(1)
    if experiment_config.get('nniManagerIp'):
        web_ui_url_list = ['{0}:{1}'.format(experiment_config['nniManagerIp'], str(args.port))]
    else:
        web_ui_url_list = get_local_urls(args.port)
    nni_config.set_config('webuiUrl', web_ui_url_list)
    
    #save experiment information
    nnictl_experiment_config = Experiments()
    nnictl_experiment_config.add_experiment(experiment_id, args.port, start_time, config_file_name, experiment_config['trainingServicePlatform'])

    print_normal(EXPERIMENT_SUCCESS_INFO % (experiment_id, '   '.join(web_ui_url_list)))
767196
def run(self):
        
        self._connection = self.connect()
        self._connection.ioloop.start()
287157
def set_local_config(experiment_config, port, config_file_name):
    ''''''
    #set machine_list
    request_data = dict()
    if experiment_config.get('localConfig'):
        request_data['local_config'] = experiment_config['localConfig']
        if request_data['local_config'] and request_data['local_config'].get('gpuIndices') \
            and isinstance(request_data['local_config'].get('gpuIndices'), int):
            request_data['local_config']['gpuIndices'] = str(request_data['local_config'].get('gpuIndices'))
        response = rest_put(cluster_metadata_url(port), json.dumps(request_data), REST_TIME_OUT)
        err_message = ''
        if not response or not check_response(response):
            if response is not None:
                err_message = response.text
                _, stderr_full_path = get_log_path(config_file_name)
                with open(stderr_full_path, 'a+') as fout:
                    fout.write(json.dumps(json.loads(err_message), indent=4, sort_keys=True, separators=(',', ':')))
            return False, err_message

    return set_trial_config(experiment_config, port, config_file_name)
1194391
def run_experiment(self, qasm, backend='simulator', shots=1, name=None,
                       seed=None, timeout=60, access_token=None, user_id=None):
        
        if access_token:
            self.req.credential.set_token(access_token)
        if user_id:
            self.req.credential.set_user_id(user_id)
        if not self.check_credentials():
            raise CredentialsError('credentials invalid')

        backend_type = self._check_backend(backend, 'experiment')
        if not backend_type:
            raise BadBackendError(backend)

        if backend not in self.__names_backend_simulator and seed:
            raise ApiError('seed not allowed for'
                           ' non-simulator backend "{}"'.format(backend))

        name = name or 'Experiment #{:%Y%m%d%H%M%S}'.format(datetime.now())
        qasm = qasm.replace('IBMQASM 2.0;', '').replace('OPENQASM 2.0;', '')
        data = json.dumps({'qasm': qasm, 'codeType': 'QASM2', 'name': name})

        if seed and len(str(seed)) < 11 and str(seed).isdigit():
            params = '&shots={}&seed={}&deviceRunType={}'.format(shots, seed,
                                                                 backend_type)
            execution = self.req.post('/codes/execute', params, data)
        elif seed:
            raise ApiError('invalid seed ({}), seeds can have'
                           ' a maximum length of 10 digits'.format(seed))
        else:
            params = '&shots={}&deviceRunType={}'.format(shots, backend_type)
            execution = self.req.post('/codes/execute', params, data)
        respond = {}
        try:
            status = execution["status"]["id"]
            id_execution = execution["id"]
            result = {}
            respond["status"] = status
            respond["idExecution"] = id_execution
            respond["idCode"] = execution["codeId"]

            if 'infoQueue' in execution:
                respond['infoQueue'] = execution['infoQueue']

            if status == "DONE":
                if "result" in execution and "data" in execution["result"]:
                    if "additionalData" in execution["result"]["data"]:
                        ad_aux = execution["result"]["data"]["additionalData"]
                        result["extraInfo"] = ad_aux
                    if execution["result"]["data"].get('p', None):
                        result["measure"] = execution["result"]["data"]["p"]
                    if execution["result"]["data"].get('valsxyz', None):
                        valsxyz = execution["result"]["data"]["valsxyz"]
                        result["bloch"] = valsxyz
                    respond["result"] = result
                    respond.pop('infoQueue', None)

                    return respond
            elif status == "ERROR":
                respond.pop('infoQueue', None)
                return respond
            else:
                if timeout:
                    for _ in range(1, timeout):
                        print("Waiting for results...")
                        result = self.get_result_from_execution(id_execution)
                        if result:
                            respond["status"] = 'DONE'
                            respond["result"] = result
                            respond["calibration"] = result["calibration"]
                            del result["calibration"]
                            respond.pop('infoQueue', None)
                            return respond
                        else:
                            time.sleep(2)
                    return respond
                else:
                    return respond
        except Exception:
            respond["error"] = execution
            return respond
364876
def run():
    """"""
    
    # Grab server args
    args = client_helper.grab_server_args()

    # Start up workbench connection
    workbench = zerorpc.Client(timeout=300, heartbeat=60)
    workbench.connect('tcp://'+args['server']+':'+args['port'])

    # Upload the file into workbench
    my_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                           '../data/pe/bad/033d91aae8ad29ed9fbb858179271232')
    with open(my_file,'rb') as f:

        # Throw file into workbench
        filename = os.path.basename(my_file)
        raw_bytes = f.read()
        md5 = workbench.store_sample(raw_bytes, filename, 'exe')
        results = workbench.work_request('view', md5)
        print 'Filename: %s' % filename
        pprint.pprint(results)
157361
def local_run():
  """"""
  server_software = os.environ.get('SERVER_SOFTWARE')
  if server_software is None:
    return True
  if 'remote_api' in server_software:
    return False
  if server_software.startswith(('Development', 'testutil')):
    return True
  return False
98941
def run_experiment(self):
        
        data=self.data
        options=self.options
        result=self.result

        command = open(self.options.experiment_script).read()
        result["experiment_script"]=command
        t0=time.time()
        exec(command)   #creates variable result
        t1=time.time()
        print(("Elapsed time for running the experiment is %.2f seconds" % (t1-t0)))
        self.result=result
        return self.result
445595
def run(self):
        """"""
        self.exc = None
        try:
            self.task()
        except BaseException:
            self.exc = sys.exc_info()
1217124
def run(self):
        
        luigi.LocalTarget(path=self.fixture).copy(self.output().path)
723427
def run(self):
        """"""
        i = 0
        operation_count = int(self._parameters['operationcount'])
        while i < operation_count:
            i += 1
            weight = random.uniform(0, self._total_weight)
            for j in range(len(self._weights)):
                if weight <= self._weights[j]:
                    do_operation(self._database, self._keys,
                                 self._parameters['table'],
                                 self._operations[j], self._latencies_ms)
                    break
1024896
def main(args,parser,subparser=None):
    '''

    '''

    # First priority to args.base
    base = args.base
    if base is None:
        base = os.environ.get('EXPFACTORY_BASE')

    # Does the base folder exist?
    if base is None:
        bot.error("You must set a base of experiments with --base" % base)
        sys.exit(1)

    if not os.path.exists(base):
        bot.error("Base folder %s does not exist." % base)
        sys.exit(1)

    # Export environment variables for the client
    experiments = args.experiments
    if experiments is None:
        experiments = " ".join(glob("%s/*" % base))

    os.environ['EXPFACTORY_EXPERIMENTS'] = experiments

    # If defined and file exists, set runtime variables
    if args.vars is not None:
        if os.path.exists(args.vars):
            os.environ['EXPFACTORY_RUNTIME_VARS'] = args.vars
            os.environ['EXPFACTORY_RUNTIME_DELIM'] = args.delim
        else:
            bot.warning('Variables file %s not found.' %args.vars)


    subid = os.environ.get('EXPFACTORY_STUDY_ID')
    if args.subid is not None:
        subid = args.subid 
        os.environ['EXPFACTORY_SUBID'] = subid

    os.environ['EXPFACTORY_RANDOM'] = str(args.disable_randomize)
    os.environ['EXPFACTORY_BASE'] = base
    
    from expfactory.server import start
    start(port=5000)
63858
def run(self):
        """"""
        _, test_data = self.data.load(train=False, test=True)
        try:
            self.model.fit_generator(
                self.samples_to_batches(self.generate_samples(), self.args.batch_size), steps_per_epoch=self.args.steps_per_epoch,
                epochs=self.epoch + self.args.epochs, validation_data=test_data,
                callbacks=self.callbacks, initial_epoch=self.epoch
            )
        finally:
            self.model.save(self.args.model)
            save_params(self.args.model)
17603
def run(self):
    
    experiment = self._context.experiment()
    if experiment is None:
      raise error.HParamsError(
          "Can't find an HParams-plugin experiment data in"
          " the log directory. Note that it takes some time to"
          " scan the log directory; if you just started"
          " Tensorboard it could be that we haven't finished"
          " scanning it yet. Consider trying again in a"
          " few seconds.")
    return experiment
705895
async function runSample() {
  const res = await mirror.locations.list({});
  console.log(res.data);
}
129057
def run(self):
    """"""
    compiler = new_compiler(compiler=self.compiler)
    if compiler.compiler_type == "msvc":
      self.define = [
          ("UNICODE", ""),
      ]

    else:
      command = "sh configure --disable-shared-libs"
      output = self._RunCommand(command)

      print_line = False
      for line in output.split("\n"):
        line = line.rstrip()
        if line == "configure:":
          print_line = True

        if print_line:
          print(line)

      self.define = [
          ("HAVE_CONFIG_H", ""),
          ("LOCALEDIR", "\"/usr/share/locale\""),
      ]

    build_ext.run(self)
936034
def run():
    """"""

    # NOTE(kiennt): Until now, this example isn't finished yet,
    #               because we don't have any completed driver

    # Get a network client with openstack driver.

    network_client = client.Client(version=_VERSION,
                        resource=_RESOURCES[0], provider=_PROVIDER)
    # net = network_client.create('daikk', '10.0.0.0/24')
    # list_subnet = network_client.list()
    # network_client.show(list_subnet[0].get("id"))
    network_client.delete("4b983028-0f8c-4b63-b10c-6e8420bb7903")