Muennighoff/xP3x-sample huggingface dataset:
inputs: Complete the below
def get_preprocessing(name, is_training=False):

    ''''Returns preprocessing_fn(image, height, width, **kwargs).
    Args:
    name: The name of the preprocessing function.
    is_training: `True` if the model is being used for training and `False`
    otherwise.
    Returns:
    preprocessing_fn: A function that preprocessing a single image (pre-batch).
    It has the following signature:
    image = preprocessing_fn(image, output_height, output_width, ...).
    Raises:
    ValueError: If Preprocessing `name` is not recognized.'
    '''
targets: preprocessing_fn_map = {'inception': inception_preprocessing, 'inception_v1': inception_preprocessing, 'inception_v2': inception_preprocessing, 'inception_v3': inception_preprocessing, 'inception_v4': inception_preprocessing, 'inception_resnet_v2': inception_preprocessing}
    if (name not in preprocessing_fn_map):
        raise ValueError(('Preprocessing    name    [%s]    was    not    recognized' % name))
    def preprocessing_fn(image, output_height, output_width, **kwargs):
        return preprocessing_fn_map[name].preprocess_image(image, output_height, output_width, is_training=is_training, **kwargs)
    return preprocessing_fn
inputs: Complete the below
def diagonal(a, offset=0, axis1=0, axis2=1):

    ''''A helper function for `theano.tensor.ExtractDiag`. It accepts tensor with
    `ndim >= 2` as input. The name `diagonal` is just meant to keep it
    consistent with numpy.
    Parameters
    a : symbolic tensor
    offset : int
    offset
    axis1 : int
    axis2 : int
    Returns
    tensor : symbolic tensor'
    '''
targets: return ExtractDiag(offset, axis1, axis2)(a)
inputs: Complete the below
def directional_variance_i(x_i, w):

    ''''the variance of the row x_i in the direction w'
    '''
targets: return (dot(x_i, direction(w)) ** 2)
inputs: I wrote the below code

    dirs = path.parts
    return dirs[(dirs.index('build') + 1)]


What's a good function header?
targets: def _get_play_name(path):
inputs: def get_lcm_config():
targets: """Get the current Local Configuration Manager settings
    Returns:
    dict: A dictionary representing the Local Configuration Manager settings
    on the machine
    CLI Example:
    .. code-block:: bash
    salt \*\ dsc.get_lcm_config
    """
    cmd = 'Get-DscLocalConfigurationManager    |    Select-Object    -Property    ConfigurationModeFrequencyMins,    LCMState,    RebootNodeIfNeeded,    ConfigurationMode,    ActionAfterReboot,    RefreshMode,    CertificateID,    ConfigurationID,    RefreshFrequencyMins,    AllowModuleOverwrite,    DebugMode,    StatusRetentionTimeInDays    '
    return _pshell(cmd)
inputs: def choose_names(installer):
targets: """Display screen to select domains to validate.
    :param installer: An installer object
    :type installer: :class:`certbot.interfaces.IInstaller`
    :returns: List of selected names
    :rtype: `list` of `str`
    """
    if (installer is None):
        logger.debug('No    installer,    picking    names    manually')
        return _choose_names_manually()
    domains = list(installer.get_all_names())
    names = get_valid_domains(domains)
    if (not names):
        return _choose_names_manually('No    names    were    found    in    your    configuration    files.    ')
    (code, names) = _filter_names(names)
    if ((code == display_util.OK) and names):
        return names
    else:
        return []
inputs: def get_collection_ids_matching_query(query_string, cursor=None):
targets: """Returns a list with all collection ids matching the given search query
    string, as well as a search cursor for future fetches.
    Args:
    query_string: str. The search query string.
    cursor: str or None. Cursor indicating where, in the list of
    collections, to start the search from.
    Returns:
    2-tuple of (returned_collection_ids, search_cursor), where:
    returned_collection_ids : list(str). A list with all collection ids
    matching the given search query string, as well as a search
    cursor for future fetches. The list contains exactly
    feconf.SEARCH_RESULTS_PAGE_SIZE results if there are at least
    that many, otherwise it contains all remaining results. (If this
    behaviour does not occur, an error will be logged.)
    search_cursor: str. Search cursor for future fetches.
    """
    returned_collection_ids = []
    search_cursor = cursor
    for _ in range(MAX_ITERATIONS):
        remaining_to_fetch = (feconf.SEARCH_RESULTS_PAGE_SIZE - len(returned_collection_ids))
        (collection_ids, search_cursor) = search_collections(query_string, remaining_to_fetch, cursor=search_cursor)
        invalid_collection_ids = []
        for (ind, model) in enumerate(collection_models.CollectionSummaryModel.get_multi(collection_ids)):
            if (model is not None):
                returned_collection_ids.append(collection_ids[ind])
            else:
                invalid_collection_ids.append(collection_ids[ind])
        if ((len(returned_collection_ids) == feconf.SEARCH_RESULTS_PAGE_SIZE) or (search_cursor is None)):
            break
        else:
            logging.error(('Search    index    contains    stale    collection    ids:    %s' % ',    '.join(invalid_collection_ids)))
    if ((len(returned_collection_ids) < feconf.SEARCH_RESULTS_PAGE_SIZE) and (search_cursor is not None)):
        logging.error(('Could    not    fulfill    search    request    for    query    string    %s;    at    least    %s    retries    were    needed.' % (query_string, MAX_ITERATIONS)))
    return (returned_collection_ids, search_cursor)
inputs: Complete the below
@library.global_function
def url(viewname, *args, **kwargs):

    ''''Helper for Django\'s ``reverse`` in templates.
    Uses sumo\'s locale-aware reverse.'
    '''
targets: locale = kwargs.pop('locale', None)
    return reverse(viewname, locale=locale, args=args, kwargs=kwargs)
