Muennighoff/xP3x-sample huggingface dataset:
inputs: I wrote the below code

    (uid, gid) = (os.geteuid(), os.getegid())
    if ((uid == euid) and (gid == egid)):
        return function(*args, **kwargs)
    else:
        if ((uid != 0) and ((uid != euid) or (gid != egid))):
            os.seteuid(0)
        if (gid != egid):
            os.setegid(egid)
        if ((euid != 0) and ((euid != uid) or (gid != egid))):
            os.seteuid(euid)
        try:
            return function(*args, **kwargs)
        finally:
            if ((euid != 0) and ((uid != euid) or (gid != egid))):
                os.seteuid(0)
            if (gid != egid):
                os.setegid(gid)
            if ((uid != 0) and ((uid != euid) or (gid != egid))):
                os.seteuid(uid)


What's a good function header?
targets: def runAsEffectiveUser(euid, egid, function, *args, **kwargs):
inputs: Complete the below
@register.tag(u'buttons')
def bootstrap_buttons(parser, token):

    ''''Render buttons for form
    **Tag name**::
    buttons
    **Parameters**:
    submit
    Text for a submit button
    reset
    Text for a reset button
    **Usage**::
    {% buttons %}{% endbuttons %}
    **Example**::
    {% buttons submit=\'OK\' reset="Cancel" %}{% endbuttons %}'
    '''
targets: kwargs = parse_token_contents(parser, token)
    kwargs[u'nodelist'] = parser.parse((u'endbuttons',))
    parser.delete_first_token()
    return ButtonsNode(**kwargs)
inputs: I wrote the below code

    if (not os.path.isdir(etcdir)):
        return iter(())
    return (name for name in os.listdir(etcdir) if (name.endswith('.py') and os.path.isfile(os.path.join(etcdir, name))))


What's a good function header?
targets: def list_config_modules(etcdir):
inputs: def copy_file(src, dst, preserve_mode=1, preserve_times=1, update=0, link=None, verbose=1, dry_run=0):
targets: """Copy a file \src\ to \dst\.
    If \dst\ is a directory, then \src\ is copied there with the same name;
    otherwise, it must be a filename.  (If the file exists, it will be
    ruthlessly clobbered.)  If \preserve_mode\ is true (the default),
    the file\s mode (type and permission bits, or whatever is analogous on
    the current platform) is copied.  If \preserve_times\ is true (the
    default), the last-modified and last-access times are copied as well.
    If \update\ is true, \src\ will only be copied if \dst\ does not exist,
    or if \dst\ does exist but is older than \src\.
    \link\ allows you to make hard links (os.link) or symbolic links
    (os.symlink) instead of copying: set it to "hard" or "sym"; if it is
    None (the default), files are copied.  Don\t set \link\ on systems that
    don\t support it: \copy_file()\ doesn\t check if hard or symbolic
    linking is available.
    Under Mac OS, uses the native file copy function in macostools; on
    other systems, uses \_copy_file_contents()\ to copy file contents.
    Return a tuple (dest_name, copied): \dest_name\ is the actual name of
    the output file, and \copied\ is true if the file was copied (or would
    have been copied, if \dry_run\ true).
    """
    from distutils.dep_util import newer
    from stat import ST_ATIME, ST_MTIME, ST_MODE, S_IMODE
    if (not os.path.isfile(src)):
        raise DistutilsFileError(("can't    copy    '%s':    doesn't    exist    or    not    a    regular    file" % src))
    if os.path.isdir(dst):
        dir = dst
        dst = os.path.join(dst, os.path.basename(src))
    else:
        dir = os.path.dirname(dst)
    if (update and (not newer(src, dst))):
        if (verbose >= 1):
            log.debug('not    copying    %s    (output    up-to-date)', src)
        return (dst, 0)
    try:
        action = _copy_action[link]
    except KeyError:
        raise ValueError(("invalid    value    '%s'    for    'link'    argument" % link))
    if (verbose >= 1):
        if (os.path.basename(dst) == os.path.basename(src)):
            log.info('%s    %s    ->    %s', action, src, dir)
        else:
            log.info('%s    %s    ->    %s', action, src, dst)
    if dry_run:
        return (dst, 1)
    if (link == 'hard'):
        if (not (os.path.exists(dst) and os.path.samefile(src, dst))):
            os.link(src, dst)
    elif (link == 'sym'):
        if (not (os.path.exists(dst) and os.path.samefile(src, dst))):
            os.symlink(src, dst)
    else:
        _copy_file_contents(src, dst)
        if (preserve_mode or preserve_times):
            st = os.stat(src)
            if preserve_times:
                os.utime(dst, (st[ST_ATIME], st[ST_MTIME]))
            if preserve_mode:
                os.chmod(dst, S_IMODE(st[ST_MODE]))
    return (dst, 1)
inputs: Complete the below
def bulk_item_promo(order):

    ''''10% discount for each LineItem with 20 or more units'
    '''
targets: discount = 0
    for item in order.cart:
        if (item.quantity >= 20):
            discount += (item.total() * 0.1)
    return discount
inputs: def getDisplayToolButtonsRepository(directoryPath, importantFileNames, names, repository):
targets: """Get the display tool buttons.
    """
    displayToolButtons = []
    for name in names:
        displayToolButton = DisplayToolButton().getFromPath((name in importantFileNames), name, os.path.join(directoryPath, name), repository)
        displayToolButtons.append(displayToolButton)
    return displayToolButtons
inputs: Complete the below
def get_api_version(resource_type):

    ''''Get the current API version for a given resource_type.
    :param resource_type: The resource type.
    :type resource_type: ResourceType.
    :returns:  str -- The API version.'
    '''
targets: from azure.cli.core._profile import CLOUD
    return _sdk_get_api_version(CLOUD.profile, resource_type)
