usage: cosmic-ray exec <session-file>

    Perform the remaining work to be done in the specified session.
    This requires that the rest of your mutation testing
    infrastructure (e.g. worker processes) are already running.
761837
def handle_exec(args):
    
    session_file = get_db_name(args.get('<session-file>'))
    cosmic_ray.commands.execute(session_file)

    return ExitCode.OK
1200099
function executable(file) {
  try {
    fs.accessSync(file, fs.X_OK);
    return true;
  } catch (e) {
    return false;
  }
}
1292776
def execute(self, cmd, block_size=DEFAULT_EXECUTE_READ_BLOCK_SIZE):
        
    
        with SshChannel(self) as sc:
            self.__log.debug("Executing command: %s" % (cmd))

            sc.open_session()
            sc.request_exec(cmd)

            buffer_ = bytearray()
            while 1:
                bytes = sc.read(block_size)
                yield bytes
                
                if len(bytes) < block_size:
                    break
314850
function execFile() {
      var child;

      if (options.strategy === 'development') {
        child = core.spawnPump(options, false, false);
        if (options.relay) child.pump(process);
      } else if (options.strategy === 'unattached') {
        child = core.spawnPump(options, true, false);
      } else if (options.strategy === 'daemon') {
        child = core.spawnDaemon(options, true);
      }

      // start child
      child.spawn();

      child.on('start', function () {
        callback(null);
      });
    }
710130
def _run_script(self, session, file_path):
        
        if file_path:
            # The 'run' command returns False in case of error
            # The 'execute' method returns False if the run command fails
            return self._shell.execute('run "{0}"'.format(file_path), session)

        return None
898873
def execute(self, command, term='xterm'):
        
        transport = self._ssh.get_transport()
        channel = transport.open_session()
        channel.get_pty(term)
        channel.exec_command(command)
        self._bridge(channel)
        channel.close()
574635
def run(self, args=(), env={}):
        

        # the following will call self._get_exec_binary
        return self._exec(self.binary, args=args, env=env)
166648
@Override
  public void exec(Frame fr, Random rng) {
    // No need to do anything if p == 0
    if (p > 0)
      new InsertNAs(p, rng).doAll(fr);
  }
687221
def do_exec(config, config_dir):
    
    if not os.path.exists(config_dir):
        print "Configuration '{}' does not exist.".format(config)
        exit(1)

    print "The parser for '{}' config has been initialized.".format(config)

    config_file = os.path.join(config_dir, 'config')
    with open(config_file, 'r') as f:
        config_data = json.load(f)

    url = config_data['url']
    torrent_dir = config_data['torrent_dir']
    ensure_dir(torrent_dir)

    filters_file = os.path.join(config_dir, 'filter')
    filters = read_file(filters_file)

    blacklist_file = os.path.join(config_dir, 'blacklist')
    blacklist = read_file(blacklist_file)

    print "Fetching URL {}".format(url)
    r = requests.get(url)
    if r.status_code != 200:
        print "Failed to fetch RSS feed."

    xml = r.text.encode('utf-8')
    parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8')
    tree  = etree.fromstring(xml, parser)
    items = tree.xpath('//item')
    downloaded = 0
    for e in items:
        e_title = e.xpath('title')[0].text
        e_link = e.xpath('link')[0].text
        if not drop_it(e_title, filters, blacklist):
            downloaded += 1
            target_file = os.path.join(torrent_dir, e_title + '.torrent')
            r = requests.get(e_link, stream=True)
            with open(target_file, 'wb') as f:
                for chunk in r.iter_content(4096):
                    f.write(chunk)

    print "Items found: {}, items downloaded: {}."\
        .format(len(items), downloaded)
