Muennighoff/xP3x-sample huggingface dataset:
inputs: Complete the below
def centroid(*args):

    ''''Find the centroid (center of mass) of the collection containing only Points,
    Segments or Polygons. The centroid is the weighted average of the individual centroid
    where the weights are the lengths (of segments) or areas (of polygons).
    Overlapping regions will add to the weight of that region.
    If there are no objects (or a mixture of objects) then None is returned.
    See Also
    sympy.geometry.point.Point, sympy.geometry.line.Segment,
    sympy.geometry.polygon.Polygon
    Examples
    >>> from sympy import Point, Segment, Polygon
    >>> from sympy.geometry.util import centroid
    >>> p = Polygon((0, 0), (10, 0), (10, 10))
    >>> q = p.translate(0, 20)
    >>> p.centroid, q.centroid
    (Point2D(20/3, 10/3), Point2D(20/3, 70/3))
    >>> centroid(p, q)
    Point2D(20/3, 40/3)
    >>> p, q = Segment((0, 0), (2, 0)), Segment((0, 0), (2, 2))
    >>> centroid(p, q)
    Point2D(1, -sqrt(2) + 2)
    >>> centroid(Point(0, 0), Point(2, 0))
    Point2D(1, 0)
    Stacking 3 polygons on top of each other effectively triples the
    weight of that polygon:
    >>> p = Polygon((0, 0), (1, 0), (1, 1), (0, 1))
    >>> q = Polygon((1, 0), (3, 0), (3, 1), (1, 1))
    >>> centroid(p, q)
    Point2D(3/2, 1/2)
    >>> centroid(p, p, p, q) # centroid x-coord shifts left
    Point2D(11/10, 1/2)
    Stacking the squares vertically above and below p has the same
    effect:
    >>> centroid(p, p.translate(0, 1), p.translate(0, -1), q)
    Point2D(11/10, 1/2)'
    '''
targets: from sympy.geometry import Polygon, Segment, Point
    if args:
        if all((isinstance(g, Point) for g in args)):
            c = Point(0, 0)
            for g in args:
                c += g
            den = len(args)
        elif all((isinstance(g, Segment) for g in args)):
            c = Point(0, 0)
            L = 0
            for g in args:
                l = g.length
                c += (g.midpoint * l)
                L += l
            den = L
        elif all((isinstance(g, Polygon) for g in args)):
            c = Point(0, 0)
            A = 0
            for g in args:
                a = g.area
                c += (g.centroid * a)
                A += a
            den = A
        c /= den
        return c.func(*[i.simplify() for i in c.args])
inputs: Complete the below
def list_saml_providers(region=None, key=None, keyid=None, profile=None):

    ''''List SAML providers.
    CLI Example:
    .. code-block:: bash
    salt myminion boto_iam.list_saml_providers'
    '''
targets: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
    try:
        providers = []
        info = conn.list_saml_providers()
        for arn in info['list_saml_providers_response']['list_saml_providers_result']['saml_provider_list']:
            providers.append(arn['arn'].rsplit('/', 1)[1])
        return providers
    except boto.exception.BotoServerError as e:
        aws = __utils__['boto.get_error'](e)
        log.debug(aws)
        msg = 'Failed    to    get    list    of    SAML    providers.'
        log.error(msg)
        return False
inputs: Complete the below
def _as_macro_if_defined(meth):

    ''''Decorator for printer methods
    When a Printer\'s method is decorated using this decorator the expressions printed
    will first be looked for in the attribute ``math_macros``, and if present it will
    print the macro name in ``math_macros`` followed by a type suffix for the type
    ``real``. e.g. printing ``sympy.pi`` would print ``M_PIl`` if real is mapped to float80.'
    '''
targets: @wraps(meth)
    def _meth_wrapper(self, expr, **kwargs):
        if (expr in self.math_macros):
            return ('%s%s' % (self.math_macros[expr], self._get_math_macro_suffix(real)))
        else:
            return meth(self, expr, **kwargs)
    return _meth_wrapper
inputs: Complete the below
def atomp(lst):

    ''''Tuple items (representing structs) are regarded as atoms.'
    '''
targets: return (not isinstance(lst, list))
inputs: Complete the below
def conv1d_sd(input, filters, image_shape, filter_shape, border_mode='valid', subsample=(1,), filter_flip=True):

    ''''using a single dot product'
    '''
