run a file on NodeMCU (.lc or .lua)
554516
async function run(filename){
    // try to establish a connection to the module
    await getConnection();

    // trigger reset
    const output = await _nodeMcuConnector.run(filename);

    // show command response
    _mculogger.log('Running "' + filename + '"');
    _mculogger.log('>----------------------------->');
    writeOutput(output + '\n');
    _mculogger.log('>----------------------------->');
}
620243
def run(self):
    """"""
    if platform.system() == 'Windows':
      # Windows doesn't support file-like objects for select(), so fall back
      # to raw_input().
      response = input(''.join((self._message,
                                os.linesep,
                                PROMPT)))
      self._answered = True
      self._callback(response)
      return

    # First, display the prompt to the console.
    console_output.cli_print(self._message, color=self._color,
                             end=os.linesep, logger=None)
    console_output.cli_print(PROMPT, color=self._color, end='', logger=None)
    sys.stdout.flush()

    # Before reading, clear any lingering buffered terminal input.
    termios.tcflush(sys.stdin, termios.TCIFLUSH)

    line = ''
    while not self._stop_event.is_set():
      inputs, _, _ = select.select([sys.stdin], [], [], 0.001)
      if sys.stdin in inputs:
        new = os.read(sys.stdin.fileno(), 1024)
        if not new:
          # Hit EOF!
          # They hit ^D (to insert EOF). Tell them to hit ^C if they
          # want to actually quit.
          print('Hit ^C (Ctrl+c) to exit.')
          break
        line += new.decode('utf-8')
        if '\n' in line:
          response = line[:line.find('\n')]
          self._answered = True
          self._callback(response)
          return
396767
def run(self):
    """"""

    module = self.distribution.ext_modules[0]
    base_dir = os.path.dirname(__file__)

    if base_dir:
      os.chdir(base_dir)

    exclusions = []

    for define in self.define or []:
      module.define_macros.append(define)

    for library in self.libraries or []:
      module.libraries.append(library)

    building_for_windows = self.plat_name in ('win32','win-amd64')
    building_for_osx = 'macosx' in self.plat_name
    building_for_linux = 'linux' in self.plat_name
    building_for_freebsd = 'freebsd' in self.plat_name
    building_for_openbsd = 'openbsd' in self.plat_name # need testing

    if building_for_linux:
      module.define_macros.append(('USE_LINUX_PROC', '1'))
    elif building_for_windows:
      module.define_macros.append(('USE_WINDOWS_PROC', '1'))
      module.define_macros.append(('_CRT_SECURE_NO_WARNINGS', '1'))
      module.libraries.append('kernel32')
      module.libraries.append('advapi32')
      module.libraries.append('user32')
      module.libraries.append('crypt32')
      module.libraries.append('ws2_32')
    elif building_for_osx:
      module.define_macros.append(('USE_MACH_PROC', '1'))
      module.include_dirs.append('/usr/local/opt/openssl/include')
      module.include_dirs.append('/opt/local/include')
      module.library_dirs.append('/opt/local/lib')
      module.include_dirs.append('/usr/local/include')
      module.library_dirs.append('/usr/local/lib')
    elif building_for_freebsd:
      module.define_macros.append(('USE_FREEBSD_PROC', '1'))
      module.include_dirs.append('/opt/local/include')
      module.library_dirs.append('/opt/local/lib')
      module.include_dirs.append('/usr/local/include')
      module.library_dirs.append('/usr/local/lib')
    elif building_for_openbsd:
      module.define_macros.append(('USE_OPENBSD_PROC', '1'))
      module.include_dirs.append('/opt/local/include')
      module.library_dirs.append('/opt/local/lib')
      module.include_dirs.append('/usr/local/include')
      module.library_dirs.append('/usr/local/lib')
    else:
      module.define_macros.append(('USE_NO_PROC', '1'))

    if has_function('memmem'):
      module.define_macros.append(('HAVE_MEMMEM', '1'))
    if has_function('strlcpy'):
      module.define_macros.append(('HAVE_STRLCPY', '1'))
    if has_function('strlcat'):
      module.define_macros.append(('HAVE_STRLCAT', '1'))

    if self.enable_profiling:
      module.define_macros.append(('PROFILING_ENABLED', '1'))

    if self.dynamic_linking:
      module.libraries.append('yara')
    else:
      if not self.define or not ('HASH_MODULE', '1') in self.define:
        if (has_function('MD5_Init', libraries=['crypto']) and
            has_function('SHA256_Init', libraries=['crypto'])):
          module.define_macros.append(('HASH_MODULE', '1'))
          module.define_macros.append(('HAVE_LIBCRYPTO', '1'))
          module.libraries.append('crypto')
        else:
          exclusions.append('yara/libyara/modules/hash.c')

      if self.enable_magic:
        module.define_macros.append(('MAGIC_MODULE', '1'))
        module.libraries.append('magic')
      else:
        exclusions.append('yara/libyara/modules/magic.c')

      if self.enable_cuckoo:
        module.define_macros.append(('CUCKOO_MODULE', '1'))
        module.libraries.append('jansson')
      else:
        exclusions.append('yara/libyara/modules/cuckoo.c')

      if self.enable_dotnet:
        module.define_macros.append(('DOTNET_MODULE', '1'))
      else:
        exclusions.append('yara/libyara/modules/dotnet.c')

      if self.enable_dex:
        module.define_macros.append(('DEX_MODULE', '1'))
      else:
        exclusions.append('yara/libyara/modules/dex.c')

      if self.enable_macho:
        module.define_macros.append(('MACHO_MODULE', '1'))
      else:
        exclusions.append('yara/libyara/modules/macho.c')

      exclusions = [os.path.normpath(x) for x in exclusions]

      for directory, _, files in os.walk('yara/libyara/'):
        for x in files:
          x = os.path.normpath(os.path.join(directory, x))
          if x.endswith('.c') and x not in exclusions:
            module.sources.append(x)

    build_ext.run(self)
