Muennighoff/xP3x-sample huggingface dataset:
inputs: Complete the below
def get_default_version(module=None):

    ''''Returns the name of the default version for the module.
    Args:
    module: Module to retrieve the default version for, if None then the current
    module will be used.
    Returns:
    String containing the name of the default version of the module.
    Raises:
    InvalidModuleError if the given module is not valid, InvalidVersionError if
    no default version could be found.'
    '''
targets: def _ResultHook(rpc):
        mapped_errors = [modules_service_pb.ModulesServiceError.INVALID_MODULE, modules_service_pb.ModulesServiceError.INVALID_VERSION]
        _CheckAsyncResult(rpc, mapped_errors, {})
        return rpc.response.version()
    request = modules_service_pb.GetDefaultVersionRequest()
    if module:
        request.set_module(module)
    response = modules_service_pb.GetDefaultVersionResponse()
    return _MakeAsyncCall('GetDefaultVersion', request, response, _ResultHook).get_result()
inputs: I wrote the below code

    name = (name[0].upper() + name[1:])
    return name.replace('_', '    ')


What's a good function header?
targets: def pretty_name(name):
inputs: Complete the below
@register.filter(expects_localtime=True)
def naturalday(value, arg=None):

    ''''For date values that are tomorrow, today or yesterday compared to
    present day returns representing string. Otherwise, returns a string
    formatted according to settings.DATE_FORMAT.'
    '''
targets: try:
        tzinfo = getattr(value, u'tzinfo', None)
        value = date(value.year, value.month, value.day)
    except AttributeError:
        return value
    except ValueError:
        return value
    today = datetime.now(tzinfo).date()
    delta = (value - today)
    if (delta.days == 0):
        return _(u'today')
    elif (delta.days == 1):
        return _(u'tomorrow')
    elif (delta.days == (-1)):
        return _(u'yesterday')
    return defaultfilters.date(value, arg)
inputs: Complete the below
def copy_hparams(hparams):

    ''''Return a copy of an HParams instance.'
    '''
targets: return tf.contrib.training.HParams(**hparams.values())
inputs: Complete the below
def isValidVariableName(name):

    ''''Checks whether a certain string could be used as a valid variable.
    Usage::
    OK, msg = isValidVariableName(name)
    >>> isValidVariableName(\'name\')
    (True, \'\')
    >>> isValidVariableName(\'0name\')
    (False, \'Variables cannot begin with numeric character\')
    >>> isValidVariableName(\'first second\')
    (False, \'Variables cannot contain punctuation or spaces\')
    >>> isValidVariableName(\'\')
    (False, "Variables cannot be missing, None, or \'\'")
    >>> isValidVariableName(None)
    (False, "Variables cannot be missing, None, or \'\'")
    >>> isValidVariableName(23)
    (False, "Variables must be string-like")
    >>> isValidVariableName(\'a_b_c\')
    (True, \'\')'
    '''
targets: if (not name):
        return (False, "Variables    cannot    be    missing,    None,    or    ''")
    if (not isinstance(name, basestring)):
        return (False, 'Variables    must    be    string-like')
    try:
        name = str(name)
    except Exception:
        if (type(name) in [str, np.unicode_]):
            msg = 'name    %s    (type    %s)    contains    non-ASCII    characters    (e.g.    accents)'
            raise AttributeError((msg % (name, type(name))))
        else:
            msg = 'name    %s    (type    %s)    could    not    be    converted    to    a    string'
            raise AttributeError((msg % (name, type(name))))
    if name[0].isdigit():
        return (False, 'Variables    cannot    begin    with    numeric    character')
    if _nonalphanumeric_re.search(name):
        return (False, 'Variables    cannot    contain    punctuation    or    spaces')
    return (True, '')
inputs: I wrote the below code

    if CONF.libvirt.disk_prefix:
        return CONF.libvirt.disk_prefix
    if (disk_bus == 'ide'):
        return 'hd'
    elif (disk_bus == 'virtio'):
        return 'vd'
    elif (disk_bus == 'xen'):
        return 'xvd'
    elif (disk_bus == 'scsi'):
        return 'sd'
    elif (disk_bus == 'usb'):
        return 'sd'
    elif (disk_bus == 'fdc'):
        return 'fd'
    elif (disk_bus == 'uml'):
        return 'ubd'
    elif (disk_bus == 'lxc'):
        return None
    elif (disk_bus == 'sata'):
        return 'sd'
    else:
        raise exception.InternalError((_('Unable    to    determine    disk    prefix    for    %s') % disk_bus))


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

    f = (_Cfunctions.get('libvlc_media_get_state', None) or _Cfunction('libvlc_media_get_state', ((1,),), None, State, Media))
    return f(p_md)


