Main function that handles extract to function
186812
function handleExtractToFunction() {
        var editor = EditorManager.getActiveEditor();
        var result = new $.Deferred(); // used only for testing purpose

        if (editor.getSelections().length > 1) {
            editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_FUNCTION_MULTICURSORS);
            result.resolve(Strings.ERROR_EXTRACTTO_FUNCTION_MULTICURSORS);
            return;
        }
        initializeSession(editor);

        var selection = editor.getSelection(),
            doc       = editor.document,
            retObj    = RefactoringUtils.normalizeText(editor.getSelectedText(), editor.indexFromPos(selection.start), editor.indexFromPos(selection.end)),
            text      = retObj.text,
            start     = retObj.start,
            end       = retObj.end,
            ast,
            scopes,
            expns,
            inlineMenu;

        RefactoringUtils.getScopeData(session, editor.posFromIndex(start)).done(function(scope) {
            ast = RefactoringUtils.getAST(doc.getText());

            var isExpression = false;
            if (!RefactoringUtils.checkStatement(ast, start, end, doc.getText())) {
                isExpression = RefactoringUtils.getExpression(ast, start, end, doc.getText());
                if (!isExpression) {
                    editor.displayErrorMessageAtCursor(Strings.ERROR_EXTRACTTO_FUNCTION_NOT_VALID);
                    result.resolve(Strings.ERROR_EXTRACTTO_FUNCTION_NOT_VALID);
                    return;
                }
            }
            scopes = RefactoringUtils.getAllScopes(ast, scope, doc.getText());

            // if only one scope, extract without menu
            if (scopes.length === 1) {
                extract(ast, text, scopes, scopes[0], scopes[0], start, end, isExpression);
                result.resolve();
                return;
            }

            inlineMenu = new InlineMenu(editor, Strings.EXTRACTTO_FUNCTION_SELECT_SCOPE);

            inlineMenu.open(scopes.filter(RefactoringUtils.isFnScope));

            result.resolve(inlineMenu);

            inlineMenu.onSelect(function (scopeId) {
                extract(ast, text, scopes, scopes[0], scopes[scopeId], start, end, isExpression);
                inlineMenu.close();
            });

            inlineMenu.onClose(function(){
                inlineMenu.close();
            });
        }).fail(function() {
            editor.displayErrorMessageAtCursor(Strings.ERROR_TERN_FAILED);
            result.resolve(Strings.ERROR_TERN_FAILED);
        });

        return result.promise();
    }
924222
function main(program) {
  program || (program = { args: [] });
  if(program.args.length === 0) {
    program.outputHelp();
    return process.exit(1);
  }

  return Promise
    .map(program.args, _.partial(exports.downloadPosting, program))
    .map(function(html) {
      return cheerio.load(html);
    })
    .map(exports.extractInfo)
    .then(_.partial(exports.outputInfo, program));
}
1226812
def decoratable_funcdef_stmt_handle(self, original, loc, tokens, is_async=False):
        """"""
        if len(tokens) == 1:
            decorators, funcdef = "", tokens[0]
        elif len(tokens) == 2:
            decorators, funcdef = tokens
        else:
            raise CoconutInternalException("invalid function definition tokens", tokens)

        # extract information about the function
        raw_lines = funcdef.splitlines(True)
        def_stmt = raw_lines.pop(0)
        func_name, func_args, func_params = None, None, None
        with self.complain_on_err():
            func_name, func_args, func_params = parse(self.split_func_name_args_params, def_stmt)

        undotted_name = None  # the function __name__ if func_name is a dotted name
        if func_name is not None:
            if "." in func_name:
                undotted_name = func_name.rsplit(".", 1)[-1]
                def_stmt = def_stmt.replace(func_name, undotted_name)

        # handle async functions
        if is_async:
            if not self.target:
                raise self.make_err(
                    CoconutTargetError,
                    "async function definition requires a specific target",
                    original, loc,
                    target="sys",
                )
            elif self.target_info >= (3, 5):
                def_stmt = "async " + def_stmt
            else:
                decorators += "@_coconut.asyncio.coroutine\n"

            # only Python 3.3+ supports returning values inside generators
            if self.target_info < (3, 3):
                func_code = self.transform_returns(raw_lines, is_async=True)
            else:
                func_code = "".join(raw_lines)

        # handle normal functions
        else:
            # tre does not work with decorators, though tco does
            attempt_tre = func_name is not None and not decorators
            if attempt_tre:
                use_mock = func_args and func_args != func_params[1:-1]
                func_store = tre_store_var + "_" + str(self.tre_store_count)
                self.tre_store_count += 1
                tre_return_grammar = self.tre_return(func_name, func_args, func_store, use_mock)
            else:
                use_mock = func_store = tre_return_grammar = None

            func_code, tco, tre = self.transform_returns(
                raw_lines,
                tre_return_grammar,
                use_mock,
            )

            if tre:
                comment, rest = split_leading_comment(func_code)
                indent, base, dedent = split_leading_trailing_indent(rest, 1)
                base, base_dedent = split_trailing_indent(base)
                docstring, base = self.split_docstring(base)
                func_code = (
                    comment + indent
                    + (docstring + "\n" if docstring is not None else "")
                    + (
                        "def " + tre_mock_var + func_params + ": return " + func_args + "\n"
                        if use_mock else ""
                    ) + "while True:\n"
                        + openindent + base + base_dedent
                        + ("\n" if "\n" not in base_dedent else "") + "return None"
                        + ("\n" if "\n" not in dedent else "") + closeindent + dedent
                    + func_store + " = " + (func_name if undotted_name is None else undotted_name) + "\n"
                )
            if tco:
                decorators += "@_coconut_tco\n"  # binds most tightly

        out = decorators + def_stmt + func_code
        if undotted_name is not None:
            out += func_name + " = " + undotted_name + "\n"
        return out
