Muennighoff/xP3x-sample huggingface dataset:
inputs: def get_host_info(node_info, host):
targets: """Simple callback that takes the node info from `/_cluster/nodes` and a
    parsed connection information and return the connection information. If
    `None` is returned this node will be skipped.
    Useful for filtering nodes (by proximity for example) or if additional
    information needs to be provided for the :class:`~elasticsearch.Connection`
    class. By default master only nodes are filtered out since they shouldn\t
    typically be used for API operations.
    :arg node_info: node information from `/_cluster/nodes`
    :arg host: connection information (host, port) extracted from the node info
    """
    if (node_info.get('roles', []) == ['master']):
        return None
    return host
inputs: Complete the below
def _anderson_ksamp_right(samples, Z, Zstar, k, n, N):

    ''''Compute A2akN equation 6 of Scholz & Stephens.
    Parameters
    samples : sequence of 1-D array_like
    Array of sample arrays.
    Z : array_like
    Sorted array of all observations.
    Zstar : array_like
    Sorted array of unique observations.
    k : int
    Number of samples.
    n : array_like
    Number of observations in each sample.
    N : int
    Total number of observations.
    Returns
    A2KN : float
    The A2KN statistics of Scholz and Stephens 1987.'
    '''
targets: A2kN = 0.0
    lj = (Z.searchsorted(Zstar[:(-1)], 'right') - Z.searchsorted(Zstar[:(-1)], 'left'))
    Bj = lj.cumsum()
    for i in arange(0, k):
        s = np.sort(samples[i])
        Mij = s.searchsorted(Zstar[:(-1)], side='right')
        inner = (((lj / float(N)) * (((N * Mij) - (Bj * n[i])) ** 2)) / (Bj * (N - Bj)))
        A2kN += (inner.sum() / n[i])
    return A2kN
inputs: I wrote the below code

    if (VCR_RECORD_MODE == u'off'):
        (yield None)
    else:
        module = request.module.__name__.split(u'tests.')[(-1)]
        class_name = request.cls.__name__
        cassette_name = u'.'.join([module, class_name, request.function.__name__])
        cassette_path = os.path.join(VCR_CASSETTE_DIR, cassette_name)
        online = True
        if (vcr.record_mode == u'none'):
            online = False
        elif (vcr.record_mode == u'once'):
            online = (not os.path.exists(cassette_path))
        if (not online):
            log.debug(u'Disabling    domain    limiters    during    VCR    playback.')
            monkeypatch.setattr(u'flexget.utils.requests.limit_domains', mock.Mock())
        with vcr.use_cassette(path=cassette_path) as cassette:
            (yield cassette)


What's a good function header?
targets: @pytest.yield_fixture()
def use_vcr(request, monkeypatch):
inputs: Complete the below
def getnameinfo(sockaddr, flags):

    ''''getnameinfo(sockaddr, flags) -> (host, port)
    Get host and port for a sockaddr.
    .. seealso:: :doc:`dns`'
    '''
targets: return get_hub().resolver.getnameinfo(sockaddr, flags)
inputs: Complete the below
def _compressed_sparse_stack(blocks, axis):

    ''''Stacking fast path for CSR/CSC matrices
    (i) vstack for CSR, (ii) hstack for CSC.'
    '''
targets: other_axis = (1 if (axis == 0) else 0)
    data = np.concatenate([b.data for b in blocks])
    indices = np.concatenate([b.indices for b in blocks])
    indptr = []
    last_indptr = 0
    constant_dim = blocks[0].shape[other_axis]
    sum_dim = 0
    for b in blocks:
        if (b.shape[other_axis] != constant_dim):
            raise ValueError(('incompatible    dimensions    for    axis    %d' % other_axis))
        sum_dim += b.shape[axis]
        indptr.append((b.indptr[:(-1)] + last_indptr))
        last_indptr += b.indptr[(-1)]
    indptr.append([last_indptr])
    indptr = np.concatenate(indptr)
    if (axis == 0):
        return csr_matrix((data, indices, indptr), shape=(sum_dim, constant_dim))
    else:
        return csc_matrix((data, indices, indptr), shape=(constant_dim, sum_dim))
inputs: Complete the below
def main():

    ''''Check starting conditions and start GUI.
    First, check command line arguments and start loggers. Set log levels. Try
    all imports and exit verbosely if a library is not found. Disable outputs
    to stdout and start the GUI.'
    '''
targets: qtlogger = logging.getLogger('PyQt5')
    qtlogger.setLevel(logging.ERROR)
    parser = argparse.ArgumentParser(description='cfclient    -    Crazyflie    graphical    control    client')
    parser.add_argument('--debug', '-d', nargs=1, default='info', type=str, help='set    debug    level    [minimal,    info,    debug,    debugfile]')
    args = parser.parse_args()
    debug = args.debug
    cflogger = logging.getLogger('')
    if ('debugfile' in debug):
        logging.basicConfig(level=logging.DEBUG)
        formatter = logging.Formatter('%(asctime)s:%(threadName)s:%(name)s:%(levelname)s:%(message)s')
        filename = ('debug-%s.log' % datetime.datetime.now())
        filehandler = logging.FileHandler(filename)
        filehandler.setLevel(logging.DEBUG)
        filehandler.setFormatter(formatter)
        cflogger.addHandler(filehandler)
    elif ('debug' in debug):
        logging.basicConfig(level=logging.DEBUG)
    elif ('minimal' in debug):
        logging.basicConfig(level=logging.WARNING)
    elif ('info' in debug):
        logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    logger.debug('Using    config    path    {}'.format(cfclient.config_path))
    logger.debug('sys.path={}'.format(sys.path))
    try:
        import usb
    except ImportError:
        logger.critical('No    pyusb    installation    found,    exiting!')
        sys.exit(1)
    if (not sys.platform.startswith('linux')):
        try:
            import sdl2
        except ImportError:
            logger.critical('No    pysdl2    installation    found,    exiting!')
            sys.exit(1)
    try:
        import PyQt5
    except ImportError:
        logger.critical('No    PyQT5    installation    found,    exiting!')
        sys.exit(1)
    if (os.name == 'posix'):
        stdout = os.dup(1)
        os.dup2(os.open('/dev/null', os.O_WRONLY), 1)
        sys.stdout = os.fdopen(stdout, 'w')
        logger.info('Disabling    STL    printouts')
    if (os.name == 'nt'):
        stdout = os.dup(1)