What's a good function header?
targets: def libvlc_media_get_state(p_md):
inputs: @docfiller
def maximum_filter1d(input, size, axis=(-1), output=None, mode='reflect', cval=0.0, origin=0):
targets: """Calculate a one-dimensional maximum filter along the given axis.
    The lines of the array along the given axis are filtered with a
    maximum filter of given size.
    Parameters
    %(input)s
    size : int
    Length along which to calculate the 1-D maximum.
    %(axis)s
    %(output)s
    %(mode)s
    %(cval)s
    %(origin)s
    Returns
    maximum1d : ndarray, None
    Maximum-filtered array with same shape as input.
    None if `output` is not None
    Notes
    This function implements the MAXLIST algorithm [1]_, as described by
    Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
    the `input` length, regardless of filter size.
    References
    .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
    .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
    Examples
    >>> from scipy.ndimage import maximum_filter1d
    >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
    array([8, 8, 8, 4, 9, 9, 9, 9])
    """
    input = numpy.asarray(input)
    if numpy.iscomplexobj(input):
        raise TypeError('Complex    type    not    supported')
    axis = _ni_support._check_axis(axis, input.ndim)
    if (size < 1):
        raise RuntimeError('incorrect    filter    size')
    (output, return_value) = _ni_support._get_output(output, input)
    if ((((size // 2) + origin) < 0) or (((size // 2) + origin) >= size)):
        raise ValueError('invalid    origin')
    mode = _ni_support._extend_mode_to_code(mode)
    _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, origin, 0)
    return return_value
inputs: I wrote the below code

    args = (args or [])
    options = PARSER.parse_args(args)
    options.file_params = dict()
    options.linters_params = dict()
    if config:
        cfg = get_config(str(options.options), rootdir=rootdir)
        for (opt, val) in cfg.default.items():
            LOGGER.info('Find    option    %s    (%s)', opt, val)
            passed_value = getattr(options, opt, _Default())
            if isinstance(passed_value, _Default):
                if (opt == 'paths'):
                    val = val.split()
                setattr(options, opt, _Default(val))
        for (name, opts) in cfg.sections.items():
            if ((not name.startswith('pylama')) or (name == cfg.default_section)):
                continue
            name = name[7:]
            if (name in LINTERS):
                options.linters_params[name] = dict(opts)
                continue
            mask = re.compile(fnmatch.translate(name))
            options.file_params[mask] = dict(opts)
    _override_options(options, **overrides)
    for name in options.__dict__:
        value = getattr(options, name)
        if isinstance(value, _Default):
            setattr(options, name, process_value(name, value.value))
    if (options.async and ('pylint' in options.linters)):
        LOGGER.warning("Can't    parse    code    asynchronously    with    pylint    enabled.")
        options.async = False
    return options


What's a good function header?
targets: def parse_options(args=None, config=True, rootdir=CURDIR, **overrides):
inputs: Complete the below
def _decimal_to_128(value):

    ''''Converts a decimal.Decimal to BID (high bits, low bits).
    :Parameters:
    - `value`: An instance of decimal.Decimal'
    '''
targets: with decimal.localcontext(_DEC128_CTX) as ctx:
        value = ctx.create_decimal(value)
    if value.is_infinite():
        return (_NINF if value.is_signed() else _PINF)
    (sign, digits, exponent) = value.as_tuple()
    if value.is_nan():
        if digits:
            raise ValueError('NaN    with    debug    payload    is    not    supported')
        if value.is_snan():
            return (_NSNAN if value.is_signed() else _PSNAN)
        return (_NNAN if value.is_signed() else _PNAN)
    significand = int(''.join([str(digit) for digit in digits]))
    bit_length = _bit_length(significand)
    high = 0
    low = 0
    for i in range(min(64, bit_length)):
        if (significand & (1 << i)):
            low |= (1 << i)
    for i in range(64, bit_length):
        if (significand & (1 << i)):
            high |= (1 << (i - 64))
    biased_exponent = (exponent + _EXPONENT_BIAS)
    if ((high >> 49) == 1):
        high = (high & 140737488355327)
        high |= _EXPONENT_MASK
        high |= ((biased_exponent & 16383) << 47)
    else:
        high |= (biased_exponent << 49)
    if sign:
        high |= _SIGN
    return (high, low)
inputs: Complete the below
@use_clip_fps_by_default
def detect_scenes(clip=None, luminosities=None, thr=10, progress_bar=True, fps=None):

    ''''Detects scenes of a clip based on luminosity changes.
    Note that for large clip this may take some time
    Returns
    cuts, luminosities
    cuts is a series of cuts [(0,t1), (t1,t2),...(...,tf)]
    luminosities are the luminosities computed for each
    frame of the clip.
    Parameters
    clip
    A video clip. Can be None if a list of luminosities is
    provided instead. If provided, the luminosity of each
    frame of the clip will be computed. If the clip has no
    \'fps\' attribute, you must provide it.
    luminosities
    A list of luminosities, e.g. returned by detect_scenes
    in a previous run.
    thr
    Determines a threshold above which the \'luminosity jumps\'
    will be considered as scene changes. A scene change is defined
    as a change between 2 consecutive frames that is larger than
    (avg * thr) where avg is the average of the absolute changes
    between consecutive frames.
    progress_bar
    We all love progress bars ! Here is one for you, in option.
    fps
    Must be provided if you provide no clip or a clip without
    fps attribute.'
    '''
targets: if (luminosities is None):
        luminosities = [f.sum() for f in clip.iter_frames(fps=fps, dtype='uint32', progress_bar=progress_bar)]
    luminosities = np.array(luminosities, dtype=float)
    if (clip is not None):
        end = clip.duration
    else:
        end = (len(luminosities) * (1.0 / fps))
    lum_diffs = abs(np.diff(luminosities))
    avg = lum_diffs.mean()
    luminosity_jumps = (1 + np.array(np.nonzero((lum_diffs > (thr * avg))))[0])
    tt = (([0] + list(((1.0 / fps) * luminosity_jumps))) + [end])
    cuts = [(t1, t2) for (t1, t2) in zip(tt, tt[1:])]
    return (cuts, luminosities)
inputs: I wrote the below code

    eslintignore_path = os.path.join(os.getcwd(), '.eslintignore')
    parsed_args = _PARSER.parse_args()
    if parsed_args.path:
        input_path = os.path.join(os.getcwd(), parsed_args.path)
        if (not os.path.exists(input_path)):
            print ('Could    not    locate    file    or    directory    %s.    Exiting.' % input_path)
            print '----------------------------------------'
            sys.exit(1)
        if os.path.isfile(input_path):
            all_files = [input_path]
        else:
            excluded_glob_patterns = _get_glob_patterns_excluded_from_eslint(eslintignore_path)
            all_files = _get_all_files_in_directory(input_path, excluded_glob_patterns)
    elif parsed_args.files:
        valid_filepaths = []
        invalid_filepaths = []
        for f in parsed_args.files:
            if os.path.isfile(f):
                valid_filepaths.append(f)
            else:
                invalid_filepaths.append(f)
        if invalid_filepaths:
            print ('The    following    file(s)    do    not    exist:    %s\nExiting.' % invalid_filepaths)
            sys.exit(1)
        all_files = valid_filepaths
    else:
        all_files = _get_changed_filenames()
    all_files = [filename for filename in all_files if (not any((fnmatch.fnmatch(filename, pattern) for pattern in EXCLUDED_PATHS)))]
    return all_files


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

    config = load_yaml_config(TRAVIS_CONFIG_FILE)
    config['deploy']['password'] = dict(secure=encrypted_password)
    save_yaml_config(TRAVIS_CONFIG_FILE, config)
    line = '#    This    file    was    autogenerated    and    will    overwrite    each    time    you    run    travis_pypi_setup.py\n'
    prepend_line(TRAVIS_CONFIG_FILE, line)


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

    int_id = ec2_id_to_id(ec2_id)
    return get_instance_uuid_from_int_id(context, int_id)


What's a good function header?
targets: def ec2_inst_id_to_uuid(context, ec2_id):
inputs: I wrote the below code

    if (region_cls is None):
        region_cls = RegionInfo
    region = _get_region(service_name, region_name, region_cls, connection_cls)
    if ((region is None) and _use_endpoint_heuristics()):
        region = _get_region_with_heuristics(service_name, region_name, region_cls, connection_cls)
    if (region is None):
        return None
    return region.connect(**kw_params)


What's a good function header?
targets: def connect(service_name, region_name, region_cls=None, connection_cls=None, **kw_params):
inputs: def getFlattenedNestedRings(nestedRings):
targets: """Get flattened nested rings.
    """
    flattenedNestedRings = []
    for nestedRing in nestedRings:
        nestedRing.addFlattenedNestedRings(flattenedNestedRings)
    return flattenedNestedRings
inputs: I wrote the below code

    if (new_version == 1):
        _create_index(engine, 'events', 'ix_events_time_fired')
    elif (new_version == 2):
        _create_index(engine, 'recorder_runs', 'ix_recorder_runs_start_end')
        _create_index(engine, 'states', 'ix_states_last_updated')
    elif (new_version == 3):
        pass
    elif (new_version == 4):
        if (old_version == 3):
            _drop_index(engine, 'states', 'ix_states_created_domain')
        if (old_version == 2):
            _drop_index(engine, 'states', 'ix_states_entity_id_created')
        _drop_index(engine, 'states', 'states__state_changes')
        _drop_index(engine, 'states', 'states__significant_changes')
        _drop_index(engine, 'states', 'ix_states_entity_id_created')
        _create_index(engine, 'states', 'ix_states_entity_id_last_updated')
    else:
        raise ValueError('No    schema    migration    defined    for    version    {}'.format(new_version))


What's a good function header?
targets: def _apply_update(engine, new_version, old_version):
inputs: def main():
targets: """Main function
    """
    generate_transaction_docs()
    generate_vote_docs()
inputs: I wrote the below code

    global templatetags_modules
    if (not templatetags_modules):
        _templatetags_modules = []
        for app_module in (['django'] + list(settings.INSTALLED_APPS)):
            try:
                templatetag_module = ('%s.templatetags' % app_module)
                import_module(templatetag_module)
                _templatetags_modules.append(templatetag_module)
            except ImportError:
                continue
        templatetags_modules = _templatetags_modules
    return templatetags_modules


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

    (l, b, w, h) = bbox.get_bounds()
    r = Rectangle(xy=(l, b), width=w, height=h, edgecolor=color, fill=False)
    if (trans is not None):
        r.set_transform(trans)
    r.set_clip_on(False)
    r.draw(renderer)


What's a good function header?
targets: def draw_bbox(bbox, renderer, color='k', trans=None):
inputs: Complete the below
def _i18n_cache_key_suffix(request, cache_key):

    ''''If necessary, adds the current locale or time zone to the cache key.'
    '''
targets: if (settings.USE_I18N or settings.USE_L10N):
        cache_key += (u'.%s' % getattr(request, u'LANGUAGE_CODE', get_language()))
    if settings.USE_TZ:
        tz_name = force_text(get_current_timezone_name(), errors=u'ignore')
        cache_key += (u'.%s' % tz_name.encode(u'ascii', u'ignore').decode(u'ascii').replace(u'    ', u'_'))
    return cache_key
inputs: def dictfind(dictionary, element):
targets: """Returns a key whose value in `dictionary` is `element`
    or, if none exists, None.
    """
    for (key, value) in dictionary.iteritems():
        if (element is value):
            return key
inputs: Complete the below
def find_strings(filename):

    ''''Return a dict of possible docstring positions.
    The dict maps line numbers to strings.  There is an entry for
    line that contains only a string or a part of a triple-quoted
    string.'
    '''
targets: d = {}
    prev_ttype = token.INDENT
    f = open(filename)
    for (ttype, tstr, start, end, line) in tokenize.generate_tokens(f.readline):
        if (ttype == token.STRING):
            if (prev_ttype == token.INDENT):
                (sline, scol) = start
                (eline, ecol) = end
                for i in range(sline, (eline + 1)):
                    d[i] = 1
        prev_ttype = ttype
    f.close()
    return d
inputs: I wrote the below code

    check_call(['git', 'checkout', '-b', name])


What's a good function header?
targets: def git_new_branch(name):
inputs: def get_course_enrollments(student_id):
targets: """Stubbed out Enrollment data request.
    """
    return _ENROLLMENTS
inputs: def map_reduce(inputs, mapper, reducer):
targets: """runs MapReduce on the inputs using mapper and reducer
    """
    collector = defaultdict(list)
    for input in inputs:
        for (key, value) in mapper(input):
            collector[key].append(value)
    return [output for (key, values) in collector.iteritems() for output in reducer(key, values)]
inputs: def inject_rename_contenttypes_operations(plan=None, apps=global_apps, using=DEFAULT_DB_ALIAS, **kwargs):
targets: """Insert a `RenameContentType` operation after every planned `RenameModel`
    operation.
    """
    if (plan is None):
        return
    try:
        ContentType = apps.get_model('contenttypes', 'ContentType')
    except LookupError:
        available = False
    else:
        if (not router.allow_migrate_model(using, ContentType)):
            return
        available = True
    for (migration, backward) in plan:
        if ((migration.app_label, migration.name) == ('contenttypes', '0001_initial')):
            if backward:
                break
            else:
                available = True
                continue
        if (not available):
            continue
        inserts = []
        for (index, operation) in enumerate(migration.operations):
            if isinstance(operation, migrations.RenameModel):
                operation = RenameContentType(migration.app_label, operation.old_name_lower, operation.new_name_lower)
                inserts.append(((index + 1), operation))
        for (inserted, (index, operation)) in enumerate(inserts):
            migration.operations.insert((inserted + index), operation)
inputs: I wrote the below code

    def decorator(f):
        @wraps(f)
        def decorated_func(request, *args, **kwargs):
            if (request.method == 'OPTIONS'):
                if (('HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META) and ('HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in request.META)):
                    response = http.HttpResponse()
                    response['Access-Control-Allow-Methods'] = ',    '.join(methods)
                    response['Access-Control-Allow-Headers'] = request.META['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
                else:
                    return http.HttpResponseBadRequest()
            elif (request.method in methods):
                response = f(request, *args, **kwargs)
            else:
                return http.HttpResponseBadRequest()
            response['Access-Control-Allow-Origin'] = origin
            return response
        return decorated_func
    return decorator


What's a good function header?
targets: def cors_enabled(origin, methods=['GET']):
inputs: I wrote the below code

    if (module_name in modnames):
        return
    try:
        mock = _ModuleMock()
        mock.LOCALEPATH = osp.join(plugin_path, module_name, 'locale')
        sys.modules[module_name] = mock
        if osp.isdir(osp.join(plugin_path, module_name)):
            module = _import_module_from_path(module_name, plugin_path)
        else:
            module = None
        if module:
            sys.modules[module_name] = module
            modlist.append(module)
            modnames.append(module_name)
    except Exception:
        sys.stderr.write('ERROR:    3rd    party    plugin    import    failed    for    `{0}`\n'.format(module_name))
        traceback.print_exc(file=sys.stderr)


What's a good function header?
targets: def _import_plugin(module_name, plugin_path, modnames, modlist):
inputs: Complete the below
def _makeRequestProxyFactory(clsToWrap):

    ''''Return a callable that proxies instances of C{clsToWrap} via
    L{_IDeprecatedHTTPChannelToRequestInterface}.
    @param clsToWrap: The class whose instances will be proxied.
    @type cls: L{_IDeprecatedHTTPChannelToRequestInterface}
    implementer.
    @return: A factory that returns
    L{_IDeprecatedHTTPChannelToRequestInterface} proxies.
    @rtype: L{callable} whose interface matches C{clsToWrap}\'s constructor.'
    '''
targets: def _makeRequestProxy(*args, **kwargs):
        instance = clsToWrap(*args, **kwargs)
        return _IDeprecatedHTTPChannelToRequestInterfaceProxy(instance)
    directlyProvides(_makeRequestProxy, providedBy(clsToWrap))
    return _makeRequestProxy
inputs: Complete the below
def ext_pillar(minion_id, pillar, conf):

    ''''Parse varstack data and return the result'
    '''
targets: vs = varstack.Varstack(config_filename=conf)
    return vs.evaluate(__grains__)
inputs: I wrote the below code

    new_words = []
    new_word = u''
    for (index, word) in enumerate(words):
        pre_word = u''
        if ((index - 1) >= 0):
            pre_word = words[(index - 1)]
        if ((pre_word in u'#([!~^:') or (word[0] in u'[]]);,:?.^')):
            new_word += word
        elif (word == u'('):
            if (pre_word in (u'if', u'for', u'while', u'switch', u')')):
                new_words.append(new_word)
                new_word = word
            elif (pre_word[(-1)] in u'+-*/%<>!=&|^'):
                new_words.append(new_word)
                new_word = word
            elif ((len(words) > 1) and ((words[0] + words[1]) == u'#define')):
                is_define_func = False
                if (u')' in words):
                    index = words.index(u')')
                    if words[(index + 1):]:
                        is_define_func = True
                if is_define_func:
                    new_word += word
                else:
                    new_words.append(new_word)
                    new_word = word
            else:
                new_word += word
        elif (word == u'='):
            if (pre_word in u'+-*/%<>!=&|^'):
                new_word += word
            else:
                new_words.append(new_word)
                new_word = word
        elif (pre_word == u'+'):
            if (word in u'+'):
                new_word += word
            else:
                new_words.append(new_word)
                new_word = word
        elif (pre_word == u'-'):
            if (word in u'->'):
                new_word += word
            else:
                is_negtive = False
                pre_2_index = (index - 2)
                if (pre_2_index >= 0):
                    pre_2_word = words[(index - 2)]
                    if (pre_2_word[(-1)] not in (none_operator_chars + u')]')):
                        is_negtive = True
                if is_negtive:
                    new_word += word
                else:
                    new_words.append(new_word)
           ...

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

    newdict = dict()
    for (k, v) in instance.items():
        if isinstance(v, datetime.datetime):
            v = v.replace(tzinfo=None)
        elif (k == 'fault'):
            continue
        elif (k == 'pci_devices'):
            continue
        newdict[k] = v
    return newdict


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

    name = name.lower()
    for ending in ('tar', 'tar.gz', 'tar.bz2', 'tar.xz', 'tgz', 'tbz2', 'txz', 'tar.lzma', 'tlz'):
        if name.endswith(('.' + ending)):
            return 'tar'
    for ending in ('zip', 'rar'):
        if name.endswith(('.' + ending)):
            return ending
    return None


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

    logger = logging.getLogger(__name__)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter('%(asctime)s    %(levelname)s    %(message)s'))
    logger.addHandler(handler)
    logger.setLevel(level)
    logger.debug(('Added    a    stderr    logging    handler    to    logger:    %s' % __name__))
    return handler


What's a good function header?
targets: def add_stderr_logger(level=logging.DEBUG):
inputs: Complete the below
@cachedmethod
def asciifyUrl(url, forceQuote=False):

    ''''Attempts to make a unicode URL usuable with ``urllib/urllib2``.
    More specifically, it attempts to convert the unicode object ``url``,
    which is meant to represent a IRI, to an unicode object that,
    containing only ASCII characters, is a valid URI. This involves:
    * IDNA/Puny-encoding the domain name.
    * UTF8-quoting the path and querystring parts.
    See also RFC 3987.
    Reference: http://blog.elsdoerfer.name/2008/12/12/opening-iris-in-python/
    >>> asciifyUrl(u\'http://www.\u0161u\u0107uraj.com\')
    u\'http://www.xn--uuraj-gxa24d.com\''
    '''
targets: parts = urlparse.urlsplit(url)
    if ((not parts.scheme) or (not parts.netloc)):
        return url
    if all(((char in string.printable) for char in url)):
        return url
    try:
        hostname = parts.hostname.encode('idna')
    except LookupError:
        hostname = parts.hostname.encode(UNICODE_ENCODING)
    def quote(s, safe):
        s = (s or '')
        if ((s.encode('ascii', 'replace') != s) or forceQuote):
            return urllib.quote(s.encode(UNICODE_ENCODING), safe=safe)
        return s
    username = quote(parts.username, '')
    password = quote(parts.password, safe='')
    path = quote(parts.path, safe='/')
    query = quote(parts.query, safe='&=')
    netloc = hostname
    if (username or password):
        netloc = ('@' + netloc)
        if password:
            netloc = ((':' + password) + netloc)
        netloc = (username + netloc)
    try:
        port = parts.port
    except:
        port = None
    if port:
        netloc += (':' + str(port))
    return urlparse.urlunsplit([parts.scheme, netloc, path, query, parts.fragment])
inputs: I wrote the below code

    from r2.lib.pages import VerifyEmail
    user.email_verified = False
    user._commit()
    Award.take_away('verified_email', user)
    token = EmailVerificationToken._new(user)
    base = (g.https_endpoint or g.origin)
    emaillink = ((base + '/verification/') + token._id)
    if dest:
        emaillink += ('?dest=%s' % dest)
    g.log.debug(('Generated    email    verification    link:    ' + emaillink))
    _system_email(user.email, VerifyEmail(user=user, emaillink=emaillink).render(style='email'), Email.Kind.VERIFY_EMAIL)


What's a good function header?
targets: def verify_email(user, dest=None):
inputs: def decipher_bifid6(msg, key):
targets: """Performs the Bifid cipher decryption on ciphertext ``msg``, and
    returns the plaintext.
    This is the version of the Bifid cipher that uses the `6 \times 6`
    Polybius square.
    INPUT:
    ``msg``: ciphertext string (digits okay); converted to upper case
    ``key``: short string for key (digits okay). If ``key`` is
    less than 36 characters long, the square will be filled with
    letters A through Z and digits 0 through 9. All letters are
    converted to uppercase.
    OUTPUT:
    plaintext from Bifid cipher (all caps, no spaces)
    Examples
    >>> from sympy.crypto.crypto import encipher_bifid6, decipher_bifid6
    >>> key = "gold bug"
    >>> encipher_bifid6(\meet me on monday at 8am\, key)
    \KFKLJJHF5MMMKTFRGPL\
    >>> decipher_bifid6(_, key)
    \MEETMEONMONDAYAT8AM\
    """
    (msg, key, _) = _prep(msg.upper(), key.upper(), None, bifid6)
    key = padded_key(key, bifid6)
    return decipher_bifid(msg, '', key)
inputs: I wrote the below code

    cj2 = cookiejar_from_dict(cookie_dict)
    for cookie in cj2:
        cj.set_cookie(cookie)
    return cj


What's a good function header?
targets: def add_dict_to_cookiejar(cj, cookie_dict):
inputs: def absent(name, database, **client_args):
targets: """Ensure that given retention policy is absent.
    name
    Name of the retention policy to remove.
    database
    Name of the database that the retention policy was defined on.
    """
    ret = {'name': name, 'changes': {}, 'result': True, 'comment': 'retention    policy    {0}    is    not    present'.format(name)}
    if __salt__['influxdb.retention_policy_exists'](database, name, **client_args):
        if __opts__['test']:
            ret['result'] = None
            ret['comment'] = 'retention    policy    {0}    is    present    and    needs    to    be    removed'.format(name)
            return ret
        if __salt__['influxdb.drop_retention_policy'](database, name, **client_args):
            ret['comment'] = 'retention    policy    {0}    has    been    removed'.format(name)
            ret['changes'][name] = 'Absent'
            return ret
        else:
            ret['comment'] = 'Failed    to    remove    retention    policy    {0}'.format(name)
            ret['result'] = False
            return ret
    return ret
inputs: Complete the below
def Condition(*args, **kwargs):

    ''''Factory function that returns a new condition variable object.
    A condition variable allows one or more threads to wait until they are
    notified by another thread.
    If the lock argument is given and not None, it must be a Lock or RLock
    object, and it is used as the underlying lock. Otherwise, a new RLock object
    is created and used as the underlying lock.'
    '''
targets: return _Condition(*args, **kwargs)
inputs: I wrote the below code

    if (not batch_size):
        batch_size = FLAGS.batch_size
    sparse_labels = tf.reshape(labels, [batch_size, 1])
    indices = tf.reshape(tf.range(batch_size), [batch_size, 1])
    concated = tf.concat(axis=1, values=[indices, sparse_labels])
    num_classes = logits[0].get_shape()[(-1)].value
    dense_labels = tf.sparse_to_dense(concated, [batch_size, num_classes], 1.0, 0.0)
    slim.losses.cross_entropy_loss(logits[0], dense_labels, label_smoothing=0.1, weight=1.0)
    slim.losses.cross_entropy_loss(logits[1], dense_labels, label_smoothing=0.1, weight=0.4, scope='aux_loss')


What's a good function header?
targets: def loss(logits, labels, batch_size=None):
inputs: def legalize_path(path, replacements, length, extension, fragment):
targets: """Given a path-like Unicode string, produce a legal path. Return
    the path and a flag indicating whether some replacements had to be
    ignored (see below).
    The legalization process (see `_legalize_stage`) consists of
    applying the sanitation rules in `replacements`, encoding the string
    to bytes (unless `fragment` is set), truncating components to
    `length`, appending the `extension`.
    This function performs up to three calls to `_legalize_stage` in
    case truncation conflicts with replacements (as can happen when
    truncation creates whitespace at the end of the string, for
    example). The limited number of iterations iterations avoids the
    possibility of an infinite loop of sanitation and truncation
    operations, which could be caused by replacement rules that make the
    string longer. The flag returned from this function indicates that
    the path has to be truncated twice (indicating that replacements
    made the string longer again after it was truncated); the
    application should probably log some sort of warning.
    """
    if fragment:
        extension = extension.decode('utf-8', 'ignore')
    (first_stage_path, _) = _legalize_stage(path, replacements, length, extension, fragment)
    (first_stage_path, _) = os.path.splitext(displayable_path(first_stage_path))
    (second_stage_path, retruncated) = _legalize_stage(first_stage_path, replacements, length, extension, fragment)
    if retruncated:
        (second_stage_path, _) = _legalize_stage(first_stage_path, None, length, extension, fragment)
    return (second_stage_path, retruncated)
inputs: def create_requester(user_id, access_token_id=None, is_guest=False, device_id=None, app_service=None):
targets: """Create a new ``Requester`` object
    Args:
    user_id (str|UserID):  id of the user making the request
    access_token_id (int|None):  *ID* of the access token used for this
    request, or None if it came via the appservice API or similar
    is_guest (bool):  True if the user making this request is a guest user
    device_id (str|None):  device_id which was set at authentication time
    app_service (ApplicationService|None):  the AS requesting on behalf of the user
    Returns:
    Requester
    """
    if (not isinstance(user_id, UserID)):
        user_id = UserID.from_string(user_id)
    return Requester(user_id, access_token_id, is_guest, device_id, app_service)
inputs: I wrote the below code

    posts = [getattr(generator, attr, None) for attr in PROCESS if (getattr(generator, attr, None) is not None)]
    for post in posts[0]:
        if ((not ('SHOW_SOURCE_ON_SIDEBAR' in generator.settings)) and (not ('SHOW_SOURCE_IN_SECTION' in generator.settings))):
            return
        if (('SHOW_SOURCE_ALL_POSTS' in generator.settings) or ('show_source' in post.metadata)):
            show_source_filename = generator.settings.get('SHOW_SOURCE_FILENAME', '{}.txt'.format(post.slug))
            try:
                source_out = os.path.join(post.settings['OUTPUT_PATH'], post.save_as)
                source_out_path = os.path.split(source_out)[0]
                copy_to = os.path.join(source_out_path, show_source_filename)
                source_url = urljoin(post.save_as, show_source_filename)
            except Exception:
                return
            out = dict()
            out['copy_raw_from'] = post.source_path
            out['copy_raw_to'] = copy_to
            logger.debug('Linked    %s    to    %s', post.source_path, copy_to)
            source_files.append(out)
            post.show_source_url = source_url


What's a good function header?
targets: def link_source_files(generator):
inputs: Complete the below
def _is_attribute_explicitly_set(attribute_name, resource, target):

    ''''Verify that an attribute is present and has a non-default value'
    '''
targets: return (('default' in resource[attribute_name]) and (attribute_name in target) and (target[attribute_name] is not attributes.ATTR_NOT_SPECIFIED) and (target[attribute_name] != resource[attribute_name]['default']))
inputs: def get_observer(settings):
targets: """Return an observer for the docutils Reporter.
    """
    def observer(msg):
        'Report    docutils/rest    messages    to    a    Nikola    user.\n\n                                Error    code    mapping:\n\n                                +------+---------+------+----------+\n                                |    dNUM    |            dNAME    |    lNUM    |                lNAME    |                d    =    docutils,    l    =    logbook\n                                +------+---------+------+----------+\n                                |                0    |            DEBUG    |                1    |                DEBUG    |\n                                |                1    |                INFO    |                2    |                    INFO    |\n                                |                2    |    WARNING    |                4    |        WARNING    |\n                                |                3    |            ERROR    |                5    |                ERROR    |\n                                |                4    |        SEVERE    |                6    |    CRITICAL    |\n                                +------+---------+------+----------+\n                                '
        errormap = {0: 1, 1: 2, 2: 4, 3: 5, 4: 6}
        text = docutils.nodes.Element.astext(msg)
        line = ((msg['line'] + settings['add_ln']) if ('line' in msg) else 0)
        out = '[{source}{colon}{line}]    {text}'.format(source=settings['source'], colon=(':' if line else ''), line=line, text=text)
        settings['logger'].log(errormap[msg['level']], out)
    return observer
inputs: I wrote the below code

    global options
    options = opt
    for fn in pre_configure:
        fn(options, file_config)


What's a good function header?
targets: def pre_begin(opt):
inputs: def basename(p):
targets: """Returns the final component of a pathname
    """
    return split(p)[1]
inputs: I wrote the below code

    base_url = ((base_url + 'users/') + username)
    try:
        url = (base_url + '/contributions')
        page = urlopen(url)
    except (HTTPError, URLError) as e:
        print 'There    was    a    problem    fetching    data    from    {0}'.format(url)
        print e
        raise SystemExit
    return page.read().decode('utf-8')


What's a good function header?
targets: def retrieve_contributions_calendar(username, base_url):
inputs: def flatten(debug=False):
targets: """Wrap response.body in a generator that recursively iterates over body.
    This allows cherrypy.response.body to consist of \nested generators\;
    that is, a set of generators that yield generators.
    """
    import types
    def flattener(input):
        numchunks = 0
        for x in input:
            if (not isinstance(x, types.GeneratorType)):
                numchunks += 1
                (yield x)
            else:
                for y in flattener(x):
                    numchunks += 1
                    (yield y)
        if debug:
            cherrypy.log(('Flattened    %d    chunks' % numchunks), 'TOOLS.FLATTEN')
    response = cherrypy.serving.response
    response.body = flattener(response.body)
inputs: Complete the below
def associate(qs, assoc_secret, assoc_handle):

    ''''Do the server\'s half of the associate call, using the given
    secret and handle.'
    '''
targets: q = parseQuery(qs)
    assert (q['openid.mode'] == 'associate')
    assert (q['openid.assoc_type'] == 'HMAC-SHA1')
    reply_dict = {'assoc_type': 'HMAC-SHA1', 'assoc_handle': assoc_handle, 'expires_in': '600'}
    if (q.get('openid.session_type') == 'DH-SHA1'):
        assert ((len(q) == 6) or (len(q) == 4))
        message = Message.fromPostArgs(q)
        session = DiffieHellmanSHA1ServerSession.fromMessage(message)
        reply_dict['session_type'] = 'DH-SHA1'
    else:
        assert (len(q) == 2)
        session = PlainTextServerSession.fromQuery(q)
    reply_dict.update(session.answer(assoc_secret))
    return kvform.dictToKV(reply_dict)
inputs: Complete the below
def display_output(data, out=None, opts=None, **kwargs):

    ''''Print the passed data using the desired output'
    '''
targets: if (opts is None):
        opts = {}
    display_data = try_printout(data, out, opts, **kwargs)
    output_filename = opts.get('output_file', None)
    log.trace('data    =    {0}'.format(data))
    try:
        if output_filename:
            if (not hasattr(output_filename, 'write')):
                ofh = salt.utils.files.fopen(output_filename, 'a')
                fh_opened = True
            else:
                ofh = output_filename
                fh_opened = False
            try:
                fdata = display_data
                if isinstance(fdata, six.text_type):
                    try:
                        fdata = fdata.encode('utf-8')
                    except (UnicodeDecodeError, UnicodeEncodeError):
                        pass
                if fdata:
                    if six.PY3:
                        ofh.write(fdata.decode())
                    else:
                        ofh.write(fdata)
                    ofh.write('\n')
            finally:
                if fh_opened:
                    ofh.close()
            return
        if display_data:
            salt.utils.print_cli(display_data)
    except IOError as exc:
        if (exc.errno != errno.EPIPE):
            raise exc
inputs: def get_domains(api_key=None):
targets: """Get a list of all domains.
    Sample response:
    "total_count": 1,
    "items": [
    "created_at": "Wed, 10 Jul 2013 19:26:52 GMT",
    "smtp_login": "postmaster@samples.mailgun.org",
    "name": "samples.mailgun.org",
    "smtp_password": "4rtqo4p6rrx9",
    "wildcard": true,
    "spam_action": "disabled",
    "state": "active"
    Get a list of all domains.
    """
    return requests.get('https://api.mailgun.net/v3/domains', auth=('api', api_key), params={'skip': 0, 'limit': 3})
inputs: Complete the below
def expect_discrete(self, fn=None, args=(), loc=0, lb=None, ub=None, conditional=False):

    ''''calculate expected value of a function with respect to the distribution
    for discrete distribution
    Parameters
    (self : distribution instance as defined in scipy stats)
    fn : function (default: identity mapping)
    Function for which integral is calculated. Takes only one argument.
    args : tuple
    argument (parameters) of the distribution
    optional keyword parameters
    lb, ub : numbers
    lower and upper bound for integration, default is set to the support
    of the distribution, lb and ub are inclusive (ul<=k<=ub)
    conditional : boolean (False)
    If true then the expectation is corrected by the conditional
    probability of the integration interval. The return value is the
    expectation of the function, conditional on being in the given
    interval (k such that ul<=k<=ub).
    Returns
    expected value : float
    Notes
    * function is not vectorized
    * accuracy: uses self.moment_tol as stopping criterium
    for heavy tailed distribution e.g. zipf(4), accuracy for
    mean, variance in example is only 1e-5,
    increasing precision (moment_tol) makes zipf very slow
    * suppnmin=100 internal parameter for minimum number of points to evaluate
    could be added as keyword parameter, to evaluate functions with
    non-monotonic shapes, points include integers in (-suppnmin, suppnmin)
    * uses maxcount=1000 limits the number of points that are evaluated
    to break loop for infinite sums
    (a maximum of suppnmin+1000 positive plus suppnmin+1000 negative integers
    are evaluated)'
    '''
targets: maxcount = 1000
    suppnmin = 100
    if (fn is None):
        def fun(x):
            return ((x + loc) * self._pmf(x, *args))
    else:
        def fun(x):
            return (fn((x + loc)) * self._pmf(x, *args))
    self._argcheck(*args)
    if (lb is None):
        lb = self.a
    else:
        lb = (lb - loc)
    if (ub is None):
        ub = self.b
    else:
        ub = (ub - loc)
    if conditional:
        invfac = (self.sf(lb, *args) - self.sf((ub + 1), *args))
    else:
        invfac = 1.0
    tot = 0.0
    (low, upp) = (self._ppf(0.001, *args), self._ppf(0.999, *args))
    low = max(min((- suppnmin), low), lb)
    upp = min(max(suppnmin, upp), ub)
    supp = np.arange(low, (upp + 1), self.inc)
    tot = np.sum(fun(supp))
    diff = 1e+100
    pos = (upp + self.inc)
    count = 0
    while ((pos <= ub) and (diff > self.moment_tol) and (count <= maxcount)):
        diff = fun(pos)
        tot += diff
        pos += self.inc
        count += 1
    if (self.a < 0):
        diff = 1e+100
        pos = (low - self.inc)
        while ((pos >= lb) and (diff > self.moment_tol) and (count <= maxcount)):
            diff = fun(pos)
            tot += diff
            pos -= self.inc
            count += 1
    if (count > maxcount):
        print('sum    did    not    converge')
    return (tot / invfac)
inputs: def init_logger():
targets: """Initialize the south logger
    """
    logger = logging.getLogger('south')
    logger.addHandler(NullHandler())
    return logger
inputs: I wrote the below code

    def wrapper(func):
        memoized_func = memoized(func)
        @functools.wraps(func)
        def wrapped(*args, **kwargs):
            args = list(args)
            request = args.pop(request_index)
            args.insert(request_index, request_func(request))
            return memoized_func(*args, **kwargs)
        return wrapped
    return wrapper


What's a good function header?
targets: def memoized_with_request(request_func, request_index=0):
inputs: def colored(text, color=None, on_color=None, attrs=None):
targets: """Colorize text.
    Available text colors:
    red, green, yellow, blue, magenta, cyan, white.
    Available text highlights:
    on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.
    Available attributes:
    bold, dark, underline, blink, reverse, concealed.
    Example:
    colored(\Hello, World!\, \red\, \on_grey\, [\blue\, \blink\])
    colored(\Hello, World!\, \green\)
    """
    if (os.getenv('ANSI_COLORS_DISABLED') is None):
        fmt_str = '\x1b[%dm%s'
        if (color is not None):
            text = (fmt_str % (COLORS[color], text))
        if (on_color is not None):
            text = (fmt_str % (HIGHLIGHTS[on_color], text))
        if (attrs is not None):
            for attr in attrs:
                text = (fmt_str % (ATTRIBUTES[attr], text))
        if (color is not None):
            text += RESET
    return text
inputs: Complete the below
def calc_hash(type, content):

    ''''Calculate some content\'s hash in the Git fashion.'
    '''
targets: header = ('%s    %d\x00' % (type, len(content)))
    sum = Sha1(header)
    sum.update(content)
    return sum.digest()
inputs: def conv1d(x, kernel, strides=1, padding='valid', data_format=None, dilation_rate=1):
targets: """1D convolution.
    # Arguments
    kernel: kernel tensor.
    strides: stride integer.
    padding: string, `"same"`, `"causal"` or `"valid"`.
    data_format: string, one of "channels_last", "channels_first"
    dilation_rate: integer.
    """
    if (data_format is None):
        data_format = image_data_format()
    if (data_format not in {'channels_first', 'channels_last'}):
        raise ValueError('Unknown    data_format    ', data_format)
    if hasattr(kernel, '_keras_shape'):
        kernel_shape = kernel._keras_shape
    else:
        kernel_shape = None
    if (padding == 'causal'):
        if (not kernel_shape):
            raise AttributeError('Causal    padding    requires    kernel._keras_shape    set.')
        left_pad = (dilation_rate * (kernel_shape[0] - 1))
        x = temporal_padding(x, (left_pad, 0))
        padding = 'valid'
    if hasattr(x, '_keras_shape'):
        shape = x._keras_shape
    else:
        shape = None
    if (data_format == 'channels_last'):
        x = expand_dims(x, 2)
        if (shape is not None):
            x._keras_shape = (shape[0], shape[1], 1, shape[2])
    else:
        x = expand_dims(x, 3)
        if (shape is not None):
            x._keras_shape = (shape[0], shape[1], shape[2], 1)
    dilation_rate = (dilation_rate, 1)
    strides = (strides, 1)
    kernel = expand_dims(kernel, 1)
    output = conv2d(x, kernel, strides=strides, padding=padding, data_format=data_format, dilation_rate=dilation_rate)
    if (data_format == 'channels_last'):
        output = squeeze(output, 2)
    else:
        output = squeeze(output, 3)
    return output