1057294
function extract(scopes, parentStatement, expns, text, insertPosition) {
        var varType          = "var",
            varName          = RefactoringUtils.getUniqueIdentifierName(scopes, "extracted"),
            varDeclaration   = varType + " " + varName + " = " + text + ";\n",
            parentStatementStartPos = session.editor.posFromIndex(parentStatement.start),
            insertStartPos   = insertPosition || parentStatementStartPos,
            selections       = [],
            doc              = session.editor.document,
            replaceExpnIndex = 0,
            posToIndent,
            edits            = [];

        // If parent statement is expression statement, then just append var declaration
        // Ex: "add(1, 2)" will become "var extracted = add(1, 2)"
        if (parentStatement.type === "ExpressionStatement" &&
                RefactoringUtils.isEqual(parentStatement.expression, expns[0]) &&
                insertStartPos.line === parentStatementStartPos.line &&
                insertStartPos.ch === parentStatementStartPos.ch) {
            varDeclaration = varType + " " + varName + " = ";
            replaceExpnIndex = 1;
        }

        posToIndent = doc.adjustPosForChange(insertStartPos, varDeclaration.split("\n"), insertStartPos, insertStartPos);

        // adjust pos for change
        for (var i = replaceExpnIndex; i < expns.length; ++i) {
            expns[i].start  = session.editor.posFromIndex(expns[i].start);
            expns[i].end    = session.editor.posFromIndex(expns[i].end);
            expns[i].start  = doc.adjustPosForChange(expns[i].start, varDeclaration.split("\n"), insertStartPos, insertStartPos);
            expns[i].end    = doc.adjustPosForChange(expns[i].end, varDeclaration.split("\n"), insertStartPos, insertStartPos);

            edits.push({
                edit: {
                    text: varName,
                    start: expns[i].start,
                    end: expns[i].end
                },
                selection: {
                    start: expns[i].start,
                    end: {line: expns[i].start.line, ch: expns[i].start.ch + varName.length}
                }
            });
        }

        // Replace and multi-select
        doc.batchOperation(function() {
            doc.replaceRange(varDeclaration, insertStartPos);

            selections = doc.doMultipleEdits(edits);
            selections.push({
                start: {line: insertStartPos.line, ch: insertStartPos.ch + varType.length + 1},
                end:   {line: insertStartPos.line, ch: insertStartPos.ch + varType.length + varName.length + 1},
                primary: true
            });
            session.editor.setSelections(selections);
            session.editor._codeMirror.indentLine(posToIndent.line, "smart");
        });
    }
1077903
def main():
    
    setup_main_logger(console=True, file_logging=False)
    params = argparse.ArgumentParser(description="Extract specific parameters.")
    arguments.add_extract_args(params)
    args = params.parse_args()
    extract_parameters(args)