611880
private void exec(File command,
                      String pathInfo,
                      HttpServletRequest req,
                      HttpServletResponse res)
        throws IOException
    {
        String path=command.toString();
        File dir=command.getParentFile();
        if(log.isDebugEnabled())log.debug("CGI: execing: "+path);

	EnvList env = new EnvList(_env);

	// these ones are from "The WWW Common Gateway Interface Version 1.1"
	// look at : http://Web.Golux.Com/coar/cgi/draft-coar-cgi-v11-03-clean.html#6.1.1
	env.set("AUTH_TYPE", req.getAuthType());
	env.set("CONTENT_LENGTH", Integer.toString(req.getContentLength()));
	env.set("CONTENT_TYPE", req.getContentType());
	env.set("GATEWAY_INTERFACE", "CGI/1.1");
	env.set("PATH_INFO", pathInfo);
	env.set("PATH_TRANSLATED", req.getPathTranslated());
	env.set("QUERY_STRING", req.getQueryString());
	env.set("REMOTE_ADDR", req.getRemoteAddr());
	env.set("REMOTE_HOST", req.getRemoteHost());
	// The identity information reported about the connection by a
	// RFC 1413 [11] request to the remote agent, if
	// available. Servers MAY choose not to support this feature, or
	// not to request the data for efficiency reasons.
	// "REMOTE_IDENT" => "NYI"
	env.set("REMOTE_USER", req.getRemoteUser());
	env.set("REQUEST_METHOD", req.getMethod());
    String scriptName = req.getRequestURI().substring(0,req.getRequestURI().length() - pathInfo.length());
	env.set("SCRIPT_NAME",scriptName);
    env.set("SCRIPT_FILENAME",getServletContext().getRealPath(scriptName));
    env.set("SERVER_NAME", req.getServerName());
	env.set("SERVER_PORT", Integer.toString(req.getServerPort()));
	env.set("SERVER_PROTOCOL", req.getProtocol());
        env.set("SERVER_SOFTWARE", getServletContext().getServerInfo());
	Enumeration enm = req.getHeaderNames();
	while (enm.hasMoreElements())
	{
	    String name = (String) enm.nextElement();
	    String value = req.getHeader(name);
	    env.set("HTTP_" + name.toUpperCase().replace( '-', '_' ), value);
	}

	// these extra ones were from printenv on www.dev.nomura.co.uk
	env.set("HTTPS", (req.isSecure()?"ON":"OFF"));
	// "DOCUMENT_ROOT" => root + "/docs",
	// "SERVER_URL" => "NYI - http://us0245",
	// "TZ" => System.getProperty("user.timezone"),

        // are we meant to decode args here ? or does the script get them
        // via PATH_INFO ?  if we are, they should be decoded and passed
        // into exec here...

        String execCmd=path;
        if (execCmd.indexOf(" ")>=0)
            execCmd="\""+execCmd+"\"";
        if (_cmdPrefix!=null)
            execCmd=_cmdPrefix+" "+execCmd;

        Process p=dir==null
            ?Runtime.getRuntime().exec(execCmd, env.getEnvArray())
            :Runtime.getRuntime().exec(execCmd, env.getEnvArray(),dir);

        // hook processes input to browser's output (async)
        final InputStream inFromReq=req.getInputStream();
        final OutputStream outToCgi=p.getOutputStream();
        final int inputLength = req.getContentLength();

        new Thread(new Runnable()
            {
                public void run()
                {
                    try{
                        if (inputLength>0)
                            IO.copy(inFromReq,outToCgi,inputLength);
                        outToCgi.close();
                    }
                    catch(IOException e){LogSupport.ignore(log,e);}
                }
            }).start();


        // hook processes output to browser's input (sync)
        // if browser closes stream, we should detect it and kill process...
        try
        {
            // read any headers off the top of our input stream
            LineInput li = new LineInput(p.getInputStream());
            HttpFields fields=new HttpFields();
            fields.read(li);

            String ContentStatus = "Status";
            String redirect = fields.get(HttpFields.__Location);
            String status   = fields.get(ContentStatus);

            if (status!=null)
            {
                log.debug("Found a Status header - setting status on response");
                fields.remove(ContentStatus);

                // NOTE: we ignore any reason phrase, otherwise we
                // would need to use res.sendError() selectively.
                int i = status.indexOf(' ');
                if (i>0)
                    status = status.substring(0,i);

                res.setStatus(Integer.parseInt(status));
            }

            // copy remaining headers into response...
	    for (Iterator i=fields.iterator(); i.hasNext();)
            {
                HttpFields.Entry e=(HttpFields.Entry)i.next();
                res.addHeader(e.getKey(),e.getValue());
            }

            if (status==null && redirect != null)
            {
                // The CGI has set Location and is counting on us to do the redirect.
                // See http://CGI-Spec.Golux.Com/draft-coar-cgi-v11-03-clean.html#7.2.1.2
                if (!redirect.startsWith("http:/")&&!redirect.startsWith("https:/"))
                    res.sendRedirect(redirect);
                else
                    res.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
            }

            // copy remains of input onto output...
            IO.copy(li, res.getOutputStream());

	    p.waitFor();
	    int exitValue = p.exitValue();
	    if(log.isDebugEnabled())log.debug("CGI: p.exitValue(): " + exitValue);
	    if (0 != exitValue)
	    {
		log.warn("Non-zero exit status ("+exitValue+
			     ") from CGI program: "+path);
		if (!res.isCommitted())
		    res.sendError(500, "Failed to exec CGI");
	    }
        }
        catch (IOException e)
        {
            // browser has probably closed its input stream - we
            // terminate and clean up...
            log.debug("CGI: Client closed connection!");
        }
	catch (InterruptedException ie)
        {
            log.debug("CGI: interrupted!");
        }
	finally
	{
            p.destroy();
	}

	if(log.isDebugEnabled())log.debug("CGI: Finished exec: " + p);
    }
