Muennighoff/xP3x-sample huggingface dataset:
inputs: def app_restore(storage, bucket_name=None):
targets: """Restores the app source code from the backups location on the filesystem.
    Args:
    storage: A str, one of the StorageTypes class members.
    bucket_name: A str, the name of the bucket to restore apps from.
    Returns:
    True on success, False otherwise.
    """
    if (not makedirs(APP_BACKUP_DIR_LOCATION)):
        logging.warning("Dir    '{0}'    already    exists.    Skipping    dir    creation...".format(APP_BACKUP_DIR_LOCATION))
    if (storage == StorageTypes.GCS):
        objects = gcs_helper.list_bucket(bucket_name)
        for app_path in objects:
            if (not app_path.startswith(gcs_helper.APPS_GCS_PREFIX)):
                continue
            app_file = app_path[len(gcs_helper.APPS_GCS_PREFIX):]
            source = 'gs://{0}/{1}'.format(bucket_name, app_path)
            destination = '{0}/{1}'.format(APP_BACKUP_DIR_LOCATION, app_file)
            if (not gcs_helper.download_from_bucket(source, destination)):
                logging.error("Error    while    downloading    '{0}'    from    GCS.".format(source))
                delete_app_tars(APP_BACKUP_DIR_LOCATION)
                return False
    apps_to_deploy = [os.path.join(APP_BACKUP_DIR_LOCATION, app) for app in os.listdir(APP_BACKUP_DIR_LOCATION)]
    if (not deploy_apps(apps_to_deploy)):
        logging.error('Failed    to    successfully    deploy    one    or    more    of    the    following    apps:    {0}'.format(apps_to_deploy))
        return False
    return True
inputs: Complete the below
def debug(mode=True):

    ''''Change the debug level.
    There is only one debug level supported at the moment.'
    '''
targets: global DEBUG
    if mode:
        warnings.simplefilter('default')
    DEBUG = bool(mode)
inputs: Complete the below
def _visible_width(s):

    ''''Visible width of a printed string. ANSI color codes are removed.
    >>> _visible_width(\'[31mhello[0m\'), _visible_width("world")
    (5, 5)'
    '''
targets: if (isinstance(s, _text_type) or isinstance(s, _binary_type)):
        return len(_strip_invisible(s))
    else:
        return len(_text_type(s))
inputs: I wrote the below code

    import pandas as pd
    result_dict = pd.read_pickle(result_pickle_file_path)
    from .report import generate_report
    generate_report(result_dict, target_report_csv_path)


What's a good function header?
targets: @cli.command()
@click.argument('result_pickle_file_path', type=click.Path(exists=True), required=True)
@click.argument('target_report_csv_path', type=click.Path(exists=True, writable=True), required=True)
def report(result_pickle_file_path, target_report_csv_path):
inputs: @protocol.commands.add(u'seek', songpos=protocol.UINT, seconds=protocol.UINT)
def seek(context, songpos, seconds):
targets: """*musicpd.org, playback section:*
    ``seek {SONGPOS} {TIME}``
    Seeks to the position ``TIME`` (in seconds) of entry ``SONGPOS`` in
    the playlist.
    *Droid MPD:*
    - issues ``seek 1 120`` without quotes around the arguments.
    """
    tl_track = context.core.playback.get_current_tl_track().get()
    if (context.core.tracklist.index(tl_track).get() != songpos):
        play(context, songpos)
    context.core.playback.seek((seconds * 1000)).get()
inputs: Complete the below
def get_view(request):

    ''''A simple view that expects a GET request, and returns a rendered template'
    '''
targets: t = Template('This    is    a    test.    {{    var    }}    is    the    value.', name='GET    Template')
    c = Context({'var': request.GET.get('var', 42)})
    return HttpResponse(t.render(c))
inputs: I wrote the below code

    from patsy.constraint import linear_constraint
    exog_names = model_results.model.exog_names
    LC = linear_constraint(test_formula, exog_names)
    return LC


What's a good function header?
targets: def make_hypotheses_matrices(model_results, test_formula):
inputs: Complete the below
@preloaderStop
def successMessage(message):

    ''''Displaying a message.'
    '''
targets: printLine(message, '\n')
inputs: def extract_cookies_to_jar(jar, request, response):
targets: """Extract the cookies from the response into a CookieJar.
    :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
    :param request: our own requests.Request object
    :param response: urllib3.HTTPResponse object
    """
    req = MockRequest(request)
    res = MockResponse(response._original_response.msg)
    jar.extract_cookies(res, req)
inputs: Complete the below
def chunk(data, index):

    ''''Split a string into two parts at the input index.'
    '''
targets: return (data[:index], data[index:])
inputs: I wrote the below code

    if (not isinstance(time, integer_types)):
        raise SaltInvocationError("'time'    must    be    an    integer")
    if (not isinstance(min_compress_len, integer_types)):
        raise SaltInvocationError("'min_compress_len'    must    be    an    integer")
    conn = _connect(host, port)
    stats = conn.get_stats()
    return conn.replace(key, value, time=time, min_compress_len=min_compress_len)


What's a good function header?
targets: def replace(key, value, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_TIME, min_compress_len=DEFAULT_MIN_COMPRESS_LEN):
inputs: def CMO(ds, count, timeperiod=(- (2 ** 31))):
targets: """Chande Momentum Oscillator
    """
    return call_talib_with_ds(ds, count, talib.CMO, timeperiod)
inputs: def __methodDict(cls, _dict):
targets: """helper function for Scrolled Canvas
    """
    baseList = list(cls.__bases__)
    baseList.reverse()
    for _super in baseList:
        __methodDict(_super, _dict)
    for (key, value) in cls.__dict__.items():
        if (type(value) == types.FunctionType):
            _dict[key] = value