inputs: Complete the below
def libvlc_media_discoverer_is_running(p_mdis):

    ''''Query if media service discover object is running.
    @param p_mdis: media service discover object.
    @return: true if running, false if not \libvlc_return_bool.'
    '''
targets: f = (_Cfunctions.get('libvlc_media_discoverer_is_running', None) or _Cfunction('libvlc_media_discoverer_is_running', ((1,),), None, ctypes.c_int, MediaDiscoverer))
    return f(p_mdis)
inputs: Complete the below
def check_symmetric(array, tol=1e-10, raise_warning=True, raise_exception=False):

    ''''Make sure that array is 2D, square and symmetric.
    If the array is not symmetric, then a symmetrized version is returned.
    Optionally, a warning or exception is raised if the matrix is not
    symmetric.
    Parameters
    array : nd-array or sparse matrix
    Input object to check / convert. Must be two-dimensional and square,
    otherwise a ValueError will be raised.
    tol : float
    Absolute tolerance for equivalence of arrays. Default = 1E-10.
    raise_warning : boolean (default=True)
    If True then raise a warning if conversion is required.
    raise_exception : boolean (default=False)
    If True then raise an exception if array is not symmetric.
    Returns
    array_sym : ndarray or sparse matrix
    Symmetrized version of the input array, i.e. the average of array
    and array.transpose(). If sparse, then duplicate entries are first
    summed and zeros are eliminated.'
    '''
targets: if ((array.ndim != 2) or (array.shape[0] != array.shape[1])):
        raise ValueError('array    must    be    2-dimensional    and    square.    shape    =    {0}'.format(array.shape))
    if sp.issparse(array):
        diff = (array - array.T)
        if (diff.format not in ['csr', 'csc', 'coo']):
            diff = diff.tocsr()
        symmetric = np.all((abs(diff.data) < tol))
    else:
        symmetric = np.allclose(array, array.T, atol=tol)
    if (not symmetric):
        if raise_exception:
            raise ValueError('Array    must    be    symmetric')
        if raise_warning:
            warnings.warn('Array    is    not    symmetric,    and    will    be    converted    to    symmetric    by    average    with    its    transpose.')
        if sp.issparse(array):
            conversion = ('to' + array.format)
            array = getattr((0.5 * (array + array.T)), conversion)()
        else:
            array = (0.5 * (array + array.T))
    return array
inputs: I wrote the below code

    mc_vars = mailchimp.listMergeVars(id=list_id)
    mc_names = set((v['name'] for v in mc_vars))
    mc_merge = mailchimp.listMergeVarAdd
    tags = [v['tag'] for v in mc_vars]
    for name in tag_names:
        tag = name_to_tag(name)
        if ('FULLNAME' not in tags):
            result = mc_merge(id=list_id, tag='FULLNAME', name='Full    Name', options={'field_type': 'text', 'public': False})
            tags.append('FULLNAME')
            log.debug(result)
        if ((name not in mc_names) and (tag not in ['EMAIL', 'FULLNAME'])):
            ftype = FIELD_TYPES.get(name, 'number')
            result = mc_merge(id=list_id, tag=tag, name=name, options={'field_type': ftype, 'public': False})
            tags.append(tag)
            log.debug(result)


What's a good function header?
targets: def update_merge_tags(mailchimp, list_id, tag_names):
inputs: def load_regions():
targets: """Actually load the region/endpoint information from the JSON files.
    By default, this loads from the default included ``boto/endpoints.json``
    file.
    Users can override/extend this by supplying either a ``BOTO_ENDPOINTS``
    environment variable or a ``endpoints_path`` config variable, either of
    which should be an absolute path to the user\s JSON file.
    :returns: The endpoints data
    :rtype: dict
    """
    endpoints = _load_builtin_endpoints()
    additional_path = None
    if os.environ.get('BOTO_ENDPOINTS'):
        additional_path = os.environ['BOTO_ENDPOINTS']
    elif boto.config.get('Boto', 'endpoints_path'):
        additional_path = boto.config.get('Boto', 'endpoints_path')
    if additional_path:
        additional = load_endpoint_json(additional_path)
        endpoints = merge_endpoints(endpoints, additional)
    return endpoints
inputs: @core_helper
def url_for_static(*args, **kw):
targets: """Returns the URL for static content that doesn\t get translated (eg CSS)
    It\ll raise CkanUrlException if called with an external URL
    This is a wrapper for :py:func:`routes.url_for`
    """
    if args:
        url = urlparse.urlparse(args[0])
        url_is_external = ((url.scheme != '') or (url.netloc != ''))
        if url_is_external:
            CkanUrlException = ckan.exceptions.CkanUrlException
            raise CkanUrlException('External    URL    passed    to    url_for_static()')
    return url_for_static_or_external(*args, **kw)
inputs: def libvlc_media_get_type(p_md):
targets: """Get the media type of the media descriptor object.
    @param p_md: media descriptor object.
    @return: media type.
    @version: LibVLC 3.0.0 and later. See libvlc_media_type_t.
    """
    f = (_Cfunctions.get('libvlc_media_get_type', None) or _Cfunction('libvlc_media_get_type', ((1,),), None, MediaType, Media))
    return f(p_md)
inputs: def __virtual__():
targets: """Load only on Windows
    """
    if (salt.utils.platform.is_windows() and HAS_WIN32):
        return 'win_path'
    return (False, 'Module    win_path:    module    only    works    on    Windows    systems')
inputs: I wrote the below code

    if gcodec.isProcedureDoneOrFileIsEmpty(gcodeText, 'multiply'):
        return gcodeText
    if (repository == None):
        repository = settings.getReadRepository(MultiplyRepository())
    if (not repository.activateMultiply.value):
        return gcodeText
    return MultiplySkein().getCraftedGcode(gcodeText, repository)