inputs: I wrote the below code

    code = int(code)
    if (not (1 <= code <= 2147483647)):
        raise ValueError('code    out    of    range')
    key = (module, name)
    if ((_extension_registry.get(key) == code) and (_inverted_registry.get(code) == key)):
        return
    if (key in _extension_registry):
        raise ValueError(('key    %s    is    already    registered    with    code    %s' % (key, _extension_registry[key])))
    if (code in _inverted_registry):
        raise ValueError(('code    %s    is    already    in    use    for    key    %s' % (code, _inverted_registry[code])))
    _extension_registry[key] = code
    _inverted_registry[code] = key


What's a good function header?
targets: def add_extension(module, name, code):
inputs: I wrote the below code

    if target_outdated(target, deps):
        system(cmd)


What's a good function header?
targets: def target_update(target, deps, cmd):
inputs: Complete the below
def listing(output_lines):

    ''''Return list of dicts with basic item info parsed from cli output.'
    '''
targets: items = []
    table_ = table(output_lines)
    for row in table_['values']:
        item = {}
        for (col_idx, col_key) in enumerate(table_['headers']):
            item[col_key] = row[col_idx]
        items.append(item)
    return items
inputs: def CopyFiles(rebalance, server_id):
targets: """Copies data store files to the corresponding data servers.
    """
    loc = data_store.DB.Location()
    if (not os.path.exists(loc)):
        return True
    if (not os.path.isdir(loc)):
        return True
    pool_cache = {}
    removed_list = []
    ok = _RecCopyFiles(rebalance, server_id, loc, '', pool_cache, removed_list)
    if (not ok):
        return False
    remove_file = _FileWithRemoveList(loc, rebalance)
    with open(remove_file, 'wb') as fp:
        for f in removed_list:
            fp.write((f.encode('utf8') + '\n'))
    return True
inputs: Complete the below
@pytest.mark.skipif(u'not    HAS_SCIPY')
def test_subpixel_gauss_1D():

    ''''Test subpixel accuracy of the integrate mode with gaussian 1D model.'
    '''
targets: gauss_1D = Gaussian1D(1, 0, 0.1)
    values = discretize_model(gauss_1D, ((-1), 2), mode=u'integrate', factor=100)
    assert_allclose(values.sum(), (np.sqrt((2 * np.pi)) * 0.1), atol=1e-05)
inputs: I wrote the below code

    _validate_path(name)
    if (not _GCS_BUCKET_REGEX.match(name)):
        raise ValueError(('Bucket    should    be    3-63    characters    long    using    only    a-z,0-9,    underscore,    dash    or    dot    but    got    %s' % name))


What's a good function header?
targets: def validate_bucket_name(name):
inputs: Complete the below
def clean_ascii_chars(txt, charlist=None):

    ''''Remove ASCII control chars.
    This is all control chars except \t, \n and \r'
    '''
targets: if (not txt):
        return ''
    global _ascii_pat
    if (_ascii_pat is None):
        chars = set(xrange(32))
        chars.add(127)
        for x in (9, 10, 13):
            chars.remove(x)
        _ascii_pat = re.compile(u'|'.join(map(unichr, chars)))
    if (charlist is None):
        pat = _ascii_pat
    else:
        pat = re.compile(u'|'.join(map(unichr, charlist)))
    return pat.sub('', txt)
inputs: Complete the below
def CreateSummaryResults():

    ''''Process the resulting .plist file from the test and generate the html results'
    '''