...
inputs: Complete the below
def check_known_inconsistencies(bill_data, bond_data):

    ''''There are a couple quirks in the data provided by Bank of Canada.
    Check that no new quirks have been introduced in the latest download.'
    '''
targets: inconsistent_dates = bill_data.index.sym_diff(bond_data.index)
    known_inconsistencies = [pd.Timestamp('2006-09-04', tz='UTC'), pd.Timestamp('2010-02-15', tz='UTC'), pd.Timestamp('2013-07-25', tz='UTC')]
    unexpected_inconsistences = inconsistent_dates.drop(known_inconsistencies)
    if len(unexpected_inconsistences):
        in_bills = bill_data.index.difference(bond_data.index).difference(known_inconsistencies)
        in_bonds = bond_data.index.difference(bill_data.index).difference(known_inconsistencies)
        raise ValueError('Inconsistent    dates    for    Canadian    treasury    bills    vs    bonds.    \nDates    with    bills    but    not    bonds:    {in_bills}.\nDates    with    bonds    but    not    bills:    {in_bonds}.'.format(in_bills=in_bills, in_bonds=in_bonds))
inputs: I wrote the below code

    be = get_backend(request)
    def cleanup():
        be = request.getfuncargvalue('backend_default')
        del be
    request.addfinalizer(cleanup)
    return be


What's a good function header?
targets: @pytest.fixture(scope='module', params=['gpu', 'cpu'])
def backend_default(request):
inputs: I wrote the below code

    assert (errors == 'strict')
    output = zlib.decompress(input)
    return (output, len(input))


What's a good function header?
targets: def zlib_decode(input, errors='strict'):
inputs: Complete the below
def delete_object(container_name, object_name, profile, **libcloud_kwargs):

    ''''Delete an object in the cloud
    :param container_name: Container name
    :type  container_name: ``str``
    :param object_name: Object name
    :type  object_name: ``str``
    :param profile: The profile key
    :type  profile: ``str``
    :param libcloud_kwargs: Extra arguments for the driver\'s delete_object method
    :type  libcloud_kwargs: ``dict``
    :return: True if an object has been successfully deleted, False
    otherwise.
    :rtype: ``bool``
    CLI Example:
    .. code-block:: bash
    salt myminion libcloud_storage.delete_object MyFolder me.jpg profile1'
    '''
targets: conn = _get_driver(profile=profile)
    libcloud_kwargs = salt.utils.args.clean_kwargs(**libcloud_kwargs)
    obj = conn.get_object(container_name, object_name, **libcloud_kwargs)
    return conn.delete_object(obj)
inputs: I wrote the below code

    if (pattern is None):
        pattern = sickbeard.NAMING_PATTERN
    if (anime_type is None):
        anime_type = sickbeard.NAMING_ANIME
    valid = (not validate_name(pattern, None, anime_type, file_only=True))
    if (multi is not None):
        valid = (valid or (not validate_name(pattern, multi, anime_type, file_only=True)))
    return valid


What's a good function header?
targets: def check_force_season_folders(pattern=None, multi=None, anime_type=None):
inputs: I wrote the below code

    a = np.atleast_1d(a)
    if (len(a) == 1):
        b = np.asarray(b)
        a = np.asarray(a)
        if ((b.ndim != 1) and (a.ndim != 1)):
            raise ValueError('object    of    too    small    depth    for    desired    array')
        x = np.asarray(x)
        inputs = [b, a, x]
        if (zi is not None):
            zi = np.asarray(zi)
            if (zi.ndim != x.ndim):
                raise ValueError('object    of    too    small    depth    for    desired    array')
            expected_shape = list(x.shape)
            expected_shape[axis] = (b.shape[0] - 1)
            expected_shape = tuple(expected_shape)
            if (zi.shape != expected_shape):
                strides = (zi.ndim * [None])
                if (axis < 0):
                    axis += zi.ndim
                for k in range(zi.ndim):
                    if ((k == axis) and (zi.shape[k] == expected_shape[k])):
                        strides[k] = zi.strides[k]
                    elif ((k != axis) and (zi.shape[k] == expected_shape[k])):
                        strides[k] = zi.strides[k]
                    elif ((k != axis) and (zi.shape[k] == 1)):
                        strides[k] = 0
                    else:
                        raise ValueError(('Unexpected    shape    for    zi:    expected    %s,    found    %s.' % (expected_shape, zi.shape)))
                zi = np.lib.stride_tricks.as_strided(zi, expected_shape, strides)
            inputs.append(zi)
        dtype = np.result_type(*inputs)
        if (dtype.char not in 'fdgFDGO'):
            raise NotImplementedError(("input    type    '%s'    not    supported" % dtype))
        b = np.array(b, dtype=dtype)
        a = np.array(a, dtype=dtype, copy=False)
        b /= a[0]
        x = np.array(x, dtype=dtype, copy=False)
        out_full = np.apply_along_axis((lambda y: np.convolve(b, y)), axis, x)
        ind = (out_full.ndim * [slice(None)])
        if (zi is not None):
            ind[axis] = slice(zi.shape[axis])
            out_full[ind] += zi
     ...