inputs: def _generatePermEncoderStr(options, encoderDict):
targets: """Generate the string that defines the permutations to apply for a given
    encoder.
    Parameters:
    options: experiment params
    encoderDict: the encoder dict, which gets placed into the description.py
    For example, if the encoderDict contains:
    \consumption\:     {
    \clipInput\: True,
    \fieldname\: u\consumption\,
    \n\: 100,
    \name\: u\consumption\,
    \type\: \AdaptiveScalarEncoder\,
    \w\: 21},
    The return string will contain:
    "PermuteEncoder(fieldName=\consumption\,
    encoderClass=\AdaptiveScalarEncoder\,
    w=21,
    n=PermuteInt(28, 521),
    clipInput=True)"
    """
    permStr = ''
    if encoderDict.get('classifierOnly', False):
        permStr = 'dict('
        for (key, value) in encoderDict.items():
            if (key == 'name'):
                continue
            if ((key == 'n') and (encoderDict['type'] != 'SDRCategoryEncoder')):
                permStr += ('n=PermuteInt(%d,    %d),    ' % ((encoderDict['w'] + 7), (encoderDict['w'] + 500)))
            elif issubclass(type(value), basestring):
                permStr += ("%s='%s',    " % (key, value))
            else:
                permStr += ('%s=%s,    ' % (key, value))
        permStr += ')'
    elif (encoderDict['type'] in ['ScalarSpaceEncoder', 'AdaptiveScalarEncoder', 'ScalarEncoder', 'LogEncoder']):
        permStr = 'PermuteEncoder('
        for (key, value) in encoderDict.items():
            if (key == 'fieldname'):
                key = 'fieldName'
            elif (key == 'type'):
                key = 'encoderClass'
            elif (key == 'name'):
                continue
            if (key == 'n'):
                permStr += ('n=PermuteInt(%d,    %d),    ' % ((encoderDict['w'] + 1), (encoderDict['w'] + 500)))
            elif (key == 'runDelta'):
                if (value and (not ('space' in encoderDict))):
                    permStr += ('space=PermuteChoices([%s,%s]),    ' % (_quoteAndEscape('delta'), _quoteAndEscape('absolute')))
                encoderDict.pop('runDelta')
            elif issubclass(type(value), basestring):
                permStr += ("%s='%s',    " % (key, value))
            else:
                permStr += ('%s=%s,    ' % (key, value))
        permStr += ')'
    elif (encoderDict['type'] in ['SDRCategoryEncoder']):
        permStr = 'PermuteEncoder('
        for (key, value) in encoderDict.items():
            if (key == 'fieldname'):
                key = 'fieldName'
            elif (key == 'type'):
                key = 'encoderClass'
            elif (key == 'name'):
                continue
            if issubclass(type(value), basestring):
               ...
inputs: Complete the below
def Deserializer(stream_or_string, **options):

    ''''Deserialize a stream or string of JSON data.
    Note: no change from Django version,
    but needed to import here to use the versioned python deserializer
    (see the import at the top for PythonDeserializer)'
    '''
targets: if isinstance(stream_or_string, basestring):
        stream = StringIO(stream_or_string)
    else:
        stream = stream_or_string
    try:
        for obj in PythonDeserializer(simplejson.load(stream), **options):
            (yield obj)
    except GeneratorExit:
        raise
    except Exception as e:
        raise DeserializationError(e)
inputs: Complete the below
def MakeResponse(code=500, data=''):

    ''''A helper for creating a HTTPError exception.'
    '''
targets: response = requests.Response()
    response.status_code = code
    response._content = data
    return response
inputs: @when(u'we    send    "\\?"    command')
def step_send_help(context):
targets: """Send \?
    to see help.
    """
    context.cli.sendline(u'\\?')
    wrappers.expect_exact(context, (context.conf[u'pager_boundary'] + u'\r\n'), timeout=5)
inputs: I wrote the below code

    from django.contrib.staticfiles.templatetags import staticfiles
    if (mod == 'static'):
        return staticfiles.static(filename)
    return ''


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

    (str_len,) = struct.unpack('>I', data[:4])
    return (data[4:(4 + str_len)], data[(4 + str_len):])


What's a good function header?
targets: def _read_next_string(data):
inputs: Complete the below
def isAlphanum(c):

    ''''return true if the character is a letter, digit, underscore,
    dollar sign, or non-ASCII character.'
    '''
targets: return (((c >= 'a') and (c <= 'z')) or ((c >= '0') and (c <= '9')) or ((c >= 'A') and (c <= 'Z')) or (c == '_') or (c == '$') or (c == '\\') or ((c is not None) and (ord(c) > 126)))
inputs: Complete the below
def increment_lineno(node, n=1):

    ''''Increment the line number of each node in the tree starting at *node* by *n*.
    This is useful to "move code" to a different location in a file.'
    '''
targets: for child in walk(node):
        if ('lineno' in child._attributes):
            child.lineno = (getattr(child, 'lineno', 0) + n)
    return node
inputs: I wrote the below code

    if (np.abs(mu).max() > 1.0):
        return 1.0
    _compose_linear_fitting_data(mu, u)
    (u['uu'], u['sing'], u['vv']) = linalg.svd(u['M'])
    u['resi'][:] = u['y'][:]
    for p in range((u['nfit'] - 1)):
        dot = np.dot(u['uu'][p], u['y'])
        for k in range((u['nterms'] - 1)):
            u['resi'][k] = (u['resi'][k] - (u['uu'][(p, k)] * dot))
    return np.dot(u['resi'], u['resi'])


What's a good function header?
targets: def _one_step(mu, u):
inputs: def eat_descriptor(descr):
targets: """Read head of a field/method descriptor.  Returns a pair of strings, where
    the first one is a human-readable string representation of the first found
    type, and the second one is the tail of the parameter.
    """
    array_dim = 0
    while (descr[0] == '['):
        array_dim += 1
        descr = descr[1:]
    if (descr[0] == 'L'):
        try:
            end = descr.find(';')
        except:
            raise ParserError(('Not    a    valid    descriptor    string:    ' + descr))
        type = descr[1:end]
        descr = descr[end:]
    else:
        global code_to_type_name
        try:
            type = code_to_type_name[descr[0]]
        except KeyError:
            raise ParserError(('Not    a    valid    descriptor    string:    %s' % descr))
    return ((type.replace('/', '.') + (array_dim * '[]')), descr[1:])