301129
async function runProgram() {
    let argvFragment = process.argv.slice(2);
    if (argvFragment.length === 0) {
        argvFragment = ['-h'];
    }

    const latest = await latestVersion(pkg.name, {version: `>${pkg.version}`})
        .catch(() => pkg.version);
    if (semver.gt(latest, pkg.version)) {
        process.stderr.write(chalk.default.white(`\n     Update available `));
        process.stderr.write(chalk.default.grey(`${pkg.version}`));
        process.stderr.write(chalk.default.white(` -> `));
        process.stderr.write(chalk.default.greenBright(`${latest}\n`));
        process.stderr.write(chalk.default.white(`     Run `));
        process.stderr.write(chalk.default.blueBright(`npm i -g ${pkg.name} `));
        process.stderr.write(chalk.default.white(`to update.\n\n`));
    }

    args = minimist(argvFragment);

    if (args.prefix) {
        intercept(function (txt) {
            return `[${pkg.name}]\n${txt}`;
        });
    }

    if (args['!'] ||
        args.help ||
        args.h ||
        args._.includes('help')) {
        return help(args, process.stdout);
    }


    if (args._.length === 1 && args._[0] === 'init') {
        const result = await initializeConfig();
        if (result) {
            await stdoutAsync(`Successfully wrote ${process.cwd()}/.qnamakerrc\n`);
        }
        return;
    }

    if (args.version || args.v) {
        await stdoutAsync(require(path.join(__dirname, '../package.json')).version + '\n');
        return;
    }

    let serviceIn = {};
    if (args.stdin) {
        let json = await stdin();
        serviceIn = JSON.parse(json);
    }

    const config = await composeConfig(args);
    args.kbId = args.kbId || serviceIn.kbId || config.kbId;
    args.subscriptionKey = args.subscriptionKey || serviceIn.subscriptionKey || config.subscriptionKey;
    args.endpointKey = args.endpointKey || serviceIn.endpointKey || config.endpointKey;
    args.hostname = args.hostname || serviceIn.hostname || config.hostname;

    ServiceBase.config = args;

    validateConfig(args);

    if (args._[0] === 'set')
        return await handleSetCommand(args, config);

    const serviceManifest = getServiceManifest(args);

    let requestBody = await validateArguments(serviceManifest);

    // special case operations
    switch (serviceManifest.operation.methodAlias) {
        case 'delete':
            if (!args.f && !args.force) {
                let kbResult = await new Knowledgebase().getKnowledgebaseDetails(config);
                let kb = JSON.parse(await kbResult.text());
                if (!args.force) {
                    let answer = readlineSync.question(`Are you sure you would like to delete ${kb.name} [${kb.id}]? [no] `, {defaultInput: 'no'});
                    if (answer.trim()[0] === 'n') {
                        process.stderr.write('operation canceled');
                        return;
                    }
                }
            }
            break;

        case 'create':
            if (args.name)
                requestBody.name = args.name;

            if (!requestBody.name) {
                if (!(args.q || args.quiet)) {
                    let answer = readlineSync.question(`What would you like to name your new knowledgebase? `);
                    if (answer && answer.length > 0)
                        requestBody.name = answer.trim();
                }
            }
            // hack to map incorrect export property from expected import.  Export uses qnaDocuments, create/update/replace qnaList :(
            if (requestBody.qnaDocuments && !requestBody.qnaList) {
                requestBody.qnaList = requestBody.qnaDocuments;
                delete requestBody.qnaDocuments;
            }
            break;

        case 'replace':
        case 'update':
            // hack to map incorrect export property from expected.  Export uses qnaDocuments, create/update/replace qnaList :(
            if (requestBody.qnaDocuments && !requestBody.qnaList) {
                requestBody.qnaList = requestBody.qnaDocuments;
                delete requestBody.qnaDocuments;
            }
            break;
    }

    let result = await qnamaker(config, serviceManifest, args, requestBody);
    if (result.error) {
        throw new Error(JSON.stringify(result.error, null, 4));
    }

    // special case response
    switch (serviceManifest.operation.name) {
        case 'getKnowledgebaseDetails': {
            config.kbId = result.id;
            let kb = await updateKbId(config);
            if (args.msbot) {
                await stdoutAsync(JSON.stringify({
                    type: 'qna',
                    name: kb.name,
                    id: kb.id,
                    kbId: kb.id,
                    subscriptionKey: config.subscriptionKey,
                    endpointKey: config.endpointKey,
                    hostname: kb.hostName
                }, null, 2) + '\n');
            } else {
                await stdoutAsync(JSON.stringify(result, null, 2) + '\n');
            }
            break;
        }
        case 'createKnowledgebase':
            if (args.wait || args.msbot) {
                result = await waitForOperationSucceeded(config, result);

                let kbId = result.resourceLocation.split('/')[2];
                config.kbId = kbId;
                let kb = await updateKbId(config);
                if (args.msbot) {
                    await stdoutAsync(JSON.stringify({
                        type: 'qna',
                        name: kb.name,
                        id: kb.id,
                        kbId: kb.id,
                        subscriptionKey: config.subscriptionKey,
                        endpointKey: config.endpointKey,
                        hostname: config.hostname
                    }, null, 2) + '\n');

                } else {
                    await stdoutAsync(JSON.stringify(result, null, 2));
                }
                if (args.wait && !(args.q || args.quiet) && !args.msbot) {
                    let answer = readlineSync.question(`Would you like to save ${kb.name} ${kb.id} in your .qnamakerrc so that future commands will be with this KB? [yes] `, {defaultInput: 'yes'});
                    if (answer[0] === 'y') {
                        await fs.writeJson(path.join(process.cwd(), '.qnamakerrc'), config, {spaces: 2});
                        await stdoutAsync('.qnamakerrc updated' + '\n');
                    }
                }
            } else {
                await stdoutAsync(JSON.stringify(result, null, 2));
            }
            break;

        case 'updateKnowledgebase':
            if (args.wait || args.msbot) {
                result = await waitForOperationSucceeded(config, result);
            }
            await stdoutAsync(JSON.stringify(result, null, 2));
            break;

        default: {
            // dump json as json stringified
            if (typeof result === 'string')
                await stdoutAsync(result + '\n');
            else
                await stdoutAsync(JSON.stringify(result, null, 2) + '\n');
            break;
        }
    }
}
1354632
def run(bam_file, sample, out_dir):
    """"""
    out = {}
    # if "rchipqc" in dd.get_tools_on(sample):
    #    out = chipqc(bam_file, sample, out_dir)

    peaks = sample.get("peaks_files", {}).get("main")
    if peaks:
        out.update(_reads_in_peaks(bam_file, peaks, sample))
    return out