targets: errors = []
    passes = []
    current_path = os.path.join(_RESULTS_PATH, 'current')
    schemes = GetCurrentSchemes()
    test_path = os.path.join(current_path, options.conf)
    print 'Creating    summary    results.'
    for testname in _SUMMARY.keys():
        if testname.endswith('.js'):
            testname = testname[:(-3)]
        temp_details = ''
        filepath = (((test_path + '/') + testname) + '/Run    1/Automation    Results.plist')
        print filepath
        xmldoc = ElementTree.parse(filepath)
        dicts = xmldoc.findall('*/array/dict')
        for tmpdict in dicts:
            error = {}
            tmppass = {}
            if ((tmpdict.find('string').text == 'Error') and (int(tmpdict.find('integer').text) == 4)):
                error['testname'] = tmpdict[3].text
                error['timestamp'] = tmpdict.find('date').text
                error['status'] = tmpdict[1].text
                errors.append(error)
            elif ((tmpdict.find('string').text == 'Pass') and (int(tmpdict.find('integer').text) == 4)):
                tmppass['testname'] = tmpdict[3].text
                tmppass['timestamp'] = tmpdict.find('date').text
                tmppass['status'] = tmpdict[1].text
                passes.append(tmppass)
            elif (tmpdict[1].text == 'Debug'):
                temp_details += (tmpdict[3].text + '\n')
        _SUMMARY[testname]['details'] = temp_details
        if (not options.regen):
            ProcessScreenshots(testname)
        for image_name in GetImageNames(testname):
            if (IsImageEqual(testname, image_name) is False):
                _SUMMARY[testname]['warnings'][image_name] = 'Warning:    The    screenshot    does    not    match    the    Baseline.        Do    you    want    to    Accept    the    Current    image    as    the    new    Baseline?'
                _SUMMARY[testname]['alert'] = True
            else:
                _SUMMARY[testname]['warnings'][image_name] = None
    fmt_args = {'errors': errors, 'passes': passes,...
inputs: Complete the below
def c_login_nodig(client):

    ''''logins, don\'t dig its own room'
    '''
targets: cname = (DUMMY_NAME % client.gid)
    cpwd = (DUMMY_PWD % client.gid)
    cmds = (('create    %s    %s' % (cname, cpwd)), ('connect    %s    %s' % (cname, cpwd)))
    return cmds
inputs: Complete the below
def _gen_keep_files(name, require, walk_d=None):

    ''''Generate the list of files that need to be kept when a dir based function
    like directory or recurse has a clean.'
    '''
targets: def _is_child(path, directory):
        '\n                                Check    whether    ``path``    is    child    of    ``directory``\n                                '
        path = os.path.abspath(path)
        directory = os.path.abspath(directory)
        relative = os.path.relpath(path, directory)
        return (not relative.startswith(os.pardir))
    def _add_current_path(path):
        _ret = set()
        if os.path.isdir(path):
            (dirs, files) = walk_d.get(path, ((), ()))
            _ret.add(path)
            for _name in files:
                _ret.add(os.path.join(path, _name))
            for _name in dirs:
                _ret.add(os.path.join(path, _name))
        return _ret
    def _process_by_walk_d(name, ret):
        if os.path.isdir(name):
            walk_ret.update(_add_current_path(name))
            (dirs, _) = walk_d.get(name, ((), ()))
            for _d in dirs:
                p = os.path.join(name, _d)
                walk_ret.update(_add_current_path(p))
                _process_by_walk_d(p, ret)
    def _process(name):
        ret = set()
        if os.path.isdir(name):
            for (root, dirs, files) in os.walk(name):
                ret.add(name)
                for name in files:
                    ret.add(os.path.join(root, name))
                for name in dirs:
                    ret.add(os.path.join(root, name))
        return ret
    keep = set()
    if isinstance(require, list):
        required_files = [comp for comp in require if ('file' in comp)]
        for comp in required_files:
            for low in __lowstate__:
                if ((low['name'] == comp['file']) or (low['__id__'] == comp['file'])):
                    fn = low['name']
                    fun = low['fun']
                    if os.path.isdir(fn):
                        if _is_child(fn, name):
                            if (fun == 'recurse'):
                                fkeep = _gen_recurse_managed_files(**low)[3]
                               ...
inputs: I wrote the below code

    entities = entities.copy()
    entities.update({'\n': '&#10;', '\r': '&#13;', ' DCTB ': '&#9;'})
    data = escape(data, entities)
    if ('"' in data):
        if ("'" in data):
            data = ('"%s"' % data.replace('"', '&quot;'))
        else:
            data = ("'%s'" % data)
    else:
        data = ('"%s"' % data)
    return data


What's a good function header?
targets: def quoteattr(data, entities={}):
inputs: I wrote the below code

    length = (max((len(str(s)) for s in str_list)) + extra)
    def pad(string):
        string = str(string)
        padding = max(0, (length - len(string)))
        return (string + (padding * '    '))
    return pad


What's a good function header?
targets: def padder(str_list, extra=0):
inputs: def downgrade(migrate_engine):
targets: """Call the correct dialect-specific downgrade.
    """
    meta.bind = migrate_engine
    t_images = _get_table('images', meta)
    t_image_members = _get_table('image_members', meta)
    t_image_properties = _get_table('image_properties', meta)
    dialect = migrate_engine.url.get_dialect().name
    if (dialect == 'sqlite'):
        _update_all_uuids_to_ids(t_images, t_image_members, t_image_properties)
        _downgrade_sqlite(t_images, t_image_members, t_image_properties)
    else:
        _downgrade_other(t_images, t_image_members, t_image_properties, dialect)
inputs: Complete the below
def debug(module, name, pm=False):

    ''''Debug a single doctest docstring.
    Provide the module (or dotted name of the module) containing the
    test to be debugged and the name (within the module) of the object
    with the docstring with tests to be debugged.'
    '''
targets: module = _normalize_module(module)
    testsrc = testsource(module, name)
    debug_script(testsrc, pm, module.__dict__)
inputs: I wrote the below code

    path = '/opt/mellanox/mxm'
    if os.path.isdir(path):
        return path
    else:
        return None


What's a good function header?
targets: def _mxm_dir():
inputs: I wrote the below code

    random_state = check_random_state(random_state)
    X = check_array(X, ensure_min_samples=2, estimator='fast_mcd')
    (n_samples, n_features) = X.shape
    if (support_fraction is None):
        n_support = int(np.ceil((0.5 * ((n_samples + n_features) + 1))))
    else:
        n_support = int((support_fraction * n_samples))
    if (n_features == 1):
        if (n_support < n_samples):
            X_sorted = np.sort(np.ravel(X))
            diff = (X_sorted[n_support:] - X_sorted[:(n_samples - n_support)])
            halves_start = np.where((diff == np.min(diff)))[0]
            location = (0.5 * (X_sorted[(n_support + halves_start)] + X_sorted[halves_start]).mean())
            support = np.zeros(n_samples, dtype=bool)
            X_centered = (X - location)
            support[np.argsort(np.abs(X_centered), 0)[:n_support]] = True
            covariance = np.asarray([[np.var(X[support])]])
            location = np.array([location])
            precision = linalg.pinvh(covariance)
            dist = (np.dot(X_centered, precision) * X_centered).sum(axis=1)
        else:
            support = np.ones(n_samples, dtype=bool)
            covariance = np.asarray([[np.var(X)]])
            location = np.asarray([np.mean(X)])
            X_centered = (X - location)
            precision = linalg.pinvh(covariance)
            dist = (np.dot(X_centered, precision) * X_centered).sum(axis=1)
    if ((n_samples > 500) and (n_features > 1)):
        n_subsets = (n_samples // 300)
        n_samples_subsets = (n_samples // n_subsets)
        samples_shuffle = random_state.permutation(n_samples)
        h_subset = int(np.ceil((n_samples_subsets * (n_support / float(n_samples)))))
        n_trials_tot = 500
        n_best_sub = 10
        n_trials = max(10, (n_trials_tot // n_subsets))
        n_best_tot = (n_subsets * n_best_sub)
        all_best_locations = np.zeros((n_best_tot, n_features))
        try:
            all_best_covariances = np.zeros((n_best_tot, n_features, n_features))
        except MemoryError:
      ...

What's a good function header?
targets: def fast_mcd(X, support_fraction=None, cov_computation_method=empirical_covariance, random_state=None):
inputs: I wrote the below code

    if (sys.platform not in supported_platforms):
        return (system, release, version)
    for cmd in ('ver', 'command    /c    ver', 'cmd    /c    ver'):
        try:
            pipe = popen(cmd)
            info = pipe.read()
            if pipe.close():
                raise OSError('command    failed')
        except OSError as why:
            continue
        else:
            break
    else:
        return (system, release, version)
    info = info.strip()
    m = _ver_output.match(info)
    if (m is not None):
        (system, release, version) = m.groups()
        if (release[(-1)] == '.'):
            release = release[:(-1)]
        if (version[(-1)] == '.'):
            version = version[:(-1)]
        version = _norm_version(version)
    return (system, release, version)


What's a good function header?
targets: def _syscmd_ver(system='', release='', version='', supported_platforms=('win32', 'win16', 'dos')):
inputs: I wrote the below code

    kwargs.setdefault('autoflush', False)
    kwargs.setdefault('autocommit', True)
    kwargs.setdefault('expire_on_commit', False)
    return Session(bind=bind, **kwargs)


What's a good function header?
targets: def create_session(bind=None, **kwargs):
inputs: I wrote the below code

    if (getattr(package, '__name__', None) == '__main__'):
        return abspath
    pp = (package_path(package) + os.path.sep)
    if abspath.startswith(pp):
        relpath = abspath[len(pp):]
        return ('%s:%s' % (package_name(package), relpath.replace(os.path.sep, '/')))
    return abspath


What's a good function header?
targets: def asset_spec_from_abspath(abspath, package):
inputs: I wrote the below code

    json_tags[(TAG_PREFIX + getattr(cls, 'json_tag'))] = cls
    return cls


What's a good function header?
targets: def register_tag(cls):
inputs: Complete the below
def load(fp, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):

    ''''Deserialize ``fp`` (a ``.read()``-supporting file-like object containing
    a JSON document) to a Python object.
    ``object_hook`` is an optional function that will be called with the
    result of any object literal decode (a ``dict``). The return value of
    ``object_hook`` will be used instead of the ``dict``. This feature
    can be used to implement custom decoders (e.g. JSON-RPC class hinting).
    ``object_pairs_hook`` is an optional function that will be called with the
    result of any object literal decoded with an ordered list of pairs.  The
    return value of ``object_pairs_hook`` will be used instead of the ``dict``.
    This feature can be used to implement custom decoders that rely on the
    order that the key and value pairs are decoded (for example,
    collections.OrderedDict will remember the order of insertion). If
    ``object_hook`` is also defined, the ``object_pairs_hook`` takes priority.
    To use a custom ``JSONDecoder`` subclass, specify it with the ``cls``
    kwarg; otherwise ``JSONDecoder`` is used.'
    '''
targets: return loads(fp.read(), cls=cls, object_hook=object_hook, parse_float=parse_float, parse_int=parse_int, parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
inputs: Complete the below
def _sphere_to_cartesian(theta, phi, r):

    ''''Convert using old function.'
    '''
targets: z = (r * np.sin(phi))
    rcos_phi = (r * np.cos(phi))
    x = (rcos_phi * np.cos(theta))
    y = (rcos_phi * np.sin(theta))
    return (x, y, z)
inputs: I wrote the below code

    opts_pillar = opts.get('pillar', {})
    opts_master = opts_pillar.get('master', {})
    opts_merged = {}
    opts_merged.update(opts_master)
    opts_merged.update(opts_pillar)
    opts_merged.update(opts)
    if profile:
        conf = opts_merged.get(profile, {})
    else:
        conf = opts_merged
    params = {}
    for key in conf:
        if key.startswith('consul.'):
            params[key.split('.')[1]] = conf[key]
    if ('dc' in params):
        pillarenv = (opts_merged.get('pillarenv') or 'base')
        params['dc'] = _resolve_datacenter(params['dc'], pillarenv)
    if HAS_CONSUL:
        if ((CONSUL_VERSION < '0.4.7') and params.get('target')):
            params.pop('target')
        return consul.Consul(**params)
    else:
        raise CommandExecutionError('(unable    to    import    consul,    module    most    likely    not    installed.    Download    python-consul    module    and    be    sure    to    import    consul)')


What's a good function header?
targets: def get_conn(opts, profile):
inputs: Complete the below
def getAroundsFromLoops(loops, radius, thresholdRatio=0.9):

    ''''Get the arounds from the loops.'
    '''
targets: return getAroundsFromPoints(getPointsFromLoops(loops, radius, thresholdRatio), radius)
inputs: I wrote the below code

    if (not callable(key)):
        key = getter(key)
    return frequencies(map(key, seq))


What's a good function header?
targets: def countby(key, seq):
inputs: def each_setup_in_pkg(top_dir):
targets: """Yield path and file object for each setup.py file
    """
    for (dir_path, dir_names, filenames) in os.walk(top_dir):
        for fname in filenames:
            if (fname == 'setup.py'):
                with open(os.path.join(dir_path, 'setup.py')) as f:
                    (yield (dir_path, f))
inputs: Complete the below
def calculate_group_counts(messages, user_email):

    ''''Strips out most of the logic from calculate_group_scores
    algorithm and just returns raw counts for each group.'
    '''
targets: res = defaultdict(int)
    for msg in messages:
        participants = _get_participants(msg, [user_email])
        if (len(participants) >= MIN_GROUP_SIZE):
            res[',    '.join(participants)] += 1
    return res
inputs: def find_management_module(app_name):
targets: """Determines the path to the management module for the given app_name,
    without actually importing the application or the management module.
    Raises ImportError if the management module cannot be found for any reason.
    """
    parts = app_name.split('.')
    parts.append('management')
    parts.reverse()
    part = parts.pop()
    path = None
    try:
        (f, path, descr) = imp.find_module(part, path)
    except ImportError as e:
        if (os.path.basename(os.getcwd()) != part):
            raise e
    while parts:
        part = parts.pop()
        (f, path, descr) = imp.find_module(part, ((path and [path]) or None))
    return path
inputs: I wrote the below code

    indentation = _get_indentation(logical_line)
    return ((indentation + untokenize_without_newlines(generate_tokens(logical_line.lstrip()))) + u'\n')


What's a good function header?
targets: def join_logical_line(logical_line):
inputs: def isestimable(C, D):
targets: """True if (Q, P) contrast `C` is estimable for (N, P) design `D`
    From an Q x P contrast matrix `C` and an N x P design matrix `D`, checks if
    the contrast `C` is estimable by looking at the rank of ``vstack([C,D])``
    and verifying it is the same as the rank of `D`.
    Parameters
    C : (Q, P) array-like
    contrast matrix. If `C` has is 1 dimensional assume shape (1, P)
    D: (N, P) array-like
    design matrix
    Returns
    tf : bool
    True if the contrast `C` is estimable on design `D`
    Examples
    >>> D = np.array([[1, 1, 1, 0, 0, 0],
    ...               [0, 0, 0, 1, 1, 1],
    ...               [1, 1, 1, 1, 1, 1]]).T
    >>> isestimable([1, 0, 0], D)
    False
    >>> isestimable([1, -1, 0], D)
    True
    """
    C = np.asarray(C)
    D = np.asarray(D)
    if (C.ndim == 1):
        C = C[None, :]
    if (C.shape[1] != D.shape[1]):
        raise ValueError(('Contrast    should    have    %d    columns' % D.shape[1]))
    new = np.vstack([C, D])
    if (np_matrix_rank(new) != np_matrix_rank(D)):
        return False
    return True
inputs: Complete the below
def _format_state_result(name, result, changes=None, comment=''):

    ''''Creates the state result dictionary.'
    '''
targets: if (changes is None):
        changes = {'old': '', 'new': ''}
    return {'name': name, 'result': result, 'changes': changes, 'comment': comment}
inputs: def create_issues_in_bulk(bulk_data, callback=None, precall=None, **additional_fields):
targets: """Create issues from `bulk_data`.
    :param bulk_data: List of issues in bulk format.
    :param callback: Callback to execute after each issue save.
    :param additional_fields: Additional fields when instantiating each issue.
    :return: List of created `Issue` instances.
    """
    issues = get_issues_from_bulk(bulk_data, **additional_fields)
    disconnect_issues_signals()
    try:
        db.save_in_bulk(issues, callback, precall)
    finally:
        connect_issues_signals()
    return issues
inputs: def __get_ssh_interface(vm_):
targets: """Return the ssh_interface type to connect to. Either \public_ips\ (default)
    or \private_ips\.
    """
    return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
inputs: Complete the below
def _get_version_from_git(pre_version):

    ''''Return a version which is equal to the tag that\'s on the current
    revision if there is one, or tag plus number of additional revisions
    if the current revision has no tag.'
    '''
targets: git_dir = _get_git_directory()
    if git_dir:
        if pre_version:
            try:
                return _run_shell_command((('git    --git-dir=' + git_dir) + '    describe    --exact-match'), throw_on_error=True).replace('-', '.')
            except Exception:
                sha = _run_shell_command((('git    --git-dir=' + git_dir) + '    log    -n1    --pretty=format:%h'))
                return ('%s.a%s.g%s' % (pre_version, _get_revno(git_dir), sha))
        else:
            return _run_shell_command((('git    --git-dir=' + git_dir) + '    describe    --always')).replace('-', '.')
    return None
inputs: def expandvars(path):
targets: """Expand shell variables of the forms $var, ${var} and %var%.
    Unknown variables are left unchanged.
    """
    if (('$' not in path) and ('%' not in path)):
        return path
    import string
    varchars = ((string.ascii_letters + string.digits) + '_-')
    if isinstance(path, _unicode):
        encoding = sys.getfilesystemencoding()
        def getenv(var):
            return os.environ[var.encode(encoding)].decode(encoding)
    else:
        def getenv(var):
            return os.environ[var]
    res = ''
    index = 0
    pathlen = len(path)
    while (index < pathlen):
        c = path[index]
        if (c == "'"):
            path = path[(index + 1):]
            pathlen = len(path)
            try:
                index = path.index("'")
                res = ((res + "'") + path[:(index + 1)])
            except ValueError:
                res = ((res + c) + path)
                index = (pathlen - 1)
        elif (c == '%'):
            if (path[(index + 1):(index + 2)] == '%'):
                res = (res + c)
                index = (index + 1)
            else:
                path = path[(index + 1):]
                pathlen = len(path)
                try:
                    index = path.index('%')
                except ValueError:
                    res = ((res + '%') + path)
                    index = (pathlen - 1)
                else:
                    var = path[:index]
                    try:
                        res = (res + getenv(var))
                    except KeyError:
                        res = (((res + '%') + var) + '%')
        elif (c == '$'):
            if (path[(index + 1):(index + 2)] == '$'):
                res = (res + c)
                index = (index + 1)
            elif (path[(index + 1):(index + 2)] == '{'):
                path = path[(index + 2):]
                pathlen = len(path)
                try:
                    index = path.index('}')
                    var = path[:index]
                    try:
                        res = (res + getenv(var))
                    except KeyError:
                        res = (((res + '${') + var) + '}')
    ...
inputs: def _configure(changes):
targets: """Calls the configuration template to apply the configuration changes on the device.
    """
    cfgred = True
    reasons = []
    fun = 'update_config'
    for key in ['added', 'updated', 'removed']:
        _updated_changes = changes.get(key, {})
        if (not _updated_changes):
            continue
        _location = _updated_changes.get('location', '')
        _contact = _updated_changes.get('contact', '')
        _community = _updated_changes.get('community', {})
        _chassis_id = _updated_changes.get('chassis_id', '')
        if (key == 'removed'):
            fun = 'remove_config'
        _ret = __salt__['snmp.{fun}'.format(fun=fun)](location=_location, contact=_contact, community=_community, chassis_id=_chassis_id, commit=False)
        cfgred = (cfgred and _ret.get('result'))
        if ((not _ret.get('result')) and _ret.get('comment')):
            reasons.append(_ret.get('comment'))
    return {'result': cfgred, 'comment': ('\n'.join(reasons) if reasons else '')}
inputs: def _encode_objectid(name, value, dummy0, dummy1):
targets: """Encode bson.objectid.ObjectId.
    """
    return (('\x07' + name) + value.binary)
inputs: I wrote the below code

    (utype, vtype) = (None, None)
    if (not (hasattr(u, 'dtype') and np.issubdtype(u.dtype, np.inexact))):
        utype = np.float64
    if (not (hasattr(v, 'dtype') and np.issubdtype(v.dtype, np.inexact))):
        vtype = np.float64
    u = _validate_vector(u, dtype=utype)
    v = _validate_vector(v, dtype=vtype)
    u_v = (u - v)
    return np.dot(u_v, u_v)


What's a good function header?
targets: def sqeuclidean(u, v):
inputs: def do_default(value, default_value=u'', boolean=False):
targets: """If the value is undefined it will return the passed default value,
    otherwise the value of the variable:
    .. sourcecode:: jinja
    {{ my_variable|default(\my_variable is not defined\) }}
    This will output the value of ``my_variable`` if the variable was
    defined, otherwise ``\my_variable is not defined\``. If you want
    to use default with variables that evaluate to false you have to
    set the second parameter to `true`:
    .. sourcecode:: jinja
    {{ \\|default(\the string was empty\, true) }}
    """
    if ((boolean and (not value)) or isinstance(value, Undefined)):
        return default_value
    return value
inputs: I wrote the below code

    if namespace:
        return db.Key.from_path(metadata.Namespace.KIND_NAME, namespace, _app=app)
    else:
        return db.Key.from_path(metadata.Namespace.KIND_NAME, metadata.Namespace.EMPTY_NAMESPACE_ID, _app=app)


What's a good function header?
targets: def _key_for_namespace(namespace, app):
inputs: Complete the below
def assert_quantities_allclose(coord, q1s, attrs):

    ''''Compare two tuples of quantities.  This assumes that the values in q1 are of
    order(1) and uses atol=1e-13, rtol=0.  It also asserts that the units of the
    two quantities are the *same*, in order to check that the representation
    output has the expected units.'
    '''
targets: q2s = [getattr(coord, attr) for attr in attrs]
    assert (len(q1s) == len(q2s))
    for (q1, q2) in zip(q1s, q2s):
        assert (q1.shape == q2.shape)
        assert allclose(q1, q2, rtol=0, atol=(1e-13 * q1.unit))
inputs: I wrote the below code

    path = (dirname(dirname(abspath(__file__))) if (path is None) else path)
    repo_name = basename(path)
    repo = git.Repo(path)
    create_git_index(client, index)
    client.create(index=index, doc_type='repos', id=repo_name, body={}, ignore=409)
    for (ok, result) in streaming_bulk(client, parse_commits(repo.refs.master.commit, repo_name), index=index, doc_type='commits', chunk_size=50):
        (action, result) = result.popitem()
        doc_id = ('/%s/commits/%s' % (index, result['_id']))
        if (not ok):
            print(('Failed    to    %s    document    %s:    %r' % (action, doc_id, result)))
        else:
            print(doc_id)


What's a good function header?
targets: def load_repo(client, path=None, index='git'):
inputs: Complete the below
def custom_key_func(key, key_prefix, version):

    ''''A customized cache key function'
    '''
targets: return ('CUSTOM-' + '-'.join([key_prefix, str(version), key]))
inputs: Complete the below
def expand_log(expr, deep=True, force=False):

    ''''Wrapper around expand that only uses the log hint.  See the expand
    docstring for more information.
    Examples
    >>> from sympy import symbols, expand_log, exp, log
    >>> x, y = symbols(\'x,y\', positive=True)
    >>> expand_log(exp(x+y)*(x+y)*log(x*y**2))
    (x + y)*(log(x) + 2*log(y))*exp(x + y)'
    '''
targets: return sympify(expr).expand(deep=deep, log=True, mul=False, power_exp=False, power_base=False, multinomial=False, basic=False, force=force)
inputs: Complete the below
def devname(pcap_name):

    ''''Return libdnet/Scapy device name for given pypcap device name'
    '''
targets: return ifaces.devname(pcap_name)
inputs: I wrote the below code

    class K(object, ):
        def __init__(self, obj):
            self.obj = obj
        def __lt__(self, other):
            return (mycmp(self.obj, other.obj) == (-1))
    return K


What's a good function header?
targets: def _CmpToKey(mycmp):
inputs: Complete the below
def get_computer_name():

    ''''Get hostname.
    CLI Example:
    .. code-block:: bash
    salt \'*\' network.get_hostname'
    '''
targets: return __salt__['network.get_hostname']()
inputs: I wrote the below code

    if (G.name == ''):
        name = 'NetworkX'
    else:
        name = G.name
    (yield ('*vertices    %s' % G.order()))
    nodes = list(G)
    nodenumber = dict(zip(nodes, range(1, (len(nodes) + 1))))
    for n in nodes:
        na = G.node.get(n, {})
        x = na.get('x', 0.0)
        y = na.get('y', 0.0)
        id = int(na.get('id', nodenumber[n]))
        nodenumber[n] = id
        shape = na.get('shape', 'ellipse')
        s = '    '.join(map(make_qstr, (id, n, x, y, shape)))
        for (k, v) in na.items():
            if (v.strip() != ''):
                s += ('    %s    %s' % (make_qstr(k), make_qstr(v)))
        (yield s)
    if G.is_directed():
        (yield '*arcs')
    else:
        (yield '*edges')
    for (u, v, edgedata) in G.edges(data=True):
        d = edgedata.copy()
        value = d.pop('weight', 1.0)
        s = '    '.join(map(make_qstr, (nodenumber[u], nodenumber[v], value)))
        for (k, v) in d.items():
            if (v.strip() != ''):
                s += ('    %s    %s' % (make_qstr(k), make_qstr(v)))
        (yield s)


What's a good function header?
targets: def generate_pajek(G):
inputs: def concrete(seq):
targets: """Make nested iterators concrete lists
    >>> data = [[1, 2], [3, 4]]
    >>> seq = iter(map(iter, data))
    >>> concrete(seq)
    [[1, 2], [3, 4]]
    """
    if isinstance(seq, Iterator):
        seq = list(seq)
    if isinstance(seq, (tuple, list)):
        seq = list(map(concrete, seq))
    return seq
inputs: I wrote the below code

    if (call == 'action'):
        raise SaltCloudSystemExit('The    list_nodes    function    must    be    called    with    -f    or    --function.')
    ret = {}
    conn = get_conn()
    server_list = conn.server_list()
    if (not server_list):
        return {}
    for server in server_list:
        server_tmp = conn.server_show(server_list[server]['id']).get(server)
        if (server_tmp is None):
            continue
        private = []
        public = []
        if ('addresses' not in server_tmp):
            server_tmp['addresses'] = {}
        for network in server_tmp['addresses']:
            for address in server_tmp['addresses'][network]:
                if salt.utils.cloud.is_public_ip(address.get('addr', '')):
                    public.append(address['addr'])
                elif (':' in address['addr']):
                    public.append(address['addr'])
                elif ('.' in address['addr']):
                    private.append(address['addr'])
        if server_tmp['accessIPv4']:
            if salt.utils.cloud.is_public_ip(server_tmp['accessIPv4']):
                public.append(server_tmp['accessIPv4'])
            else:
                private.append(server_tmp['accessIPv4'])
        if server_tmp['accessIPv6']:
            public.append(server_tmp['accessIPv6'])
        ret[server] = {'id': server_tmp['id'], 'image': server_tmp['image']['id'], 'size': server_tmp['flavor']['id'], 'state': server_tmp['state'], 'private_ips': private, 'public_ips': public}
    return ret


What's a good function header?
targets: def list_nodes(call=None, **kwargs):
inputs: Complete the below
def get_tests_info(input_dir, msg_dir, prefix, suffix):

    ''''get python input examples and output messages
    We use following conventions for input files and messages:
    for different inputs:
    test for python  >= x.y    ->  input   =  <name>_pyxy.py
    test for python  <  x.y    ->  input   =  <name>_py_xy.py
    for one input and different messages:
    message for python >=  x.y ->  message =  <name>_pyxy.txt
    lower versions             ->  message with highest num'
    '''
targets: result = []
    for fname in glob(join(input_dir, ((prefix + '*') + suffix))):
        infile = basename(fname)
        fbase = splitext(infile)[0]
        pyrestr = fbase.rsplit('_py', 1)[(-1)]
        if pyrestr.isdigit():
            if (SYS_VERS_STR < pyrestr):
                continue
        if (pyrestr.startswith('_') and pyrestr[1:].isdigit()):
            if (SYS_VERS_STR >= pyrestr[1:]):
                continue
        messages = glob(join(msg_dir, (fbase + '*.txt')))
        if messages:
            for outfile in sorted(messages, reverse=True):
                py_rest = outfile.rsplit('_py', 1)[(-1)][:(-4)]
                if (py_rest.isdigit() and (SYS_VERS_STR >= py_rest)):
                    break
        else:
            outfile = join(msg_dir, (fbase + '.txt'))
        result.append((infile, outfile))
    return result
inputs: Complete the below
def get_field_precision(df, doc=None, currency=None):

    ''''get precision based on DocField options and fieldvalue in doc'
    '''
targets: from frappe.utils import get_number_format_info
    if cint(df.precision):
        precision = cint(df.precision)
    elif (df.fieldtype == u'Currency'):
        precision = cint(frappe.db.get_default(u'currency_precision'))
        if (not precision):
            number_format = (frappe.db.get_default(u'number_format') or u'#,###.##')
            (decimal_str, comma_str, precision) = get_number_format_info(number_format)
    else:
        precision = (cint(frappe.db.get_default(u'float_precision')) or 3)
    return precision
inputs: I wrote the below code

    node = MockNode()
    value = MockValue(data=0, node=node)
    values = MockEntityValues(primary=value)
    device = zwave.get_device(node=node, values=values, node_config={})
    assert isinstance(device, zwave.ZwaveSwitch)


What's a good function header?
targets: def test_get_device_detects_switch(mock_openzwave):
inputs: I wrote the below code

    conf = Config(None, {'type': 'alexa'})
    number = conf.entity_id_to_number('light.test')
    assert (number == 'light.test')
    number = conf.entity_id_to_number('light.test')
    assert (number == 'light.test')
    number = conf.entity_id_to_number('light.test2')
    assert (number == 'light.test2')
    entity_id = conf.number_to_entity_id('light.test')
    assert (entity_id == 'light.test')


What's a good function header?
targets: def test_config_alexa_entity_id_to_number():
inputs: def addsitepackages(known_paths):
targets: """Add site-packages (and possibly site-python) to sys.path
    """
    for sitedir in getsitepackages():
        if os.path.isdir(sitedir):
            addsitedir(sitedir, known_paths)
    return known_paths
inputs: I wrote the below code

    @wraps(view_func)
    def _checklogin(request, *args, **kwargs):
        if (request.user.is_active and request.user.is_staff):
            return view_func(request, *args, **kwargs)
        assert hasattr(request, 'session'), "The    Django    admin    requires    session    middleware    to    be    installed.    Edit    your    MIDDLEWARE_CLASSES    setting    to    insert    'django.contrib.sessions.middleware.SessionMiddleware'."
        defaults = {'template_name': 'admin/login.html', 'authentication_form': AdminAuthenticationForm, 'extra_context': {'title': _('Log    in'), 'app_path': request.get_full_path(), REDIRECT_FIELD_NAME: request.get_full_path()}}
        return login(request, **defaults)
    return _checklogin


What's a good function header?
targets: def staff_member_required(view_func):
inputs: Complete the below
def debris_basin():

    ''''Debris Basins, RESTful controller'
    '''
targets: return s3_rest_controller()
inputs: def inverse(x, n):
targets: """Returns x^-1 (mod n)
    >>> inverse(7, 4)
    3
    >>> (inverse(143, 4) * 143) % 4
    1
    """
    (divider, inv, _) = extended_gcd(x, n)
    if (divider != 1):
        raise ValueError(('x    (%d)    and    n    (%d)    are    not    relatively    prime' % (x, n)))
    return inv
inputs: I wrote the below code

    if (not uri.startswith(u'http')):
        uri = (u'http://' + uri)
    if (headers is None):
        headers = default_headers
    else:
        tmp = default_headers.copy()
        headers = tmp.update(headers)
    u = requests.get(uri, timeout=timeout, headers=headers, verify=verify_ssl)
    info = u.headers
    u.close()
    return info


What's a good function header?
targets: @deprecated
def head(uri, timeout=20, headers=None, verify_ssl=True):
inputs: I wrote the below code

    img = load_image(image_path)
    img = pil_to_nparray(img)
    try:
        channel = img.shape[2]
    except:
        channel = 1
    return channel


What's a good function header?
targets: def get_img_channel(image_path):
inputs: def hypervolume(front, **kargs):
targets: """Returns the index of the individual with the least the hypervolume
    contribution. The provided *front* should be a set of non-dominated
    individuals having each a :attr:`fitness` attribute.
    """
    wobj = (numpy.array([ind.fitness.wvalues for ind in front]) * (-1))
    ref = kargs.get('ref', None)
    if (ref is None):
        ref = (numpy.max(wobj, axis=0) + 1)
    def contribution(i):
        return hv.hypervolume(numpy.concatenate((wobj[:i], wobj[(i + 1):])), ref)
    contrib_values = map(contribution, range(len(front)))
    return numpy.argmax(contrib_values)
inputs: Complete the below
def create_cookie(name, value, **kwargs):

    ''''Make a cookie from underspecified parameters.
    By default, the pair of `name` and `value` will be set for the domain \'\'
    and sent on every request (this is sometimes called a "supercookie").'
    '''
targets: result = dict(version=0, name=name, value=value, port=None, domain='', path='/', secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)
    badargs = (set(kwargs) - set(result))
    if badargs:
        err = 'create_cookie()    got    unexpected    keyword    arguments:    %s'
        raise TypeError((err % list(badargs)))
    result.update(kwargs)
    result['port_specified'] = bool(result['port'])
    result['domain_specified'] = bool(result['domain'])
    result['domain_initial_dot'] = result['domain'].startswith('.')
    result['path_specified'] = bool(result['path'])
    return cookielib.Cookie(**result)
inputs: Complete the below
def call(conf, context, topic, msg, timeout, connection_pool):

    ''''Sends a message on a topic and wait for a response.'
    '''
targets: rv = multicall(conf, context, topic, msg, timeout, connection_pool)
    rv = list(rv)
    if (not rv):
        return
    return rv[(-1)]
inputs: I wrote the below code

    course_key = course.id
    coupons = Coupon.objects.filter(course_id=course_key).order_by('-is_active')
    course_price = paid_mode.min_price
    total_amount = None
    if access['finance_admin']:
        single_purchase_total = PaidCourseRegistration.get_total_amount_of_purchased_item(course_key)
        bulk_purchase_total = CourseRegCodeItem.get_total_amount_of_purchased_item(course_key)
        total_amount = (single_purchase_total + bulk_purchase_total)
    section_data = {'section_key': 'e-commerce', 'section_display_name': _('E-Commerce'), 'access': access, 'course_id': unicode(course_key), 'currency_symbol': settings.PAID_COURSE_REGISTRATION_CURRENCY[1], 'ajax_remove_coupon_url': reverse('remove_coupon', kwargs={'course_id': unicode(course_key)}), 'ajax_get_coupon_info': reverse('get_coupon_info', kwargs={'course_id': unicode(course_key)}), 'get_user_invoice_preference_url': reverse('get_user_invoice_preference', kwargs={'course_id': unicode(course_key)}), 'sale_validation_url': reverse('sale_validation', kwargs={'course_id': unicode(course_key)}), 'ajax_update_coupon': reverse('update_coupon', kwargs={'course_id': unicode(course_key)}), 'ajax_add_coupon': reverse('add_coupon', kwargs={'course_id': unicode(course_key)}), 'get_sale_records_url': reverse('get_sale_records', kwargs={'course_id': unicode(course_key)}), 'get_sale_order_records_url': reverse('get_sale_order_records', kwargs={'course_id': unicode(course_key)}), 'instructor_url': reverse('instructor_dashboard', kwargs={'course_id': unicode(course_key)}), 'get_registration_code_csv_url': reverse('get_registration_codes', kwargs={'course_id': unicode(course_key)}), 'generate_registration_code_csv_url': reverse('generate_registration_codes', kwargs={'course_id': unicode(course_key)}), 'active_registration_code_csv_url': reverse('active_registration_codes', kwargs={'course_id': unicode(course_key)}), 'spent_registration_code_csv_url': reverse('spent_registration_codes', kwargs={'course_id': unicode(course_key)}), 'set_course_mode_url':...

What's a good function header?
targets: def _section_e_commerce(course, access, paid_mode, coupons_enabled, reports_enabled):
inputs: Complete the below
def foreign(expr):

    ''''Annotate a portion of a primaryjoin expression
    with a \'foreign\' annotation.
    See the section :ref:`relationship_custom_foreign` for a
    description of use.
    .. versionadded:: 0.8
    .. seealso::
    :ref:`relationship_custom_foreign`
    :func:`.remote`'
    '''
targets: return _annotate_columns(expression._clause_element_as_expr(expr), {'foreign': True})
inputs: Complete the below
@with_open_mode('rb')
@with_sizes('medium')
def read_seek_bytewise(f):

    ''''alternate read & seek one unit'
    '''
targets: f.seek(0)
    while f.read(1):
        f.seek(1, 1)