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

    original_uri = uri
    seen_uris = set()
    deadline = (time.time() + timeout)
    while (time.time() < deadline):
        if (uri in seen_uris):
            logger.info(u'Unwrapping    stream    from    URI    (%s)    failed:    playlist    referenced    itself', uri)
            return (None, None)
        else:
            seen_uris.add(uri)
        logger.debug(u'Unwrapping    stream    from    URI:    %s', uri)
        try:
            scan_timeout = (deadline - time.time())
            if (scan_timeout < 0):
                logger.info(u'Unwrapping    stream    from    URI    (%s)    failed:    timed    out    in    %sms', uri, timeout)
                return (None, None)
            scan_result = scanner.scan(uri, timeout=scan_timeout)
        except exceptions.ScannerError as exc:
            logger.debug(u'GStreamer    failed    scanning    URI    (%s):    %s', uri, exc)
            scan_result = None
        if (scan_result is not None):
            if (scan_result.playable or ((not scan_result.mime.startswith(u'text/')) and (not scan_result.mime.startswith(u'application/')))):
                logger.debug(u'Unwrapped    potential    %s    stream:    %s', scan_result.mime, uri)
                return (uri, scan_result)
        download_timeout = (deadline - time.time())
        if (download_timeout < 0):
            logger.info(u'Unwrapping    stream    from    URI    (%s)    failed:    timed    out    in    %sms', uri, timeout)
            return (None, None)
        content = http.download(requests_session, uri, timeout=(download_timeout / 1000))
        if (content is None):
            logger.info(u'Unwrapping    stream    from    URI    (%s)    failed:    error    downloading    URI    %s', original_uri, uri)
            return (None, None)
        uris = playlists.parse(content)
        if (not uris):
            logger.debug(u'Failed    parsing    URI    (%s)    as    playlist;    found    potential    stream.', uri)
            return (uri, None)
        logger.debug(u'Parsed   ...

What's a good function header?
targets: def _unwrap_stream(uri, timeout, scanner, requests_session):
inputs: Complete the below
def f_classif(X, y):

    ''''Compute the ANOVA F-value for the provided sample.
    Read more in the :ref:`User Guide <univariate_feature_selection>`.
    Parameters
    X : {array-like, sparse matrix} shape = [n_samples, n_features]
    The set of regressors that will be tested sequentially.
    y : array of shape(n_samples)
    The data matrix.
    Returns
    F : array, shape = [n_features,]
    The set of F values.
    pval : array, shape = [n_features,]
    The set of p-values.
    See also
    chi2: Chi-squared stats of non-negative features for classification tasks.
    f_regression: F-value between label/feature for regression tasks.'
    '''
targets: (X, y) = check_X_y(X, y, ['csr', 'csc', 'coo'])
    args = [X[safe_mask(X, (y == k))] for k in np.unique(y)]
    return f_oneway(*args)
inputs: Complete the below
@pytest.fixture
def wiki_user(db, django_user_model):

    ''''A test user.'
    '''
targets: return django_user_model.objects.create(username='wiki_user', email='wiki_user@example.com', date_joined=datetime(2017, 4, 14, 12, 0))
inputs: Complete the below
def make_collectstatic():

    ''''make_collectstatic() -> True/False'
    '''
targets: statuses = []
    hue_exec = os.path.join(common.INSTALL_ROOT, 'build', 'env', 'bin', 'hue')
    if os.path.exists(hue_exec):
        statuses.append(runcmd([hue_exec, 'collectstatic', '--noinput']))
    return (not any(statuses))
inputs: def install_packages(module, opkg_path, packages):
targets: """Installs one or more packages if not already installed.
    """
    p = module.params
    force = p['force']
    if force:
        force = ('--force-%s' % force)
    install_c = 0
    for package in packages:
        if query_package(module, opkg_path, package):
            continue
        (rc, out, err) = module.run_command(('%s    install    %s    %s' % (opkg_path, force, package)))
        if (not query_package(module, opkg_path, package)):
            module.fail_json(msg=('failed    to    install    %s:    %s' % (package, out)))
        install_c += 1
    if (install_c > 0):
        module.exit_json(changed=True, msg=('installed    %s    package(s)' % install_c))
    module.exit_json(changed=False, msg='package(s)    already    present')
inputs: I wrote the below code

    gemm_code = ''
    const = 'const'
    if (not config.blas.ldflags):
        current_filedir = dirname(__file__)
        gemm_common_filepath = normpath((current_filedir + '/alt_gemm_common.c'))
        gemm_template_filepath = normpath((current_filedir + '/alt_gemm_template.c'))
        common_code = ''
        sgemm_code = ''
        dgemm_code = ''
        with open(gemm_common_filepath) as code:
            common_code = code.read()
        with open(gemm_template_filepath) as code:
            template_code = code.read()
            sgemm_code = (template_code % {'float_type': 'float', 'float_size': 4, 'npy_float': 'NPY_FLOAT32', 'name': 'sgemm_'})
            dgemm_code = (template_code % {'float_type': 'double', 'float_size': 8, 'npy_float': 'NPY_FLOAT64', 'name': 'dgemm_'})
        if ((not common_code) or (not sgemm_code)):
            raise IOError('Unable    to    load    NumPy    implementation    of    gemm    code    from    C    source    files.')
        else:
            const = ''
        gemm_code += common_code
        gemm_code += sgemm_code
        gemm_code += dgemm_code
    header = '\n                extern    "C"\n                {\n\n                                void    xerbla_(char*,    void    *);\n\n                /***********/\n                /*    Level    1    */\n                /***********/\n\n                /*    Single    Precision    */\n\n                                void    srot_(const    int*,    float    *,    const    int*,    float    *,    const    int*,    const    float    *,    const    float    *);\n                                void    srotg_(float    *,float    *,float    *,float    *);\n                                void    srotm_(    const    int*,    float    *,    const    int*,    float    *,    const    int*,    const    float    *);\n                                void    srotmg_(float    *,float    *,float    *,const    float    *,    float    *);\n                                void    sswap_(    const    int*,    float    *,   ...

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

    if (kwargs.get('instance') and kwargs.get('created')):
        return
    comment = ((('comment' in kwargs) and kwargs['comment']) or kwargs['instance'])
    entry = comment.content_object
    if isinstance(entry, Entry):
        entry.comment_count = entry.comments.count()
        entry.pingback_count = entry.pingbacks.count()
        entry.trackback_count = entry.trackbacks.count()
        entry.save(update_fields=['comment_count', 'pingback_count', 'trackback_count'])


What's a good function header?
targets: def count_discussions_handler(sender, **kwargs):
inputs: def density(w, **kwargs):
targets: """Compute density of a sparse vector
    Return a value between 0 and 1
    """
    if hasattr(w, 'toarray'):
        d = (float(w.nnz) / (w.shape[0] * w.shape[1]))
    else:
        d = (0 if (w is None) else (float((w != 0).sum()) / w.size))
    return d
inputs: I wrote the below code

    auth_logout(request)
    if (redirect_field_name in request.REQUEST):
        next_page = request.REQUEST[redirect_field_name]
        if (not is_safe_url(url=next_page, host=request.get_host())):
            next_page = request.path
    if next_page:
        return HttpResponseRedirect(next_page)
    current_site = get_current_site(request)
    context = {'site': current_site, 'site_name': current_site.name, 'title': _('Logged    out')}
    if (extra_context is not None):
        context.update(extra_context)
    return TemplateResponse(request, template_name, context, current_app=current_app)


What's a good function header?
targets: def logout(request, next_page=None, template_name='registration/logged_out.html', redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None):
inputs: Complete the below
def add_path(path, config=None):

    ''''Ensure that the path, or the root of the current package (if
    path is in a package), is in sys.path.'
    '''
targets: log.debug(('Add    path    %s' % path))
    if (not path):
        return []
    added = []
    parent = os.path.dirname(path)
    if (parent and os.path.exists(os.path.join(path, '__init__.py'))):
        added.extend(add_path(parent, config))
    elif (not (path in sys.path)):
        log.debug('insert    %s    into    sys.path', path)
        sys.path.insert(0, path)
        added.append(path)
    if (config and config.srcDirs):
        for dirname in config.srcDirs:
            dirpath = os.path.join(path, dirname)
            if os.path.isdir(dirpath):
                sys.path.insert(0, dirpath)
                added.append(dirpath)
    return added
inputs: def expand_args(args, flist):
targets: """read names in flist and append to args
    """
    expanded = args[:]
    if flist:
        try:
            if (flist == '-'):
                fd = sys.stdin
            else:
                fd = open(flist)
            while 1:
                line = fd.readline()
                if (not line):
                    break
                expanded.append(line[:(-1)])
        except IOError:
            print ('Error    reading    file    list    %s' % flist)
            raise
    return expanded
inputs: def find_space(addr_space, procs, mod_base):
targets: """Search for an address space (usually looking for a GUI process)
    """
    if addr_space.is_valid_address(mod_base):
        return addr_space
    for proc in procs:
        ps_ad = proc.get_process_address_space()
        if (ps_ad != None):
            if ps_ad.is_valid_address(mod_base):
                return ps_ad
    return None
inputs: Complete the below
def find_scene_absolute_numbering(indexer_id, indexer, absolute_number):

    ''''Same as get_scene_numbering(), but returns None if scene numbering is not set'
    '''
targets: if ((indexer_id is None) or (absolute_number is None)):
        return absolute_number
    indexer_id = int(indexer_id)
    indexer = int(indexer)
    main_db_con = db.DBConnection()
    rows = main_db_con.select(u'SELECT    scene_absolute_number    FROM    scene_numbering    WHERE    indexer    =    ?    and    indexer_id    =    ?    and    absolute_number    =    ?    and    scene_absolute_number    !=    0', [indexer, indexer_id, absolute_number])
    if rows:
        return int(rows[0]['scene_absolute_number'])
inputs: Complete the below
def _get_query_handle_and_state(query_history):

    ''''Front-end wrapper to handle exceptions. Expects the query to be submitted.'
    '''
targets: handle = query_history.get_handle()
    if (handle is None):
        raise PopupException(_('Failed    to    retrieve    query    state    from    the    Query    Server.'))
    state = dbms.get(query_history.owner, query_history.get_query_server_config()).get_state(handle)
    if (state is None):
        raise PopupException(_('Failed    to    contact    Server    to    check    query    status.'))
    return (handle, state)
inputs: def __get_image(conn, vm_):
targets: """The get_image for GCE allows partial name matching and returns a
    libcloud object.
    """
    img = config.get_cloud_config_value('image', vm_, __opts__, default='debian-7', search_global=False)
    return conn.ex_get_image(img)
inputs: I wrote the below code

    attributes = {}
    attrs = ''
    if (';' in header):
        (header, attrs) = [x.strip() for x in header.split(';', 1)]
    m = True
    while m:
        m = ATTRIBUTES_RE.match(attrs)
        if m:
            attrs = attrs[len(m.group(0)):]
            attributes[m.group(1)] = m.group(2).strip('"')
    return (header, attributes)


What's a good function header?
targets: def parse_content_disposition(header):
inputs: Complete the below
def chrome_extensions(attrs=None, where=None):

    ''''Return chrome_extensions information from osquery
    CLI Example:
    .. code-block:: bash
    salt \'*\' osquery.chrome_extensions'
    '''
targets: if salt.utils.platform.is_darwin():
        return _osquery_cmd(table='chrome_extensions', attrs=attrs, where=where)
    return {'result': False, 'comment': 'Only    available    on    macOS    systems.'}
inputs: I wrote the below code

    name = config.get(CONF_NAME)
    ohmid = config.get(CONF_ID)
    add_devices([OhmconnectSensor(name, ohmid)], True)


What's a good function header?
targets: def setup_platform(hass, config, add_devices, discovery_info=None):
inputs: Complete the below
def load_pack_index_file(path, f):

    ''''Load an index file from a file-like object.
    :param path: Path for the index file
    :param f: File-like object
    :return: A PackIndex loaded from the given file'
    '''
targets: (contents, size) = _load_file_contents(f)
    if (contents[:4] == '\xfftOc'):
        version = struct.unpack('>L', contents[4:8])[0]
        if (version == 2):
            return PackIndex2(path, file=f, contents=contents, size=size)
        else:
            raise KeyError(('Unknown    pack    index    format    %d' % version))
    else:
        return PackIndex1(path, file=f, contents=contents, size=size)
inputs: def color_config(text):
targets: """Set color opitons of Text widget.
    Should be called whenever ColorDelegator is called.
    """
    theme = idleConf.CurrentTheme()
    normal_colors = idleConf.GetHighlight(theme, 'normal')
    cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg')
    select_colors = idleConf.GetHighlight(theme, 'hilite')
    text.config(foreground=normal_colors['foreground'], background=normal_colors['background'], insertbackground=cursor_color, selectforeground=select_colors['foreground'], selectbackground=select_colors['background'], inactiveselectbackground=select_colors['background'])
inputs: Complete the below
def GetRequestCpuUsage():

    ''''Returns the number of megacycles used so far by this request.
    Returns:
    The number of megacycles used so far by this request. Does not include CPU
    used by API calls.'
    '''
targets: return _apphosting_runtime___python__apiproxy.get_request_cpu_usage()
inputs: I wrote the below code

    if (type(ob) != pythoncom.TypeIIDs[pythoncom.IID_IEnumVARIANT]):
        ob = ob.QueryInterface(pythoncom.IID_IEnumVARIANT)
    return EnumVARIANT(ob, resultCLSID)


What's a good function header?
targets: def WrapEnum(ob, resultCLSID=None):
inputs: def get_email(recipients, sender=u'', msg=u'', subject=u'[No    Subject]', text_content=None, footer=None, print_html=None, formatted=None, attachments=None, content=None, reply_to=None, cc=[], email_account=None, expose_recipients=None, inline_images=[], header=None):
targets: """Prepare an email with the following format:
    - multipart/mixed
    - multipart/alternative
    - text/plain
    - multipart/related
    - text/html
    - inline image
    - attachment
    """
    content = (content or msg)
    emailobj = EMail(sender, recipients, subject, reply_to=reply_to, cc=cc, email_account=email_account, expose_recipients=expose_recipients)
    if (not content.strip().startswith(u'<')):
        content = markdown(content)
    emailobj.set_html(content, text_content, footer=footer, header=header, print_html=print_html, formatted=formatted, inline_images=inline_images)
    if isinstance(attachments, dict):
        attachments = [attachments]
    for attach in (attachments or []):
        if (attach.get(u'fcontent') is None):
            continue
        emailobj.add_attachment(**attach)
    return emailobj
inputs: I wrote the below code

    if (not hasattr(package, 'rindex')):
        raise ValueError("'package'    not    set    to    a    string")
    dot = len(package)
    for x in range(level, 1, (-1)):
        try:
            dot = package.rindex('.', 0, dot)
        except ValueError:
            raise ValueError('attempted    relative    import    beyond    top-level    package')
    return ('%s.%s' % (package[:dot], name))


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

    finder = PackageFinder([data.find_links], [], session=PipSession())
    req = InstallRequirement.from_line('gmpy')
    found = finder.find_requirement(req, False)
    assert found.url.endswith('gmpy-1.15.tar.gz'), found


What's a good function header?
targets: def test_no_partial_name_match(data):
inputs: def extract(request, response=None):
targets: """Extract the IDs of products in the history cookie
    """
    ids = []
    cookie_name = settings.OSCAR_RECENTLY_VIEWED_COOKIE_NAME
    if (cookie_name in request.COOKIES):
        try:
            ids = json.loads(request.COOKIES[cookie_name])
        except ValueError:
            if response:
                response.delete_cookie(cookie_name)
        else:
            if (not isinstance(ids, list)):
                ids = []
    return ids
inputs: def _parse_canonical_dbpointer(doc):
targets: """Decode a JSON (deprecated) DBPointer to bson.dbref.DBRef.
    """
    dbref = doc['$dbPointer']
    if (len(doc) != 1):
        raise TypeError(('Bad    $dbPointer,    extra    field(s):    %s' % (doc,)))
    if isinstance(dbref, DBRef):
        dbref_doc = dbref.as_doc()
        if (dbref.database is not None):
            raise TypeError(('Bad    $dbPointer,    extra    field    $db:    %s' % (dbref_doc,)))
        if (not isinstance(dbref.id, ObjectId)):
            raise TypeError(('Bad    $dbPointer,    $id    must    be    an    ObjectId:    %s' % (dbref_doc,)))
        if (len(dbref_doc) != 2):
            raise TypeError(('Bad    $dbPointer,    extra    field(s)    in    DBRef:    %s' % (dbref_doc,)))
        return dbref
    else:
        raise TypeError(('Bad    $dbPointer,    expected    a    DBRef:    %s' % (doc,)))
inputs: I wrote the below code

    pubsub_client = pubsub.Client()
    topic = pubsub_client.topic(topic_name)
    subscription = topic.subscription(subscription_name)
    permissions_to_check = ['pubsub.subscriptions.consume', 'pubsub.subscriptions.update']
    allowed_permissions = subscription.check_iam_permissions(permissions_to_check)
    print 'Allowed    permissions    for    subscription    {}    on    topic    {}:    {}'.format(subscription.name, topic.name, allowed_permissions)


What's a good function header?
targets: def check_subscription_permissions(topic_name, subscription_name):
inputs: def get_meth_class(obj):
targets: """Return method class
    """
    if PY2:
        return obj.im_class
    else:
        return obj.__self__.__class__
inputs: I wrote the below code

    def f(rv):
        if (not rv.is_Mul):
            return rv
        (n, d) = rv.as_numer_denom()
        if (n.is_Atom or d.is_Atom):
            return rv
        def ok(k, e):
            return ((e.is_integer or k.is_positive) and ((k.func in (sin, cos)) or (half and k.is_Add and (len(k.args) >= 2) and any((any((((ai.func is cos) or (ai.is_Pow and (ai.base is cos))) for ai in Mul.make_args(a))) for a in k.args)))))
        n = n.as_powers_dict()
        ndone = [(k, n.pop(k)) for k in list(n.keys()) if (not ok(k, n[k]))]
        if (not n):
            return rv
        d = d.as_powers_dict()
        ddone = [(k, d.pop(k)) for k in list(d.keys()) if (not ok(k, d[k]))]
        if (not d):
            return rv
        def factorize(d, ddone):
            newk = []
            for k in d:
                if (k.is_Add and (len(k.args) > 1)):
                    knew = (factor(k) if half else factor_terms(k))
                    if (knew != k):
                        newk.append((k, knew))
            if newk:
                for (i, (k, knew)) in enumerate(newk):
                    del d[k]
                    newk[i] = knew
                newk = Mul(*newk).as_powers_dict()
                for k in newk:
                    v = (d[k] + newk[k])
                    if ok(k, v):
                        d[k] = v
                    else:
                        ddone.append((k, v))
                del newk
        factorize(n, ndone)
        factorize(d, ddone)
        t = []
        for k in n:
            if (k.func is sin):
                a = cos(k.args[0], evaluate=False)
                if ((a in d) and (d[a] == n[k])):
                    t.append((tan(k.args[0]) ** n[k]))
                    n[k] = d[a] = None
                elif half:
                    a1 = (1 + a)
                    if ((a1 in d) and (d[a1] == n[k])):
                        t.append((tan((k.args[0] / 2)) ** n[k]))
                        n[k] = d[a1] = None
            elif (k.func is cos):
                a =...

What's a good function header?
targets: def TR2i(rv, half=False):
inputs: def create_logout_url(dest_url, _auth_domain=None):
targets: """Computes the logout URL for this request and specified destination URL,
    for both federated login App and Google Accounts App.
    Args:
    dest_url: String that is the desired final destination URL for the user
    once logout is complete. If \dest_url\ does not have a host
    specified, we will use the host from the current request.
    Returns:
    Logout URL as a string
    """
    req = user_service_pb.CreateLogoutURLRequest()
    resp = user_service_pb.CreateLogoutURLResponse()
    req.set_destination_url(dest_url)
    if _auth_domain:
        req.set_auth_domain(_auth_domain)
    try:
        apiproxy_stub_map.MakeSyncCall('user', 'CreateLogoutURL', req, resp)
    except apiproxy_errors.ApplicationError as e:
        if (e.application_error == user_service_pb.UserServiceError.REDIRECT_URL_TOO_LONG):
            raise RedirectTooLongError
        else:
            raise e
    return resp.logout_url()
inputs: def _retry_on_unavailable(exc):
targets: """Retry only errors whose status code is \UNAVAILABLE\.
    """
    from grpc import StatusCode
    return (exc.code() == StatusCode.UNAVAILABLE)
inputs: def load(parser, token):
targets: """Load a custom template tag set.
    For example, to load the template tags in ``django/templatetags/news/photos.py``::
    {% load news.photos %}
    """
    bits = token.contents.split()
    for taglib in bits[1:]:
        try:
            lib = get_library(('django.templatetags.%s' % taglib.split('.')[(-1)]))
            parser.add_library(lib)
        except InvalidTemplateLibrary as e:
            raise TemplateSyntaxError, ("'%s'    is    not    a    valid    tag    library:    %s" % (taglib, e))
    return LoadNode()
inputs: def create_lexicon_context(path):
targets: """Construct a SyntaxNet TaskContext file for standard lexical resources.
    """
    context = task_spec_pb2.TaskSpec()
    for name in ['word-map', 'tag-map', 'tag-to-category', 'lcword-map', 'category-map', 'char-map', 'char-ngram-map', 'label-map', 'prefix-table', 'suffix-table']:
        context.input.add(name=name).part.add(file_pattern=os.path.join(path, name))
    return context
inputs: Complete the below
def id_srando():

    ''''Reset seed values to their original values.'
    '''
targets: _id.id_srando()
inputs: def _check_precisions_full(precisions, covariance_type):
targets: """Check the precision matrices are symmetric and positive-definite.
    """
    for prec in precisions:
        _check_precision_matrix(prec, covariance_type)
inputs: @deprecated_renamed_argument('clobber', 'overwrite', '2.0')
def writeto(filename, data, header=None, output_verify='exception', overwrite=False, checksum=False):
targets: """Create a new FITS file using the supplied data/header.
    Parameters
    filename : file path, file object, or file like object
    File to write to.  If opened, must be opened in a writeable binary
    mode such as \wb\ or \ab+\.
    data : array, record array, or groups data object
    data to write to the new file
    header : `Header` object, optional
    the header associated with ``data``. If `None`, a header
    of the appropriate type is created for the supplied data. This
    argument is optional.
    output_verify : str
    Output verification option.  Must be one of ``"fix"``, ``"silentfix"``,
    ``"ignore"``, ``"warn"``, or ``"exception"``.  May also be any
    combination of ``"fix"`` or ``"silentfix"`` with ``"+ignore"``,
    ``+warn``, or ``+exception" (e.g. ``"fix+warn"``).  See :ref:`verify`
    for more info.
    overwrite : bool, optional
    If ``True``, overwrite the output file if it exists. Raises an
    ``OSError`` (``IOError`` for Python 2) if ``False`` and the
    output file exists. Default is ``False``.
    .. versionchanged:: 1.3
    ``overwrite`` replaces the deprecated ``clobber`` argument.
    checksum : bool, optional
    If `True`, adds both ``DATASUM`` and ``CHECKSUM`` cards to the
    headers of all HDU\s written to the file.
    """
    hdu = _makehdu(data, header)
    if (hdu.is_image and (not isinstance(hdu, PrimaryHDU))):
        hdu = PrimaryHDU(data, header=header)
    hdu.writeto(filename, overwrite=overwrite, output_verify=output_verify, checksum=checksum)
inputs: Complete the below
@register.filter(is_safe=True)
def random(value):

    ''''Returns a random item from the list.'
    '''
targets: return random_module.choice(value)
inputs: Complete the below
def addFacesByGrid(faces, grid):

    ''''Add faces from grid.'
    '''
targets: cellTopLoops = getIndexedCellLoopsFromIndexedGrid(grid)
    for cellTopLoop in cellTopLoops:
        addFacesByConvex(faces, cellTopLoop)
inputs: def add_multi_constructor(tag_prefix, multi_constructor, Loader=Loader):
targets: """Add a multi-constructor for the given tag prefix.
    Multi-constructor is called for a node if its tag starts with tag_prefix.
    Multi-constructor accepts a Loader instance, a tag suffix,
    and a node object and produces the corresponding Python object.
    """
    Loader.add_multi_constructor(tag_prefix, multi_constructor)
inputs: I wrote the below code

    alpha = ppf(((confidence + 1) / 2), (sample_size - 1))
    margin = (stddev / sqrt(sample_size))
    return ((point_estimate - (alpha * margin)), (point_estimate + (alpha * margin)))


What's a good function header?
targets: def confidence_interval_continuous(point_estimate, stddev, sample_size, confidence=0.95, **kwargs):
inputs: I wrote the below code

    data = f.read(1)
    if data:
        return ord(data)
    raise ValueError('not    enough    data    in    stream    to    read    uint1')


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

    proxy_username = None
    proxy_password = None
    proxy_username = os.environ.get('proxy-username')
    if (not proxy_username):
        proxy_username = os.environ.get('proxy_username')
    proxy_password = os.environ.get('proxy-password')
    if (not proxy_password):
        proxy_password = os.environ.get('proxy_password')
    if (not proxy_username):
        if ('@' in proxy_settings):
            protocol_and_proxy_auth = proxy_settings.split('@')[0].split(':')
            if (len(protocol_and_proxy_auth) == 3):
                proxy_username = protocol_and_proxy_auth[1].lstrip('/')
                proxy_password = protocol_and_proxy_auth[2]
            elif (len(protocol_and_proxy_auth) == 2):
                proxy_username = protocol_and_proxy_auth[0]
                proxy_password = protocol_and_proxy_auth[1]
    if proxy_username:
        user_auth = base64.encodestring(('%s:%s' % (proxy_username, proxy_password)))
        return ('Basic    %s\r\n' % user_auth.strip())
    else:
        return ''


What's a good function header?
targets: def _get_proxy_auth(proxy_settings):
inputs: Complete the below
def _collins_crt(r, R, P, p, K):

    ''''Wrapper of CRT for Collins\'s resultant algorithm.'
    '''
targets: return gf_int(gf_crt([r, R], [P, p], K), (P * p))
inputs: Complete the below
def describe_token(token):

    ''''Returns a description of the token.'
    '''
targets: if (token.type == 'name'):
        return token.value
    return _describe_token_type(token.type)
inputs: I wrote the below code

    if (lin_op.type is lo.NEG):
        result = value
    elif (lin_op.type is lo.MUL):
        coeff = mul(lin_op.data, {}, True)
        if np.isscalar(coeff):
            result = (coeff * value)
        else:
            result = (coeff.T * value)
    elif (lin_op.type is lo.DIV):
        divisor = mul(lin_op.data, {}, True)
        result = (value / divisor)
    elif (lin_op.type is lo.CONV):
        result = conv_mul(lin_op, value, True, True)
    else:
        result = op_tmul(lin_op, value)
    return result


What's a good function header?
targets: def op_abs_tmul(lin_op, value):
inputs: Complete the below
def load():

    ''''Load the yearly sunspot data and returns a data class.
    Returns
    Dataset instance:
    See DATASET_PROPOSAL.txt for more information.
    Notes
    This dataset only contains data for one variable, so the attributes
    data, raw_data, and endog are all the same variable.  There is no exog
    attribute defined.'
    '''
targets: data = _get_data()
    endog_name = 'SUNACTIVITY'
    endog = array(data[endog_name], dtype=float)
    dataset = Dataset(data=data, names=[endog_name], endog=endog, endog_name=endog_name)
    return dataset
inputs: def _get_network_obj(addr):
targets: """Try to convert a string into a valid IP Network object.
    """
    ip_netw = None
    try:
        ip_netw = IPNetwork(addr)
    except AddrFormatError:
        return ip_netw
    return ip_netw
inputs: Complete the below
def ensure_dir_exists(directory):

    ''''Given a valid directory path, make sure it exists.'
    '''
targets: if dir:
        if (not os.path.isdir(directory)):
            os.makedirs(directory)
inputs: I wrote the below code

    def _eat_client_exception(*args):
        try:
            return direct_head_container(*args)
        except ClientException as err:
            if (err.http_status == 404):
                return err.http_headers
        except (Timeout, socket.error):
            pass
    pile = GreenPile()
    (part, nodes) = container_ring.get_nodes(account_name, container_name)
    for node in nodes:
        pile.spawn(_eat_client_exception, node, part, account_name, container_name)
    headers = [x for x in pile if (x is not None)]
    if (len(headers) < majority_size(len(nodes))):
        return
    return best_policy_index(headers)


What's a good function header?
targets: @LRUCache(maxtime=CONTAINER_POLICY_TTL)
def direct_get_container_policy_index(container_ring, account_name, container_name):
inputs: Complete the below
def collect_members(module_to_name):

    ''''Collect all symbols from a list of modules.
    Args:
    module_to_name: Dictionary mapping modules to short names.
    Returns:
    Dictionary mapping name to (fullname, member) pairs.'
    '''
targets: members = {}
    for (module, module_name) in module_to_name.items():
        all_names = getattr(module, '__all__', None)
        for (name, member) in inspect.getmembers(module):
            if ((inspect.isfunction(member) or inspect.isclass(member)) and (not _always_drop_symbol_re.match(name)) and ((all_names is None) or (name in all_names))):
                fullname = ('%s.%s' % (module_name, name))
                if (name in members):
                    (other_fullname, other_member) = members[name]
                    if (member is not other_member):
                        raise RuntimeError(('Short    name    collision    between    %s    and    %s' % (fullname, other_fullname)))
                    if (len(fullname) == len(other_fullname)):
                        raise RuntimeError(("Can't    decide    whether    to    use    %s    or    %s    for    %s:    both    full    names    have    length    %d" % (fullname, other_fullname, name, len(fullname))))
                    if (len(fullname) > len(other_fullname)):
                        continue
                members[name] = (fullname, member)
    return members
inputs: def lookup_object(model, object_id, slug, slug_field):
targets: """Return the ``model`` object with the passed ``object_id``.  If
    ``object_id`` is None, then return the object whose ``slug_field``
    equals the passed ``slug``.  If ``slug`` and ``slug_field`` are not passed,
    then raise Http404 exception.
    """
    lookup_kwargs = {}
    if object_id:
        lookup_kwargs[('%s__exact' % model._meta.pk.name)] = object_id
    elif (slug and slug_field):
        lookup_kwargs[('%s__exact' % slug_field)] = slug
    else:
        raise GenericViewError('Generic    view    must    be    called    with    either    an    object_id    or    a    slug/slug_field.')
    try:
        return model.objects.get(**lookup_kwargs)
    except ObjectDoesNotExist:
        raise Http404(('No    %s    found    for    %s' % (model._meta.verbose_name, lookup_kwargs)))
inputs: def _sweep_poly_phase(t, poly):
targets: """Calculate the phase used by sweep_poly to generate its output.
    See `sweep_poly` for a description of the arguments.
    """
    intpoly = polyint(poly)
    phase = ((2 * pi) * polyval(intpoly, t))
    return phase
inputs: Complete the below
def histogram(image_data, rpc=None):

    ''''Calculates the histogram of the given image.
    Args:
    image_data: str, source image data.
    rpc: An optional UserRPC object.
    Returns: 3 256-element lists containing the number of occurences of each
    value of each color in the order RGB.
    Raises:
    NotImageError when the image data given is not an image.
    BadImageError when the image data given is corrupt.
    LargeImageError when the image data given is too large to process.
    Error when something unknown, but bad, happens.'
    '''
targets: rpc = histogram_async(image_data, rpc=rpc)
    return rpc.get_result()
inputs: Complete the below
def make_cookie_values(cj, class_name):

    ''''Makes a string of cookie keys and values.
    Can be used to set a Cookie header.'
    '''
targets: path = ('/' + class_name)
    cookies = [((c.name + '=') + c.value) for c in cj if ((c.domain == 'class.coursera.org') and (c.path == path))]
    return ';    '.join(cookies)
inputs: def compat_patch_logging_config(logging_config):
targets: """Backwards-compatibility shim for #16288 fix. Takes initial value of
    ``LOGGING`` setting and patches it in-place (issuing deprecation warning)
    if "mail_admins" logging handler is configured but has no filters.
    """
    if ('filters' not in logging_config.get('handlers', {}).get('mail_admins', {'filters': []})):
        warnings.warn("You    have    no    filters    defined    on    the    'mail_admins'    logging    handler:    adding    implicit    debug-false-only    filter.    See    http://docs.djangoproject.com/en/dev/releases/1.4/#request-exceptions-are-now-always-logged", DeprecationWarning)
        filter_name = 'require_debug_false'
        filters = logging_config.setdefault('filters', {})
        while (filter_name in filters):
            filter_name = (filter_name + '_')
        filters[filter_name] = {'()': 'django.utils.log.RequireDebugFalse'}
        logging_config['handlers']['mail_admins']['filters'] = [filter_name]
inputs: I wrote the below code

    info = show_fiff(fname_evoked)
    keys = ['FIFF_EPOCH', 'FIFFB_HPI_COIL', 'FIFFB_PROJ_ITEM', 'FIFFB_PROCESSED_DATA', 'FIFFB_EVOKED', 'FIFF_NAVE', 'FIFF_EPOCH']
    assert_true(all(((key in info) for key in keys)))
    info = show_fiff(fname_raw, read_limit=1024)
    assert_true(('COORD_TRANS' in show_fiff(fname_fsaverage_trans)))


What's a good function header?
targets: @testing.requires_testing_data
def test_show_fiff():
inputs: I wrote the below code

    p = subprocess.Popen(args=command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    (stdout, stderr) = p.communicate()
    if p.returncode:
        template = description
        template += '    failed:    (cmd=[%s],    stdout=[%s],    stderr=[%s])'
        message = (template % (command, stdout, stderr))
        raise AssertionError(message)


What's a good function header?
targets: def check_command(command, description):
inputs: I wrote the below code

    logging.warning('Hermes    is    shutting    down.')
    IOLoop.instance().stop()


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

    if (not bin_env):
        raise CommandNotFoundError('Could    not    find    a    `activate`    binary')
    if os.path.isdir(bin_env):
        if salt.utils.platform.is_windows():
            activate_bin = os.path.join(bin_env, 'Scripts', 'activate.bat')
        else:
            activate_bin = os.path.join(bin_env, 'bin', 'activate')
        if os.path.isfile(activate_bin):
            return activate_bin
    raise CommandNotFoundError('Could    not    find    a    `activate`    binary')


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

    if filename.split('/')[2].startswith(_CREATION_HANDLE_PREFIX):
        raise InvalidFileNameError(('File    %s    should    have    finalized    filename' % filename))


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

    (fc, f) = dmp_ground_primitive(f, u, K)
    (gc, g) = dmp_ground_primitive(g, u, K)
    c = K.lcm(fc, gc)
    h = dmp_quo(dmp_mul(f, g, u, K), dmp_gcd(f, g, u, K), u, K)
    return dmp_mul_ground(h, c, u, K)


What's a good function header?
targets: def dmp_rr_lcm(f, g, u, K):
inputs: def libvlc_media_player_new(p_libvlc_instance):
targets: """Create an empty Media Player object.
    @param p_libvlc_instance: the libvlc instance in which the Media Player should be created.
    @return: a new media player object, or NULL on error.
    """
    f = (_Cfunctions.get('libvlc_media_player_new', None) or _Cfunction('libvlc_media_player_new', ((1,),), class_result(MediaPlayer), ctypes.c_void_p, Instance))
    return f(p_libvlc_instance)
inputs: Complete the below
def laplacian(csgraph, normed=False, return_diag=False, use_out_degree=False):

    ''''Return the Laplacian matrix of a directed graph.
    Parameters
    csgraph : array_like or sparse matrix, 2 dimensions
    compressed-sparse graph, with shape (N, N).
    normed : bool, optional
    If True, then compute normalized Laplacian.
    return_diag : bool, optional
    If True, then also return an array related to vertex degrees.
    use_out_degree : bool, optional
    If True, then use out-degree instead of in-degree.
    This distinction matters only if the graph is asymmetric.
    Default: False.
    Returns
    lap : ndarray or sparse matrix
    The N x N laplacian matrix of csgraph. It will be a numpy array (dense)
    if the input was dense, or a sparse matrix otherwise.
    diag : ndarray, optional
    The length-N diagonal of the Laplacian matrix.
    For the normalized Laplacian, this is the array of square roots
    of vertex degrees or 1 if the degree is zero.
    Notes
    The Laplacian matrix of a graph is sometimes referred to as the
    "Kirchoff matrix" or the "admittance matrix", and is useful in many
    parts of spectral graph theory.  In particular, the eigen-decomposition
    of the laplacian matrix can give insight into many properties of the graph.
    Examples
    >>> from scipy.sparse import csgraph
    >>> G = np.arange(5) * np.arange(5)[:, np.newaxis]
    >>> G
    array([[ 0,  0,  0,  0,  0],
    [ 0,  1,  2,  3,  4],
    [ 0,  2,  4,  6,  8],
    [ 0,  3,  6,  9, 12],
    [ 0,  4,  8, 12, 16]])
    >>> csgraph.laplacian(G, normed=False)
    array([[  0,   0,   0,   0,   0],
    [  0,   9,  -2,  -3,  -4],
    [  0,  -2,  16,  -6,  -8],
    [  0,  -3,  -6,  21, -12],
    [  0,  -4,  -8, -12,  24]])'
    '''
targets: if ((csgraph.ndim != 2) or (csgraph.shape[0] != csgraph.shape[1])):
        raise ValueError('csgraph    must    be    a    square    matrix    or    array')
    if (normed and (np.issubdtype(csgraph.dtype, np.signedinteger) or np.issubdtype(csgraph.dtype, np.uint))):
        csgraph = csgraph.astype(float)
    create_lap = (_laplacian_sparse if isspmatrix(csgraph) else _laplacian_dense)
    degree_axis = (1 if use_out_degree else 0)
    (lap, d) = create_lap(csgraph, normed=normed, axis=degree_axis)
    if return_diag:
        return (lap, d)
    return lap
inputs: @shared_task(bind=True)
def ids(self, i):
targets: """Returns a tuple of ``root_id``, ``parent_id`` and
    the argument passed as ``i``.
    """
    return (self.request.root_id, self.request.parent_id, i)
inputs: Complete the below
def kit_item():

    ''''REST controller to retrieve budget_kit_item field options'
    '''
targets: s3.prep = (lambda r: (r.representation == 's3json'))
    return s3_rest_controller()
inputs: I wrote the below code

    if (not name):
        raise SaltInvocationError('Required    parameter    `name`    is    missing.')
    server = _connect()
    if (not job_exists(name)):
        raise SaltInvocationError('Job    `{0}`    does    not    exist.'.format(name))
    job_info = server.get_job_info(name)
    if job_info:
        return job_info
    return False


What's a good function header?
targets: def get_job_info(name=None):
inputs: Complete the below
def get_tld_list():

    ''''Returns a list of TLDs as objects
    CLI Example:
    .. code-block:: bash
    salt \'my-minion\' namecheap_domains.get_tld_list'
    '''
targets: response_xml = salt.utils.namecheap.get_request(salt.utils.namecheap.get_opts('namecheap.domains.gettldlist'))
    if (response_xml is None):
        return []
    tldresult = response_xml.getElementsByTagName('Tlds')[0]
    tlds = []
    for e in tldresult.getElementsByTagName('Tld'):
        tld = salt.utils.namecheap.atts_to_dict(e)
        tld['data'] = e.firstChild.data
        categories = []
        subcategories = e.getElementsByTagName('Categories')[0]
        for c in subcategories.getElementsByTagName('TldCategory'):
            categories.append(salt.utils.namecheap.atts_to_dict(c))
        tld['categories'] = categories
        tlds.append(tld)
    return tlds
inputs: def getdecoder(encoding):
targets: """Lookup up the codec for the given encoding and return
    its decoder function.
    Raises a LookupError in case the encoding cannot be found.
    """
    return lookup(encoding).decode
inputs: Complete the below
def internal_prep_stream_message(realm, sender, stream_name, topic, content):

    ''''See _internal_prep_message for details of how this works.'
    '''
targets: parsed_recipients = [stream_name]
    return _internal_prep_message(realm=realm, sender=sender, recipient_type_name='stream', parsed_recipients=parsed_recipients, subject=topic, content=content)
inputs: Complete the below
def crc32(path):

    ''''Return a CRC32 checksum of a file'
    '''
targets: return (binascii.crc32(open(path, 'rb').read()) & 4294967295)
inputs: def _nssplit(qualifiedName):
targets: """Split a qualified name into namespace part and local part.
    """
    fields = qualifiedName.split(':', 1)
    if (len(fields) == 2):
        return fields
    else:
        return (None, fields[0])
inputs: Complete the below
def _parse_localename(localename):

    ''''Parses the locale code for localename and returns the
    result as tuple (language code, encoding).
    The localename is normalized and passed through the locale
    alias engine. A ValueError is raised in case the locale name
    cannot be parsed.
    The language code corresponds to RFC 1766.  code and encoding
    can be None in case the values cannot be determined or are
    unknown to this implementation.'
    '''
targets: code = normalize(localename)
    if ('@' in code):
        (code, modifier) = code.split('@')
        if ((modifier == 'euro') and ('.' not in code)):
            return (code, 'iso-8859-15')
    if ('.' in code):
        return tuple(code.split('.')[:2])
    elif (code == 'C'):
        return (None, None)
    raise ValueError, ('unknown    locale:    %s' % localename)
inputs: @np.deprecate(message='stats.betai    is    deprecated    in    scipy    0.17.0;    use    special.betainc    instead')
def betai(a, b, x):
targets: """Return the incomplete beta function.
    I_x(a,b) = 1/B(a,b)*(Integral(0,x) of t^(a-1)(1-t)^(b-1) dt)
    where a,b>0 and B(a,b) = G(a)*G(b)/(G(a+b)) where G(a) is the gamma
    function of a.
    The standard broadcasting rules apply to a, b, and x.
    Parameters
    a : array_like or float > 0
    b : array_like or float > 0
    x : array_like or float
    x will be clipped to be no greater than 1.0 .
    Returns
    betai : ndarray
    Incomplete beta function.
    """
    return _betai(a, b, x)
inputs: Complete the below
def is_iterable(x):

    ''''A implementation independent way of checking for iterables'
    '''
targets: try:
        iter(x)
    except TypeError:
        return False
    else:
        return True
inputs: Complete the below
def _get_file_mode(filename, default='readonly'):

    ''''Allow file object to already be opened in any of the valid modes and
    and leave the file in the same state (opened or closed) as when
    the function was called.'
    '''
targets: mode = default
    closed = fileobj_closed(filename)
    fmode = fileobj_mode(filename)
    if (fmode is not None):
        mode = FILE_MODES.get(fmode)
        if (mode is None):
            raise IOError('File    mode    of    the    input    file    object    ({!r})    cannot    be    used    to    read/write    FITS    files.'.format(fmode))
    return (mode, closed)
inputs: Complete the below
def __virtual__():

    ''''Only load this module if pymongo is installed'
    '''
targets: if HAS_MONGODB:
        return 'mongodb'
    else:
        return (False, 'The    mongodb    execution    module    cannot    be    loaded:    the    pymongo    library    is    not    available.')
inputs: def get_port_from_device(port_id):
targets: """Get port from database
    """
    LOG.debug(_('get_port_with_securitygroups()    called:port_id=%s'), port_id)
    session = db.get_session()
    sg_binding_port = sg_db.SecurityGroupPortBinding.port_id
    query = session.query(models_v2.Port, sg_db.SecurityGroupPortBinding.security_group_id)
    query = query.outerjoin(sg_db.SecurityGroupPortBinding, (models_v2.Port.id == sg_binding_port))
    query = query.filter((models_v2.Port.id == port_id))
    port_and_sgs = query.all()
    if (not port_and_sgs):
        return None
    port = port_and_sgs[0][0]
    plugin = manager.QuantumManager.get_plugin()
    port_dict = plugin._make_port_dict(port)
    port_dict[ext_sg.SECURITYGROUPS] = [sg_id for (port, sg_id) in port_and_sgs if sg_id]
    port_dict['security_group_rules'] = []
    port_dict['security_group_source_groups'] = []
    port_dict['fixed_ips'] = [ip['ip_address'] for ip in port['fixed_ips']]
    return port_dict
inputs: Complete the below
@mock_ec2_deprecated
def test_igw_detach_unattached():

    ''''internet gateway fail to detach unattached'
    '''
targets: conn = boto.connect_vpc(u'the_key', u'the_secret')
    igw = conn.create_internet_gateway()
    vpc = conn.create_vpc(VPC_CIDR)
    with assert_raises(EC2ResponseError) as cm:
        conn.detach_internet_gateway(igw.id, vpc.id)
    cm.exception.code.should.equal(u'Gateway.NotAttached')
    cm.exception.status.should.equal(400)
    cm.exception.request_id.should_not.be.none
inputs: def S_IMODE(mode):
targets: """Return the portion of the file\s mode that can be set by
    os.chmod().
    """
    return (mode & 4095)
inputs: @frame_transform_graph.transform(coord.StaticMatrixTransform, Sagittarius, coord.Galactic)
def sgr_to_galactic():
targets: """Compute the transformation matrix from heliocentric Sgr coordinates to
    spherical Galactic.
    """
    return matrix_transpose(SGR_MATRIX)
inputs: I wrote the below code

    for key in keys:
        if ((key in b) and (a[key] != b[key])):
            return False
    return True


What's a good function header?
targets: def targets_equal(keys, a, b):