What's a good function header?
targets: def getCraftedTextFromText(gcodeText, repository=None):
inputs: def commit_on_success(using=None):
targets: """This decorator activates commit on response. This way, if the view function
    runs successfully, a commit is made; if the viewfunc produces an exception,
    a rollback is made. This is one of the most common ways to do transaction
    control in Web apps.
    """
    warnings.warn('commit_on_success    is    deprecated    in    favor    of    atomic.', PendingDeprecationWarning, stacklevel=2)
    def entering(using):
        enter_transaction_management(using=using)
    def exiting(exc_type, using):
        try:
            if (exc_type is not None):
                if is_dirty(using=using):
                    rollback(using=using)
            elif is_dirty(using=using):
                try:
                    commit(using=using)
                except:
                    rollback(using=using)
                    raise
        finally:
            leave_transaction_management(using=using)
    return _transaction_func(entering, exiting, using)
inputs: def command_copytree(args):
targets: """Copy one or more source directory(s) below a destination directory.
    Parts of the destination directory path are created if needed.
    Similar to the UNIX command: \cp -R srcdir destdir\
    """
    for srcdir in args.srcdirs:
        basename = os.path.basename(srcdir)
        destdir2 = os.path.normpath(os.path.join(args.destdir, basename))
        if os.path.exists(destdir2):
            shutil.rmtree(destdir2)
        sys.stdout.write(('copytree:    %s    =>    %s\n' % (srcdir, destdir2)))
        shutil.copytree(srcdir, destdir2)
    return 0
inputs: def CDLENGULFING(barDs, count):
targets: """Engulfing Pattern
    """
    return call_talib_with_ohlc(barDs, count, talib.CDLENGULFING)
inputs: Complete the below
def false(*args, **kwargs):

    ''''Always returns False'
    '''
targets: return False
inputs: def _symlink(src, dest):
targets: """Create a symlink.
    """
    try:
        os.symlink(src, dest)
    except OSError:
        warn(('Could    not    create    symbolic    link    %s.    Check    that    your    partition    handles    symbolic    links.    The    file    will    be    copied    instead.' % dest))
        shutil.copy(src, dest)
inputs: I wrote the below code

    if (argv is None):
        argv = sys.argv
    print(u'Fetching    samples    from:')
    for s in (test_lyrics.GOOGLE_SOURCES + test_lyrics.DEFAULT_SOURCES):
        print(s['url'])
        url = (s['url'] + s['path'])
        fn = test_lyrics.url_to_filename(url)
        if (not os.path.isfile(fn)):
            html = requests.get(url, verify=False).text
            with safe_open_w(fn) as f:
                f.write(html.encode('utf-8'))


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

    from tornado.ioloop import IOLoop
    @functools.wraps(method)
    def wrapper(self, *args, **kwargs):
        self._auto_finish = False
        with stack_context.ExceptionStackContext(self._stack_context_handle_exception):
            result = method(self, *args, **kwargs)
            if (result is not None):
                result = gen.convert_yielded(result)
                def future_complete(f):
                    f.result()
                    if (not self._finished):
                        self.finish()
                IOLoop.current().add_future(result, future_complete)
                return None
            return result
    return wrapper


What's a good function header?
targets: def asynchronous(method):
inputs: Complete the below
def demo():

    ''''A simple demonstration showing how to use canvas widgets.'
    '''
targets: def fill(cw):
        from random import randint
        cw['fill'] = ('#00%04d' % randint(0, 9999))
    def color(cw):
        from random import randint
        cw['color'] = ('#ff%04d' % randint(0, 9999))
    cf = CanvasFrame(closeenough=10, width=300, height=300)
    c = cf.canvas()
    ct3 = TextWidget(c, 'hiya    there', draggable=1)
    ct2 = TextWidget(c, 'o        o\n||\n___\n        U', draggable=1, justify='center')
    co = OvalWidget(c, ct2, outline='red')
    ct = TextWidget(c, 'o        o\n||\n\\___/', draggable=1, justify='center')
    cp = ParenWidget(c, ct, color='red')
    cb = BoxWidget(c, cp, fill='cyan', draggable=1, width=3, margin=10)
    equation = SequenceWidget(c, SymbolWidget(c, 'forall'), TextWidget(c, 'x'), SymbolWidget(c, 'exists'), TextWidget(c, 'y:    '), TextWidget(c, 'x'), SymbolWidget(c, 'notequal'), TextWidget(c, 'y'))
    space = SpaceWidget(c, 0, 30)
    cstack = StackWidget(c, cb, ct3, space, co, equation, align='center')
    foo = TextWidget(c, 'try    clicking\nand    dragging', draggable=1, justify='center')
    cs = SequenceWidget(c, cstack, foo)
    zz = BracketWidget(c, cs, color='green4', width=3)
    cf.add_widget(zz, 60, 30)
    cb.bind_click(fill)
    ct.bind_click(color)
    co.bind_click(fill)
    ct2.bind_click(color)
    ct3.bind_click(color)
    cf.mainloop()
inputs: I wrote the below code

    if ((len(args) == 1) and (args[0].type in (u'NUMBER', u'INTEGER'))):
        return min(1, max(0, args[0].value))


What's a good function header?
targets: def parse_alpha(args):
inputs: Complete the below
def _format_range_unified(start, stop):

    ''''Convert range to the "ed" format'
    '''
targets: beginning = (start + 1)
    length = (stop - start)
    if (length == 1):
        return '{}'.format(beginning)
    if (not length):
        beginning -= 1
    return '{},{}'.format(beginning, length)
inputs: I wrote the below code

    indent = None
    separators = (',', ':')
    if (current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug):
        indent = 2
        separators = (',    ', ':    ')
    if (args and kwargs):
        raise TypeError('jsonify()    behavior    undefined    when    passed    both    args    and    kwargs')
    elif (len(args) == 1):
        data = args[0]
    else:
        data = (args or kwargs)
    return current_app.response_class((dumps(data, indent=indent, separators=separators), '\n'), mimetype=current_app.config['JSONIFY_MIMETYPE'])