35999
function checkExec (mode, callback) {
  if (!exercise.passed)
    return callback(null, true) // shortcut if we've already had a failure

  childProcess.exec(
        '"'
      + process.execPath
      + '" "'
      + copyTempDir
      + '" "'
      + expected
      + '"'
    , function (err, stdout, stderr) {
        if (err) {
          process.stderr.write(stderr)
          process.stdout.write(stdout)
          return callback(err)
        }

        var pass = stdout.toString().replace('\r', '') == expected + '\n'
          , seminl = !pass && stdout.toString() == expected

        if (!seminl && !pass) {
          process.stderr.write(stderr)
          process.stdout.write(stdout)
        }

        if (seminl)
          exercise.emit('fail', 'Addon prints out expected string (missing newline)')
        else
          exercise.emit(pass ? 'pass' : 'fail', 'Addon prints out expected string')

        callback(null, pass)
      }
  )
}
823737
def run(self, *args, **kwargs):
        
        if self.gw and shiboken.isValid(self.gw):
            self.gw.deleteLater()
        mayawin = maya_main_window()
        self.gw = self.GenesisWin(parent=mayawin)
        self.gw.last_file.connect(self.save_lastfile)
        if not self.gw.get_current_file():
            c = self.get_config()
            try:
                f = models.TaskFile.objects.get(pk=c['lastfile'])
            except models.TaskFile.DoesNotExist:
                pass
            else:
                self.gw.browser.set_selection(f)
        self.gw.show()
35452
private void executeCommand(long index, long sequence, long timestamp, ServerCommit commit, ServerSessionContext session, CompletableFuture<Result> future, ThreadContext context) {
    if (!log.isOpen()) {
      context.executor().execute(() -> future.completeExceptionally(new IllegalStateException("log closed")));
      return;
    }

    // If the session is already in an inactive state, complete the future exceptionally.
    if (!session.state().active()) {
      context.executor().execute(() -> future.completeExceptionally(new UnknownSessionException("inactive session: " + session.id())));
      return;
    }

    // Trigger scheduled callbacks in the state machine.
    executor.tick(index, timestamp);

    // Update the state machine context with the commit index and local server context. The synchronous flag
    // indicates whether the server expects linearizable completion of published events. Events will be published
    // based on the configured consistency level for the context.
    executor.init(commit.index(), commit.time(), ServerStateMachineContext.Type.COMMAND);

    // Store the event index to return in the command response.
    long eventIndex = session.getEventIndex();

    try {
      // Execute the state machine operation and get the result.
      Object output = executor.executeOperation(commit);

      // Once the operation has been applied to the state machine, commit events published by the command.
      // The state machine context will build a composite future for events published to all sessions.
      executor.commit();

      // Store the result for linearizability and complete the command.
      Result result = new Result(index, eventIndex, output);
      session.registerResult(sequence, result);
      context.executor().execute(() -> future.complete(result));
    } catch (Exception e) {
      // If an exception occurs during execution of the command, store the exception.
      Result result = new Result(index, eventIndex, e);
      session.registerResult(sequence, result);
      context.executor().execute(() -> future.complete(result));
    }
  }