What's a good function header?
targets: def lfilter(b, a, x, axis=(-1), zi=None):
inputs: def load_smbclient_auth_file(path):
targets: """Load credentials from an smbclient-style authentication file (used by
    smbclient, mount.cifs and others).  returns (domain, username, password)
    or raises AuthFileSyntaxError or any I/O exceptions.
    """
    lineno = 0
    domain = None
    username = None
    password = None
    for line in open(path):
        lineno += 1
        line = line.strip()
        if (line.startswith('#') or (line == '')):
            continue
        parts = line.split('=', 1)
        if (len(parts) != 2):
            raise AuthFileSyntaxError(path, lineno, 'No    "="    present    in    line')
        (k, v) = (parts[0].strip(), parts[1].strip())
        if (k == 'username'):
            username = v
        elif (k == 'password'):
            password = v
        elif (k == 'domain'):
            domain = v
        else:
            raise AuthFileSyntaxError(path, lineno, ('Unknown    option    %s' % repr(k)))
    return (domain, username, password)
inputs: I wrote the below code

    draft_dir = (course_data_path + '/drafts')
    if (not os.path.exists(draft_dir)):
        return
    errorlog = make_error_tracker()
    data_dir = xml_module_store.data_dir
    if (not data_dir.endswith('/')):
        data_dir += '/'
    draft_course_dir = draft_dir.replace(data_dir, '', 1)
    system = ImportSystem(xmlstore=xml_module_store, course_id=source_course_id, course_dir=draft_course_dir, error_tracker=errorlog.tracker, load_error_modules=False, mixins=xml_module_store.xblock_mixins, field_data=KvsFieldData(kvs=DictKeyValueStore()), target_course_id=target_id)
    def _import_module(module):
        module_location = module.location.map_into_course(target_id)
        _update_module_location(module, module_location.replace(revision=MongoRevisionKey.draft))
        parent_url = get_parent_url(module)
        index = index_in_children_list(module)
        if ((parent_url is not None) and (index is not None)):
            course_key = descriptor.location.course_key
            parent_location = course_key.make_usage_key_from_deprecated_string(parent_url)
            parent_location = parent_location.map_into_course(target_id)
            parent = store.get_item(parent_location, depth=0)
            non_draft_location = module.location.map_into_course(target_id)
            if (not any(((child.block_id == module.location.block_id) for child in parent.children))):
                parent.children.insert(index, non_draft_location)
                store.update_item(parent, user_id)
        _update_and_import_module(module, store, user_id, source_course_id, target_id, runtime=mongo_runtime)
        for child in module.get_children():
            _import_module(child)
    drafts = []
    for (rootdir, __, filenames) in os.walk(draft_dir):
        for filename in filenames:
            if filename.startswith('._'):
                continue
            module_path = os.path.join(rootdir, filename)
            with open(module_path, 'r') as f:
                try:
                    xml =...

What's a good function header?
targets: def _import_course_draft(xml_module_store, store, user_id, course_data_path, source_course_id, target_id, mongo_runtime):
inputs: def get_limits():
targets: """"limits": {
    "users": 1,
    "space": 0.5, # in GB
    "emails": 1000 # per month
    "expiry": "2099-12-31"
    """
    return frappe._dict((frappe.local.conf.limits or {}))
inputs: Complete the below
def create_quiver(x, y, u, v, scale=0.1, arrow_scale=0.3, angle=(math.pi / 9), **kwargs):

    ''''Returns data for a quiver plot.
    :param (list|ndarray) x: x coordinates of the arrow locations
    :param (list|ndarray) y: y coordinates of the arrow locations
    :param (list|ndarray) u: x components of the arrow vectors
    :param (list|ndarray) v: y components of the arrow vectors
    :param (float in [0,1]) scale: scales size of the arrows(ideally to
    avoid overlap). Default = .1
    :param (float in [0,1]) arrow_scale: value multiplied to length of barb
    to get length of arrowhead. Default = .3
    :param (angle in radians) angle: angle of arrowhead. Default = pi/9
    :param kwargs: kwargs passed through plotly.graph_objs.Scatter
    for more information on valid kwargs call
    help(plotly.graph_objs.Scatter)
    :rtype (dict): returns a representation of quiver figure.
    Example 1: Trivial Quiver
    import plotly.plotly as py
    from plotly.figure_factory import create_quiver
    import math
    # 1 Arrow from (0,0) to (1,1)
    fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1)
    py.plot(fig, filename=\'quiver\')
    Example 2: Quiver plot using meshgrid
    import plotly.plotly as py
    from plotly.figure_factory import create_quiver
    import numpy as np
    import math
    # Add data
    x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2))
    u = np.cos(x)*y
    v = np.sin(x)*y
    #Create quiver
    fig = create_quiver(x, y, u, v)
    # Plot
    py.plot(fig, filename=\'quiver\')
    Example 3: Styling the quiver plot
    import plotly.plotly as py
    from plotly.figure_factory import create_quiver
    import numpy as np
    import math
    # Add data
    x, y = np.meshgrid(np.arange(-np.pi, math.pi, .5),
    np.arange(-math.pi, math.pi, .5))
    u = np.cos(x)*y
    v = np.sin(x)*y
    # Create quiver
    fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi/6,
    name=\'Wind Velocity\', line=Line(width=1))
    # Add title to layout
    fig[\'layout\'].update(title=\'Quiver Plot\')
    # Plot
    py.plot(fig, filename=\'quiver\')'
    '''