607346
async function upload(localFiles, options, onProgess){

    // the index of the current uploaded file
    let fileUploadIndex = 0;

    async function uploadFile(localFile, remoteFilename){

        // increment upload index
        fileUploadIndex++;

        // get file stats
        try{
            const stats = await _fs.statx(localFile);

            // check if file is directory
            if (stats.isDirectory()) {
                _mculogger.error('Path "' + localFile + '" is a directory.');
                return;
            }

        // local file available
        }catch (err){
            _logger.error('Local file not found "' + localFile + '" skipping...');
            _logger.debug(err);
            return;
        }

        // display filename
        _logger.log('Uploading "' + localFile + '" >> "' + remoteFilename + '"...');

        // normalize the remote filename (strip relative parts)
        remoteFilename = remoteFilename.replace(/\.\.\//g, '').replace(/\.\./g, '').replace(/^\.\//, '');

        // delete old file (may existent)
        await _nodeMcuConnector.remove(remoteFilename);

        // start file transfer
        await _nodeMcuConnector.upload(localFile, remoteFilename, options, function(current, total){
            // proxy and append file-number
            onProgess(current, total, fileUploadIndex);
        });

        // compile flag set ? and is a lua file ?
        if (options.compile && _path.extname(localFile).toLowerCase() == '.lua'){
            _mculogger.log(' |- compiling lua file..');

            await _nodeMcuConnector.compile(remoteFilename);
            _mculogger.log(' |- success');

            // drop original lua file
            await _nodeMcuConnector.remove(remoteFilename);
            _mculogger.log(' |- original Lua file removed');
        }
    }

    // try to establish a connection to the module
    await getConnection();

    // single file upload ?
    if (localFiles.length == 1){
        // extract first element
        const localFile = localFiles[0];

        // filename defaults to original filename minus path.
        // this behaviour can be overridden by --keeppath and --remotename options
        const remoteFile = options.remotename ? options.remotename : (options.keeppath ? localFile : _path.basename(localFile));

        // start single file upload
        await uploadFile(localFile, remoteFile);

        // log message
        _logger.log('File Transfer complete!');

        // run file ?
        if (options.run === true){
            await run(remoteFile);
        }

    // bulk upload ?
    }else{

        // file available ?
        while (localFiles.length > 0){
             // extract file
             const localFile = localFiles.shift();

             // keep-path option set ?
             const remoteFile = (options.keeppath ? localFile : _path.basename(localFile));

             // trigger upload
             await uploadFile(localFile, remoteFile);
        }

        // log message
        _logger.log('Bulk File Transfer complete!');
    }
}
1213946
function run(files) {
	worker(
		files,
		(err) => {
			if (err) {
				console.error(chalk[constants.COLORS.warning](err.message));
				process.exit(1);
			}

			console.log(chalk[constants.COLORS.info]('No issues found.'));

			return null;
		}
	);
}
729535
function run(argv, options, loader) {
  debug('argv', argv, 'options', options);

  if (options.help || options.h) {
    return loader.printUsage('env');
  }

  var selector = options._; // the argv, stripped of the flags (both -- and -)

  installPaths(function(er, paths) {
    var execPaths = resolvePaths(paths);

    execPaths['slc-npm'] = slcNpmPath(execPaths.slc);
    execPaths['node-npm'] = nodeNpmPath(execPaths.node);

    var env = {
      cwd: process.cwd(),
      paths: {
        link: paths,
        exec: execPaths
      },
      versions: process.versions,
      platform: process.platform,
      config: process.config,
      // redundant with .paths: execPath: process.execPath,
      features: process.features
    };
    try {
      env = selectProperties(selector, env);//XXX argv--> includes options?
    } catch (er) {
      return loader.error(er.message);
    }
    console.log(env);
  });
}
712329
def run(self, cmd, fn=None, globals=None, locals=None):
        """"""
        if globals is None:
            import __main__
            globals = __main__.__dict__
        if locals is None:
            locals = globals
        self.reset()
        if isinstance(cmd, str):
            str_cmd = cmd
            cmd = compile(str_cmd, fn or "<wdb>", "exec")
            self.compile_cache[id(cmd)] = str_cmd
        if fn:
            from linecache import getline
            lno = 1
            while True:
                line = getline(fn, lno, globals)
                if line is None:
                    lno = None
                    break
                if executable_line(line):
                    break
                lno += 1

        self.start_trace()
        if lno is not None:
            self.breakpoints.add(LineBreakpoint(fn, lno, temporary=True))
        try:
            execute(cmd, globals, locals)
        finally:
            self.stop_trace()
1330684
def run(*args):
    """"""

    if not args:
        args = sys.argv[1:]

    if len(args) < 2:
        print('Usage: runenv <envfile> <command> <params>')
        sys.exit(0)
    os.environ.update(create_env(args[0]))
    os.environ['_RUNENV_WRAPPED'] = '1'
    runnable_path = args[1]

    if not runnable_path.startswith(('/', '.')):
        runnable_path = spawn.find_executable(runnable_path)

    try:
        if not(stat.S_IXUSR & os.stat(runnable_path)[stat.ST_MODE]):
            print('File `%s is not executable' % runnable_path)
            sys.exit(1)
        return subprocess.check_call(
            args[1:], env=os.environ
        )
    except subprocess.CalledProcessError as e:
        return e.returncode
111772
function run(options, callback) {
  var settings = {}
  var stdin = new PassThrough()
  var tree
  var detectConfig
  var hasConfig
  var detectIgnore
  var hasIgnore

  try {
    stdin = process.stdin
  } catch (error) {
    /* Obscure bug in Node (seen on windows):
     * - https://github.com/nodejs/node/blob/f856234/lib/internal/
     *   process/stdio.js#L82;
     * - https://github.com/AtomLinter/linter-markdown/pull/85.
     */
  }

  if (!callback) {
    throw new Error('Missing `callback`')
  }

  if (!options || !options.processor) {
    return next(new Error('Missing `processor`'))
  }

  /* Processor. */
  settings.processor = options.processor

  /* Path to run as. */
  settings.cwd = options.cwd || process.cwd()

  /* Input. */
  settings.files = options.files || []
  settings.extensions = (options.extensions || []).map(extension)

  settings.filePath = options.filePath || null
  settings.streamIn = options.streamIn || stdin

  /* Output. */
  settings.streamOut = options.streamOut || process.stdout
  settings.streamError = options.streamError || process.stderr
  settings.alwaysStringify = options.alwaysStringify
  settings.output = options.output
  settings.out = options.out

  /* Null overwrites config settings, `undefined` doesn’t. */
  if (settings.output === null || settings.output === undefined) {
    settings.output = undefined
  }

  if (settings.output && settings.out) {
    return next(new Error('Cannot accept both `output` and `out`'))
  }

  /* Process phase management. */
  tree = options.tree || false

  settings.treeIn = options.treeIn
  settings.treeOut = options.treeOut
  settings.inspect = options.inspect

  if (settings.treeIn === null || settings.treeIn === undefined) {
    settings.treeIn = tree
  }

  if (settings.treeOut === null || settings.treeOut === undefined) {
    settings.treeOut = tree
  }

  /* Configuration. */
  detectConfig = options.detectConfig
  hasConfig = Boolean(options.rcName || options.packageField)

  if (detectConfig && !hasConfig) {
    return next(
      new Error('Missing `rcName` or `packageField` with `detectConfig`')
    )
  }

  settings.detectConfig =
    detectConfig === null || detectConfig === undefined
      ? hasConfig
      : detectConfig
  settings.rcName = options.rcName || null
  settings.rcPath = options.rcPath || null
  settings.packageField = options.packageField || null
  settings.settings = options.settings || {}
  settings.configTransform = options.configTransform
  settings.defaultConfig = options.defaultConfig

  /* Ignore. */
  detectIgnore = options.detectIgnore
  hasIgnore = Boolean(options.ignoreName)

  settings.detectIgnore =
    detectIgnore === null || detectIgnore === undefined
      ? hasIgnore
      : detectIgnore
  settings.ignoreName = options.ignoreName || null
  settings.ignorePath = options.ignorePath || null
  settings.silentlyIgnore = Boolean(options.silentlyIgnore)

  if (detectIgnore && !hasIgnore) {
    return next(new Error('Missing `ignoreName` with `detectIgnore`'))
  }

  /* Plug-ins. */
  settings.pluginPrefix = options.pluginPrefix || null
  settings.plugins = options.plugins || {}

  /* Reporting. */
  settings.reporter = options.reporter || null
  settings.reporterOptions = options.reporterOptions || null
  settings.color = options.color || false
  settings.silent = options.silent || false
  settings.quiet = options.quiet || false
  settings.frail = options.frail || false

  /* Process. */
  fileSetPipeline.run({files: options.files || []}, settings, next)

  function next(error, context) {
    var stats = statistics((context || {}).files)
    var failed = Boolean(
      settings.frail ? stats.fatal || stats.warn : stats.fatal
    )

    if (error) {
      callback(error)
    } else {
      callback(null, failed ? 1 : 0, context)
    }
  }
}
592893
def run(arguments):
    """"""
    parser = argparse.ArgumentParser(
        description="Exports font icons as PNG images."
    )
    parser.add_argument(
        '--list',
        action='store_true',
        help="list all available icon names and exit"
    )
    parser.add_argument(
        '--download',
        choices=[x for x in AVAILABLE_ICON_FONTS.keys()],
        help="download latest icon font and exit"
    )

    required_group = parser.add_argument_group("required arguments")
    required_group.add_argument(
        '--ttf',
        metavar='TTF-FILE',
        type=open,
        help='path to TTF file'
    )
    required_group.add_argument(
        '--css',
        metavar='CSS-FILE',
        type=open,
        help="path to CSS file"
    )

    exp_group = parser.add_argument_group("exporting icons")
    exp_group.add_argument(
        'icons',
        type=str,
        nargs='*',
        help="names of the icons to export (or 'ALL' for all icons)"
    )
    exp_group.add_argument(
        '--size',
        type=int,
        default=16,
        help="icon size in pixels (default: 16)"
    )
    exp_group.add_argument(
        '--scale',
        type=str,
        default='auto',
        help="scaling factor between 0 and 1, or 'auto' for automatic scaling "
             "(default: auto); be careful, as setting it may lead to icons "
             "being cropped"
    )
    exp_group.add_argument(
        '--color',
        type=str,
        default='black',
        help="color name or hex value (default: black)"
    )
    exp_group.add_argument(
        '--filename',
        type=str,
        help="name of the output file (without '.png' extension); "
             "it's used as a prefix if multiple icons are exported"
    )
    exp_group.add_argument(
        '--keep_prefix',
        default=False,
        action='store_true',
        help="do not remove common icon prefix "
             "(i.e. 'fa-arrow-right' instead of 'arrow-right')"
    )

    args = parser.parse_args(arguments)

    # Parse '--download' argument first
    if args.download:
        downloader = download_icon_font(args.download, os.getcwd())
        downloader.download_files()
        print("Icon font '{name}' successfully downloaded".format(
            name=args.download)
        )
        parser.exit()

    # If not '--download', then css and tff files are required
    if not args.css or not args.ttf:
        parser.error("You have to provide CSS and TTF files")

    icon_font = IconFont(css_file=args.css.name,
                         ttf_file=args.ttf.name,
                         keep_prefix=args.keep_prefix)
    args.css.close()
    args.ttf.close()

    # Then '--list'
    if args.list:
        for icon in icon_font.css_icons.keys():
            print(icon)
        parser.exit()

    # If not '--list' or '--download', parse passed icons
    selected_icons = list()
    if not args.icons:
        parser.error("You have to pass at least one icon name")
    elif args.icons == ['ALL']:
        selected_icons = icon_font.css_icons.keys()
    else:
        for icon in args.icons:
            if (args.keep_prefix and
                    not icon.startswith(icon_font.common_prefix)):
                # Prepend icon name with prefix
                icon = icon_font.common_prefix + icon
            elif (not args.keep_prefix and
                  icon.startswith(icon_font.common_prefix)):
                # Remove prefix from icon name
                icon = icon[len(icon_font.common_prefix):]

            # Check if given icon names exist
            if icon in icon_font.css_icons:
                selected_icons.append(icon)
            else:
                parser.error("Unknown icon name '{icon}'".format(icon=icon))

    # Parse filename and remove the extension if necessary
    given_filename = args.filename or ''
    if given_filename.lower().endswith('.png'):
        given_filename = given_filename[:-4]

    # Some fonts have empty values
    # (prefix only - which we remove - for common styles)
    selected_icons = list(filter(None, selected_icons))

    # Commence exporting
    for icon in selected_icons:
        if len(selected_icons) > 1:
            # Multiple icons - treat the filename option as name prefix
            filename = '{prefix}{icon}.png'.format(
                prefix=given_filename, icon=icon,
            )
        else:
            if given_filename:
                # Use the specified filename
                filename = given_filename + '.png'
            else:
                # Use icon name as filename
                filename = str(icon) + '.png'

        print("Exporting icon '{icon}' as '{filename}'"
              "({size}x{size} pixels)".format(icon=icon,
                                              filename=filename,
                                              size=args.size))

        icon_font.export_icon(icon=icon, filename=filename, size=args.size,
                              color=args.color, scale=args.scale)

    print()
    print("All done")
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)
120746
def run():
    """"""

    # Use print() instead of logging when running in CLI mode:
    set_pyftpsync_logger(None)

    parser = argparse.ArgumentParser(
        description="Synchronize folders over FTP.",
        epilog="See also https://github.com/mar10/pyftpsync",
        parents=[verbose_parser],
    )

    # Note: we want to allow --version to be combined with --verbose. However
    # on Py2, argparse makes sub-commands mandatory, unless `action="version"` is used.
    if check_cli_verbose(3) > 3:
        version_info = "pyftpsync/{} Python/{} {}".format(
            __version__, PYTHON_VERSION, platform.platform()
        )
    else:
        version_info = "{}".format(__version__)

    parser.add_argument("-V", "--version", action="version", version=version_info)

    subparsers = parser.add_subparsers(help="sub-command help")

    # --- Create the parser for the "upload" command ---------------------------

    sp = subparsers.add_parser(
        "upload",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="copy new and modified files to remote folder",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--force",
        action="store_true",
        help="overwrite remote files, even if the target is newer "
        "(but no conflict was detected)",
    )
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["local", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )
    sp.add_argument(
        "--delete",
        action="store_true",
        help="remove remote files if they don't exist locally",
    )
    sp.add_argument(
        "--delete-unmatched",
        action="store_true",
        help="remove remote files if they don't exist locally "
        "or don't match the current filter (implies '--delete' option)",
    )

    sp.set_defaults(command="upload")

    # --- Create the parser for the "download" command -------------------------

    sp = subparsers.add_parser(
        "download",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="copy new and modified files from remote folder to local target",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--force",
        action="store_true",
        help="overwrite local files, even if the target is newer "
        "(but no conflict was detected)",
    )
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["remote", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )
    sp.add_argument(
        "--delete",
        action="store_true",
        help="remove local files if they don't exist on remote target",
    )
    sp.add_argument(
        "--delete-unmatched",
        action="store_true",
        help="remove local files if they don't exist on remote target "
        "or don't match the current filter (implies '--delete' option)",
    )

    sp.set_defaults(command="download")

    # --- Create the parser for the "sync" command -----------------------------

    sp = subparsers.add_parser(
        "sync",
        parents=[verbose_parser, common_parser, matcher_parser, creds_parser],
        help="synchronize new and modified files between remote folder and local target",
    )

    sp.add_argument(
        "local",
        metavar="LOCAL",
        default=".",
        help="path to local folder (default: %(default)s)",
    )
    sp.add_argument("remote", metavar="REMOTE", help="path to remote folder")
    sp.add_argument(
        "--resolve",
        default="ask",
        choices=["old", "new", "local", "remote", "skip", "ask"],
        help="conflict resolving strategy (default: '%(default)s')",
    )

    sp.set_defaults(command="sync")

    # --- Create the parser for the "run" command -----------------------------

    add_run_parser(subparsers)

    # --- Create the parser for the "scan" command -----------------------------

    add_scan_parser(subparsers)

    # --- Parse command line ---------------------------------------------------

    args = parser.parse_args()

    args.verbose -= args.quiet
    del args.quiet

    # print("verbose", args.verbose)

    ftp_debug = 0
    if args.verbose >= 6:
        ftp_debug = 1

    # Modify the `args` from the `pyftpsync.yaml` config:
    if getattr(args, "command", None) == "run":
        handle_run_command(parser, args)

    if callable(getattr(args, "command", None)):
        # scan_handler
        try:
            return args.command(parser, args)
        except KeyboardInterrupt:
            print("\nAborted by user.", file=sys.stderr)
            sys.exit(3)

    elif not hasattr(args, "command"):
        parser.error(
            "missing command (choose from 'upload', 'download', 'run', 'sync', 'scan')"
        )

    # Post-process and check arguments
    if hasattr(args, "delete_unmatched") and args.delete_unmatched:
        args.delete = True

    args.local_target = make_target(args.local, {"ftp_debug": ftp_debug})

    if args.remote == ".":
        parser.error("'.' is expected to be the local target (not remote)")
    args.remote_target = make_target(args.remote, {"ftp_debug": ftp_debug})
    if not isinstance(args.local_target, FsTarget) and isinstance(
        args.remote_target, FsTarget
    ):
        parser.error("a file system target is expected to be local")

    # Let the command handler do its thing
    opts = namespace_to_dict(args)
    if args.command == "upload":
        s = UploadSynchronizer(args.local_target, args.remote_target, opts)
    elif args.command == "download":
        s = DownloadSynchronizer(args.local_target, args.remote_target, opts)
    elif args.command == "sync":
        s = BiDirSynchronizer(args.local_target, args.remote_target, opts)
    else:
        parser.error("unknown command '{}'".format(args.command))

    s.is_script = True

    try:
        s.run()
    except KeyboardInterrupt:
        print("\nAborted by user.", file=sys.stderr)
        sys.exit(3)
    finally:
        # Prevent sporadic exceptions in ftplib, when closing in __del__
        s.local.close()
        s.remote.close()

    stats = s.get_stats()
    if args.verbose >= 5:
        pprint(stats)
    elif args.verbose >= 1:
        if args.dry_run:
            print("(DRY-RUN) ", end="")
        print(
            "Wrote {}/{} files in {} directories, skipped: {}.".format(
                stats["files_written"],
                stats["local_files"],
                stats["local_dirs"],
                stats["conflict_files_skipped"],
            ),
            end="",
        )
        if stats["interactive_ask"]:
            print()
        else:
            print(" Elap: {}.".format(stats["elap_str"]))

    return