105924
async def _run(self, data_id, script):
        """"""
        self.data_id = data_id

        # Fetch data instance to get any executor requirements.
        self.process = PROCESS
        requirements = self.process['requirements']
        self.requirements = requirements.get('executor', {}).get(self.name, {})  # pylint: disable=no-member
        self.resources = requirements.get('resources', {})

        logger.debug("Preparing output files for Data with id {}".format(data_id))
        os.chdir(EXECUTOR_SETTINGS['DATA_DIR'])
        try:
            log_file = self._create_file('stdout.txt')
            json_file = self._create_file('jsonout.txt')
        except FileExistsError:
            logger.error("Stdout or jsonout out file already exists.")
            # Looks like executor was already ran for this Data object,
            # so don't raise the error to prevent setting status to error.
            await self._send_manager_command(ExecutorProtocol.ABORT, expect_reply=False)
            return

        proc_pid = await self.start()

        await self.update_data_status(
            status=DATA_META['STATUS_PROCESSING'],
            process_pid=proc_pid
        )

        # Run process and handle intermediate results
        logger.info("Running program for Data with id {}".format(data_id))
        logger.debug("The program for Data with id {} is: \n{}".format(data_id, script))
        await self.run_script(script)
        spawn_processes = []
        output = {}
        process_error, process_warning, process_info = [], [], []
        process_progress, process_rc = 0, 0

        # read process output
        try:
            stdout = self.get_stdout()
            while True:
                line = await stdout.readline()
                logger.debug("Process's output: {}".format(line.strip()))

                if not line:
                    break
                line = line.decode('utf-8')

                try:
                    if line.strip().startswith('run'):
                        # Save process and spawn if no errors
                        log_file.write(line)
                        log_file.flush()

                        for obj in iterjson(line[3:].strip()):
                            spawn_processes.append(obj)
                    elif line.strip().startswith('export'):
                        file_name = line[6:].strip()

                        export_folder = SETTINGS['FLOW_EXECUTOR']['UPLOAD_DIR']
                        unique_name = 'export_{}'.format(uuid.uuid4().hex)
                        export_path = os.path.join(export_folder, unique_name)

                        self.exported_files_mapper[self.data_id][file_name] = unique_name

                        shutil.move(file_name, export_path)
                    else:
                        # If JSON, save to MongoDB
                        updates = {}
                        for obj in iterjson(line):
                            for key, val in obj.items():
                                if key.startswith('proc.'):
                                    if key == 'proc.error':
                                        process_error.append(val)
                                        if not process_rc:
                                            process_rc = 1
                                            updates['process_rc'] = process_rc
                                        updates['process_error'] = process_error
                                        updates['status'] = DATA_META['STATUS_ERROR']
                                    elif key == 'proc.warning':
                                        process_warning.append(val)
                                        updates['process_warning'] = process_warning
                                    elif key == 'proc.info':
                                        process_info.append(val)
                                        updates['process_info'] = process_info
                                    elif key == 'proc.rc':
                                        process_rc = int(val)
                                        updates['process_rc'] = process_rc
                                        if process_rc != 0:
                                            updates['status'] = DATA_META['STATUS_ERROR']
                                    elif key == 'proc.progress':
                                        process_progress = int(float(val) * 100)
                                        updates['process_progress'] = process_progress
                                else:
                                    output[key] = val
                                    updates['output'] = output

                        if updates:
                            await self.update_data_status(**updates)
                            # Process meta fields are collected in listener, so we can clear them.
                            process_error, process_warning, process_info = [], [], []

                        if process_rc > 0:
                            log_file.close()
                            json_file.close()
                            await self._send_manager_command(ExecutorProtocol.FINISH, extra_fields={
                                ExecutorProtocol.FINISH_PROCESS_RC: process_rc
                            })
                            return

                        # Debug output
                        # Not referenced in Data object
                        json_file.write(line)
                        json_file.flush()

                except ValueError as ex:
                    # Ignore if not JSON
                    log_file.write(line)
                    log_file.flush()

        except MemoryError as ex:
            logger.error("Out of memory:\n\n{}".format(ex))

        except IOError as ex:
            # TODO: if ex.errno == 28: no more free space
            raise ex
        finally:
            # Store results
            log_file.close()
            json_file.close()

        return_code = await self.end()

        if process_rc < return_code:
            process_rc = return_code

        # send a notification to the executor listener that we're done
        finish_fields = {
            ExecutorProtocol.FINISH_PROCESS_RC: process_rc
        }
        if spawn_processes and process_rc == 0:
            finish_fields[ExecutorProtocol.FINISH_SPAWN_PROCESSES] = spawn_processes
            finish_fields[ExecutorProtocol.FINISH_EXPORTED_FILES] = self.exported_files_mapper

        return finish_fields
