A helper method which runs the given script file with the given command line arguments

@param scriptFile the file of the script to run
@param list       the command line arguments to pass in
18030
public Object run(File scriptFile, List list) throws CompilationFailedException, IOException {
        return run(scriptFile, (String[]) list.toArray(EMPTY_STRING_ARRAY));
    }
249283
protected void executeScript(URL scriptUrl) {
        log.debug("Executing script '{}'", scriptUrl);
        final Jedis jedis = pool.getResource();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(scriptUrl.openStream(), StandardCharsets.UTF_8))) {
            reader.lines()
                    .filter(line -> !Strings.isNullOrEmpty(line) && line.charAt(0) != '#' && !line.startsWith("//"))
                    .forEach(line -> {
                        try {
                            log.trace("execute: {}", line);
                            String[] args = line.split(" ", 3);
                            String command = null;
                            if (args.length == 1) {
                                command = String.format("return redis.call('%s')", args[0]);
                            } else if (args.length == 2) {
                                command = String.format("return redis.call('%s', '%s')", args[0], args[1]);
                            } else if (args.length == 3) {
                                command = String.format("return redis.call('%s', '%s', '%s')", args[0], args[1], unwrapQuotes(args[2]));
                            } else {
                                log.error("Unexpected number of script arguments {}", args.length);
                            }
                            log.trace("command: {}", command);
                            Object result = jedis.eval(command);
                        } catch (Exception e) {
                            log.error("Failed to execute '{}'", line, e);
                        }
                    });
        } catch (IOException e) {
            log.error("Failed to execute script '{}'", scriptUrl, e);
            pool.returnBrokenResource(jedis);
//            jedis = null;
        } finally {
            if (jedis != null) {
                pool.returnResource(jedis);
            }
        }
    }
375858
public final void setSourceFile(final String srcFile) {
        if (SwingUtilities.isEventDispatchThread()) {
            setSourceFileIntern(srcFile);
        } else {
            try {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        setSourceFileIntern(srcFile);
                    }
                });
            } catch (final Exception ex) {
                ignore();
            }
        }
    }
947575
public static void runScript(Database database, String logFilename,
                                 int logType) {

        IntKeyHashMap sessionMap = new IntKeyHashMap();
        Session       current    = null;
        int           currentId  = 0;

        database.setReferentialIntegrity(false);

        ScriptReaderBase scr = null;
        String           statement;
        int              statementType;

        try {
            StopWatch sw = new StopWatch();

            scr = ScriptReaderBase.newScriptReader(database, logFilename,
                                                   logType);

            while (scr.readLoggedStatement(current)) {
                int sessionId = scr.getSessionNumber();

                if (current == null || currentId != sessionId) {
                    currentId = sessionId;
                    current   = (Session) sessionMap.get(currentId);

                    if (current == null) {
                        current =
                            database.getSessionManager().newSession(database,
                                database.getUserManager().getSysUser(), false,
                                true, 0);

                        sessionMap.put(currentId, current);
                    }
                }

                if (current.isClosed()) {
                    sessionMap.remove(currentId);

                    continue;
                }

                Result result = null;

                statementType = scr.getStatementType();

                switch (statementType) {

                    case ScriptReaderBase.ANY_STATEMENT :
                        statement = scr.getLoggedStatement();
                        result    = current.executeDirectStatement(statement);

                        if (result != null && result.isError()) {
                            if (result.getException() != null) {
                                throw result.getException();
                            }

                            throw Error.error(result);
                        }
                        break;

                    case ScriptReaderBase.SEQUENCE_STATEMENT :
                        scr.getCurrentSequence().reset(scr.getSequenceValue());
                        break;

                    case ScriptReaderBase.COMMIT_STATEMENT :
                        current.commit(false);
                        break;

                    case ScriptReaderBase.INSERT_STATEMENT : {
                        current.beginAction(null);

                        Object[] data = scr.getData();

                        scr.getCurrentTable().insertNoCheckFromLog(current,
                                data);
                        current.endAction(Result.updateOneResult);

                        break;
                    }
                    case ScriptReaderBase.DELETE_STATEMENT : {
                        current.beginAction(null);

                        Object[] data = scr.getData();

                        scr.getCurrentTable().deleteNoCheckFromLog(current,
                                data);
                        current.endAction(Result.updateOneResult);

                        break;
                    }
                    case ScriptReaderBase.SET_SCHEMA_STATEMENT : {
                        current.setSchema(scr.getCurrentSchema());
                    }
                }

                if (current.isClosed()) {
                    sessionMap.remove(currentId);
                }
            }
        } catch (Throwable e) {
            String message;

            // catch out-of-memory errors and terminate
            if (e instanceof EOFException) {

                // end of file - normal end
            } else if (e instanceof OutOfMemoryError) {
                message = "out of memory processing " + logFilename
                          + " line: " + scr.getLineNumber();

                database.logger.appLog.logContext(SimpleLog.LOG_ERROR,
                                                  message);

                throw Error.error(ErrorCode.OUT_OF_MEMORY);
            } else {

                // stop processing on bad log line
                message = logFilename + " line: " + scr.getLineNumber() + " "
                          + e.toString();

                database.logger.appLog.logContext(SimpleLog.LOG_ERROR,
                                                  message);
            }
        } finally {
            if (scr != null) {
                scr.close();
            }

            database.getSessionManager().closeAllSessions();
            database.setReferentialIntegrity(true);
        }
    }