inputs: Complete the below
def get_free_namespace_port(protocol, namespace=None, start=1024, end=None):

    ''''Return an unused port from given namespace
    WARNING: This function returns a port that is free at the execution time of
    this function. If this port is used later for binding then there
    is a potential danger that port will be no longer free. It\'s up to
    the programmer to handle error if port is already in use.
    :param protocol: Return free port for given protocol. Supported protocols
    are \'tcp\' and \'udp\'.
    :param namespace: Namespace in which free port has to be returned.
    :param start: The starting port number.
    :param end: The ending port number (free port that is returned would be
    between (start, end) values.'
    '''
targets: if (protocol == n_const.PROTO_NAME_TCP):
        param = '-tna'
    elif (protocol == n_const.PROTO_NAME_UDP):
        param = '-una'
    else:
        raise ValueError(('Unsupported    protocol    %s' % protocol))
    ip_wrapper = ip_lib.IPWrapper(namespace=namespace)
    output = ip_wrapper.netns.execute(['ss', param])
    used_ports = _get_source_ports_from_ss_output(output)
    return get_unused_port(used_ports, start, end)
inputs: Complete the below
def RGS_generalized(m):

    ''''Computes the m + 1 generalized unrestricted growth strings
    and returns them as rows in matrix.
    Examples
    >>> from sympy.combinatorics.partitions import RGS_generalized
    >>> RGS_generalized(6)
    Matrix([
    [  1,   1,   1,  1,  1, 1, 1],
    [  1,   2,   3,  4,  5, 6, 0],
    [  2,   5,  10, 17, 26, 0, 0],
    [  5,  15,  37, 77,  0, 0, 0],
    [ 15,  52, 151,  0,  0, 0, 0],
    [ 52, 203,   0,  0,  0, 0, 0],
    [203,   0,   0,  0,  0, 0, 0]])'
    '''
targets: d = zeros((m + 1))
    for i in range(0, (m + 1)):
        d[(0, i)] = 1
    for i in range(1, (m + 1)):
        for j in range(m):
            if (j <= (m - i)):
                d[(i, j)] = ((j * d[((i - 1), j)]) + d[((i - 1), (j + 1))])
            else:
                d[(i, j)] = 0
    return d
inputs: def __virtual__():
targets: """Only load if zc.buildout libs available
    """
    return __virtualname__
inputs: def group_from(type):
targets: """Get the group part of an event type name.
    Example:
    >>> group_from(\task-sent\)
    \task\
    >>> group_from(\custom-my-event\)
    \custom\
    """
    return type.split(u'-', 1)[0]
inputs: Complete the below
def add_move(move):

    ''''Add an item to six.moves.'
    '''
targets: setattr(_MovedItems, move.name, move)
inputs: def connect(client=None):
targets: """Construct a DB-API connection to Google BigQuery.
    :type client: :class:`~google.cloud.bigquery.Client`
    :param client:
    (Optional) A client used to connect to BigQuery. If not passed, a
    client is created using default options inferred from the environment.
    :rtype: :class:`~google.cloud.bigquery.dbapi.Connection`
    :returns: A new DB-API connection to BigQuery.
    """
    if (client is None):
        client = bigquery.Client()
    return Connection(client)
inputs: Complete the below
def get_makefile_filename():

    ''''Return the path of the Makefile.'
    '''
targets: if _PYTHON_BUILD:
        return os.path.join(_PROJECT_BASE, 'Makefile')
    if hasattr(sys, 'abiflags'):
        config_dir_name = ('config-%s%s' % (_PY_VERSION_SHORT, sys.abiflags))
    else:
        config_dir_name = 'config'
    return os.path.join(get_path('stdlib'), config_dir_name, 'Makefile')
inputs: I wrote the below code

    if response.has_header('Vary'):
        vary_headers = cc_delim_re.split(response['Vary'])
    else:
        vary_headers = []
    existing_headers = {header.lower() for header in vary_headers}
    additional_headers = [newheader for newheader in newheaders if (newheader.lower() not in existing_headers)]
    response['Vary'] = ',    '.join((vary_headers + additional_headers))


What's a good function header?
targets: def patch_vary_headers(response, newheaders):
inputs: def c12_mapping(char):
targets: """Map non-ASCII whitespace to spaces.
    """
    return (u'    ' if stringprep.in_table_c12(char) else None)
inputs: I wrote the below code

    g = Expression.fromstring(argument_pair[0])
    alist = [lp.parse(a) for a in argument_pair[1]]
    m = MaceCommand(g, assumptions=alist)
    m.build_model()
    for a in alist:
        print(('            %s' % a))
    print(('|-    %s:    %s\n' % (g, m.build_model())))
    for format in ['standard', 'portable', 'xml', 'cooked']:
        spacer()
        print(("Using    '%s'    format" % format))
        spacer()
        print(m.model(format=format))


What's a good function header?
targets: def test_transform_output(argument_pair):
inputs: def get_info(inst):
targets: """Retrieves instance template information
    """
    return {'name': inst.name, 'extra': inst.extra}
inputs: I wrote the below code

    lgrp = __salt__['group.info'](name)
    if (not lgrp):
        return False
    change = {}
    if gid:
        if (lgrp['gid'] != gid):
            change['gid'] = gid
    if members:
        if (set(lgrp['members']) ^ set(members)):
            change['members'] = members
    if addusers:
        users_2add = [user for user in addusers if (user not in lgrp['members'])]
        if users_2add:
            change['addusers'] = users_2add
    if delusers:
        users_2del = [user for user in delusers if (user in lgrp['members'])]
        if users_2del:
            change['delusers'] = users_2del
    return change