906893
@Override
	public void execute() {
		// save archive dir of the outer module so it can be reset later
		String previousArchiveDir = archiveDirProvider.get().getPath();

		try {
			// make sure archive dirs are within that of the container module
			moduleArchiveDir = moduleArchiveDirProvider.get().getPath();
			config.put(JFunkConstants.ARCHIVE_DIR, moduleArchiveDir);

			for (ModuleWithCallbacks moduleWithCallbacks : modulesWithCallbacks) {
				TestModule testModule = moduleWithCallbacks.testModule;

				Runnable beforeModuleCallback = moduleWithCallbacks.beforeModuleCallback;
				if (beforeModuleCallback != null) {
					beforeModuleCallback.run();
				}

				scriptContext.run(testModule);

				Runnable afterModuleCallback = moduleWithCallbacks.afterModuleCallback;
				if (afterModuleCallback != null) {
					afterModuleCallback.run();
				}
			}
		} finally {
			// reset for outer module, so property is correctly archived
			config.put(JFunkConstants.ARCHIVE_DIR, previousArchiveDir);

			// it does not make sense to archive datasets in the container module,
			// these would be those of the test module executed last
			config.put(JFunkConstants.ARCHIVE_DATASETS, "false");
		}
	}
287334
def run(self, files, working_area):
        

        # Ensure that dictionary is ordered by check declaration order (via self.check_names)
        # NOTE: Requires CPython 3.6. If we need to support older versions of Python, replace with OrderedDict.
        results = {name: None for name in self.check_names}
        checks_root = working_area.parent
        with futures.ProcessPoolExecutor() as executor:

            # Start all checks that have no dependencies
            not_done = set(executor.submit(run_check(name, self.checks_spec, checks_root))
                           for name, _ in self.child_map[None])
            not_passed = []

            while not_done:
                done, not_done = futures.wait(not_done, return_when=futures.FIRST_COMPLETED)
                for future in done:
                    # Get result from completed check
                    result, state = future.result()
                    results[result.name] = result
                    if result.passed:
                        # Dispatch dependent checks
                        for child_name, _ in self.child_map[result.name]:
                            not_done.add(executor.submit(
                                run_check(child_name, self.checks_spec, checks_root, state)))
                    else:
                        not_passed.append(result.name)

        for name in not_passed:
            self._skip_children(name, results)

        return results.values()
1161591
@Override
    public void execute() throws MojoExecutionException {
        new WisdomExecutor().executeInBackground(this);
        File pid = new File(getWisdomRootDirectory(), "RUNNING_PID");
        if (WisdomExecutor.waitForFile(pid)) {
            try {
                getLog().info("Wisdom launched in background in process '" + FileUtils.readFileToString(pid) + "'.");
            } catch (IOException e) {
                getLog().warn("Cannot read the 'RUNNING_PID' file", e);
            }
        } else {
            getLog().error("The " + pid.getName() + " file was not created despite the 'successful' launch of Wisdom");
        }
    }