Return executable javascript code for all registered commands
176738
protected function get_js_commands()
    {
        $out = '';

        foreach ($this->commands as $i => $args) {
            $method = array_shift($args);
            foreach ($args as $i => $arg) {
                $args[$i] = self::json_serialize($arg, $this->devel_mode, false);
            }

            $out .= sprintf(
                "this.%s(%s);\n",
                preg_replace('/^parent\./', '', $method),
                implode(',', $args)
            );
        }

        return $out;
    }
623998
def get_return_code(self, stderr=STDOUT):
        
        args = shlex.split(self.cmd)
        return call(args, stdout=PIPE, stderr=stderr)
599692
def exec(self, globals=None, locals=None):
        
        if locals is None:
            locals = {}
        builtins.exec(self.to_code(), globals, locals)
        return locals
1097844
def jshint():
    """"""
    with fab_settings(warn_only=True):
        needs_to_abort = False
        # because jshint fails with exit code 2, we need to allow this as
        # a successful exit code in our env
        if 2 not in env.ok_ret_codes:
            env.ok_ret_codes.append(2)
        output = local(
            'find -name "{}" -print'.format('*.js'),
            capture=True,
        )
        files = output.split()
        jshint_installed = local('command -v jshint', capture=True)
        if not jshint_installed.succeeded:
            warn(red(
                "To enable an extended check of your js files, please"
                " install jshint by entering:\n\n    npm install -g jshint"
            ))
        else:
            for file in files:
                if hasattr(settings, 'JSHINT_CHECK_EXCLUDES'):
                    excludes = settings.JSHINT_CHECK_EXCLUDES
                else:
                    excludes = settings.SYNTAX_CHECK_EXCLUDES
                if any(s in file for s in excludes):
                    continue
                jshint_result = local(
                    'jshint {0}'.format(file),
                    capture=True
                )
                if jshint_result:
                    warn(red('JS errors detected in file {0}'.format(
                        file
                    )))
                    puts(jshint_result)
                    needs_to_abort = True
        if needs_to_abort:
            abort(red('There have been errors. Please fix them and run'
                      ' the check again.'))
        else:
            puts(green('jshint found no errors. Very good!'))
218550
function callEngineScripts(engines, project_dir) {

    return Q.all(
        engines.map(function(engine){
            // CB-5192; on Windows scriptSrc doesn't have file extension so we shouldn't check whether the script exists
            var scriptPath = engine.scriptSrc ? '"' + engine.scriptSrc + '"' : null;
            if(scriptPath && (isWindows || fs.existsSync(engine.scriptSrc)) ) {

                var d = Q.defer();
                if(!isWindows) { // not required on Windows
                    fs.chmodSync(engine.scriptSrc, '755');
                }
                child_process.exec(scriptPath, function(error, stdout, stderr) {
                    if (error) {
                        events.emit('warn', engine.name +' version check failed ('+ scriptPath +'), continuing anyways.');
                        engine.currentVersion = null;
                    } else {
                        engine.currentVersion = cleanVersionOutput(stdout, engine.name);
                        if (engine.currentVersion === '') {
                            events.emit('warn', engine.name +' version check returned nothing ('+ scriptPath +'), continuing anyways.');
                            engine.currentVersion = null;
                        }
                    }

                    d.resolve(engine);
                });
                return d.promise;

            } else {

                if(engine.currentVersion) {
                    engine.currentVersion = cleanVersionOutput(engine.currentVersion, engine.name);
                } else {
                    events.emit('warn', engine.name +' version not detected (lacks script '+ scriptPath +' ), continuing.');
                }

                return Q(engine);
            }
        })
    );
}
191917
def command(function):
    """"""
    def decorate(*args, **kwargs):
        exit_code = 1
        try:
            exit_code = function(*args, **kwargs)
        except Exception as e:
            if str(e):
                click.secho('Error: ' + str(e), fg='red')
        finally:
            return exit_code
    return decorate