What's a good function header?
targets: def _changes(name, gid=None, addusers=None, delusers=None, members=None):
inputs: Complete the below
def del_tags(name=None, kwargs=None, call=None, instance_id=None, resource_id=None):

    ''''Delete tags for a resource. Normally a VM name or instance_id is passed in,
    but a resource_id may be passed instead. If both are passed in, the
    instance_id will be used.
    CLI Examples:
    .. code-block:: bash
    salt-cloud -a del_tags mymachine tags=mytag,
    salt-cloud -a del_tags mymachine tags=tag1,tag2,tag3
    salt-cloud -a del_tags resource_id=vol-3267ab32 tags=tag1,tag2,tag3'
    '''
targets: if (kwargs is None):
        kwargs = {}
    if ('tags' not in kwargs):
        raise SaltCloudSystemExit('A    tag    or    tags    must    be    specified    using    tags=list,of,tags')
    if ((not name) and ('resource_id' in kwargs)):
        instance_id = kwargs['resource_id']
        del kwargs['resource_id']
    if (not instance_id):
        instance_id = _get_node(name)['instanceId']
    params = {'Action': 'DeleteTags', 'ResourceId.1': instance_id}
    for (idx, tag) in enumerate(kwargs['tags'].split(',')):
        params['Tag.{0}.Key'.format(idx)] = tag
    aws.query(params, setname='tagSet', location=get_location(), provider=get_provider(), opts=__opts__, sigver='4')
    if resource_id:
        return get_tags(resource_id=resource_id)
    else:
        return get_tags(instance_id=instance_id)
inputs: Complete the below
def __virtual__():

    ''''Only load if influxdb lib is present'
    '''
targets: if HAS_INFLUXDB:
        return __virtualname__
    return (False, 'The    influxdb    execution    module    could    not    be    loaded:influxdb    library    not    available.')
inputs: I wrote the below code

    def decorator(func):
        _checks[name] = func
        return func
    if func:
        return decorator(func)
    return decorator


What's a good function header?
targets: def register(name, func=None):
inputs: @patch('coursera.api.get_page')
def test_list_courses(get_page, course):
targets: """Test course listing method.
    """
    get_page.side_effect = [json.loads(slurp_fixture('json/list-courses-input.json'))]
    expected_output = json.loads(slurp_fixture('json/list-courses-output.json'))
    expected_output = expected_output['courses']
    output = course.list_courses()
    assert (expected_output == output)
inputs: Complete the below
def long_substr(data):

    ''''https://stackoverflow.com/a/2894073'
    '''
targets: substr = ''
    if ((len(data) > 1) and (len(data[0]) > 0)):
        for i in range(len(data[0])):
            for j in range(((len(data[0]) - i) + 1)):
                if ((j > len(substr)) and is_substr(data[0][i:(i + j)], data)):
                    substr = data[0][i:(i + j)]
    return substr
inputs: def api_idor(SCAN_REQUESTS, URLS_CONF):
targets: """1. Without Cookie and Auth headers
    2. With a Valid Cookie and Auth header of another user
    TO-DO:
    Add feature to allow user to select session parameter
    """
    global STATUS, ACCEPTED_CONTENT_TYPE
    print '\n[INFO]    Performing    API    IDOR    Checks'
    result = []
    try:
        (LOGIN_API, PIN_API, REGISTER_API, LOGOUT_API) = getAPI(URLS_CONF)
        LOGIN_API_COMBINED = (LOGIN_API + PIN_API)
        LOGIN_API_COMBINED = list(set(LOGIN_API_COMBINED))
        (url_n_cookie_pair, url_n_header_pair) = getAuthTokensTwoUser(SCAN_REQUESTS, URLS_CONF)
        "'\n                                IDOR    Checks    starts    now.\n                                "
        for request in SCAN_REQUESTS:
            url = request['url']
            if ((url not in LOGIN_API_COMBINED) and (url not in REGISTER_API)):
                req1 = req_cookie = req_authheader = request
                res1 = HTTP_Request(req1)
                if res1:
                    if res1.headers:
                        y = 'nil'
                        if ('Content-Type' in res1.headers):
                            y = 'Content-Type'
                        elif ('content-type' in res1.headers):
                            y = 'content-type'
                        if (y != 'nil'):
                            content_typ = res1.headers[y]
                            if (';' in content_typ):
                                content_typ = content_typ.split(';')[0]
                            if (content_typ in ACCEPTED_CONTENT_TYPE):
                                if (getProtocolDomain(url) in url_n_cookie_pair):
                                    cookie = 'nil'
                                    if ('Cookie' in req_cookie['headers']):
                                        cookie = 'Cookie'
                                    elif ('cookie' in req_cookie['headers']):
                                        cookie = 'cookie'
                                    if (cookie != 'nil'):
                                        cookies_pair = url_n_cookie_pair[getProtocolDomain(url)]
                                        for (cookie1, cookie2) in cookies_pair.items():
                ...
inputs: I wrote the below code

    def converter(self, spec_like, *args, **kwargs):
        if (not isinstance(spec_like, spack.spec.Spec)):
            spec_like = spack.spec.Spec(spec_like)
        return function(self, spec_like, *args, **kwargs)
    return converter


What's a good function header?
targets: def _autospec(function):
inputs: Complete the below
def expose(func=None, alias=None):

    ''''Expose the function, optionally providing an alias or set of aliases.'
    '''
targets: def expose_(func):
        func.exposed = True
        if (alias is not None):
            if isinstance(alias, basestring):
                parents[alias.replace('.', '_')] = func
            else:
                for a in alias:
                    parents[a.replace('.', '_')] = func
        return func
    import sys
    import types
    if isinstance(func, (types.FunctionType, types.MethodType)):
        if (alias is None):
            func.exposed = True
            return func
        else:
            parents = sys._getframe(1).f_locals
            return expose_(func)
    elif (func is None):
        if (alias is None):
            parents = sys._getframe(1).f_locals
            return expose_
        else:
            parents = sys._getframe(1).f_locals
            return expose_
    else:
        parents = sys._getframe(1).f_locals
        alias = func
        return expose_