targets: utils.validate_equal_length(x, y, u, v)
    utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale)
    (barb_x, barb_y) = _Quiver(x, y, u, v, scale, arrow_scale, angle).get_barbs()
    (arrow_x, arrow_y) = _Quiver(x, y, u, v, scale, arrow_scale, angle).get_quiver_arrows()
    quiver = graph_objs.Scatter(x=(barb_x + arrow_x), y=(barb_y + arrow_y), mode='lines', **kwargs)
    data = [quiver]
    layout = graph_objs.Layout(hovermode='closest')
    return graph_objs.Figure(data=data, layout=layout)
inputs: Complete the below
def _add_name_space(message, namespace=None):

    ''''Populate the name_space field in a messagecol buffer.
    Args:
    message: A messagecol buffer supporting the set_name_space() operation.
    namespace: The name of the namespace part. If None, use the
    default namespace. The empty namespace (i.e. \'\') will clear
    the name_space field.'
    '''
targets: if (namespace is None):
        namespace = namespace_manager.get_namespace()
    if (not namespace):
        message.clear_name_space()
    else:
        message.set_name_space(namespace)
inputs: I wrote the below code

    if is_available('pgrep'):
        results = call((GET_PID_BY_NAME_PGREP % process_name), None)
        if results:
            try:
                pids = list(map(int, results))
                if multiple:
                    return pids
                elif (len(pids) == 1):
                    return pids[0]
            except ValueError:
                pass
    if is_available('pidof'):
        results = call((GET_PID_BY_NAME_PIDOF % process_name), None)
        if (results and (len(results) == 1)):
            try:
                pids = list(map(int, results[0].split()))
                if multiple:
                    return pids
                elif (len(pids) == 1):
                    return pids[0]
            except ValueError:
                pass
    if is_available('ps'):
        if (not is_bsd()):
            results = call((GET_PID_BY_NAME_PS_LINUX % process_name), None)
            if results:
                try:
                    pids = list(map(int, results[1:]))
                    if multiple:
                        return pids
                    elif (len(pids) == 1):
                        return pids[0]
                except ValueError:
                    pass
        if is_bsd():
            results = call(GET_PID_BY_NAME_PS_BSD, None)
            if results:
                results = [r.split()[0] for r in results if r.endswith(('    %s' % process_name))]
                try:
                    pids = list(map(int, results))
                    if multiple:
                        return pids
                    elif (len(pids) == 1):
                        return pids[0]
                except ValueError:
                    pass
    if is_available('lsof'):
        results = call((GET_PID_BY_NAME_LSOF % process_name), None)
        if results:
            try:
                pids = list(map(int, results))
                if multiple:
                    return pids
                elif (len(pids) == 1):
                    return pids[0]
            except...

What's a good function header?
targets: def pid_by_name(process_name, multiple=False):
inputs: Complete the below
def iso8601_from_timestamp(timestamp):

    ''''Returns a iso8601 formated date from timestamp'
    '''
targets: return isotime(datetime.datetime.utcfromtimestamp(timestamp))
inputs: Complete the below
def get_brick(var):

    ''''Retrieves the brick that created this variable.
    See :func:`get_annotation`.'
    '''
targets: return get_annotation(var, Brick)
inputs: I wrote the below code

    arr = np.asarray(arr)
    shape = arr.shape
    if (shape[(-1)] < 3):
        raise ValueError('Input    array    has    less    than    3    color    channels')
    return dtype.img_as_float(arr, force_copy=True)


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

    if ((source not in _MAPPINGS) or (target not in _MAPPINGS[source])):
        if (target == u'universal'):
            _load_universal_map(source)
    return _MAPPINGS[source][target]


What's a good function header?
targets: def tagset_mapping(source, target):
inputs: Complete the below
def items_for_result(cl, result, form):

    ''''Generates the actual list of data.'
    '''