373113
protected void run(String[] args) throws Exception {
		LOG.info("Running 'run' command.");

		final Options commandOptions = CliFrontendParser.getRunCommandOptions();

		final Options commandLineOptions = CliFrontendParser.mergeOptions(commandOptions, customCommandLineOptions);

		final CommandLine commandLine = CliFrontendParser.parse(commandLineOptions, args, true);

		final RunOptions runOptions = new RunOptions(commandLine);

		// evaluate help flag
		if (runOptions.isPrintHelp()) {
			CliFrontendParser.printHelpForRun(customCommandLines);
			return;
		}

		if (runOptions.getJarFilePath() == null) {
			throw new CliArgsException("The program JAR file was not specified.");
		}

		final PackagedProgram program;
		try {
			LOG.info("Building program from JAR file");
			program = buildProgram(runOptions);
		}
		catch (FileNotFoundException e) {
			throw new CliArgsException("Could not build the program from JAR file.", e);
		}

		final CustomCommandLine<?> customCommandLine = getActiveCustomCommandLine(commandLine);

		try {
			runProgram(customCommandLine, commandLine, runOptions, program);
		} finally {
			program.deleteExtractedLibraries();
		}
	}
137002
public static void runCommand(String[] cmdArray, File logFile, File dir) {
        Process proc = System.runProcess(cmdArray, logFile, dir);
        if (proc.exitValue() != 0) {
            throw new RuntimeException("Command failed with exit code " + proc.exitValue() + ": "
                    + System.cmdToString(cmdArray) + "\n" + QFiles.tail(logFile));
        }
    }
637032
public static void main(final String[] args) {
        String url = "http://files.grouplens.org/datasets/movielens/ml-100k.zip";
        String folder = "data/ml-100k";
        String modelPath = "data/ml-100k/model/";
        String recPath = "data/ml-100k/recommendations/";
        String dataFile = "data/ml-100k/ml-100k/u.data";
        int nFolds = N_FOLDS;
        prepareSplits(url, nFolds, dataFile, folder, modelPath);
        recommend(nFolds, modelPath, recPath);
        // the strategy files are (currently) being ignored
        prepareStrategy(nFolds, modelPath, recPath, modelPath);
        evaluate(nFolds, modelPath, recPath);
    }