What's a good function header?
targets: def jsonify(*args, **kwargs):
inputs: I wrote the below code

    if (a % b):
        return ((a // b) + 1)
    return (a // b)


What's a good function header?
targets: def _divide_with_ceil(a, b):
inputs: def make_pretty_name(method):
targets: """Makes a pretty name for a function/method.
    """
    meth_pieces = [method.__name__]
    if (hasattr(method, '__self__') and (method.__self__ is not None)):
        try:
            meth_pieces.insert(0, method.__self__.__class__.__name__)
        except AttributeError:
            pass
    return '.'.join(meth_pieces)
inputs: I wrote the below code

    means_men = (20, 35, 30, 35, 27)
    means_women = (25, 32, 34, 20, 25)
    plt.title('\xe5\x8f\xaf\xe8\xa7\x86\xe5\x8c\x96\xe6\xa0\x87\xe9\xa2\x98', fontproperties=myfont)
    index = np.arange(len(means_men))
    bar_width = 0.35
    plt.bar(index, means_men, width=bar_width, alpha=0.2, color='b', label='\xe7\x94\xb7\xe7\x94\x9f')
    plt.bar((index + bar_width), means_women, width=bar_width, alpha=0.8, color='r', label='\xe5\xa5\xb3\xe7\x94\x9f')
    plt.legend(loc='upper    right', prop=myfont, shadow=True)
    for (x, y) in zip(index, means_men):
        plt.text(x, (y + 0.3), y, ha='center', va='bottom')
    for (x, y) in zip(index, means_women):
        plt.text((x + bar_width), (y + 0.3), y, ha='center', va='bottom')
    plt.ylim(0, 45)
    plt.xlabel('\xe5\x88\x86\xe7\xbb\x84Group', fontproperties=myfont)
    plt.ylabel('\xe5\xbe\x97\xe5\x88\x86Scores', fontproperties=myfont)
    plt.xticks((index + (bar_width / 2)), ('A\xe7\xbb\x84', 'B\xe7\xbb\x84', 'C\xe7\xbb\x84', 'D\xe7\xbb\x84', 'E\xe7\xbb\x84'), fontproperties=myfont)
    plt.show()
    return


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

    (y_min, x_min, y_max, x_max) = boxlist.get_coordinates()
    return ((y_max - y_min) * (x_max - x_min))


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

    if (version is None):
        from django import VERSION as version
    else:
        assert (len(version) == 5)
        assert (version[3] in (u'alpha', u'beta', u'rc', u'final'))
    parts = (2 if (version[2] == 0) else 3)
    main = u'.'.join((str(x) for x in version[:parts]))
    sub = u''
    if ((version[3] == u'alpha') and (version[4] == 0)):
        git_changeset = get_git_changeset()
        if git_changeset:
            sub = (u'.dev%s' % git_changeset)
    elif (version[3] != u'final'):
        mapping = {u'alpha': u'a', u'beta': u'b', u'rc': u'c'}
        sub = (mapping[version[3]] + str(version[4]))
    return str((main + sub))


What's a good function header?
targets: def get_version(version=None):
inputs: I wrote the below code

    print 'Start    testing    the    network    ...'
    if (batch_size is None):
        dp_dict = dict_to_one(network.all_drop)
        feed_dict = {x: X_test, y_: y_test}
        feed_dict.update(dp_dict)
        if (cost is not None):
            print ('            test    loss:    %f' % sess.run(cost, feed_dict=feed_dict))
        print ('            test    acc:    %f' % sess.run(acc, feed_dict=feed_dict))
    else:
        (test_loss, test_acc, n_batch) = (0, 0, 0)
        for (X_test_a, y_test_a) in iterate.minibatches(X_test, y_test, batch_size, shuffle=True):
            dp_dict = dict_to_one(network.all_drop)
            feed_dict = {x: X_test_a, y_: y_test_a}
            feed_dict.update(dp_dict)
            if (cost is not None):
                (err, ac) = sess.run([cost, acc], feed_dict=feed_dict)
                test_loss += err
            else:
                ac = sess.run(acc, feed_dict=feed_dict)
            test_acc += ac
            n_batch += 1
        if (cost is not None):
            print ('            test    loss:    %f' % (test_loss / n_batch))
        print ('            test    acc:    %f' % (test_acc / n_batch))


What's a good function header?
targets: def test(sess, network, acc, X_test, y_test, x, y_, batch_size, cost=None):
inputs: I wrote the below code

    if pieces['closest-tag']:
        rendered = pieces['closest-tag']
        if (pieces['distance'] or pieces['dirty']):
            rendered += ('.post%d' % pieces['distance'])
            if pieces['dirty']:
                rendered += '.dev0'
            rendered += plus_or_dot(pieces)
            rendered += ('g%s' % pieces['short'])
    else:
        rendered = ('0.post%d' % pieces['distance'])
        if pieces['dirty']:
            rendered += '.dev0'
        rendered += ('+g%s' % pieces['short'])
    return rendered


What's a good function header?
targets: def render_pep440_post(pieces):
inputs: Complete the below
def H(s):

    ''''The hash function H'
    '''
targets: return md5_hex(s)
inputs: Complete the below
def create_api_key(name, description, enabled=True, stageKeys=None, region=None, key=None, keyid=None, profile=None):

    ''''Create an API key given name and description.
    An optional enabled argument can be provided.  If provided, the
    valid values are True|False.  This argument defaults to True.
    An optional stageKeys argument can be provided in the form of
    list of dictionary with \'restApiId\' and \'stageName\' as keys.
    CLI Example:
    .. code-block:: bash
    salt myminion boto_apigateway.create_api_key name description
    salt myminion boto_apigateway.create_api_key name description enabled=False
    salt myminion boto_apigateway.create_api_key name description \
    stageKeys=\'[{"restApiId": "id", "stageName": "stagename"}]\''
    '''
targets: try:
        stageKeys = (list() if (stageKeys is None) else stageKeys)
        conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
        response = conn.create_api_key(name=name, description=description, enabled=enabled, stageKeys=stageKeys)
        if (not response):
            return {'created': False}
        return {'created': True, 'apiKey': _convert_datetime_str(response)}
    except ClientError as e:
        return {'created': False, 'error': salt.utils.boto3.get_error(e)}
inputs: I wrote the below code

    mobsf_subdir_tools = CONFIG['MobSF']['tools']
    binscope_path = (mobsf_subdir_tools + 'BinScope')
    if platform.machine().endswith('64'):
        binscope_url = CONFIG['binscope']['url_x64']
        binscope_installer_path = (binscope_path + '\\BinScope_x64.msi')
    else:
        binscope_url = CONFIG['binscope']['url_x86']
        binscope_installer_path = (binscope_path + '\\BinScope_x86.msi')
    if (not os.path.exists(binscope_path)):
        os.makedirs(binscope_path)
    binscope_installer_file = open(binscope_installer_path, 'wb')
    print '[*]    Downloading    BinScope..'
    binscope_installer = urlrequest.urlopen(binscope_url)
    print '[*]    Saving    to    File    {}'.format(binscope_installer_path)
    binscope_installer_file.write(bytes(binscope_installer.read()))
    binscope_installer_file.close()
    print '[*]    Installing    BinScope    to    {}'.format(binscope_path)
    os.system(((((((('msiexec' + '    INSTALLLOCATION="') + binscope_path) + '"    ') + '/i    "') + binscope_installer_path) + '"    ') + '/passive'))
    CONFIG['binscope']['file'] = (binscope_path + '\\Binscope.exe')
    with open(os.path.join(CONFIG_PATH, CONFIG_FILE), 'w') as configfile:
        CONFIG.write(configfile)


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

    apiproxy_stub_map.apiproxy.RegisterStub('app_identity_service', app_identity_stub.AppIdentityServiceStub())
    blob_storage = datastore_blob_storage.DatastoreBlobStorage(app_id)
    apiproxy_stub_map.apiproxy.RegisterStub('blobstore', blobstore_stub.BlobstoreServiceStub(blob_storage, request_data=request_data))
    apiproxy_stub_map.apiproxy.RegisterStub('capability_service', capability_stub.CapabilityServiceStub())
    apiproxy_stub_map.apiproxy.RegisterStub('channel', channel_service_stub.ChannelServiceStub(request_data=request_data))
    datastore = datastore_distributed.DatastoreDistributed(app_id, datastore_path, require_indexes=datastore_require_indexes, trusted=trusted)
    apiproxy_stub_map.apiproxy.ReplaceStub('datastore_v3', datastore)
    apiproxy_stub_map.apiproxy.RegisterStub('file', file_service_stub.FileServiceStub(blob_storage))
    serve_address = os.environ['NGINX_HOST']
    try:
        from google.appengine.api.images import images_stub
    except ImportError:
        logging.warning('Could    not    initialize    images    API;    you    are    likely    missing    the    Python    "PIL"    module.')
        from google.appengine.api.images import images_not_implemented_stub
        apiproxy_stub_map.apiproxy.RegisterStub('images', images_not_implemented_stub.ImagesNotImplementedServiceStub(host_prefix=images_host_prefix))
    else:
        host_prefix = 'http://{}'.format(serve_address)
        apiproxy_stub_map.apiproxy.RegisterStub('images', images_stub.ImagesServiceStub(host_prefix=host_prefix))
    apiproxy_stub_map.apiproxy.RegisterStub('logservice', logservice_stub.LogServiceStub(persist=True))
    apiproxy_stub_map.apiproxy.RegisterStub('mail', mail_stub.MailServiceStub(mail_smtp_host, mail_smtp_port, mail_smtp_user, mail_smtp_password, enable_sendmail=mail_enable_sendmail, show_mail_body=mail_show_mail_body))
    apiproxy_stub_map.apiproxy.RegisterStub('memcache', memcache_distributed.MemcacheService())
    apiproxy_stub_map.apiproxy.RegisterStub('search',...

What's a good function header?
targets: def setup_stubs(request_data, app_id, application_root, trusted, blobstore_path, datastore_consistency, datastore_path, datastore_require_indexes, datastore_auto_id_policy, images_host_prefix, logs_path, mail_smtp_host, mail_smtp_port, mail_smtp_user, mail_smtp_password, mail_enable_sendmail, mail_show_mail_body, matcher_prospective_search_path, search_index_path, taskqueue_auto_run_tasks, taskqueue_default_http_server, uaserver_path, user_login_url, user_logout_url, xmpp_path):
inputs: I wrote the below code

    module = AnsibleModule(argument_spec=dict(kubeconfig=dict(default='/etc/origin/master/admin.kubeconfig', type='str'), state=dict(default='present', type='str', choices=['present', 'list']), debug=dict(default=False, type='bool'), kind=dict(default='dc', choices=['dc', 'rc'], type='str'), namespace=dict(default='default', type='str'), replicas=dict(default=None, type='int'), name=dict(default=None, type='str')), supports_check_mode=True)
    rval = OCScale.run_ansible(module.params, module.check_mode)
    if ('failed' in rval):
        module.fail_json(**rval)
    module.exit_json(**rval)


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

    data = show_ver()
    info = {'software': _parse_software(data), 'hardware': _parse_hardware(data), 'plugins': _parse_plugins(data)}
    return info


What's a good function header?
targets: def system_info():
inputs: Complete the below
def IsBlockInNameSpace(nesting_state, is_forward_declaration):

    ''''Checks that the new block is directly in a namespace.
    Args:
    nesting_state: The _NestingState object that contains info about our state.
    is_forward_declaration: If the class is a forward declared class.
    Returns:
    Whether or not the new block is directly in a namespace.'
    '''
targets: if is_forward_declaration:
        return ((len(nesting_state.stack) >= 1) and isinstance(nesting_state.stack[(-1)], _NamespaceInfo))
    return ((len(nesting_state.stack) > 1) and nesting_state.stack[(-1)].check_namespace_indentation and isinstance(nesting_state.stack[(-2)], _NamespaceInfo))
inputs: def findall(pattern, string, flags=0):
targets: """Return a list of all non-overlapping matches in the string.
    If one or more capturing groups are present in the pattern, return
    a list of groups; this will be a list of tuples if the pattern
    has more than one group.
    Empty matches are included in the result.
    """
    return _compile(pattern, flags).findall(string)
inputs: def _ellipsis_match(want, got):
targets: """Essentially the only subtle case:
    >>> _ellipsis_match(\aa...aa\, \aaa\)
    False
    """
    if (ELLIPSIS_MARKER not in want):
        return (want == got)
    ws = want.split(ELLIPSIS_MARKER)
    assert (len(ws) >= 2)
    (startpos, endpos) = (0, len(got))
    w = ws[0]
    if w:
        if got.startswith(w):
            startpos = len(w)
            del ws[0]
        else:
            return False
    w = ws[(-1)]
    if w:
        if got.endswith(w):
            endpos -= len(w)
            del ws[(-1)]
        else:
            return False
    if (startpos > endpos):
        return False
    for w in ws:
        startpos = got.find(w, startpos, endpos)
        if (startpos < 0):
            return False
        startpos += len(w)
    return True
inputs: Complete the below
def get_entry_map(dist, group=None):

    ''''Return the entry point map for `group`, or the full entry map'
    '''
targets: return get_distribution(dist).get_entry_map(group)
inputs: def get_file_contents(*args, **kwargs):
targets: """Retrieves the contents of a filename or file-like object.
    See  the `get_readable_fileobj` docstring for details on parameters.
    Returns
    content
    The content of the file (as requested by ``encoding``).
    """
    with get_readable_fileobj(*args, **kwargs) as f:
        return f.read()
inputs: def analytics_upageviews(revision_ids, start_date, end_date=None):
targets: """Given a sequence of document revision IDs, returns a dict matching
    those with the number of users Google Analytics thinks has visited
    each revision since start_date.
    """
    scopes = ['https://www.googleapis.com/auth/analytics.readonly']
    try:
        ga_cred_dict = json.loads(config.GOOGLE_ANALYTICS_CREDENTIALS)
    except (ValueError, TypeError):
        raise ImproperlyConfigured('GOOGLE_ANALYTICS_CREDENTIALS    Constance    setting    is    badly    formed.')
    if (not ga_cred_dict):
        raise ImproperlyConfigured('An    empty    GOOGLE_ANALYTICS_CREDENTIALS    Constance    setting    is    not    permitted.')
    credentials = ServiceAccountCredentials.from_json_keyfile_dict(ga_cred_dict, scopes=scopes)
    http_auth = credentials.authorize(Http())
    service = build('analyticsreporting', 'v4', http=http_auth)
    if (end_date is None):
        end_date = datetime.date.today()
    if hasattr(start_date, 'date'):
        start_date = start_date.date()
    if hasattr(end_date, 'date'):
        end_date = end_date.date()
    start_date = start_date.isoformat()
    end_date = end_date.isoformat()
    request = service.reports().batchGet(body={'reportRequests': [{'dimensions': [{'name': 'ga:dimension12'}], 'metrics': [{'expression': 'ga:uniquePageviews'}], 'dimensionFilterClauses': [{'filters': [{'dimensionName': 'ga:dimension12', 'operator': 'IN_LIST', 'expressions': map(str, revision_ids)}]}], 'dateRanges': [{'startDate': start_date, 'endDate': end_date}], 'viewId': '66726481'}]})
    response = request.execute()
    data = {int(r): 0 for r in revision_ids}
    data.update({int(row['dimensions'][0]): int(row['metrics'][0]['values'][0]) for row in response['reports'][0]['data'].get('rows', ())})
    return data
inputs: def makeXMLTags(tagStr):
targets: """Helper to construct opening and closing tag expressions for XML, given a tag name. Matches
    tags only in the given upper/lower case.
    Example: similar to L{makeHTMLTags}
    """
    return _makeTags(tagStr, True)
inputs: I wrote the below code

    if kwargs.get('label', None):
        bfield.label = kwargs['label']
    bfield.field.widget.attrs.update(kwargs)
    return bfield


What's a good function header?
targets: @library.global_function
def field_with_attrs(bfield, **kwargs):
inputs: I wrote the below code

    if (':' not in s):
        return ('', s)
    colon = 0
    for i in range(len(s)):
        if (s[i] == ':'):
            colon = (i + 1)
    (path, file) = (s[:(colon - 1)], s[colon:])
    if (path and (not (':' in path))):
        path = (path + ':')
    return (path, file)


What's a good function header?
targets: def split(s):
inputs: Complete the below
def format_timezone(offset, unnecessary_negative_timezone=False):

    ''''Format a timezone for Git serialization.
    :param offset: Timezone offset as seconds difference to UTC
    :param unnecessary_negative_timezone: Whether to use a minus sign for
    UTC or positive timezones (-0000 and --700 rather than +0000 / +0700).'
    '''
targets: if ((offset % 60) != 0):
        raise ValueError('Unable    to    handle    non-minute    offset.')
    if ((offset < 0) or unnecessary_negative_timezone):
        sign = '-'
        offset = (- offset)
    else:
        sign = '+'
    return ('%c%02d%02d' % (sign, (offset / 3600), ((offset / 60) % 60))).encode('ascii')
inputs: Complete the below
def find_command(cmd, paths=None, pathext=None):

    ''''Searches the PATH for the given command and returns its path'
    '''
targets: if (paths is None):
        paths = os.environ.get('PATH', '').split(os.pathsep)
    if isinstance(paths, string_types):
        paths = [paths]
    if (pathext is None):
        pathext = get_pathext()
    pathext = [ext for ext in pathext.lower().split(os.pathsep) if len(ext)]
    if (os.path.splitext(cmd)[1].lower() in pathext):
        pathext = ['']
    for path in paths:
        cmd_path = os.path.join(path, cmd)
        for ext in pathext:
            cmd_path_ext = (cmd_path + ext)
            if os.path.isfile(cmd_path_ext):
                return cmd_path_ext
        if os.path.isfile(cmd_path):
            return cmd_path
    raise BadCommand(('Cannot    find    command    %r' % cmd))
inputs: def dmp_primitive(f, u, K):
targets: """Returns multivariate content and a primitive polynomial.
    Examples
    >>> from sympy.polys import ring, ZZ
    >>> R, x,y, = ring("x,y", ZZ)
    >>> R.dmp_primitive(2*x*y + 6*x + 4*y + 12)
    (2*y + 6, x + 2)
    """
    (cont, v) = (dmp_content(f, u, K), (u - 1))
    if (dmp_zero_p(f, u) or dmp_one_p(cont, v, K)):
        return (cont, f)
    else:
        return (cont, [dmp_quo(c, cont, v, K) for c in f])
inputs: def ParseResponseEx(response, select_default=False, form_parser_class=FormParser, request_class=urllib2.Request, entitydefs=None, encoding=DEFAULT_ENCODING, _urljoin=urlparse.urljoin, _urlparse=urlparse.urlparse, _urlunparse=urlparse.urlunparse):
targets: """Identical to ParseResponse, except that:
    1. The returned list contains an extra item.  The first form in the list
    contains all controls not contained in any FORM element.
    2. The arguments ignore_errors and backwards_compat have been removed.
    3. Backwards-compatibility mode (backwards_compat=True) is not available.
    """
    return _ParseFileEx(response, response.geturl(), select_default, False, form_parser_class, request_class, entitydefs, False, encoding, _urljoin=_urljoin, _urlparse=_urlparse, _urlunparse=_urlunparse)
inputs: I wrote the below code

    def decorate(function):
        @wraps(function)
        def inner(*args, **kwargs):
            with WAFFLE_SWITCHES.override(switch, active=active):
                function(*args, **kwargs)
        return inner
    return decorate


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

    model = context['model']
    session = model.Session
    return session.execute(q)


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

    if (not code):
        return (None, None)
    if (not isinstance(code, basestring)):
        raise ValueError(u'Invalid    language    code    specified    by    parser')
    code = re.split(u'[^a-z]', code.lower())[0][:3]
    for spec in codes:
        if (code in spec[:(-1)]):
            return (code, spec[(-1)])
    return (code, (u'Unknown    (%r)' % code))


What's a good function header?
targets: def resolve(code):
inputs: Complete the below
@transaction.atomic
def mass_get_or_create(model_class, base_queryset, id_field, default_dict, global_defaults):

    ''''Updates the data by inserting all not found records
    Doesnt delete records if not in the new data
    example usage
    >>> model_class = ListItem #the class for which you are doing the insert
    >>> base_query_set = ListItem.objects.filter(user=request.user, list=1) #query for retrieving currently stored items
    >>> id_field = \'user_id\' #the id field on which to check
    >>> default_dict = {\'12\': dict(comment=\'my_new_item\'), \'13\': dict(comment=\'super\')} #list of default values for inserts
    >>> global_defaults = dict(user=request.user, list_id=1) #global defaults'
    '''
targets: current_instances = list(base_queryset)
    current_ids = set([unicode(getattr(c, id_field)) for c in current_instances])
    given_ids = map(unicode, default_dict.keys())
    new_ids = [g for g in given_ids if (g not in current_ids)]
    prepared_models = []
    for new_id in new_ids:
        defaults = default_dict[new_id]
        defaults[id_field] = new_id
        defaults.update(global_defaults)
        model_instance = model_class(**defaults)
        prepared_models.append(model_instance)
    if hasattr(model_class.objects, 'bulk_create'):
        model_class.objects.bulk_create(prepared_models)
    else:
        [m.save() for m in prepared_models]
    inserted_model_instances = prepared_models
    return (current_instances, inserted_model_instances)
inputs: def ParsePropertyQuery(query, filters, orders):
targets: """Parse __property__  queries.
    Raises exceptions for illegal queries.
    Args:
    query: A Query PB.
    filters: the normalized filters from query.
    orders: the normalized orders from query.
    Returns:
    The kind range (a ValueRange over (kind, property) pairs) requested
    in the query.
    """
    Check((not query.has_transaction()), 'transactional    queries    on    __property__    not    allowed')
    key_range = ParseKeyFilteredQuery(filters, orders)
    key_range.Remap((lambda x: _PropertyKeyToString(x, '')))
    if query.has_ancestor():
        ancestor = datastore_types.Key._FromPb(query.ancestor())
        (ancestor_kind, ancestor_property) = _PropertyKeyToString(ancestor, None)
        if (ancestor_property is not None):
            key_range.Update(datastore_pb.Query_Filter.EQUAL, (ancestor_kind, ancestor_property))
        else:
            key_range.Update(datastore_pb.Query_Filter.GREATER_THAN_OR_EQUAL, (ancestor_kind, ''))
            key_range.Update(datastore_pb.Query_Filter.LESS_THAN_OR_EQUAL, ((ancestor_kind + '\x00'), ''))
        query.clear_ancestor()
    return key_range
inputs: I wrote the below code

    chips = []
    for value in chops:
        chips.append(int2str64(value))
    encoded = ','.join(chips)
    return encoded


What's a good function header?
targets: def encode64chops(chops):
inputs: Complete the below
def add_dict_to_cookiejar(cj, cookie_dict):

    ''''Returns a CookieJar from a key/value dictionary.
    :param cj: CookieJar to insert cookies into.
    :param cookie_dict: Dict of key/values to insert into CookieJar.'
    '''
targets: cj2 = cookiejar_from_dict(cookie_dict)
    cj.update(cj2)
    return cj
inputs: def _nested_variable(init, name=None, trainable=False):
targets: """Returns a nested collection of TensorFlow variables.
    Args:
    init: Nested collection of TensorFlow initializers.
    name: Variable name.
    trainable: Make variables trainable (`False` by default).
    Returns:
    Nested collection (same structure as `init`) of TensorFlow variables.
    """
    if (isinstance(init, list) or isinstance(init, tuple)):
        result = [_nested_variable(i, name, trainable) for i in init]
        if isinstance(init, tuple):
            return tuple(result)
        return result
    else:
        return tf.Variable(init, name=name, trainable=trainable)
inputs: Complete the below
def delete(url, **kwargs):

    ''''Sends a DELETE request.
    :param url: URL for the new :class:`Request` object.
    :param \*\*kwargs: Optional arguments that ``request`` takes.
    :return: :class:`Response <Response>` object
    :rtype: requests.Response'
    '''
targets: return request('delete', url, **kwargs)
inputs: I wrote the below code

    adhoc_session = False
    session = kwargs.pop('session', None)
    if (session is None):
        session = sessions.session()
        adhoc_session = True
    try:
        return session.request(method=method, url=url, **kwargs)
    finally:
        if adhoc_session:
            session.close()


What's a good function header?
targets: @catch_exceptions_if_in_safe_mode
def request(method, url, **kwargs):
inputs: I wrote the below code

    if (call != 'function'):
        raise SaltCloudSystemExit('The    show_service    function    must    be    called    with    -f    or    --function.')
    if (not conn):
        conn = get_conn()
    if (kwargs is None):
        kwargs = {}
    if ('name' not in kwargs):
        raise SaltCloudSystemExit('A    name    must    be    specified    as    "name"')
    data = conn.get_hosted_service_properties(kwargs['name'], kwargs.get('details', False))
    ret = object_to_dict(data)
    return ret


What's a good function header?
targets: def show_service(kwargs=None, conn=None, call=None):
inputs: I wrote the below code

    files = ['/etc/init/{0}.conf'.format(name), '/etc/init/{0}.override'.format(name)]
    for file_name in itertools.ifilter(os.path.isfile, files):
        with salt.utils.files.fopen(file_name) as fp_:
            if re.search('^\\s*manual', fp_.read(), re.MULTILINE):
                return True
    return False


What's a good function header?
targets: def _upstart_is_disabled(name):
inputs: Complete the below
def getLoopsIntersection(importRadius, loopLists):

    ''''Get intersection loops.'
    '''
targets: intercircle.directLoopLists(True, loopLists)
    if (len(loopLists) < 1):
        return []
    if (len(loopLists) < 2):
        return loopLists[0]
    intercircle.directLoopLists(True, loopLists)
    loopsIntersection = loopLists[0]
    for loopList in loopLists[1:]:
        loopsIntersection = getLoopsIntersectionByPair(importRadius, loopsIntersection, loopList)
    return loopsIntersection
inputs: Complete the below
def libvlc_video_get_spu_delay(p_mi):

    ''''Get the current subtitle delay. Positive values means subtitles are being
    displayed later, negative values earlier.
    @param p_mi: media player.
    @return: time (in microseconds) the display of subtitles is being delayed.
    @version: LibVLC 2.0.0 or later.'
    '''
targets: f = (_Cfunctions.get('libvlc_video_get_spu_delay', None) or _Cfunction('libvlc_video_get_spu_delay', ((1,),), None, ctypes.c_int64, MediaPlayer))
    return f(p_mi)
inputs: Complete the below
@click.command('set-url-root')
@click.argument('site')
@click.argument('url-root')
def set_url_root(site, url_root):

    ''''Set url root for site'
    '''
targets: from bench.config.site_config import set_url_root
    set_url_root(site, url_root)
inputs: def _sanitize_tag(match):
targets: """Return the tag if it is allowed or the empty string otherwise
    """
    tag = match.group(0)
    if (ALLOWED_BASIC_TAG_PATTERN.match(tag) or ALLOWED_A_PATTERN.match(tag) or ALLOWED_IMG_PATTERN.match(tag)):
        return tag
    else:
        return ''
inputs: I wrote the below code

    max_x = np.max(x)
    return (max_x + np.log(np.sum(np.exp((x - max_x)))))


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

    full_str = sep.join(items)
    if (len(full_str) < max_chars):
        return full_str
    n_chars = 0
    n_items = 0
    for (j, item) in enumerate(items):
        n_chars += (len(item) + len(sep))
        if (n_chars < (max_chars - len(overflow_marker))):
            n_items += 1
        else:
            break
    return sep.join((list(items[:n_items]) + [overflow_marker]))


What's a good function header?
targets: def limited_join(sep, items, max_chars=30, overflow_marker='...'):
inputs: Complete the below
def _search_dialog(parent):

    ''''Display search test box.'
    '''
targets: from tkinter import Toplevel, Text
    from tkinter.ttk import Button
    box = Toplevel(parent)
    box.title('Test    SearchDialog')
    (x, y) = map(int, parent.geometry().split('+')[1:])
    box.geometry(('+%d+%d' % (x, (y + 175))))
    text = Text(box, inactiveselectbackground='gray')
    text.pack()
    text.insert('insert', ('This    is    a    sample    string.\n' * 5))
    def show_find():
        text.tag_add('sel', '1.0', 'end')
        _setup(text).open(text)
        text.tag_remove('sel', '1.0', 'end')
    button = Button(box, text='Search    (selection    ignored)', command=show_find)
    button.pack()
inputs: def hessian(fun, argnum=0):
targets: """Returns a function that computes the exact Hessian.
    """
    return jacobian(jacobian(fun, argnum), argnum)