targets: first = True
    pk = cl.lookup_opts.pk.attname
    for field_name in cl.list_display:
        row_class = u''
        try:
            (f, attr, value) = lookup_field(field_name, result, cl.model_admin)
        except ObjectDoesNotExist:
            result_repr = EMPTY_CHANGELIST_VALUE
        else:
            if (f is None):
                if (field_name == u'action_checkbox'):
                    row_class = mark_safe(u'    class="action-checkbox"')
                allow_tags = getattr(attr, u'allow_tags', False)
                boolean = getattr(attr, u'boolean', False)
                if boolean:
                    allow_tags = True
                result_repr = display_for_value(value, boolean)
                if allow_tags:
                    result_repr = mark_safe(result_repr)
                if isinstance(value, (datetime.date, datetime.time)):
                    row_class = mark_safe(u'    class="nowrap"')
            else:
                if isinstance(f.rel, models.ManyToOneRel):
                    field_val = getattr(result, f.name)
                    if (field_val is None):
                        result_repr = EMPTY_CHANGELIST_VALUE
                    else:
                        result_repr = field_val
                else:
                    result_repr = display_for_field(value, f)
                if isinstance(f, (models.DateField, models.TimeField, models.ForeignKey)):
                    row_class = mark_safe(u'    class="nowrap"')
        if (force_text(result_repr) == u''):
            result_repr = mark_safe(u'&nbsp;')
        if ((first and (not cl.list_display_links)) or (field_name in cl.list_display_links)):
            table_tag = {True: u'th', False: u'td'}[first]
            first = False
            url = cl.url_for_result(result)
            if cl.to_field:
                attr = str(cl.to_field)
            else:
                attr = pk
            value = result.serializable_value(attr)
            result_id = repr(force_text(value))[1:]
            (yield...
inputs: Complete the below
@contextlib.contextmanager
def silence():

    ''''A context manager that silences sys.stdout and sys.stderr.'
    '''
targets: old_stdout = sys.stdout
    old_stderr = sys.stderr
    sys.stdout = _DummyFile()
    sys.stderr = _DummyFile()
    (yield)
    sys.stdout = old_stdout
    sys.stderr = old_stderr
inputs: I wrote the below code

    pass


What's a good function header?
targets: def _snapshot_metadata_update(context, snapshot_id, metadata, delete):
inputs: I wrote the below code

    if (code in ct.INDEX_LABELS):
        return ct.INDEX_LIST[code]
    elif (len(code) != 6):
        return ''
    else:
        return (('sh%s' % code) if (code[:1] in ['5', '6', '9']) else ('sz%s' % code))


What's a good function header?
targets: def _code_to_symbol(code):
inputs: Complete the below
@transaction.non_atomic_requests
@ensure_csrf_cookie
@cache_control(no_cache=True, no_store=True, must_revalidate=True)
@require_global_staff
@require_http_methods(['POST', 'DELETE'])
def certificate_invalidation_view(request, course_id):

    ''''Invalidate/Re-Validate students to/from certificate.
    :param request: HttpRequest object
    :param course_id: course identifier of the course for whom to add/remove certificates exception.
    :return: JsonResponse object with success/error message or certificate invalidation data.'
    '''
targets: course_key = CourseKey.from_string(course_id)
    try:
        certificate_invalidation_data = parse_request_data(request)
        certificate = validate_request_data_and_get_certificate(certificate_invalidation_data, course_key)
    except ValueError as error:
        return JsonResponse({'message': error.message}, status=400)
    if (request.method == 'POST'):
        try:
            certificate_invalidation = invalidate_certificate(request, certificate, certificate_invalidation_data)
        except ValueError as error:
            return JsonResponse({'message': error.message}, status=400)
        return JsonResponse(certificate_invalidation)
    elif (request.method == 'DELETE'):
        try:
            re_validate_certificate(request, course_key, certificate)
        except ValueError as error:
            return JsonResponse({'message': error.message}, status=400)
        return JsonResponse({}, status=204)
inputs: def _print_unix(objects, sep, end, file, flush):
targets: """A print_() implementation which writes bytes
    """
    encoding = _encoding
    if isinstance(sep, text_type):
        sep = sep.encode(encoding, 'replace')
    if (not isinstance(sep, bytes)):
        raise TypeError
    if isinstance(end, text_type):
        end = end.encode(encoding, 'replace')
    if (not isinstance(end, bytes)):
        raise TypeError
    if (end == '\n'):
        end = os.linesep
        if PY3:
            end = end.encode('ascii')
    parts = []
    for obj in objects:
        if ((not isinstance(obj, text_type)) and (not isinstance(obj, bytes))):
            obj = text_type(obj)
        if isinstance(obj, text_type):
            if PY2:
                obj = obj.encode(encoding, 'replace')
            else:
                try:
                    obj = obj.encode(encoding, 'surrogateescape')
                except UnicodeEncodeError:
                    obj = obj.encode(encoding, 'replace')
        assert isinstance(obj, bytes)
        parts.append(obj)
    data = (sep.join(parts) + end)
    assert isinstance(data, bytes)
    file = getattr(file, 'buffer', file)
    try:
        file.write(data)
    except TypeError:
        if PY3:
            surr_data = data.decode(encoding, 'surrogateescape')
            try:
                file.write(surr_data)
            except (TypeError, ValueError):
                file.write(data.decode(encoding, 'replace'))
        else:
            file.write(data.decode(encoding, 'replace'))
    if flush:
        file.flush()
inputs: I wrote the below code

    ctx.db.commit()
    ctx.db_transaction = True


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

    inner_mlp = MLP(layers=[Linear(10, 'h0', 0.1), Linear(10, 'h1', 0.1)], layer_name='inner_mlp')
    outer_mlp = MLP(layers=[CompositeLayer(layer_name='composite', layers=[inner_mlp, Linear(10, 'h2', 0.1)])], nvis=10)
    X = outer_mlp.get_input_space().make_theano_batch()
    f = theano.function([X], outer_mlp.fprop(X))
    f(np.random.rand(5, 10).astype(theano.config.floatX))


What's a good function header?
targets: def test_nested_mlp():
inputs: Complete the below
def _minpoly_exp(ex, x):

    ''''Returns the minimal polynomial of ``exp(ex)``'
    '''
targets: (c, a) = ex.args[0].as_coeff_Mul()
    p = sympify(c.p)
    q = sympify(c.q)
    if (a == (I * pi)):
        if c.is_rational:
            if ((c.p == 1) or (c.p == (-1))):
                if (q == 3):
                    return (((x ** 2) - x) + 1)
                if (q == 4):
                    return ((x ** 4) + 1)
                if (q == 6):
                    return (((x ** 4) - (x ** 2)) + 1)
                if (q == 8):
                    return ((x ** 8) + 1)
                if (q == 9):
                    return (((x ** 6) - (x ** 3)) + 1)
                if (q == 10):
                    return (((((x ** 8) - (x ** 6)) + (x ** 4)) - (x ** 2)) + 1)
                if q.is_prime:
                    s = 0
                    for i in range(q):
                        s += ((- x) ** i)
                    return s
            factors = [cyclotomic_poly(i, x) for i in divisors((2 * q))]
            mp = _choose_factor(factors, x, ex)
            return mp
        else:
            raise NotAlgebraic(("%s    doesn't    seem    to    be    an    algebraic    element" % ex))
    raise NotAlgebraic(("%s    doesn't    seem    to    be    an    algebraic    element" % ex))
inputs: def GetOrderedIntersection(handler_list):
targets: """Implements algorithm for combining and reordering Handlers.
    GetOrderedIntersection performs the heavy lifting of converting a randomly
    ordered list of Handlers (globbed patterns, each with various potentially
    conflicting properties attached), into an ordered list of handlers with
    property values resolved.
    The purpose of this process is to convert the Web.xml URL mapping scheme to
    that of app.yaml. In Web.xml the most specific path, according to
    literal-ness and length, is chosen. In app.yaml the first listed matching
    path is chosen. Thus to preserve user preferences through the translation
    process we order the patterns from specific to general.
    For example, if three handlers are given as input (in any order):
    "/admin/*" (security=admin)
    "/*.png" (type=static)
    "*" (type=dynamic, security=required)
    we want to get this ordered list as output:
    1. "/admin/*.png" (security=admin, type=static)
    2. "/admin/*" (security=admin, type=dynamic)
    3. "/*.png" (security=required, type=static)
    4. "*" (type=dynamic, security=required).
    so that the properties of any given path are those of the longest matching
    path. The SimpleHandler and OverlappedHandler classes provide the logic for
    attaching globbed patterns to the right properties and resolving potential
    property value conflicts.
    Args:
    handler_list: List of SimpleHandlers in arbitrary order.
    Returns:
    An ordered list of OverlappedHandlers and SimpleHandlers. See the above
    example for what this would look like.
    """
    results = _Intersect(handler_list)
    results = sorted(results, key=(lambda h: h.pattern))
    _ReorderHandlers(results)
    _GivePropertiesFromGeneralToSpecific(results)
    return _RemoveRedundantHandlers(results)
inputs: Complete the below
def load_vint(buf, pos):

    ''''Load variable-size int.'
    '''
targets: limit = min((pos + 11), len(buf))
    res = ofs = 0
    while (pos < limit):
        b = _byte_code(buf[pos])
        res += ((b & 127) << ofs)
        pos += 1
        ofs += 7
        if (b < 128):
            return (res, pos)
    raise BadRarFile('cannot    load    vint')
inputs: Complete the below
def _get_created(created):

    ''''Returns a datetime.
    If `created` is "now", it returns `datetime.datetime.now()`. If `created`
    is set use that. Otherwise generate a random datetime in the year 2011.'
    '''
targets: if (created == 'now'):
        return datetime.now()
    elif created:
        return created
    else:
        return datetime(2011, random.randint(1, 12), random.randint(1, 28), random.randint(0, 23), random.randint(0, 59), random.randint(0, 59))
inputs: @frappe.whitelist()
def mark_as_trash(communication):
targets: """set email status to trash
    """
    frappe.db.set_value('Communication', communication, 'email_status', 'Trash')
inputs: Complete the below
def gen_key(path):

    ''''Generate a key for use with salt-ssh'
    '''
targets: cmd = u'ssh-keygen    -P    ""    -f    {0}    -t    rsa    -q'.format(path)
    if (not os.path.isdir(os.path.dirname(path))):
        os.makedirs(os.path.dirname(path))
    subprocess.call(cmd, shell=True)
inputs: def abstractMethod():
targets: """This should be called when an abstract method is called that should have been
    implemented by a subclass. It should not be called in situations where no implementation
    (i.e. a \pass\ behavior) is acceptable.
    """
    raise NotImplementedError('Method    not    implemented!')
inputs: I wrote the below code

    family = address_type(address)
    s = socket.socket(getattr(socket, family))
    t = _init_timeout()
    while 1:
        try:
            s.connect(address)
        except socket.error as e:
            if ((e.args[0] != errno.ECONNREFUSED) or _check_timeout(t)):
                debug('failed    to    connect    to    address    %s', address)
                raise
            time.sleep(0.01)
        else:
            break
    else:
        raise
    fd = duplicate(s.fileno())
    conn = _multiprocessing.Connection(fd)
    s.close()
    return conn


What's a good function header?
targets: def SocketClient(address):
inputs: def get_easy_s3(config_file=None, cache=False):
targets: """Factory for EasyS3 class that attempts to load AWS credentials from
    the StarCluster config file. Returns an EasyS3 object if
    successful.
    """
    cfg = get_config(config_file, cache)
    return cfg.get_easy_s3()
inputs: I wrote the below code

    f.contextfunction = True
    return f


What's a good function header?
targets: def contextfunction(f):
inputs: Complete the below
def expire():

    ''''Expire the current session cookie.'
    '''
targets: name = cherrypy.serving.request.config.get('tools.sessions.name', 'session_id')
    one_year = (((60 * 60) * 24) * 365)
    e = (time.time() - one_year)
    cherrypy.serving.response.cookie[name]['expires'] = httputil.HTTPDate(e)
inputs: def get_token(request):
targets: """Returns the CSRF token required for a POST form. The token is an
    alphanumeric value.
    A side effect of calling this function is to make the csrf_protect
    decorator and the CsrfViewMiddleware add a CSRF cookie and a \Vary: Cookie\
    header to the outgoing response.  For this reason, you may need to use this
    function lazily, as is done by the csrf context processor.
    """
    request.META[u'CSRF_COOKIE_USED'] = True
    return request.META.get(u'CSRF_COOKIE', None)
inputs: I wrote the below code

    if __salt__['config.option']('virt.tunnel'):
        return 'virsh    migrate    --p2p    --tunnelled    --live    --persistent    --undefinesource    '
    return 'virsh    migrate    --live    --persistent    --undefinesource    '


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

    names[t[1]] = t[3]


What's a good function header?
targets: def p_statement_assign(t):
inputs: @hooks.before('Events    >    Events    under    an    Event    Sub-topic    >    List    All    Events    under    an    Event    Sub-topic')
def evnt_sub_topic_event_get_list(transaction):
targets: """GET /event-sub-topics/1/events
    :param transaction:
    :return:
    """
    with stash['app'].app_context():
        event_sub_topic = EventSubTopicFactory()
        db.session.add(event_sub_topic)
        event = EventFactoryBasic(event_sub_topic_id=1)
        db.session.add(event)
        db.session.commit()
inputs: I wrote the below code

    (b, a) = normalize(b, a)
    b = ((b + 0.0) / a[0])
    a = ((a + 0.0) / a[0])
    k = b[0]
    b /= b[0]
    z = roots(b)
    p = roots(a)
    return (z, p, k)


What's a good function header?
targets: def tf2zpk(b, a):
inputs: Complete the below
def fetch_differentiable_fixed_embeddings(comp, state, stride):

    ''''Looks up fixed features with separate, differentiable, embedding lookup.
    Args:
    comp: Component whose fixed features we wish to look up.
    state: live MasterState object for the component.
    stride: Tensor containing current batch * beam size.
    Returns:
    state handle: updated state handle to be used after this call
    fixed_embeddings: list of NamedTensor objects'
    '''
targets: _validate_embedded_fixed_features(comp)
    num_channels = len(comp.spec.fixed_feature)
    if (not num_channels):
        return (state.handle, [])
    (state.handle, indices, ids, weights, num_steps) = dragnn_ops.bulk_fixed_features(state.handle, component=comp.name, num_channels=num_channels)
    fixed_embeddings = []
    for (channel, feature_spec) in enumerate(comp.spec.fixed_feature):
        differentiable_or_constant = ('constant' if feature_spec.is_constant else 'differentiable')
        tf.logging.info('[%s]    Adding    %s    fixed    feature    "%s"', comp.name, differentiable_or_constant, feature_spec.name)
        size = ((stride * num_steps) * feature_spec.size)
        fixed_embedding = network_units.embedding_lookup(comp.get_variable(network_units.fixed_embeddings_name(channel)), indices[channel], ids[channel], weights[channel], size)
        if feature_spec.is_constant:
            fixed_embedding = tf.stop_gradient(fixed_embedding)
        fixed_embeddings.append(network_units.NamedTensor(fixed_embedding, feature_spec.name))
    return (state.handle, fixed_embeddings)
inputs: Complete the below
def import_no_db_in_virt(logical_line, filename):

    ''''Check for db calls from nova/virt
    As of grizzly-2 all the database calls have been removed from
    nova/virt, and we want to keep it that way.
    N307'
    '''
targets: if (('nova/virt' in filename) and (not filename.endswith('fake.py'))):
        if logical_line.startswith('from    nova    import    db'):
            (yield (0, 'N307:    nova.db    import    not    allowed    in    nova/virt/*'))
inputs: Complete the below
def get_registered(msg_type_name, default_package=None):

    ''''@param msg_type_name: name of message type
    @type  msg_type_name: str
    @return: msg spec for msg type name
    @rtype: L{MsgSpec}'
    '''
targets: if (msg_type_name in REGISTERED_TYPES):
        return REGISTERED_TYPES[msg_type_name]
    elif default_package:
        (p, n) = roslib.names.package_resource_name(msg_type_name)
        if (not p):
            return REGISTERED_TYPES[roslib.names.resource_name(default_package, msg_type_name)]
    raise KeyError(msg_type_name)
inputs: Complete the below
def encrypt_int(message, ekey, n):

    ''''Encrypts a message using encryption key \'ekey\', working modulo n'
    '''
targets: assert_int(message, 'message')
    assert_int(ekey, 'ekey')
    assert_int(n, 'n')
    if (message < 0):
        raise ValueError('Only    non-negative    numbers    are    supported')
    if (message > n):
        raise OverflowError(('The    message    %i    is    too    long    for    n=%i' % (message, n)))
    return pow(message, ekey, n)
inputs: I wrote the below code

    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
    assert_almost_equal(a, b, rtol, atol, names)


What's a good function header?
targets: def assert_almost_equal_ignore_nan(a, b, rtol=None, atol=None, names=('a', 'b')):
inputs: Complete the below
def EncodedFile(file, data_encoding, file_encoding=None, errors='strict'):

    ''''Return a wrapped version of file which provides transparent
    encoding translation.
    Strings written to the wrapped file are interpreted according
    to the given data_encoding and then written to the original
    file as string using file_encoding. The intermediate encoding
    will usually be Unicode but depends on the specified codecs.
    Strings are read from the file using file_encoding and then
    passed back to the caller as string using data_encoding.
    If file_encoding is not given, it defaults to data_encoding.
    errors may be given to define the error handling. It defaults
    to \'strict\' which causes ValueErrors to be raised in case an
    encoding error occurs.
    The returned wrapped file object provides two extra attributes
    .data_encoding and .file_encoding which reflect the given
    parameters of the same name. The attributes can be used for
    introspection by Python programs.'
    '''
targets: if (file_encoding is None):
        file_encoding = data_encoding
    data_info = lookup(data_encoding)
    file_info = lookup(file_encoding)
    sr = StreamRecoder(file, data_info.encode, data_info.decode, file_info.streamreader, file_info.streamwriter, errors)
    sr.data_encoding = data_encoding
    sr.file_encoding = file_encoding
    return sr
inputs: def formatdate(timeval=None, localtime=False, usegmt=False):
targets: """Returns a date string as specified by RFC 2822, e.g.:
    Fri, 09 Nov 2001 01:08:47 -0000
    Optional timeval if given is a floating point time value as accepted by
    gmtime() and localtime(), otherwise the current time is used.
    Optional localtime is a flag that when True, interprets timeval, and
    returns a date relative to the local timezone instead of UTC, properly
    taking daylight savings time into account.
    Optional argument usegmt means that the timezone is written out as
    an ascii string, not numeric one (so "GMT" instead of "+0000"). This
    is needed for HTTP, and is only used when localtime==False.
    """
    if (timeval is None):
        timeval = time.time()
    if localtime:
        now = time.localtime(timeval)
        if (time.daylight and now[(-1)]):
            offset = time.altzone
        else:
            offset = time.timezone
        (hours, minutes) = divmod(abs(offset), 3600)
        if (offset > 0):
            sign = '-'
        else:
            sign = '+'
        zone = ('%s%02d%02d' % (sign, hours, (minutes // 60)))
    else:
        now = time.gmtime(timeval)
        if usegmt:
            zone = 'GMT'
        else:
            zone = '-0000'
    return ('%s,    %02d    %s    %04d    %02d:%02d:%02d    %s' % (['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]], now[2], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][(now[1] - 1)], now[0], now[3], now[4], now[5], zone))
inputs: def login_protected_view(request):
targets: """A simple view that is login protected.
    """
    t = Template('This    is    a    login    protected    test.    Username    is    {{    user.username    }}.', name='Login    Template')
    c = Context({'user': request.user})
    return HttpResponse(t.render(c))
inputs: I wrote the below code

    _sanity_check(fh)
    dhead = _parse_header(fh)
    (dcmetrics_ascii, dcmetrics_name) = _parse_char_metrics(fh)
    doptional = _parse_optional(fh)
    return (dhead, dcmetrics_ascii, dcmetrics_name, doptional[0], doptional[1])


What's a good function header?
targets: def parse_afm(fh):
inputs: def _SharedSuffix(pattern1, pattern2):
targets: """Returns the shared suffix of two patterns.
    """
    return _SharedPrefix(pattern1[::(-1)], pattern2[::(-1)])[::(-1)]
inputs: Complete the below
def absent(name, user='root', identifier=False, special=None, **kwargs):

    ''''Verifies that the specified cron job is absent for the specified user; only
    the name is matched when removing a cron job.
    name
    The command that should be absent in the user crontab.
    user
    The name of the user whose crontab needs to be modified, defaults to
    the root user
    identifier
    Custom-defined identifier for tracking the cron line for future crontab
    edits. This defaults to the state id
    special
    The special keyword used in the job (eg. @reboot, @hourly...)'
    '''
targets: name = name.strip()
    if (identifier is False):
        identifier = name
    ret = {'name': name, 'result': True, 'changes': {}, 'comment': ''}
    if __opts__['test']:
        status = _check_cron(user, name, identifier=identifier)
        ret['result'] = None
        if (status == 'absent'):
            ret['result'] = True
            ret['comment'] = 'Cron    {0}    is    absent'.format(name)
        elif ((status == 'present') or (status == 'update')):
            ret['comment'] = 'Cron    {0}    is    set    to    be    removed'.format(name)
        return ret
    if (special is None):
        data = __salt__['cron.rm_job'](user, name, identifier=identifier)
    else:
        data = __salt__['cron.rm_special'](user, special, name)
    if (data == 'absent'):
        ret['comment'] = 'Cron    {0}    already    absent'.format(name)
        return ret
    if (data == 'removed'):
        ret['comment'] = "Cron    {0}    removed    from    {1}'s    crontab".format(name, user)
        ret['changes'] = {user: name}
        return ret
    ret['comment'] = 'Cron    {0}    for    user    {1}    failed    to    commit    with    error    {2}'.format(name, user, data)
    ret['result'] = False
    return ret
inputs: def _get_marker_param(request):
targets: """Extract marker id from request or fail
    """
    return request.GET['marker']
inputs: def Name(name, prefix=None):
targets: """Return a NAME leaf
    """
    return Leaf(token.NAME, name, prefix=prefix)
inputs: @task(rate_limit='5/m')
@timeit
def _rebuild_kb_chunk(data):
targets: """Re-render a chunk of documents.
    Note: Don\t use host components when making redirects to wiki pages; those
    redirects won\t be auto-pruned when they\re 404s.
    """
    log.info(('Rebuilding    %s    documents.' % len(data)))
    pin_this_thread()
    messages = []
    start = time.time()
    for pk in data:
        message = None
        try:
            document = Document.objects.get(pk=pk)
            url = document.redirect_url()
            if (url and points_to_document_view(url) and (not document.redirect_document())):
                log.warn(('Invalid    redirect    document:    %d' % pk))
            html = document.parse_and_calculate_links()
            if (document.html != html):
                Document.objects.filter(pk=pk).update(html=html)
                statsd.incr('wiki.rebuild_chunk.change')
            else:
                statsd.incr('wiki.rebuild_chunk.nochange')
        except Document.DoesNotExist:
            message = ('Missing    document:    %d' % pk)
        except Revision.DoesNotExist:
            message = ('Missing    revision    for    document:    %d' % pk)
        except ValidationError as e:
            message = ('ValidationError    for    %d:    %s' % (pk, e.messages[0]))
        except SlugCollision:
            message = ('SlugCollision:    %d' % pk)
        except TitleCollision:
            message = ('TitleCollision:    %d' % pk)
        if message:
            log.debug(message)
            messages.append(message)
    d = (time.time() - start)
    statsd.timing('wiki.rebuild_chunk', int(round((d * 1000))))
    if messages:
        subject = ('[%s]    Exceptions    raised    in    _rebuild_kb_chunk()' % settings.PLATFORM_NAME)
        mail_admins(subject=subject, message='\n'.join(messages))
    if (not transaction.get_connection().in_atomic_block):
        transaction.commit()
    unpin_this_thread()