1319057
def main():
    
    # Define Parser object and add to toil
    parser = build_parser()
    Job.Runner.addToilOptions(parser)
    args = parser.parse_args()
    # Store inputs from argparse
    inputs = {'genetorrent': args.genetorrent,
              'genetorrent_key': args.genetorrent_key,
              'ssec': args.ssec,
              's3_dir': args.s3_dir}
    # Sanity checks
    if args.ssec:
        assert os.path.isfile(args.ssec)
    if args.genetorrent:
        assert os.path.isfile(args.genetorrent)
    if args.genetorrent_key:
        assert os.path.isfile(args.genetorrent_key)
    samples = parse_genetorrent(args.genetorrent)
    # Start pipeline
    # map_job accepts a function, an iterable, and *args. The function is launched as a child
    # process with one element from the iterable and *args, which in turn spawns a tree of child jobs.
    Job.Runner.startToil(Job.wrapJobFn(map_job, download_and_transfer_sample, samples, inputs), args)
1316734
function extractor(input) {
  var ast;
  var defaultMessages = {};

  if (typeof input === "string") {

    // input as a filename.
    if ((/\.js$/i).test(input) && !(/\n/).test(input)) {
      input = fs.readFileSync(input);
    }

    // input as a file content.
    ast = esprima.parse(input);

  // input as an AST.
  } else {
    ast = input;
  }

  // Traverse AST and perform transforms.
  traverse(ast, function(node) {
    transforms.forEach(function(visitor) {
      if (visitor.test(node)) {
        visitor.transform(node);
      }
    });
  });

  // Traverse AST and collect default messages.
  traverse(ast, function(node) {
    extend(defaultMessages, visitors.filter(function(visitor) {
      return visitor.test(node);
    }).reduce(function(defaultMessages, visitor) {
      var aux = visitor.getDefaultMessage(node);
      defaultMessages[aux.path] = aux.message;
      return defaultMessages;
    }, {}));
  });

  return defaultMessages;
}
9317
def main(argv=None):
    '''  '''
    parser = get_parser()

    # Parse arguments and run the function
    global args
    args = parser.parse_args(argv)
    args.func()
953919
def main():
    
    filename = pmag.get_named_arg('-f')
    if not filename:
        return
    with open(filename, 'rb+') as f:
        content = f.read()
        f.seek(0)
        f.write(content.replace(b'\r', b''))
        f.truncate()
965960
def main(args=sys.argv[1:]):
    
    parser = argparse.ArgumentParser(description="""Aggregate results of
            nestly runs""")
    subparsers = parser.add_subparsers()
    delim_parser = subparsers.add_parser('delim', help="""Combine control files
            with delimited files.""")
    delim_parser.set_defaults(func=delim)
    key_group = delim_parser.add_mutually_exclusive_group()
    key_group.add_argument('-k', '--keys', help="""Comma separated list of
            keys from the JSON file to include [default: all keys]""",
            type=comma_separated_values)
    key_group.add_argument('-x', '--exclude-keys', help="""Comma separated
            list of keys from the JSON file not to include [default:
            %(default)s]""", type=comma_separated_values)
    delim_parser.add_argument('-m', '--missing-action', choices=('fail',
        'warn'), help="""Action to take when a file is missing [default:
        %(default)s]""", default='fail')
    delim_parser.add_argument('file_template', help="""Template for the
            delimited file to read in each directory [e.g. '{run_id}.csv']""")
    delim_parser.add_argument('control_files', metavar="control.json",
            help="""Control files""", nargs="*")
    delim_parser.add_argument('-d', '--directory', help="""Run on all control
            files under %(metavar)s. May be used in place of specifying control
            files.""", metavar='DIR')
    delim_parser.add_argument('-s', '--separator', default=DEFAULT_SEP,
            help="""Separator [default: %(default)s]""")
    delim_parser.add_argument('-t', '--tab', action='store_const',
            dest='separator', const='\t', help="""Files are tab-separated""")
    delim_parser.add_argument('-o', '--output', default=sys.stdout,
        type=argparse.FileType('w'), help="""Output file [default: stdout]""")

    arguments = parser.parse_args()

    arguments.func(arguments)