1041284
def encoding_and_executable(notebook, metadata, ext):
    """"""
    lines = []
    comment = _SCRIPT_EXTENSIONS.get(ext, {}).get('comment')
    jupytext_metadata = metadata.get('jupytext', {})

    if ext not in ['.Rmd', '.md'] and 'executable' in jupytext_metadata:
        lines.append(comment + '!' + jupytext_metadata.pop('executable'))

    if 'encoding' in jupytext_metadata:
        lines.append(jupytext_metadata.pop('encoding'))
    elif ext not in ['.Rmd', '.md']:
        for cell in notebook.cells:
            try:
                cell.source.encode('ascii')
            except (UnicodeEncodeError, UnicodeDecodeError):
                lines.append(comment + _UTF8_HEADER)
                break

    return lines
858163
def _exec_cmd(command):
    """"""
    proc = sp.Popen(command,
                    stdout=sp.PIPE,
                    shell=True)
    if six.PY2:
        res = proc.communicate()[0]
    else:
        res = proc.communicate(timeout=5)[0]
    return res, proc.returncode
681254
function compileWASM (config) {

  // check that emscripten path is correct
  if (!fs.existsSync(config.emscripten_path)) {
    return process.stdout.write(colors.red(`Error: Could not find emscripten directory at ${config.emscripten_path}\n`));
  }

  const shellScript = getShellScript(config);
  
  // format exported functions, if present, from config for shell script
  let expFuncStr = '';
  if (config.exported_functions && config.exported_functions.length > 0) {
    let expFuncs = config.exported_functions.reduce((acc, val) => acc.concat('\'', val, '\'\,'), '[');
    expFuncs = expFuncs.substring(0, expFuncs.length - 1).concat(']');
    expFuncStr = `-s EXPORTED_FUNCTIONS="${expFuncs}" `;
  }

  // format flags from config for shell script
  const flags = config.flags.reduce((acc, val) => acc.concat(' ', val), '');
  // construct the default compile mode string.
  let commandStr = `emcc -o ${config.outputfile} ${config.inputfile} ${expFuncStr} ${flags}`;
  // generate a command string suitable for cmake
  if(config.mode == "build") {
    // assuming make
    config.generator = config.generator ? config.generator : 'make';
    switch(config.generator) {
      case 'ninja':
        config.gen_flag = 'Ninja';
      default:
        config.gen_flag = '"Unix Makefiles"';
        break;
    }
    // need to triple escape double quotes
    expFuncStr = expFuncStr.replace(/"/g, '\\\"');
    let modFlags = flags.replace(/"/g, '\\\"');
    let cxxFlagStr = `SET(WASM_CXXFLAGS "${modFlags} ${expFuncStr}" CACHE PATH "")`;
    // pass through cmake configuration, inc. compiler flags, exported functions
    commandStr = `cd wasm && emcmake cmake -G ${config.gen_flag} `+
      `-DWASM_CXXFLAGS=\"${modFlags} ${expFuncStr}\" ` +
      `.. && emmake ${config.generator} -j${cpuCount-1}`;
  }
  process.stdout.write(colors.cyan('Running emscripten...\n'));
  // execute shell script
  // exec(shellScript, (error, stdout, stderr) => {

  exec(`
  if [[ :$PATH: != *:"/emsdk":* ]]
  then
    # use path to emsdk folder, relative to project directory
    BASEDIR="${config.emscripten_path}"
    EMSDK_ENV=$(find "$BASEDIR" -type f -name "emsdk_env.sh")
    source "$EMSDK_ENV"
  fi

  ${commandStr}
  `, { shell: '/bin/bash' }, (error, stdout, stderr) => {
    // check for emcc compile errors
    if (stderr) {
      process.stderr.write(colors.red.bold('EMSCRIPTEN COMPILE ERROR\n'));
      process.stderr.write(colors.white(stderr));
    } else {
      process.stdout.write(stdout);
      insertEventListener(config);
      process.stdout.write(colors.green.bold('Compiled C++ to WASM\n'));
    }
  });
}
808395
def execute_code(self, lines, current_client=True, clear_variables=False):
        """"""
        sw = self.get_current_shellwidget()
        if sw is not None:
            if sw._reading:
                pass
            else:
                if not current_client:
                    # Clear console and reset namespace for
                    # dedicated clients
                    # See issue 5748
                    try:
                        sw.sig_prompt_ready.disconnect()
                    except TypeError:
                        pass
                    sw.reset_namespace(warning=False)
                elif current_client and clear_variables:
                    sw.reset_namespace(warning=False)
                # Needed to handle an error when kernel_client is none
                # See issue 6308
                try:
                    sw.execute(to_text_string(lines))
                except AttributeError:
                    pass
            self.activateWindow()
            self.get_current_client().get_control().setFocus()
390316
def cmdline(executable):
    

    args = [executable.executable]
    indexed_args = []

    for parameter in executable:

        optional = (parameter.type == 'boolean') or parameter.default
        has_value = parameter.type != 'boolean'


        if parameter.longflag:  # use longflag where possible
            flag = "--%s" % parameter.longflag
        elif parameter.flag:
            flag = "-%s VALUE" % parameter.flag
        elif parameter.index:
            flag = parameter.name
            optional = False


        if has_value:
            flag += " VALUE"

        if optional:
            flag = "[" + flag + "]"

        if parameter.index:
            indexed_args.insert(int(parameter.index), flag)
        else:
            args.append(flag)

    return args + indexed_args
48330
def get_command_from_result(script, result, debug=False):
    
    if not debug:
        command = "python waf --run \"" + script + " " + " ".join(
            ['--%s=%s' % (param, value) for param, value in
             result['params'].items()]) + "\""
    else:
        command = "python waf --run " + script + " --command-template=\"" +\
            "gdb --args %s " + " ".join(['--%s=%s' % (param, value) for
                                         param, value in
                                         result['params'].items()]) + "\""
    return command
962449
def _WorkerCommand_executable(self):
        """"""
        worker = self.workersArguments

        c = []
        if worker.executable:
            c.append(worker.executable)
        # This trick is used to parse correctly quotes
        # (ie. myScript.py 'arg1 "arg2" arg3')
        # Because it is parsed by a shell, every quote gets re-interpreted.
        # It replaces simple quotation marks with \\\" which gets evaluated to
        # \" by the second shell which prints it out as a double quote.
        if worker.args:
            if self.isLocal():
                # If local, no shell is used so no escaping needed
                c.extend([
                    '{0}'.format(a) for a in worker.args
                ])
            else:
                c.extend([
                    '"{0}"'.format(a.replace('"', '\\\"')) for a in worker.args
                ])
        return c
1023794
def executable(self):
        """"""
        if not hasattr(self.local, 'conn'):
            self.local.conn = self.engine.connect()
        return self.local.conn
1342320
function exp(cmd, confdir) {
  return function (files, opt) {
    var defaultOpt = {
      cwd: process.cwd()
    };
    opt = append(defaultOpt, opt);

    if (typeof files == 'string')
      files = [ files ];

    require(path.resolve(confdir, cmd + '.js'))(files, opt);
  };
}
74538
function checkCommand (command, errorCallback) {
    var exec = command
    var args = this.argsExecutable
    var shell = false
    if (this.win) {
      // Arguments have to be manually quoted
      exec = `"${exec}"`
      args = args.map(a => `"${a}"`)
      shell = true
    }

    this.log.verbose(`- executing "${command}" to get executable path`)
    this.run(exec, args, shell, function (err, execPath) {
      // Possible outcomes:
      // - Error: not in PATH, not executable or execution fails
      // - Gibberish: the next command to check version will fail
      // - Absolute path to executable
      if (err) {
        this.addLog(`- "${command}" is not in PATH or produced an error`)
        return errorCallback(err)
      }
      this.addLog(`- executable path is "${execPath}"`)
      this.checkExecPath(execPath, errorCallback)
    }.bind(this))
  }
1082505
def exec_func(code, glob_vars, loc_vars=None):
    """"""
    if loc_vars is None:
        exec(code, glob_vars)
    else:
        exec(code, glob_vars, loc_vars)