inputs: I wrote the below code

    name = getattr(obj, 'name', None)
    if (name and isinstance(name, basestring) and (name[0] != '<') and (name[(-1)] != '>')):
        return os.path.basename(name)


What's a good function header?
targets: def guess_filename(obj):
inputs: def getCraftedTextFromText(text, repository=None):
targets: """Preface and convert an svg text.
    """
    if gcodec.isProcedureDoneOrFileIsEmpty(text, 'preface'):
        return text
    if (repository == None):
        repository = settings.getReadRepository(PrefaceRepository())
    return PrefaceSkein().getCraftedGcode(repository, text)
inputs: def getargvalues(frame):
targets: """Get information about arguments passed into a particular frame.
    A tuple of four things is returned: (args, varargs, varkw, locals).
    \args\ is a list of the argument names (it may contain nested lists).
    \varargs\ and \varkw\ are the names of the * and ** arguments or None.
    \locals\ is the locals dictionary of the given frame.
    """
    (args, varargs, varkw) = getargs(frame.f_code)
    return ArgInfo(args, varargs, varkw, frame.f_locals)
inputs: def _arrays_to_mgr(arrays, arr_names, index, columns, dtype=None):
targets: """Segregate Series based on type and coerce into matrices.
    Needs to handle a lot of exceptional cases.
    """
    if (index is None):
        index = extract_index(arrays)
    else:
        index = _ensure_index(index)
    arrays = _homogenize(arrays, index, dtype)
    axes = [_ensure_index(columns), _ensure_index(index)]
    return create_block_manager_from_arrays(arrays, arr_names, axes)
inputs: I wrote the below code

    batch_job = GetBatchJob(client, batch_job_id)
    if (batch_job['status'] == 'CANCELED'):
        raise Exception(('Batch    Job    with    ID    "%s"    was    canceled    before    completing.' % batch_job_id))
    poll_attempt = 0
    while ((poll_attempt in range(max_poll_attempts)) and (batch_job['status'] in PENDING_STATUSES)):
        sleep_interval = ((30 * (2 ** poll_attempt)) + (random.randint(0, 10000) / 1000))
        print ('Batch    Job    not    ready,    sleeping    for    %s    seconds.' % sleep_interval)
        time.sleep(sleep_interval)
        batch_job = GetBatchJob(client, batch_job_id)
        poll_attempt += 1
        if ('downloadUrl' in batch_job):
            url = batch_job['downloadUrl']['url']
            print ('Batch    Job    with    Id    "%s",    Status    "%s",    and    DownloadUrl    "%s"    ready.' % (batch_job['id'], batch_job['status'], url))
            return url
    print ('BatchJob    with    ID    "%s"    is    being    canceled    because    it    was    in    a    pending    state    after    polling    %d    times.' % (batch_job_id, max_poll_attempts))
    CancelBatchJob(client, batch_job)


What's a good function header?
targets: def GetBatchJobDownloadUrlWhenReady(client, batch_job_id, max_poll_attempts=MAX_POLL_ATTEMPTS):
inputs: def equateZ(point, returnValue):
targets: """Get equation for rectangular z.
    """
    point.z = returnValue
inputs: Complete the below
def __virtual__():

    ''''Only works on Windows systems.'
    '''
targets: if (not salt.utils.platform.is_windows()):
        return (False, 'Module    win_snmp:    Requires    Windows')
    if (not __salt__['reg.read_value'](_HKEY, _SNMP_KEY)['success']):
        return (False, 'Module    win_snmp:    SNMP    not    installed')
    return __virtualname__
inputs: I wrote the below code

    kit_dir = op.join(io_dir, 'kit', 'tests', 'data')
    sqd_path = op.join(kit_dir, 'test.sqd')
    mrk_path = op.join(kit_dir, 'test_mrk.sqd')
    elp_path = op.join(kit_dir, 'test_elp.txt')
    hsp_path = op.join(kit_dir, 'test_hsp.txt')
    raw_kit = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path)
    with warnings.catch_warnings(record=True):
        assert_raises(RuntimeError, maxwell_filter, raw_kit)
    raw_sss = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True)
    _assert_n_free(raw_sss, 65, 65)
    raw_sss_auto = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True, mag_scale='auto')
    assert_allclose(raw_sss._data, raw_sss_auto._data)
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            assert_raises(RuntimeError, maxwell_filter, raw_kit, ignore_ref=True, regularize=None)
            raw_sss = maxwell_filter(raw_kit, origin='auto', ignore_ref=True, bad_condition='warning', verbose='warning')
    log_file = log_file.getvalue()
    assert_true(('badly    conditioned' in log_file))
    assert_true(('more    than    20    mm    from' in log_file))
    _assert_n_free(raw_sss, 28, 34)
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            raw_sss = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True, bad_condition='warning', regularize=None, verbose='warning')
    log_file = log_file.getvalue()
    assert_true(('badly    conditioned' in log_file))
    _assert_n_free(raw_sss, 80)
    with warnings.catch_warnings(record=True):
        with catch_logging() as log_file:
            raw_sss = maxwell_filter(raw_kit, origin=(0.0, 0.0, 0.04), ignore_ref=True, verbose=True)
    log_file = log_file.getvalue()
    assert_true(('badly    conditioned' not in log_file))
    _assert_n_free(raw_sss, 65)
    bti_dir = op.join(io_dir, 'bti', 'tests', 'data')
    bti_pdf = op.join(bti_dir, 'test_pdf_linux')
    bti_config = op.join(bti_dir, 'test_config_linux')
    bti_hs =...

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

    import frappe
    from jinja2 import TemplateSyntaxError
    jenv = get_jenv()
    try:
        jenv.from_string(html)
    except TemplateSyntaxError as e:
        frappe.msgprint(u'Line    {}:    {}'.format(e.lineno, e.message))
        frappe.throw(frappe._(u'Syntax    error    in    template'))


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

    _active.value = gettext_module.NullTranslations()
    _active.value.to_language = (lambda *args: None)