1033752
def _make_parser_func(sep):
    

    def parser_func(
        filepath_or_buffer,
        sep=sep,
        delimiter=None,
        header="infer",
        names=None,
        index_col=None,
        usecols=None,
        squeeze=False,
        prefix=None,
        mangle_dupe_cols=True,
        dtype=None,
        engine=None,
        converters=None,
        true_values=None,
        false_values=None,
        skipinitialspace=False,
        skiprows=None,
        nrows=None,
        na_values=None,
        keep_default_na=True,
        na_filter=True,
        verbose=False,
        skip_blank_lines=True,
        parse_dates=False,
        infer_datetime_format=False,
        keep_date_col=False,
        date_parser=None,
        dayfirst=False,
        iterator=False,
        chunksize=None,
        compression="infer",
        thousands=None,
        decimal=b".",
        lineterminator=None,
        quotechar='"',
        quoting=0,
        escapechar=None,
        comment=None,
        encoding=None,
        dialect=None,
        tupleize_cols=None,
        error_bad_lines=True,
        warn_bad_lines=True,
        skipfooter=0,
        doublequote=True,
        delim_whitespace=False,
        low_memory=True,
        memory_map=False,
        float_precision=None,
    ):
        _, _, _, kwargs = inspect.getargvalues(inspect.currentframe())
        if not kwargs.get("sep", sep):
            kwargs["sep"] = "\t"
        return _read(**kwargs)

    return parser_func
899980
def _handle_extract_pattern(self, pattern):
        ''''''
        if pattern is None or not pattern:
            patterns = []
        elif isinstance(pattern, str):
            patterns = [pattern]
        elif isinstance(pattern, Iterable):
            patterns = pattern
        else:
            raise ValueError(
                f'Unacceptable value for parameter pattern: {pattern}')
        #
        for pattern in patterns:
            res = extract_pattern(pattern, self._targets)
            self.set(**res)
            # also make k, v pair with _input
            self._handle_paired_with({'_' + x: y for x, y in res.items()})
379657
def extract(path, to_path='', ext='', **kwargs):
    
    Archive(path, ext=ext).extract(to_path, **kwargs)
996259
def main():
    """"""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrTable

    # Get the output format and document
    fmt = args.fmt
    doc = json.loads(STDIN.read())

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    AttrTable = elt('Table', 6)

    # Chop up the doc
    meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
    blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]

    # Process the metadata variables
    process(meta)

    # First pass
    detach_attrs_table = detach_attrs_factory(Table)
    insert_secnos = insert_secnos_factory(Table)
    delete_secnos = delete_secnos_factory(Table)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_table, insert_secnos,
                                process_tables, delete_secnos,
                                detach_attrs_table], blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references,
                                        use_cleveref_default, False,
                                        plusname if not capitalize else
                                        [name.title() for name in plusname],
                                        starname, 'table')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Insert supporting TeX
    if fmt in ['latex']:

        rawblocks = []

        if has_unnumbered_tables:
            rawblocks += [RawBlock('tex', TEX0),
                          RawBlock('tex', TEX1),
                          RawBlock('tex', TEX2)]

        if captionname != 'Table':
            rawblocks += [RawBlock('tex', TEX3 % captionname)]

        insert_rawblocks = insert_rawblocks_factory(rawblocks)

        altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                                   [insert_rawblocks], altered)

    # Update the doc
    if PANDOCVERSION >= '1.18':
        doc['blocks'] = altered
    else:
        doc = doc[:1] + altered

    # Dump the results
    json.dump(doc, STDOUT)

    # Flush stdout
    STDOUT.flush()
148093
def main() -> None:
    """""""
    modules = [
        "functions_100_with_no_contract",

        "functions_100_with_1_contract",
        "functions_100_with_5_contracts",
        "functions_100_with_10_contracts",

        "functions_100_with_1_disabled_contract",
        "functions_100_with_5_disabled_contracts",
        "functions_100_with_10_disabled_contracts",

        "classes_100_with_no_invariant",

        "classes_100_with_1_invariant",
        "classes_100_with_5_invariants",
        "classes_100_with_10_invariants",

        "classes_100_with_1_disabled_invariant",
        "classes_100_with_5_disabled_invariants",
        "classes_100_with_10_disabled_invariants",
    ]

    for a_module in modules:
        durations = []  # type: List[float]
        for i in range(0, 10):
            duration = float(
                subprocess.check_output(["./measure.py", "--module", a_module], cwd=os.path.dirname(__file__)).strip())
            durations.append(duration)

        print("Duration to import the module {} (in milliseconds): {:.2f} ± {:.2f}".format(
            a_module, statistics.mean(durations) * 10e3, statistics.stdev(durations) * 10e3))