423632
public static <T> T executeScriptEngine(final String scriptFile, final Object[] args, final Class<T> clazz) {
        try {
            val engineName = getScriptEngineName(scriptFile);
            val engine = new ScriptEngineManager().getEngineByName(engineName);
            if (engine == null || StringUtils.isBlank(engineName)) {
                LOGGER.warn("Script engine is not available for [{}]", engineName);
                return null;
            }

            val resourceFrom = ResourceUtils.getResourceFrom(scriptFile);
            val theScriptFile = resourceFrom.getFile();
            if (theScriptFile.exists()) {
                LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath());

                try (val reader = Files.newBufferedReader(theScriptFile.toPath(), StandardCharsets.UTF_8)) {
                    engine.eval(reader);
                }
                val invocable = (Invocable) engine;
                LOGGER.debug("Executing script's run method, with parameters [{}]", args);
                val result = invocable.invokeFunction("run", args);
                LOGGER.debug("Groovy script result is [{}]", result);
                return getGroovyScriptExecutionResultOrThrow(clazz, result);
            }
            LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile);
        } catch (final Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }
630133
public void setScripts(java.util.Collection<Script> scripts) {
        if (scripts == null) {
            this.scripts = null;
            return;
        }

        this.scripts = new java.util.ArrayList<Script>(scripts);
    }
1339478
protected final void loadAllClassByDir(String scriptLibDir) throws Exception {
		List<File> jarFiles = findJarFile(scriptLibDir);
		loadAllClass(jarFiles);
	}
159
function list(scriptModule, agent, msg, cb) {
    const servers = [];
    const scripts = [];
    const idMap = agent.idMap;

    for (const sid in idMap) {
        if (idMap.hasOwnProperty(sid)) {
            servers.push(sid);
        }
    }

    fs.readdir(scriptModule.root, (err, filenames) => {
        if (err) {
            filenames = [];
        }
        for (let i = 0, l = filenames.length; i < l; i++) {
            scripts.push(filenames[i]);
        }

        cb(null, {
            servers: servers,
            scripts: scripts
        });
    });
}
331888
protected void execute(List<String> scripts) throws SQLException
   {
      SecurityHelper.validateSecurityPermission(JCRRuntimePermissions.MANAGE_REPOSITORY_PERMISSION);

      // set needed auto commit mode
      boolean autoCommit = connection.getAutoCommit();
      if (autoCommit != this.autoCommit)
      {
         connection.setAutoCommit(this.autoCommit);
      }

      Statement st = connection.createStatement();
      try
      {
         for (String scr : scripts)
         {
            String sql = JDBCUtils.cleanWhitespaces(scr.trim());
            if (!sql.isEmpty())
            {
               if (LOG.isDebugEnabled())
               {
                  LOG.debug("Execute script: \n[" + sql + "]");
               }

               executeQuery(st, sql);
            }
         }
      }
      finally
      {
         try
         {
            st.close();
         }
         catch (SQLException e)
         {
            LOG.error("Can't close the Statement." + e.getMessage());
         }

         // restore previous auto commit mode
         if (autoCommit != this.autoCommit)
         {
            connection.setAutoCommit(autoCommit);
         }
      }
   }
1305524
public static void main(final String[] args) {
        final Set<String> paths = new HashSet<String>();
        final String propertyFile = System.getProperty("file");
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(propertyFile));
        } catch (IOException e) {
            e.printStackTrace();
        }

        for (String pr : properties.stringPropertyNames()) {
            System.out.println(pr + " : " + properties.getProperty(pr));
        }

        listAllFiles(paths, properties.getProperty(INPUT));

        runLenskitRecommenders(paths, properties);
        runMahoutRecommenders(paths, properties);
        runRanksysRecommenders(paths, properties);
    }