What's a good function header?
targets: def deactivate_all():
inputs: Complete the below
def main(argv, version=DEFAULT_VERSION):

    ''''Install or upgrade setuptools and EasyInstall'
    '''
targets: try:
        import setuptools
    except ImportError:
        egg = None
        try:
            egg = download_setuptools(version, delay=0)
            sys.path.insert(0, egg)
            from setuptools.command.easy_install import main
            return main((list(argv) + [egg]))
        finally:
            if (egg and os.path.exists(egg)):
                os.unlink(egg)
    else:
        if (setuptools.__version__ == '0.0.1'):
            use_setuptools(version)
    req = ('setuptools>=' + version)
    import pkg_resources
    try:
        pkg_resources.require(req)
    except pkg_resources.VersionConflict:
        try:
            from setuptools.command.easy_install import main
        except ImportError:
            from easy_install import main
        main((list(argv) + [download_setuptools(delay=0)]))
        sys.exit(0)
    else:
        if argv:
            from setuptools.command.easy_install import main
            main(argv)
        else:
            print 'Setuptools    version', version, 'or    greater    has    been    installed.'
            print '(Run    "ez_setup.py    -U    setuptools"    to    reinstall    or    upgrade.)'
inputs: def failureFromJSON(failureDict):
targets: """Load a L{Failure} from a dictionary deserialized from JSON.
    @param failureDict: a JSON-deserialized object like one previously returned
    by L{failureAsJSON}.
    @type failureDict: L{dict} mapping L{unicode} to attributes
    @return: L{Failure}
    @rtype: L{Failure}
    """
    newFailure = getattr(Failure, '__new__', None)
    if (newFailure is None):
        f = types.InstanceType(Failure)
    else:
        f = newFailure(Failure)
    if (not _PY3):
        failureDict = asBytes(failureDict)
    typeInfo = failureDict['type']
    failureDict['type'] = type(typeInfo['__name__'], (), typeInfo)
    f.__dict__ = failureDict
    return f
inputs: I wrote the below code

    a = AddressList(address)
    lst = a.addresslist
    if (not lst):
        return (None, None)
    return lst[0]


What's a good function header?
targets: def parseaddr(address):
inputs: def _CheckDocumentId(doc_id):
targets: """Checks doc_id is a valid document identifier, and returns it.
    Document ids must be visible printable ASCII and not start with \!\.
    """
    _ValidateString(doc_id, 'doc_id', MAXIMUM_DOCUMENT_ID_LENGTH)
    _ValidateVisiblePrintableAsciiNotReserved(doc_id, 'doc_id')
    return doc_id
inputs: I wrote the below code

    level_tags = constants.DEFAULT_TAGS.copy()
    level_tags.update(getattr(settings, 'MESSAGE_TAGS', {}))
    return level_tags


What's a good function header?
targets: def get_level_tags():
inputs: Complete the below
def get_nexusvlan_binding(vlan_id, switch_ip):

    ''''Lists a vlan and switch binding'
    '''
targets: LOG.debug(_('get_nexusvlan_binding()    called'))
    session = db.get_session()
    try:
        binding = session.query(nexus_models_v2.NexusPortBinding).filter_by(vlan_id=vlan_id).filter_by(switch_ip=switch_ip).all()
        return binding
    except exc.NoResultFound:
        raise c_exc.NexusPortBindingNotFound(vlan_id=vlan_id)
inputs: I wrote the below code

    kwargs = {}
    if name:
        kwargs['name'] = name
    return url(('^%s$' % path), views.commonplace, {'repo': 'fireplace'}, **kwargs)


What's a good function header?
targets: def fireplace_route(path, name=None):
inputs: Complete the below
def _MatchPostfix(postfix_props, index_props):

    ''''Matches a postfix constraint with an existing index.
    postfix_props constraints are specified through a list of:
    - sets of string: any order any direction;
    - list of tuples(string, direction): the given order, and, if specified, the
    given direction.
    For example:
    [set(\'A\', \'B\'), [(\'C\', None), (\'D\', ASC)]]
    matches:
    [(\'F\', ASC), (\'B\', ASC), (\'A\', DESC), (\'C\', DESC), (\'D\', ASC)]
    with a return value of [(\'F\', ASC)], but does not match:
    [(\'F\', ASC), (\'A\', DESC), (\'C\', DESC), (\'D\', ASC)]
    [(\'B\', ASC), (\'F\', ASC), (\'A\', DESC), (\'C\', DESC), (\'D\', ASC)]
    [(\'F\', ASC), (\'B\', ASC), (\'A\', DESC), (\'C\', DESC), (\'D\', DESC)]
    Args:
    postfix_props: A tuple of sets and lists, as output by
    CompositeIndexForQuery. They should define the requirements for the
    postfix of the index.
    index_props: A list of tuples (property_name, property_direction), that
    define the index to try and match.
    Returns:
    The list of tuples that define the prefix properties in the given index.
    None if the constraints could not be satisfied.'
    '''
targets: index_props_rev = reversed(index_props)
    for property_group in reversed(postfix_props):
        index_group_iter = itertools.islice(index_props_rev, len(property_group))
        if isinstance(property_group, (frozenset, set)):
            index_group = set((prop for (prop, _) in index_group_iter))
            if (index_group != property_group):
                return None
        else:
            index_group = list(index_group_iter)
            if (len(index_group) != len(property_group)):
                return None
            for ((index_prop, index_dir), (prop, direction)) in itertools.izip(index_group, reversed(property_group)):
                if ((index_prop != prop) or (direction and (index_dir != direction))):
                    return None
    remaining = list(index_props_rev)
    remaining.reverse()
    return remaining