253644
def run(self, node, client):
        
        perms = os.stat(self.source).st_mode
        client.put(path=self.target, chmod=perms,
                   contents=open(self.source, 'rb').read())
        return node
389820
def run(self):
        
        _ctrl_proto = ctypes.CFUNCTYPE(None, ctypes.c_int, ctypes.c_char_p, ctypes.c_void_p)
        check_call(_LIB.MXKVStoreRunServer(self.handle, _ctrl_proto(self._controller()), None))
1278570
def run(
    commands,
    shell=None,
    prompt_template="default",
    speed=1,
    quiet=False,
    test_mode=False,
    commentecho=False,
):
    """"""
    if not quiet:
        secho("We'll do it live!", fg="red", bold=True)
        secho(
            "STARTING SESSION: Press Ctrl-C at any time to exit.",
            fg="yellow",
            bold=True,
        )
        click.pause()

    click.clear()
    state = SessionState(
        shell=shell,
        prompt_template=prompt_template,
        speed=speed,
        test_mode=test_mode,
        commentecho=commentecho,
    )

    i = 0
    while i < len(commands):
        command = commands[i].strip()
        i += 1
        if not command:
            continue
        is_comment = command.startswith("#")
        if not is_comment:
            command_as_list = shlex.split(ensure_utf8(command))
        else:
            command_as_list = None
        shell_match = SHELL_RE.match(command)
        if is_comment:
            # Parse comment magic
            match = OPTION_RE.match(command)
            if match:
                option, arg = match.group("option"), match.group("arg")
                func = OPTION_MAP[option]
                func(state, arg)
            elif state.commentecho():
                comment = command.lstrip("#")
                secho(comment, fg="yellow", bold=True)
            continue
        # Handle 'export' and 'alias' commands by storing them in SessionState
        elif command_as_list and command_as_list[0] in ["alias", "export"]:
            magictype(
                command, prompt_template=state["prompt_template"], speed=state["speed"]
            )
            # Store the raw commands instead of using add_envvar and add_alias
            # to avoid having to parse the command ourselves
            state.add_command(command)
        # Handle ```python and ```ipython by running "player" consoles
        elif shell_match:
            shell_name = shell_match.groups()[0].strip()
            py_commands = []
            more = True
            while more:  # slurp up all the python code
                try:
                    py_command = commands[i].rstrip()
                except IndexError:
                    raise SessionError(
                        "Unmatched {0} code block in "
                        "session file.".format(shell_name)
                    )
                i += 1
                if py_command.startswith("```"):
                    i += 1
                    more = False
                else:
                    py_commands.append(py_command)
            # Run the player console
            magictype(
                shell_name,
                prompt_template=state["prompt_template"],
                speed=state["speed"],
            )

            if shell_name == "ipython":
                try:
                    from doitlive.ipython_consoles import start_ipython_player
                except ImportError:
                    raise RuntimeError(
                        "```ipython blocks require IPython to be installed"
                    )
                # dedent all the commands to account for IPython's autoindentation
                ipy_commands = [textwrap.dedent(cmd) for cmd in py_commands]
                start_ipython_player(ipy_commands, speed=state["speed"])
            else:
                start_python_player(py_commands, speed=state["speed"])
        else:
            # goto_stealthmode determines when to switch to stealthmode
            goto_stealthmode = magicrun(command, **state)
            # stealthmode allows user to type live commands outside of automated script
            i -= stealthmode(state, goto_stealthmode)
    echo_prompt(state["prompt_template"])
    wait_for(RETURNS)
    if not quiet:
        secho("FINISHED SESSION", fg="yellow", bold=True)