266090
def run(cmdfile,subsetfile=None, lookupfile=None):
    
    #Define the test case pattern
    pattern="""class %s(basecase.%sCase):
    def setUp(self):
        self.obsmode="%s"
        self.spectrum="%s"
        self.subset=%s
        self.etcid="%s"
        self.setglobal(__file__)
        self.runpy()\n"""

    #Open the (params:etcid) dictionary if it exists
    if lookupfile is not None:
        f=open(lookupfile)
        lookup=pickle.load(f)
        f.close()
    else:
        lookup={}
        
    #Process the subsetfile if present
    subsetflag={}
    if subsetfile is not None:
        #Then this file contains a list of case names that should have a
        #subset flag set.
        f=open(subsetfile)
        for line in f:
            if not line.startswith('#') and len(line.strip())>0:
                cols=line.strip().split()
                subsetflag[cols[0]]=True
        f.close()

    #Open the main input and output files
    f=open(cmdfile)
    out=open(cmdfile.replace('.txt','.py'),'w')
    out.write("""from pytools import testutil
import sys
import basecase
""")

    #Set up some bookkeeping
    count={'countrate':0,'calcspec':0,'calcphot':0,'SpecSourcerateSpec':0,'thermback':0}
    dupcatcher={}
    dupcounter={'countrate':0,'calcspec':0,'calcphot':0,'SpecSourcerateSpec':0,'thermback':0}
    
    #Now start the main loop
    for line in f:
    
    #parse the line
        ktuple=line2ktuple(line)
        cmd,obsmode,spectrum=ktuple
        count[cmd]+=1
        casename="%sCase%d"%(cmd,count[cmd])        
        if ktuple in dupcatcher:
            dupcounter[cmd]+=1
            dupcatcher[ktuple].append(casename)
        else:
            dupcatcher[ktuple]=[casename]
            etcid=lookup.get(ktuple,None)
            if etcid is not None and len(etcid) == 1:
                etcid=etcid[0]
            defn=pattern%(casename,cmd,obsmode,spectrum,subsetflag.get(casename,False),etcid)
            out.write(defn)

    out.write("""\n\n
if __name__ == '__main__':
    if 'debug' in sys.argv:
        testutil.debug(__name__)
    else:
        testutil.testall(__name__,2)
""")

    f.close()

    for k in count:
        total= "#%s:%d - %d dup =%d\n"%(k,count[k],dupcounter[k],count[k]-dupcounter[k])
        sys.stdout.write(total)
        out.write(total)
    out.close()

        
    return dupcatcher
21205
protected void executeScript(URL scriptUrl) {
        log.debug("Executing script '{}'", scriptUrl);
        try (Connection conn = dataSource.getConnection()) {
            try (Statement stat = conn.createStatement()) {
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(scriptUrl.openStream(), StandardCharsets.UTF_8))) {
                    reader.lines()
                            .filter(line -> !Strings.isNullOrEmpty(line) && line.charAt(0) != '#' && !line.startsWith("//"))
                            .forEach(line -> {
                                try {
                                    log.trace("execute: {}", line);
                                    stat.execute(line.trim());
                                } catch (SQLException e) {
                                    log.error("Failed to execute '{}'", line, e);
                                }
                            });
                }
            }
        } catch (SQLException | IOException e) {
            log.error("Failed to execute script '{}'", scriptUrl, e);
        }
    }
68959
private void processFile(Script s, File file) throws IOException {
        if (!file.exists())
            throw new FileNotFoundException(file.getName());

        if (!editFiles) {

            try(BufferedReader reader = new BufferedReader(new FileReader(file))) {
                PrintWriter writer = new PrintWriter(System.out);
                processReader(s, reader, writer);
                writer.flush();
            }
        } else {
            File backup;
            if (backupExtension == null) {
                backup = File.createTempFile("groovy_", ".tmp");
                backup.deleteOnExit();
            } else {
                backup = new File(file.getPath() + backupExtension);
            }
            backup.delete();
            if (!file.renameTo(backup))
                throw new IOException("unable to rename " + file + " to " + backup);


            try(BufferedReader reader = new BufferedReader(new FileReader(backup));
                PrintWriter writer = new PrintWriter(new FileWriter(file))) {
                processReader(s, reader, writer);
            }
        }
    }
296428
function runScriptFile(scriptFile)  {
	//node gets the node arguments, the nscript arguments and the actual script args combined. Slice all node and nscript args away!
	scriptArgs = scriptArgs.slice(scriptArgs.indexOf(scriptFile) + 1);
	if (shell.verbose())
		console.warn("Starting nscript " + scriptFile + scriptArgs.join(" "));

	runNscriptFunction(require(path.resolve(process.cwd(), scriptFile))); //nscript scripts should always export a single function that is the main
}