inputs: def cloudnetwork(vm_):
targets: """Determine if we should use an extra network to bootstrap
    Either \False\ (default) or \True\.
    """
    return config.get_cloud_config_value('cloudnetwork', vm_, __opts__, default=False, search_global=False)
inputs: Complete the below
def Timer(*args, **kwargs):

    ''''Factory function to create a Timer object.
    Timers call a function after a specified number of seconds:
    t = Timer(30.0, f, args=[], kwargs={})
    t.start()
    t.cancel()     # stop the timer\'s action if it\'s still waiting'
    '''
targets: return _Timer(*args, **kwargs)
inputs: def changes_command(args):
targets: """List all changes records for a zone.
    """
    changes = list_changes(args.project_id, args.name)
    for change in changes:
        print change
inputs: Complete the below
def is_connection_dropped(conn):

    ''''Returns True if the connection is dropped and should be closed.
    :param conn:
    :class:`httplib.HTTPConnection` object.
    Note: For platforms like AppEngine, this will always return ``False`` to
    let the platform handle connection recycling transparently for us.'
    '''
targets: sock = getattr(conn, 'sock', False)
    if (not sock):
        return False
    if (not poll):
        if (not select):
            return False
        try:
            return select([sock], [], [], 0.0)[0]
        except SocketError:
            return True
    p = poll()
    p.register(sock, POLLIN)
    for (fno, ev) in p.poll(0.0):
        if (fno == sock.fileno()):
            return True
inputs: Complete the below
@helpers.intercept_errors(errors.UserAPIInternalError, ignore_errors=[errors.UserAPIRequestError])
def activate_account(activation_key):

    ''''Activate a user\'s account.
    Args:
    activation_key (unicode): The activation key the user received via email.
    Returns:
    None
    Raises:
    errors.UserNotAuthorized
    errors.UserAPIInternalError: the operation failed due to an unexpected error.'
    '''
targets: try:
        registration = Registration.objects.get(activation_key=activation_key)
    except Registration.DoesNotExist:
        raise errors.UserNotAuthorized
    else:
        registration.activate()
inputs: Complete the below
def _launch_reaper(id, pid):

    ''''Start a process that will free a lock when process pid terminates'
    '''
targets: from subprocess import Popen, PIPE
    me = __file__
    if me.endswith('.pyc'):
        me = me[:(-1)]
    myloc = os.path.dirname(me)
    if (not myloc):
        myloc = os.getcwd()
    reaper_cmd = os.path.join(myloc, 'run_on_me_or_pid_quit')
    Popen([reaper_cmd, str(pid), me, '--free', str(id)], stdout=open('/dev/null', 'w'))
inputs: Complete the below
@constructor
def prod(input, axis=None, dtype=None, keepdims=False, acc_dtype=None, no_zeros_in_input=False):

    ''''Computes the product along the given axis(es) of a tensor `input`.
    When axis is None (the default value), the product is performed
    over the flattened tensor.
    For full documentation see ``tensor.elemwise.Prod``.
    Parameters
    keepdims: bool
    If this is set to True, the axes which are reduced are left in
    the result as dimensions with size one. With this option, the result
    will broadcast correctly against the original tensor.'
    '''
targets: out = elemwise.Prod(axis, dtype=dtype, acc_dtype=acc_dtype, no_zeros_in_input=no_zeros_in_input)(input)
    if keepdims:
        out = makeKeepDims(input, out, axis)
    return out
inputs: Complete the below
def discuss(r, **attr):

    ''''Custom Method to manage the discussion of a Post'
    '''
targets: id = r.id
    rheader = s3db.cms_rheader(r)
    ckeditor = URL(c='static', f='ckeditor', args='ckeditor.js')
    s3.scripts.append(ckeditor)
    adapter = URL(c='static', f='ckeditor', args=['adapters', 'jquery.js'])
    s3.scripts.append(adapter)
    js = ''.join(('i18n.reply="', str(T('Reply')), '"\nvar    img_path=S3.Ap.concat(\'/static/img/jCollapsible/\')\nvar    ck_config={toolbar:[[\'Bold\',\'Italic\',\'-\',\'NumberedList\',\'BulletedList\',\'-\',\'Link\',\'Unlink\',\'-\',\'Smiley\',\'-\',\'Source\',\'Maximize\']],toolbarCanCollapse:false,removePlugins:\'elementspath\'}\nfunction    comment_reply(id){\n    $(\'#cms_comment_post_id__row\').hide()\n    $(\'#cms_comment_post_id__row1\').hide()\n    $(\'#comment-title\').html(i18n.reply)\n    $(\'#cms_comment_body\').ckeditorGet().destroy()\n    $(\'#cms_comment_body\').ckeditor(ck_config)\n    $(\'#comment-form\').insertAfter($(\'#comment-\'+id))\n    $(\'#cms_comment_parent\').val(id)\n    var    post_id=$(\'#comment-\'+id).attr(\'post_id\')\n    $(\'#cms_comment_post_id\').val(post_id)\n}'))
    s3.js_global.append(js)
    response.view = 'cms/discuss.html'
    return dict(rheader=rheader, id=id)
inputs: def get_item_workdays(scorecard):
targets: """Gets the number of days in this period
    """
    supplier = frappe.get_doc(u'Supplier', scorecard.supplier)
    total_item_days = frappe.db.sql(u'\n DCTB  DCTB  DCTB SELECT\n DCTB  DCTB  DCTB  DCTB SUM(DATEDIFF(    %(end_date)s,    po_item.schedule_date)    *    (po_item.qty))\n DCTB  DCTB  DCTB FROM\n DCTB  DCTB  DCTB  DCTB `tabPurchase    Order    Item`    po_item,\n DCTB  DCTB  DCTB  DCTB `tabPurchase    Order`    po\n DCTB  DCTB  DCTB WHERE\n DCTB  DCTB  DCTB  DCTB po.supplier    =    %(supplier)s\n DCTB  DCTB  DCTB  DCTB AND    po_item.received_qty    <    po_item.qty\n DCTB  DCTB  DCTB  DCTB AND    po_item.schedule_date    BETWEEN    %(start_date)s    AND    %(end_date)s\n DCTB  DCTB  DCTB  DCTB AND    po_item.parent    =    po.name', {u'supplier': supplier.name, u'start_date': scorecard.start_date, u'end_date': scorecard.end_date}, as_dict=0)[0][0]
    if (not total_item_days):
        total_item_days = 0
    return total_item_days