targets: if (border_mode not in ('valid', 0, (0,))):
        raise RuntimeError(('Unsupported    border_mode    for    conv1d_sd:    %s' % border_mode))
    (batch_size, num_input_channels, input_length) = image_shape
    (num_filters, num_input_channels_, filter_length) = filter_shape
    stride = subsample[0]
    if ((filter_length % stride) > 0):
        raise RuntimeError(('Filter    length    (%d)    is    not    a    multiple    of    the    stride    (%d)' % (filter_length, stride)))
    num_steps = (filter_length // stride)
    output_length = (((input_length - filter_length) + stride) // stride)
    padded_length = (((input_length // filter_length) * filter_length) + ((num_steps - 1) * stride))
    truncated_length = min(input_length, padded_length)
    input_truncated = input[:, :, :truncated_length]
    input_padded_shape = (batch_size, num_input_channels, padded_length)
    input_padded = T.zeros(input_padded_shape)
    input_padded = T.set_subtensor(input_padded[:, :, :truncated_length], input_truncated)
    inputs = []
    for num in range(num_steps):
        shift = (num * stride)
        length = ((padded_length - shift) // filter_length)
        r_input_shape = (batch_size, num_input_channels, length, filter_length)
        r_input = input_padded[:, :, shift:((length * filter_length) + shift)].reshape(r_input_shape)
        inputs.append(r_input)
    inputs_stacked = T.stack(*inputs)
    filters_flipped = (filters[:, :, ::(-1)] if filter_flip else filters)
    r_conved = T.tensordot(inputs_stacked, filters_flipped, np.asarray([[2, 4], [1, 2]]))
    r_conved = r_conved.dimshuffle(1, 3, 2, 0)
    conved = r_conved.reshape((r_conved.shape[0], r_conved.shape[1], (r_conved.shape[2] * r_conved.shape[3])))
    return conved[:, :, :output_length]
inputs: Complete the below
def get_bound(pts):

    ''''Compute a minimal rectangle that covers all the points.'
    '''
targets: (x0, y0, x1, y1) = (INF, INF, (- INF), (- INF))
    for (x, y) in pts:
        x0 = min(x0, x)
        y0 = min(y0, y)
        x1 = max(x1, x)
        y1 = max(y1, y)
    return (x0, y0, x1, y1)
inputs: I wrote the below code

    good_codes = [httplib.OK, httplib.FOUND, httplib.MOVED_PERMANENTLY]
    (host, path) = urlparse.urlparse(url)[1:3]
    try:
        conn = httplib.HTTPConnection(host)
        conn.request(u'HEAD', path)
        return (conn.getresponse().status in good_codes)
    except StandardError:
        return None


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

    argument_spec = dict(state=dict(choices=['present', 'absent'], default='present'), type=dict(choices=['ip', 'vxlan'], required=True), record_name=dict(type='str'), match=dict(choices=['destination-address', 'destination-port', 'tos', 'protocol', 'source-address', 'source-port']), collect_counter=dict(choices=['bytes', 'packets']), collect_interface=dict(choices=['input', 'output']), description=dict(type='str'))
    argument_spec.update(ce_argument_spec)
    module = NetstreamTemplate(argument_spec=argument_spec)
    module.work()


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

    if (':' in expr):
        (type, value) = expr.split(':', 1)
        if (type == 'name'):
            return value
    else:
        type = expr
    return _describe_token_type(type)


What's a good function header?
targets: def describe_token_expr(expr):
inputs: def map(requests, prefetch=True, size=None):
targets: """
    """
    requests = list(requests)
    pool = (Pool(size) if size else None)
    jobs = [send(r, pool, prefetch=prefetch) for r in requests]
    gevent.joinall(jobs)
    return [r.response for r in requests]
inputs: def get_new_desktop_name(parent_hwnd):
targets: """Create a dialog box to ask the user for name of desktop to be created
    """
    msgs = {win32con.WM_COMMAND: desktop_name_dlgproc, win32con.WM_CLOSE: desktop_name_dlgproc, win32con.WM_DESTROY: desktop_name_dlgproc}
    style = (((win32con.WS_BORDER | win32con.WS_VISIBLE) | win32con.WS_CAPTION) | win32con.WS_SYSMENU)
    h = win32gui.CreateDialogIndirect(win32api.GetModuleHandle(None), [['One    ugly    dialog    box    !', (100, 100, 200, 100), style, 0], ['Button', 'Create', win32con.IDOK, (10, 10, 30, 20), (((win32con.WS_VISIBLE | win32con.WS_TABSTOP) | win32con.BS_HOLLOW) | win32con.BS_DEFPUSHBUTTON)], ['Button', 'Never    mind', win32con.IDCANCEL, (45, 10, 50, 20), ((win32con.WS_VISIBLE | win32con.WS_TABSTOP) | win32con.BS_HOLLOW)], ['Static', 'Desktop    name:', 71, (10, 40, 70, 10), win32con.WS_VISIBLE], ['Edit', '', 72, (75, 40, 90, 10), win32con.WS_VISIBLE]], parent_hwnd, msgs)
    win32gui.EnableWindow(h, True)
    hcontrol = win32gui.GetDlgItem(h, 72)
    win32gui.EnableWindow(hcontrol, True)
    win32gui.SetFocus(hcontrol)
inputs: Complete the below
def gammaincc(a, x, dps=50, maxterms=(10 ** 8)):

    ''''Compute gammaincc exactly like mpmath does but allow for more
    terms in hypercomb. See
    mpmath/functions/expintegrals.py#L187
    in the mpmath github repository.'
    '''
targets: with mp.workdps(dps):
        (z, a) = (a, x)
        if mp.isint(z):
            try:
                return mpf2float(mp.gammainc(z, a=a, regularized=True))
            except mp.libmp.NoConvergence:
                pass
        nega = mp.fneg(a, exact=True)
        G = [z]
        try:
            def h(z):
                r = (z - 1)
                return [([mp.exp(nega), a], [1, r], [], G, [1, (- r)], [], (1 / nega))]
            return mpf2float(mp.hypercomb(h, [z], force_series=True))
        except mp.libmp.NoConvergence:
            def h(z):
                T1 = ([], [1, (z - 1)], [z], G, [], [], 0)
                T2 = ([(- mp.exp(nega)), a, z], [1, z, (-1)], [], G, [1], [(1 + z)], a)
                return (T1, T2)
            return mpf2float(mp.hypercomb(h, [z], maxterms=maxterms))
inputs: Complete the below
def flush(bank, key=None, cachedir=None):

    ''''Remove the key from the cache bank with all the key content. If no key is
    specified remove the entire bank with all keys and sub-banks inside.
    CLI Examples:
    .. code-block:: bash
    salt-run cache.flush cloud/active/ec2/myec2 cachedir=/var/cache/salt/
    salt-run cache.flush cloud/active/ec2/myec2 myminion cachedir=/var/cache/salt/'
    '''
targets: if (cachedir is None):
        cachedir = __opts__['cachedir']
    try:
        cache = salt.cache.Cache(__opts__, cachedir=cachedir)
    except TypeError:
        cache = salt.cache.Cache(__opts__)
    return cache.flush(bank, key)
inputs: def create_mean_initializer():
targets: """Returns a default initializer for the `moving_mean` in batch norm.
    """
    return tf.zeros_initializer()
inputs: I wrote the below code

    if (not value):
        return u''
    if isinstance(value, six.text_type):
        return value
    if isinstance(value, six.binary_type):
        return value.decode(encoding)
    return six.text_type(value)


What's a good function header?
targets: def to_text(value, encoding=u'utf-8'):
inputs: def _hasclass(context, *cls):
targets: """Checks if the context node has all the classes passed as arguments
    """
    node_classes = set(context.context_node.attrib.get('class', '').split())
    return node_classes.issuperset(cls)
inputs: Complete the below
def _plot_onscroll(event, params):

    ''''Handle scroll events.'
    '''
targets: if (event.key == 'control'):
        if (event.step < 0):
            event.key = '-'
        else:
            event.key = '+'
        _plot_onkey(event, params)
        return
    if params['butterfly']:
        return
    _plot_raw_onscroll(event, params, len(params['ch_names']))
inputs: def find_font_face_rules(sheet, oeb):
targets: """Find all @font-face rules in the given sheet and extract the relevant info from them.
    sheet can be either a ManifestItem or a CSSStyleSheet.
    """
    ans = []
    try:
        rules = sheet.data.cssRules
    except AttributeError:
        rules = sheet.cssRules
    for (i, rule) in enumerate(rules):
        if (rule.type != rule.FONT_FACE_RULE):
            continue
        props = get_font_properties(rule, default=u'normal')
        if ((not props[u'font-family']) or (not props[u'src'])):
            continue
        try:
            path = sheet.abshref(props[u'src'])
        except AttributeError:
            path = props[u'src']
        ff = oeb.manifest.hrefs.get(urlnormalize(path), None)
        if (not ff):
            continue
        props[u'item'] = ff
        if (props[u'font-weight'] in {u'bolder', u'lighter'}):
            props[u'font-weight'] = u'400'
        props[u'weight'] = int(props[u'font-weight'])
        props[u'rule'] = rule
        props[u'chars'] = set()
        ans.append(props)
    return ans
inputs: Complete the below
def CastTo(ob, target):

    ''''\'Cast\' a COM object to another interface'
    '''
targets: if hasattr(target, 'index'):
        if ('CLSID' not in ob.__class__.__dict__):
            ob = gencache.EnsureDispatch(ob)
        if ('CLSID' not in ob.__class__.__dict__):
            raise ValueError('Must    be    a    makepy-able    object    for    this    to    work')
        clsid = ob.CLSID
        mod = gencache.GetModuleForCLSID(clsid)
        mod = gencache.GetModuleForTypelib(mod.CLSID, mod.LCID, mod.MajorVersion, mod.MinorVersion)
        target_clsid = mod.NamesToIIDMap.get(target)
        if (target_clsid is None):
            raise ValueError(("The    interface    name    '%s'    does    not    appear    in    the    same    library    as    object    '%r'" % (target, ob)))
        mod = gencache.GetModuleForCLSID(target_clsid)
        target_class = getattr(mod, target)
        target_class = getattr(target_class, 'default_interface', target_class)
        return target_class(ob)
    raise ValueError
inputs: def _flatten_params(params):
targets: """Converts a dictionary of parameters to a list of parameters.
    Any unicode strings in keys or values will be encoded as UTF-8.
    Args:
    params: Dictionary mapping parameter keys to values. Values will be
    converted to a string and added to the list as tuple (key, value). If
    a values is iterable and not a string, each contained value will be
    added as a separate (key, value) tuple.
    Returns:
    List of (key, value) tuples.
    """
    def get_string(value):
        if isinstance(value, unicode):
            return unicode(value).encode('utf-8')
        else:
            return str(value)
    param_list = []
    for (key, value) in params.iteritems():
        key = get_string(key)
        if isinstance(value, basestring):
            param_list.append((key, get_string(value)))
        else:
            try:
                iterator = iter(value)
            except TypeError:
                param_list.append((key, str(value)))
            else:
                param_list.extend(((key, get_string(v)) for v in iterator))
    return param_list
inputs: Complete the below
def _MakeDispatchListIntoYaml(application, dispatch_list):

    ''''Converts list of DispatchEntry objects into a YAML string.'
    '''
targets: statements = [('application:    %s' % application), 'dispatch:']
    for entry in dispatch_list:
        statements += entry.ToYaml()
    return ('\n'.join(statements) + '\n')
inputs: Complete the below
def listdir(dirname, ref=u'HEAD'):

    ''''Get the contents of a directory according to Git
    Query Git for the content of a directory, taking ignored
    files into account.'
    '''
targets: dirs = []
    files = []
    entries = ls_tree(dirname, ref=ref)
    for entry in entries:
        if (entry[0][0] == u't'):
            dirs.append(entry[1])
        else:
            files.append(entry[1])
    untracked = untracked_files(paths=[dirname], directory=True)
    for path in untracked:
        if path.endswith(u'/'):
            dirs.append(path[:(-1)])
        else:
            files.append(path)
    dirs.sort()
    files.sort()
    return (dirs, files)
inputs: @testing.requires_testing_data
def test_crop():
targets: """Test cropping raw files.
    """
    raw = concatenate_raws([read_raw_fif(f) for f in [fif_fname, fif_fname]])
    split_size = 10.0
    sfreq = raw.info['sfreq']
    nsamp = ((raw.last_samp - raw.first_samp) + 1)
    tmins = np.r_[(1.0, np.round(np.arange(0.0, (nsamp - 1), (split_size * sfreq))))]
    tmins = np.sort(tmins)
    tmaxs = np.concatenate(((tmins[1:] - 1), [(nsamp - 1)]))
    tmaxs /= sfreq
    tmins /= sfreq
    raws = ([None] * len(tmins))
    for (ri, (tmin, tmax)) in enumerate(zip(tmins, tmaxs)):
        raws[ri] = raw.copy().crop(tmin, tmax)
    all_raw_2 = concatenate_raws(raws, preload=False)
    assert_equal(raw.first_samp, all_raw_2.first_samp)
    assert_equal(raw.last_samp, all_raw_2.last_samp)
    assert_array_equal(raw[:, :][0], all_raw_2[:, :][0])
    tmins = np.round(np.arange(0.0, (nsamp - 1), (split_size * sfreq)))
    tmaxs = np.concatenate(((tmins[1:] - 1), [(nsamp - 1)]))
    tmaxs /= sfreq
    tmins /= sfreq
    raws = ([None] * len(tmins))
    for (ri, (tmin, tmax)) in enumerate(zip(tmins, tmaxs)):
        raws[ri] = raw.copy().crop(tmin, tmax)
    all_raw_1 = concatenate_raws(raws, preload=False)
    all_raw_2 = raw.copy().crop(0, None)
    for ar in [all_raw_1, all_raw_2]:
        assert_equal(raw.first_samp, ar.first_samp)
        assert_equal(raw.last_samp, ar.last_samp)
        assert_array_equal(raw[:, :][0], ar[:, :][0])
    data = np.zeros((1, 1002001))
    info = create_info(1, 1000)
    raw = RawArray(data, info)
    for tmin in range(0, 1001, 100):
        raw1 = raw.copy().crop(tmin=tmin, tmax=(tmin + 2))
        assert_equal(raw1[:][0].shape, (1, 2001))
inputs: def ReserveKeys(keys):
targets: """Reserve all ids in the paths of the given keys.
    Args:
    keys: A list of keys with ids in their paths, for which the corresponding
    id sequences should be advanced to prevent id collisions.
    """
    datastore._GetConnection()._reserve_keys(ConvertKeys(keys))
inputs: def humanFrequency(hertz):
targets: """Convert a frequency in hertz to human classic representation.
    It uses the values: 1 KHz is 1000 Hz, 1 MHz is 1000 KMhz, etc.
    The result is an unicode string.
    >>> humanFrequency(790)
    u\790 Hz\
    >>> humanFrequency(629469)
    u\629.5 kHz\
    """
    divisor = 1000
    if (hertz < divisor):
        return (u'%u    Hz' % hertz)
    units = [u'kHz', u'MHz', u'GHz', u'THz']
    hertz = float(hertz)
    for unit in units:
        hertz = (hertz / divisor)
        if (hertz < divisor):
            return (u'%.1f    %s' % (hertz, unit))
    return (u'%s    %s' % (hertz, unit))
inputs: I wrote the below code

    lenPad = ((messageLength - 2) - len(data))
    return ((('\x01' + ('\xff' * lenPad)) + '\x00') + data)


What's a good function header?
targets: def pkcs1Pad(data, messageLength):
inputs: Complete the below
def _node_redundancy(G, v):

    ''''Returns the redundancy of the node `v` in the bipartite graph `G`.
    If `G` is a graph with `n` nodes, the redundancy of a node is the ratio
    of the "overlap" of `v` to the maximum possible overlap of `v`
    according to its degree. The overlap of `v` is the number of pairs of
    neighbors that have mutual neighbors themselves, other than `v`.
    `v` must have at least two neighbors in `G`.'
    '''
targets: n = len(G[v])
    overlap = sum((1 for (u, w) in combinations(G[v], 2) if ((set(G[u]) & set(G[w])) - {v})))
    return ((2 * overlap) / (n * (n - 1)))
inputs: @core_helper
def follow_button(obj_type, obj_id):
targets: """Return a follow button for the given object type and id.
    If the user is not logged in return an empty string instead.
    :param obj_type: the type of the object to be followed when the follow
    button is clicked, e.g. \user\ or \dataset\
    :type obj_type: string
    :param obj_id: the id of the object to be followed when the follow button
    is clicked
    :type obj_id: string
    :returns: a follow button as an HTML snippet
    :rtype: string
    """
    obj_type = obj_type.lower()
    assert (obj_type in _follow_objects)
    if c.user:
        context = {'model': model, 'session': model.Session, 'user': c.user}
        action = ('am_following_%s' % obj_type)
        following = logic.get_action(action)(context, {'id': obj_id})
        return snippet('snippets/follow_button.html', following=following, obj_id=obj_id, obj_type=obj_type)
    return ''
inputs: I wrote the below code

    disp = Dispatch(clsid)
    if (not disp.__class__.__dict__.get('CLSID')):
        try:
            ti = disp._oleobj_.GetTypeInfo()
            disp_clsid = ti.GetTypeAttr()[0]
            (tlb, index) = ti.GetContainingTypeLib()
            tla = tlb.GetLibAttr()
            gencache.EnsureModule(tla[0], tla[1], tla[3], tla[4], bValidateFile=0)
            disp_class = gencache.GetClassForProgID(str(disp_clsid))
        except pythoncom.com_error:
            raise TypeError('This    COM    object    can    not    automate    the    makepy    process    -    please    run    makepy    manually    for    this    object')
    else:
        disp_class = disp.__class__
    clsid = disp_class.CLSID
    try:
        from types import ClassType as new_type
    except ImportError:
        new_type = type
    events_class = getevents(clsid)
    if (events_class is None):
        raise ValueError('This    COM    object    does    not    support    events.')
    result_class = new_type('COMEventClass', (disp_class, events_class, user_event_class), {'__setattr__': _event_setattr_})
    instance = result_class(disp._oleobj_)
    events_class.__init__(instance, instance)
    if hasattr(user_event_class, '__init__'):
        user_event_class.__init__(instance)
    return EventsProxy(instance)


What's a good function header?
targets: def DispatchWithEvents(clsid, user_event_class):
inputs: I wrote the below code

    for line in codecs.getreader(encoding)(stream):
        (yield line.encode('utf-8'))


What's a good function header?
targets: def utf8_recoder(stream, encoding):
inputs: I wrote the below code

    ckpt = tf.train.get_checkpoint_state(os.path.dirname((config.CPT_PATH + '/checkpoint')))
    if (ckpt and ckpt.model_checkpoint_path):
        print('Loading    parameters    for    the    Chatbot')
        saver.restore(sess, ckpt.model_checkpoint_path)
    else:
        print('Initializing    fresh    parameters    for    the    Chatbot')


What's a good function header?
targets: def _check_restore_parameters(sess, saver):
inputs: Complete the below
def csrf_response_exempt(view_func):

    ''''Modifies a view function so that its response is exempt
    from the post-processing of the CSRF middleware.'
    '''
targets: def wrapped_view(*args, **kwargs):
        resp = view_func(*args, **kwargs)
        resp.csrf_exempt = True
        return resp
    return wraps(view_func, assigned=available_attrs(view_func))(wrapped_view)
inputs: Complete the below
@profiler.trace
def remove_tenant_user_role(request, project=None, user=None, role=None, group=None, domain=None):

    ''''Removes a given single role for a user from a tenant.'
    '''
targets: manager = keystoneclient(request, admin=True).roles
    if (VERSIONS.active < 3):
        return manager.remove_user_role(user, role, project)
    else:
        return manager.revoke(role, user=user, project=project, group=group, domain=domain)
inputs: I wrote the below code

    lock = 'perm({})    or    perm(events_without_validation)'.format(WITHOUT_VALIDATION)
    autovalid = caller.locks.check_lockstring(caller, lock)
    callback = caller.db._callback
    handler = get_event_handler()
    if ((not handler) or (not callback) or (not all(((key in callback) for key in ('obj', 'name', 'number', 'valid'))))):
        caller.msg("Couldn't    save    this    callback.")
        return False
    if ((callback['obj'], callback['name'], callback['number']) in handler.db.locked):
        handler.db.locked.remove((callback['obj'], callback['name'], callback['number']))
    handler.edit_callback(callback['obj'], callback['name'], callback['number'], buf, caller, valid=autovalid)
    return True


What's a good function header?
targets: def _ev_save(caller, buf):
inputs: I wrote the below code

    if isinstance(uri, tuple):
        uri = url_unparse(uri)
    uri = url_parse(to_unicode(uri, charset))
    path = url_unquote(uri.path, charset, errors, '%/;?')
    query = url_unquote(uri.query, charset, errors, '%;/?:@&=+,$#')
    fragment = url_unquote(uri.fragment, charset, errors, '%;/?:@&=+,$#')
    return url_unparse((uri.scheme, uri.decode_netloc(), path, query, fragment))


What's a good function header?
targets: def uri_to_iri(uri, charset='utf-8', errors='replace'):
inputs: Complete the below
def ensemble(nets):

    ''''Takes as input a list of nets, and then computes the accuracy on
    the test data when classifications are computed by taking a vote
    amongst the nets.  Returns a tuple containing a list of indices
    for test data which is erroneously classified, and a list of the
    corresponding erroneous predictions.
    Note that this is a quick-and-dirty kluge: it\'d be more reusable
    (and faster) to define a Theano function taking the vote.  But
    this works.'
    '''
targets: (test_x, test_y) = test_data
    for net in nets:
        i = T.lscalar()
        net.test_mb_predictions = theano.function([i], net.layers[(-1)].y_out, givens={net.x: test_x[(i * net.mini_batch_size):((i + 1) * net.mini_batch_size)]})
        net.test_predictions = list(np.concatenate([net.test_mb_predictions(i) for i in xrange(1000)]))
    all_test_predictions = zip(*[net.test_predictions for net in nets])
    def plurality(p):
        return Counter(p).most_common(1)[0][0]
    plurality_test_predictions = [plurality(p) for p in all_test_predictions]
    test_y_eval = test_y.eval()
    error_locations = [j for j in xrange(10000) if (plurality_test_predictions[j] != test_y_eval[j])]
    erroneous_predictions = [plurality(all_test_predictions[j]) for j in error_locations]
    print 'Accuracy    is    {:.2%}'.format((1 - (len(error_locations) / 10000.0)))
    return (error_locations, erroneous_predictions)
inputs: I wrote the below code

    key = (environment.block_start_string, environment.block_end_string, environment.variable_start_string, environment.variable_end_string, environment.comment_start_string, environment.comment_end_string, environment.line_statement_prefix, environment.line_comment_prefix, environment.trim_blocks, environment.newline_sequence)
    lexer = _lexer_cache.get(key)
    if (lexer is None):
        lexer = Lexer(environment)
        _lexer_cache[key] = lexer
    return lexer


What's a good function header?
targets: def get_lexer(environment):
inputs: def get_descrs(arrays, col_name_map):
targets: """Find the dtypes descrs resulting from merging the list of arrays\ dtypes,
    using the column name mapping ``col_name_map``.
    Return a list of descrs for the output.
    """
    out_descrs = []
    for (out_name, in_names) in six.iteritems(col_name_map):
        in_cols = [arr[name] for (arr, name) in zip(arrays, in_names) if (name is not None)]
        names = [name for name in in_names if (name is not None)]
        try:
            dtype = common_dtype(in_cols)
        except TableMergeError as tme:
            raise TableMergeError(u"The    '{0}'    columns    have    incompatible    types:    {1}".format(names[0], tme._incompat_types))
        uniq_shapes = set((col.shape[1:] for col in in_cols))
        if (len(uniq_shapes) != 1):
            raise TableMergeError(u'Key    columns    {0!r}    have    different    shape'.format(names))
        shape = uniq_shapes.pop()
        out_descrs.append((fix_column_name(out_name), dtype, shape))
    return out_descrs
inputs: Complete the below
def W3CDTF_to_datetime(formatted_string):

    ''''Convert from a timestamp string to a datetime object.'
    '''
targets: match = W3CDTF_REGEX.match(formatted_string)
    dt = [int(v) for v in match.groups()[:6]]
    return datetime.datetime(*dt)
inputs: def copy_recursively(source_dir, target_dir):
targets: """Recursively copy a source directory (and all its contents) to a target
    directory.
    :Parameters:
    source_dir : str
    Source directory to copy recursively. This path must
    exist and must specify a directory; otherwise, this
    function throws a ``ValueError``
    target_dir : str
    Directory to which to copy the contents of ``source_dir``.
    This directory must not already exist.
    :raise ValueError: If: ``source_dir`` does not exist; ``source_dir`` exists
    but is not a directory; or ``target_dir`` exists but is
    not a directory.
    """
    shutil.copytree(source_dir, target_dir)
inputs: Complete the below
def _add_gamma_multipliers(bem):

    ''''Add gamma and multipliers in-place.'
    '''
targets: bem['sigma'] = np.array([surf['sigma'] for surf in bem['surfs']])
    sigma = np.r_[(0.0, bem['sigma'])]
    bem['source_mult'] = (2.0 / (sigma[1:] + sigma[:(-1)]))
    bem['field_mult'] = (sigma[1:] - sigma[:(-1)])
    assert (len(bem['surfs']) == len(bem['field_mult']))
    bem['gamma'] = ((sigma[1:] - sigma[:(-1)])[np.newaxis, :] / (sigma[1:] + sigma[:(-1)])[:, np.newaxis])
inputs: def generate_min(extra_mods='', overwrite=False, so_mods='', python2_bin='python2', python3_bin='python3'):
targets: """Generate the salt-thin tarball and print the location of the tarball
    Optional additional mods to include (e.g. mako) can be supplied as a comma
    delimited string.  Permits forcing an overwrite of the output file as well.
    CLI Example:
    .. code-block:: bash
    salt-run thin.generate_min
    """
    conf_mods = __opts__.get('min_extra_mods')
    if conf_mods:
        extra_mods = ','.join([conf_mods, extra_mods])
    return salt.utils.thin.gen_min(__opts__['cachedir'], extra_mods, overwrite, so_mods, python2_bin, python3_bin)
inputs: def _PPIGuessPayloadClass(p, **kargs):
targets: """This function tells the PacketListField how it should extract the
    TLVs from the payload.  We pass cls only the length string
    pfh_len says it needs.  If a payload is returned, that means
    part of the sting was unused.  This converts to a Raw layer, and
    the remainder of p is added as Raw\s payload.  If there is no
    payload, the remainder of p is added as out\s payload.
    """
    if (len(p) >= 4):
        (t, pfh_len) = struct.unpack('<HH', p[:4])
        cls = getPPIType(t, 'default')
        pfh_len += 4
        out = cls(p[:pfh_len], **kargs)
        if out.payload:
            out.payload = conf.raw_layer(out.payload.load)
            if (len(p) > pfh_len):
                out.payload.payload = conf.padding_layer(p[pfh_len:])
        elif (len(p) > pfh_len):
            out.payload = conf.padding_layer(p[pfh_len:])
    else:
        out = conf.raw_layer(p, **kargs)
    return out
inputs: I wrote the below code

    _do_hypervisor_list(cs, matching=args.matching, limit=args.limit, marker=args.marker)


What's a good function header?
targets: @api_versions.wraps('2.33')
@utils.arg('--matching', metavar='<hostname>', default=None, help=_('List    hypervisors    matching    the    given    <hostname>    (or    pattern).    If    matching    is    used    limit    and    marker    options    will    be    ignored.'))
@utils.arg('--marker', dest='marker', metavar='<marker>', default=None, help=_('The    last    hypervisor    of    the    previous    page;    displays    list    of    hypervisors    after    "marker".'))
@utils.arg('--limit', dest='limit', metavar='<limit>', type=int, default=None, help=_("Maximum    number    of    hypervisors    to    display.    If    limit    is    bigger    than    'CONF.api.max_limit'    option    of    Nova    API,    limit    'CONF.api.max_limit'    will    be    used    instead."))
def do_hypervisor_list(cs, args):
inputs: Complete the below
@csrf_exempt
def bitbucket_build(request):

    ''''Consume webhooks from multiple versions of Bitbucket\'s API
    .. warning:: **DEPRECATED**
    Use :py:cls:`readthedocs.restapi.views.intergrations.BitbucketWebhookView`
    instead of this view function
    New webhooks are set up with v2, but v1 webhooks will still point to this
    endpoint. There are also "services" that point here and submit
    ``application/x-www-form-urlencoded`` data.
    API v1
    https://confluence.atlassian.com/bitbucket/events-resources-296095220.html
    API v2
    https://confluence.atlassian.com/bitbucket/event-payloads-740262817.html#EventPayloads-Push
    Services
    https://confluence.atlassian.com/bitbucket/post-service-management-223216518.html'
    '''
targets: if (request.method == 'POST'):
        try:
            if (request.META['CONTENT_TYPE'] == 'application/x-www-form-urlencoded'):
                data = json.loads(request.POST.get('payload'))
            else:
                data = json.loads(request.body)
            version = (2 if (request.META.get('HTTP_USER_AGENT') == 'Bitbucket-Webhooks/2.0') else 1)
            if (version == 1):
                branches = [commit.get('branch', '') for commit in data['commits']]
                repository = data['repository']
                search_url = 'bitbucket.org{0}'.format(repository['absolute_url'].rstrip('/'))
            elif (version == 2):
                changes = data['push']['changes']
                branches = [change['new']['name'] for change in changes]
                search_url = 'bitbucket.org/{0}'.format(data['repository']['full_name'])
        except (TypeError, ValueError, KeyError):
            log.error('Invalid    Bitbucket    webhook    payload', exc_info=True)
            return HttpResponse('Invalid    request', status=400)
        log.info('Bitbucket    webhook    search:    url=%s    branches=%s', search_url, branches)
        log.debug('Bitbucket    webhook    payload:\n\n%s\n\n', data)
        projects = get_project_from_url(search_url)
        if (projects and branches):
            return _build_url(search_url, projects, branches)
        elif (not branches):
            log.error('Commit/branch    not    found    url=%s    branches=%s', search_url, branches)
            return HttpResponseNotFound('Commit/branch    not    found')
        log.error('Project    match    not    found:    url=%s', search_url)
        return HttpResponseNotFound('Project    match    not    found')
    return HttpResponse('Method    not    allowed,    POST    is    required', status=405)
inputs: I wrote the below code

    (_, factors) = factor_list(a.minpoly, extension=b)
    for (f, _) in factors:
        if (f.degree() == 1):
            coeffs = f.rep.TC().to_sympy_list()
            (d, terms) = ((len(coeffs) - 1), [])
            for (i, coeff) in enumerate(coeffs):
                terms.append((coeff * (b.root ** (d - i))))
            root = Add(*terms)
            if ((a.root - root).evalf(chop=True) == 0):
                return coeffs
            if ((a.root + root).evalf(chop=True) == 0):
                return [(- c) for c in coeffs]
    else:
        return None


What's a good function header?
targets: def field_isomorphism_factor(a, b):
inputs: def iriencode(value):
targets: """Escapes an IRI value for use in a URL.
    """
    return force_unicode(iri_to_uri(value))
inputs: def DownloadCollection(coll_path, target_path, token=None, overwrite=False, dump_client_info=False, flatten=False, max_threads=10):
targets: """Iterate through a Collection object downloading all files.
    Args:
    coll_path: Path to an AFF4 collection.
    target_path: Base directory to write to.
    token: Token for access.
    overwrite: If True, overwrite existing files.
    dump_client_info: If True, this will detect client paths, and dump a yaml
    version of the client object to the root path. This is useful for seeing
    the hostname/users of the machine the client id refers to.
    flatten: If True, produce a "files" flat folder with links to all the found
    files.
    max_threads: Use this many threads to do the downloads.
    """
    completed_clients = set()
    coll = _OpenCollectionPath(coll_path, token=token)
    if (coll is None):
        logging.error('%s    is    not    a    valid    collection.    Typo?    Are    you    sure    something    was    written    to    it?', coll_path)
        return
    thread_pool = threadpool.ThreadPool.Factory('Downloader', max_threads)
    thread_pool.Start()
    try:
        collection_urn = coll.collection_id
    except AttributeError:
        collection_urn = coll.urn
    try:
        original_client_id = rdf_client.ClientURN(collection_urn.Split()[0])
    except IOError:
        original_client_id = None
    logging.info('Expecting    to    download    %s    files', len(coll))
    for grr_message in coll:
        source = None
        if isinstance(grr_message, rdf_flows.GrrMessage):
            source = grr_message.source
            grr_message = grr_message.payload
        if isinstance(grr_message, rdfvalue.RDFURN):
            urn = grr_message
        elif isinstance(grr_message, rdf_client.StatEntry):
            urn = rdfvalue.RDFURN(grr_message.AFF4Path((source or original_client_id)))
        elif isinstance(grr_message, rdf_file_finder.FileFinderResult):
            urn = rdfvalue.RDFURN(grr_message.stat_entry.AFF4Path((source or original_client_id)))
        elif isinstance(grr_message, collectors.ArtifactFilesDownloaderResult):
            if grr_message.HasField('downloaded_file'):
                urn = grr_message.downloaded_file.AFF4Path((source or original_client_id))
            else:
                continue
        elif isinstance(grr_message, rdfvalue.RDFBytes):
            try:
                os.makedirs(target_path)
            except OSError:
                pass
            try:
                client_id = source.Split()[0]
                with open(os.path.join(target_path, client_id), 'wb') as fd:
                    fd.write(str(grr_message))
            except AttributeError:
                pass
            continue
        else:
            continue
       ...
inputs: Complete the below
def main():

    ''''Main function
    :return: None'
    '''
targets: module = AnsibleModule(argument_spec=ClcSnapshot.define_argument_spec(), supports_check_mode=True)
    clc_snapshot = ClcSnapshot(module)
    clc_snapshot.process_request()
inputs: Complete the below
def hpfilter(X, lamb=1600):

    ''''Hodrick-Prescott filter
    Parameters
    X : array-like
    The 1d ndarray timeseries to filter of length (nobs,) or (nobs,1)
    lamb : float
    The Hodrick-Prescott smoothing parameter. A value of 1600 is
    suggested for quarterly data. Ravn and Uhlig suggest using a value
    of 6.25 (1600/4**4) for annual data and 129600 (1600*3**4) for monthly
    data.
    Returns
    cycle : array
    The estimated cycle in the data given lamb.
    trend : array
    The estimated trend in the data given lamb.
    Examples
    >>> import statsmodels.api as sm
    >>> import pandas as pd
    >>> dta = sm.datasets.macrodata.load_pandas().data
    >>> index = pd.DatetimeIndex(start=\'1959Q1\', end=\'2009Q4\', freq=\'Q\')
    >>> dta.set_index(index, inplace=True)
    >>> cycle, trend = sm.tsa.filters.hpfilter(dta.realgdp, 1600)
    >>> gdp_decomp = dta[[\'realgdp\']]
    >>> gdp_decomp["cycle"] = cycle
    >>> gdp_decomp["trend"] = trend
    >>> import matplotlib.pyplot as plt
    >>> fig, ax = plt.subplots()
    >>> gdp_decomp[["realgdp", "trend"]]["2000-03-31":].plot(ax=ax,
    ...                                                      fontsize=16);
    >>> plt.show()
    .. plot:: plots/hpf_plot.py
    Notes
    The HP filter removes a smooth trend, `T`, from the data `X`. by solving
    min sum((X[t] - T[t])**2 + lamb*((T[t+1] - T[t]) - (T[t] - T[t-1]))**2)
    T   t
    Here we implemented the HP filter as a ridge-regression rule using
    scipy.sparse. In this sense, the solution can be written as
    T = inv(I - lamb*K\'K)X
    where I is a nobs x nobs identity matrix, and K is a (nobs-2) x nobs matrix
    such that
    K[i,j] = 1 if i == j or i == j + 2
    K[i,j] = -2 if i == j + 1
    K[i,j] = 0 otherwise
    See Also
    statsmodels.tsa.filters.bk_filter.bkfilter
    statsmodels.tsa.filters.cf_filter.cffilter
    statsmodels.tsa.seasonal.seasonal_decompose
    References
    Hodrick, R.J, and E. C. Prescott. 1980. "Postwar U.S. Business Cycles: An
    Empricial Investigation." `Carnegie Mellon University...'''
targets: _pandas_wrapper = _maybe_get_pandas_wrapper(X)
    X = np.asarray(X, float)
    if (X.ndim > 1):
        X = X.squeeze()
    nobs = len(X)
    I = sparse.eye(nobs, nobs)
    offsets = np.array([0, 1, 2])
    data = np.repeat([[1.0], [(-2.0)], [1.0]], nobs, axis=1)
    K = sparse.dia_matrix((data, offsets), shape=((nobs - 2), nobs))
    use_umfpack = True
    trend = spsolve((I + (lamb * K.T.dot(K))), X, use_umfpack=use_umfpack)
    cycle = (X - trend)
    if (_pandas_wrapper is not None):
        return (_pandas_wrapper(cycle), _pandas_wrapper(trend))
    return (cycle, trend)
inputs: Complete the below
def build_dev_from_opts(opts):

    ''''Convert optparse stype options into a device dictionary.'
    '''
targets: for (attribute, shortopt, longopt) in (['region', '-r', '--region'], ['zone', '-z', '--zone'], ['ip', '-i', '--ip'], ['port', '-p', '--port'], ['device', '-d', '--device'], ['weight', '-w', '--weight']):
        if (getattr(opts, attribute, None) is None):
            raise ValueError(('Required    argument    %s/%s    not    specified.' % (shortopt, longopt)))
    ip = validate_and_normalize_address(opts.ip)
    replication_ip = validate_and_normalize_address((opts.replication_ip or opts.ip))
    replication_port = (opts.replication_port or opts.port)
    if (not validate_device_name(opts.device)):
        raise ValueError('Invalid    device    name')
    return {'region': opts.region, 'zone': opts.zone, 'ip': ip, 'port': opts.port, 'device': opts.device, 'meta': opts.meta, 'replication_ip': replication_ip, 'replication_port': replication_port, 'weight': opts.weight}
inputs: def dispatch_on(*dispatch_args):
targets: """Factory of decorators turning a function into a generic function
    dispatching on the given arguments.
    """
    assert dispatch_args, 'No    dispatch    args    passed'
    dispatch_str = ('(%s,)' % ',    '.join(dispatch_args))
    def check(arguments, wrong=operator.ne, msg=''):
        'Make    sure    one    passes    the    expected    number    of    arguments'
        if wrong(len(arguments), len(dispatch_args)):
            raise TypeError(('Expected    %d    arguments,    got    %d%s' % (len(dispatch_args), len(arguments), msg)))
    def gen_func_dec(func):
        'Decorator    turning    a    function    into    a    generic    function'
        argset = set(getfullargspec(func).args)
        if (not (set(dispatch_args) <= argset)):
            raise NameError(('Unknown    dispatch    arguments    %s' % dispatch_str))
        typemap = {}
        def vancestors(*types):
            '\n                                                Get    a    list    of    sets    of    virtual    ancestors    for    the    given    types\n                                                '
            check(types)
            ras = [[] for _ in range(len(dispatch_args))]
            for types_ in typemap:
                for (t, type_, ra) in zip(types, types_, ras):
                    if (issubclass(t, type_) and (type_ not in t.__mro__)):
                        append(type_, ra)
            return [set(ra) for ra in ras]
        def ancestors(*types):
            '\n                                                Get    a    list    of    virtual    MROs,    one    for    each    type\n                                                '
            check(types)
            lists = []
            for (t, vas) in zip(types, vancestors(*types)):
                n_vas = len(vas)
                if (n_vas > 1):
                    raise RuntimeError(('Ambiguous    dispatch    for    %s:    %s' % (t, vas)))
                elif (n_vas == 1):
                    (va,) = vas
                    mro = type('t', (t, va), {}).__mro__[1:]
                else:
                    mro = t.__mro__
               ...
inputs: Complete the below
def install(io_loop=None):

    ''''Install this package as the default Twisted reactor.'
    '''
targets: if (not io_loop):
        io_loop = tornado.ioloop.IOLoop.current()
    reactor = TornadoReactor(io_loop)
    from twisted.internet.main import installReactor
    installReactor(reactor)
    return reactor
inputs: Complete the below
def get_quantifier(ch, input_iter):

    ''''Parse a quantifier from the input, where "ch" is the first character in the
    quantifier.
    Returns the minimum number of occurences permitted by the quantifier and
    either None or the next character from the input_iter if the next character
    is not part of the quantifier.'
    '''
targets: if (ch in u'*?+'):
        try:
            (ch2, escaped) = next(input_iter)
        except StopIteration:
            ch2 = None
        if (ch2 == u'?'):
            ch2 = None
        if (ch == u'+'):
            return (1, ch2)
        return (0, ch2)
    quant = []
    while (ch != u'}'):
        (ch, escaped) = next(input_iter)
        quant.append(ch)
    quant = quant[:(-1)]
    values = u''.join(quant).split(u',')
    try:
        (ch, escaped) = next(input_iter)
    except StopIteration:
        ch = None
    if (ch == u'?'):
        ch = None
    return (int(values[0]), ch)
inputs: def get_auth_from_url(url):
targets: """Given a url with authentication components, extract them into a tuple of
    username,password.
    """
    parsed = urlparse(url)
    try:
        auth = (unquote(parsed.username), unquote(parsed.password))
    except (AttributeError, TypeError):
        auth = ('', '')
    return auth
inputs: Complete the below
def list_nodes_min(call=None):

    ''''Return a list of the instances that are on the provider. Only a list of
    instances names, and their state, is returned.
    CLI Examples:
    .. code-block:: bash
    salt-cloud -f list_nodes_min my-qingcloud'
    '''
targets: if (call != 'function'):
        raise SaltCloudSystemExit('The    list_nodes_min    function    must    be    called    with    -f    or    --function.')
    nodes = list_nodes_full()
    result = {}
    for (instance_id, full_node) in nodes.items():
        result[instance_id] = {'name': full_node['instance_name'], 'status': full_node['status']}
    return result
inputs: def get_subordinate_users(user, site):
targets: """Returns users queryset, containing all subordinate users to given user
    including users created by given user and not assigned to any page.
    Not assigned users must be returned, because they shouldn\t get lost, and
    user should still have possibility to see them.
    Only users created_by given user which are on the same, or lover level are
    returned.
    If user haves global permissions or is a superuser, then he can see all the
    users.
    This function is currently used in PagePermissionInlineAdminForm for limit
    users in permission combobox.
    Example:
    A,W                    level 0
    /                              user    B,GroupE           level 1
    Z       /                           C,X     D,Y,W                  level 2
    Rules: W was created by user, Z was created by user, but is not assigned
    to any page.
    Will return [user, C, X, D, Y, Z]. W was created by user, but is also
    assigned to higher level.
    """
    from cms.utils.page_permissions import get_change_permissions_id_list
    try:
        user_level = get_user_permission_level(user, site)
    except NoPermissionsException:
        qs = get_user_model().objects.distinct().filter(((Q(is_staff=True) & Q(pageuser__created_by=user)) & Q(pagepermission__page=None)))
        qs = qs.exclude(pk=user.pk).exclude(groups__user__pk=user.pk)
        return qs
    if (user_level == ROOT_USER_LEVEL):
        return get_user_model().objects.all()
    page_id_allow_list = get_change_permissions_id_list(user, site, check_global=False)
    qs = get_user_model().objects.distinct().filter(((Q(is_staff=True) & (Q(pagepermission__page__id__in=page_id_allow_list) & Q(pagepermission__page__depth__gte=user_level))) | (Q(pageuser__created_by=user) & Q(pagepermission__page=None))))
    qs = qs.exclude(pk=user.pk).exclude(groups__user__pk=user.pk)
    return qs