763175
def main():
    
    usage = '%prog [options] "<input file>"'
    if '__main__.py' in sys.argv[0]: # python -m pyminifier
        usage = 'pyminifier [options] "<input file>"'
    parser = OptionParser(usage=usage, version=__version__)
    parser.disable_interspersed_args()
    parser.add_option(
        "-o", "--outfile",
        dest="outfile",
        default=None,
        help="Save output to the given file.",
        metavar="<file path>"
    )
    parser.add_option(
        "-d", "--destdir",
        dest="destdir",
        default="./minified",
        help=("Save output to the given directory. "
              "This option is required when handling multiple files. "
              "Defaults to './minified' and will be created if not present. "),
        metavar="<file path>"
    )
    parser.add_option(
        "--nominify",
        action="store_true",
        dest="nominify",
        default=False,
        help="Don't bother minifying (only used with --pyz).",
    )
    parser.add_option(
        "--use-tabs",
        action="store_true",
        dest="tabs",
        default=False,
        help="Use tabs for indentation instead of spaces.",
    )
    parser.add_option(
        "--bzip2",
        action="store_true",
        dest="bzip2",
        default=False,
        help=("bzip2-compress the result into a self-executing python script.  "
              "Only works on stand-alone scripts without implicit imports.")
    )
    parser.add_option(
        "--gzip",
        action="store_true",
        dest="gzip",
        default=False,
        help=("gzip-compress the result into a self-executing python script.  "
              "Only works on stand-alone scripts without implicit imports.")
    )
    if lzma:
        parser.add_option(
            "--lzma",
            action="store_true",
            dest="lzma",
            default=False,
            help=("lzma-compress the result into a self-executing python script.  "
                  "Only works on stand-alone scripts without implicit imports.")
        )
    parser.add_option(
        "--pyz",
        dest="pyz",
        default=None,
        help=("zip-compress the result into a self-executing python script. "
              "This will create a new file that includes any necessary implicit"
              " (local to the script) modules.  Will include/process all files "
              "given as arguments to pyminifier.py on the command line."),
        metavar="<name of archive>.pyz"
    )
    parser.add_option(
        "-O", "--obfuscate",
        action="store_true",
        dest="obfuscate",
        default=False,
        help=(
            "Obfuscate all function/method names, variables, and classes.  "
            "Default is to NOT obfuscate."
        )
    )
    parser.add_option(
        "--obfuscate-classes",
        action="store_true",
        dest="obf_classes",
        default=False,
        help="Obfuscate class names."
    )
    parser.add_option(
        "--obfuscate-functions",
        action="store_true",
        dest="obf_functions",
        default=False,
        help="Obfuscate function and method names."
    )
    parser.add_option(
        "--obfuscate-variables",
        action="store_true",
        dest="obf_variables",
        default=False,
        help="Obfuscate variable names."
    )
    parser.add_option(
        "--obfuscate-import-methods",
        action="store_true",
        dest="obf_import_methods",
        default=False,
        help="Obfuscate globally-imported mouled methods (e.g. 'Ag=re.compile')."
    )
    parser.add_option(
        "--obfuscate-builtins",
        action="store_true",
        dest="obf_builtins",
        default=False,
        help="Obfuscate built-ins (i.e. True, False, object, Exception, etc)."
    )
    parser.add_option(
        "--replacement-length",
        dest="replacement_length",
        default=1,
        help=(
            "The length of the random names that will be used when obfuscating "
            "identifiers."
        ),
        metavar="1"
    )
    parser.add_option(
        "--nonlatin",
        action="store_true",
        dest="use_nonlatin",
        default=False,
        help=(
            "Use non-latin (unicode) characters in obfuscation (Python 3 only)."
            "  WARNING: This results in some SERIOUSLY hard-to-read code."
        )
    )
    parser.add_option(
        "--prepend",
        dest="prepend",
        default=None,
        help=(
            "Prepend the text in this file to the top of our output.  "
            "e.g. A copyright notice."
        ),
        metavar="<file path>"
    )
    options, files = parser.parse_args()
    if not files:
        parser.print_help()
        sys.exit(2)
    pyminify(options, files)
527635
def main():
    
    # Define Parser object and add to toil
    parser = build_parser()
    Job.Runner.addToilOptions(parser)
    args = parser.parse_args()
    # Store inputs from argparse
    inputs = {'sra': args.sra,
              'dbgap_key': args.dbgap_key,
              'ssec': args.ssec,
              's3_dir': args.s3_dir,
              'single_end': args.single_end,
              'sudo': args.sudo}
    # Sanity checks
    if args.ssec:
        assert os.path.isfile(args.ssec)
    if args.sra:
        assert os.path.isfile(args.sra)
    if args.dbgap_key:
        assert os.path.isfile(args.dbgap_key)
    # Start Pipeline
    Job.Runner.startToil(Job.wrapJobFn(start_batch, inputs), args)