inputs: I wrote the below code

    if ((rhi == (rlo + 1)) and (chi == (clo + 1))):
        return cellnameabs(rlo, clo)
    return ('%s:%s' % (cellnameabs(rlo, clo), cellnameabs((rhi - 1), (chi - 1))))


What's a good function header?
targets: def rangename2d(rlo, rhi, clo, chi):
inputs: Complete the below
def conv_block(inputs, filters, dilation_rates_and_kernel_sizes, **kwargs):

    ''''A block of standard 2d convolutions.'
    '''
targets: return conv_block_internal(conv, inputs, filters, dilation_rates_and_kernel_sizes, **kwargs)
inputs: Complete the below
def incoming():

    ''''Incoming Shipments for Sites
    Used from Requests rheader when looking at Transport Status'
    '''
targets: return s3db.inv_incoming()
inputs: def inject_content_head_last(html, content):
targets: """å°ææ¬åå®¹æå¥å°headçå°Ÿéš
    :type html: str
    :type content: str
    :rtype: str
    """
    head_end_pos = html.find('</head')
    if (head_end_pos == (-1)):
        return html
    return ((html[:head_end_pos] + content) + html[head_end_pos:])
inputs: I wrote the below code

    attributes = []
    class_vars = []
    metas = []
    variables_seen = set()
    for table in tables:
        attributes.extend((v for v in table.domain.attributes if (v not in variables_seen)))
        variables_seen.update(table.domain.attributes)
        class_vars.extend((v for v in table.domain.class_vars if (v not in variables_seen)))
        variables_seen.update(table.domain.class_vars)
        metas.extend((v for v in table.domain.metas if (v not in variables_seen)))
        variables_seen.update(table.domain.metas)
    domain = Orange.data.Domain(attributes, class_vars, metas)
    tables = [tab.transform(domain) for tab in tables]
    return tables[0].concatenate(tables, axis=0)


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

    Distance.__dict__['_weights'].computed = False


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

    if hasattr(shutil, 'which'):
        return shutil.which(cmd, path=path)
    elif ((path is None) and (os.environ.get('PATH') is None)):
        return None
    else:
        return find_executable(cmd, path=path)


What's a good function header?
targets: def which(cmd, path=None):
inputs: I wrote the below code

    if (len(a) != len(b)):
        return False
    result = 0
    for (x, y) in zip(a, b):
        result |= (ord(x) ^ ord(y))
    return (result == 0)


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

    if (not result):
        raise GEOSException(('Error    encountered    checking    Coordinate    Sequence    returned    from    GEOS    C    function    "%s".' % func.__name__))
    return result


What's a good function header?
targets: def check_cs_ptr(result, func, cargs):
inputs: Complete the below
def almost_equal_ignore_nan(a, b, rtol=None, atol=None):

    ''''Test that two NumPy arrays are almost equal (ignoring NaN in either array).
    Combines a relative and absolute measure of approximate eqality.
    If either the relative or absolute check passes, the arrays are considered equal.
    Including an absolute check resolves issues with the relative check where all
    array values are close to zero.
    Parameters
    a : np.ndarray
    b : np.ndarray
    rtol : None or float
    The relative threshold. Default threshold will be used if set to ``None``.
    atol : None or float
    The absolute threshold. Default threshold will be used if set to ``None``.'
    '''
targets: a = np.copy(a)
    b = np.copy(b)
    nan_mask = np.logical_or(np.isnan(a), np.isnan(b))
    a[nan_mask] = 0
    b[nan_mask] = 0
    return almost_equal(a, b, rtol, atol)
inputs: I wrote the below code

    f = open_file(filename, mode)
    try:
        return f.write(value)
    finally:
        f.close()


What's a good function header?
targets: def write_file(filename, value, mode='w'):
inputs: def getopt(args, shortopts, longopts=[]):
targets: """getopt(args, options[, long_options]) -> opts, args
    Parses command line options and parameter list.  args is the
    argument list to be parsed, without the leading reference to the
    running program.  Typically, this means "sys.argv[1:]".  shortopts
    is the string of option letters that the script wants to
    recognize, with options that require an argument followed by a
    colon (i.e., the same format that Unix getopt() uses).  If
    specified, longopts is a list of strings with the names of the
    long options which should be supported.  The leading \--\
    characters should not be included in the option name.  Options
    which require an argument should be followed by an equal sign
    The return value consists of two elements: the first is a list of
    (option, value) pairs; the second is the list of program arguments
    left after the option list was stripped (this is a trailing slice
    of the first argument).  Each option-and-value pair returned has
    the option as its first element, prefixed with a hyphen (e.g.,
    \-x\), and the option argument as its second element, or an empty
    string if the option has no argument.  The options occur in the
    list in the same order in which they were found, thus allowing
    multiple occurrences.  Long and short options may be mixed.
    """
    opts = []
    if (type(longopts) == type('')):
        longopts = [longopts]
    else:
        longopts = list(longopts)
    while (args and args[0].startswith('-') and (args[0] != '-')):
        if (args[0] == '--'):
            args = args[1:]
            break
        if args[0].startswith('--'):
            (opts, args) = do_longs(opts, args[0][2:], longopts, args[1:])
        else:
            (opts, args) = do_shorts(opts, args[0][1:], shortopts, args[1:])
    return (opts, args)