id_within_dataset
int64
1
55.5k
snippet
stringlengths
19
14.2k
tokens
listlengths
6
1.63k
nl
stringlengths
6
352
split_within_dataset
stringclasses
1 value
is_duplicated
bool
2 classes
29,050
def run_post_add_script(component, translation, filename): run_hook(component, translation, component.post_add_script, None, filename)
[ "def", "run_post_add_script", "(", "component", ",", "translation", ",", "filename", ")", ":", "run_hook", "(", "component", ",", "translation", ",", "component", ".", "post_add_script", ",", "None", ",", "filename", ")" ]
post add hook .
train
false
29,051
def add_releases_to_collection(collection, releases=[]): releaselist = ';'.join(releases) return _do_mb_put(('collection/%s/releases/%s' % (collection, releaselist)))
[ "def", "add_releases_to_collection", "(", "collection", ",", "releases", "=", "[", "]", ")", ":", "releaselist", "=", "';'", ".", "join", "(", "releases", ")", "return", "_do_mb_put", "(", "(", "'collection/%s/releases/%s'", "%", "(", "collection", ",", "relea...
add releases to a collection .
train
false
29,052
def DEFINE_multi_int(name, default, help, lower_bound=None, upper_bound=None, flag_values=FLAGS, **args): parser = IntegerParser(lower_bound, upper_bound) serializer = ArgumentSerializer() DEFINE_multi(parser, serializer, name, default, help, flag_values, **args)
[ "def", "DEFINE_multi_int", "(", "name", ",", "default", ",", "help", ",", "lower_bound", "=", "None", ",", "upper_bound", "=", "None", ",", "flag_values", "=", "FLAGS", ",", "**", "args", ")", ":", "parser", "=", "IntegerParser", "(", "lower_bound", ",", ...
registers a flag whose value can be a list of arbitrary integers .
train
true
29,053
def test_wrap_at_without_new(): l1 = Longitude(([1] * u.deg)) l2 = Longitude(([2] * u.deg)) l = np.concatenate([l1, l2]) assert (l._wrap_angle is not None)
[ "def", "test_wrap_at_without_new", "(", ")", ":", "l1", "=", "Longitude", "(", "(", "[", "1", "]", "*", "u", ".", "deg", ")", ")", "l2", "=", "Longitude", "(", "(", "[", "2", "]", "*", "u", ".", "deg", ")", ")", "l", "=", "np", ".", "concaten...
regression test for subtle bugs from situations where an angle is created via numpy channels that dont do the standard __new__ but instead depend on array_finalize to set state .
train
false
29,054
def _build_option_description(k): o = _get_registered_option(k) d = _get_deprecated_option(k) s = (u('%s ') % k) if o.doc: s += '\n'.join(o.doc.strip().split('\n')) else: s += 'No description available.' if o: s += (u('\n [default: %s] [currently: %s]') % (o.defval, _get_option(k, True))) if d: s += u('\n (Deprecated') s += ((u(', use `%s` instead.') % d.rkey) if d.rkey else '') s += u(')') s += '\n\n' return s
[ "def", "_build_option_description", "(", "k", ")", ":", "o", "=", "_get_registered_option", "(", "k", ")", "d", "=", "_get_deprecated_option", "(", "k", ")", "s", "=", "(", "u", "(", "'%s '", ")", "%", "k", ")", "if", "o", ".", "doc", ":", "s", "+=...
builds a formatted description of a registered option and prints it .
train
false
29,055
def test_mpl_preserve_image_tight(): f = create_figure() exp = mplhooks.figure_to_rgb_array(f) (width, height) = f.canvas.get_width_height() s = mplhooks.figure_to_tight_array(f, (0.5 * width), (0.5 * height), True) obs = mplhooks.figure_to_rgb_array(f) plt.close(f) assert np.all((exp == obs))
[ "def", "test_mpl_preserve_image_tight", "(", ")", ":", "f", "=", "create_figure", "(", ")", "exp", "=", "mplhooks", ".", "figure_to_rgb_array", "(", "f", ")", "(", "width", ",", "height", ")", "=", "f", ".", "canvas", ".", "get_width_height", "(", ")", "...
make sure that the figure preserves height settings .
train
false
29,056
def rewind_body(prepared_request): body_seek = getattr(prepared_request.body, 'seek', None) if ((body_seek is not None) and isinstance(prepared_request._body_position, integer_types)): try: body_seek(prepared_request._body_position) except (IOError, OSError): raise UnrewindableBodyError('An error occured when rewinding request body for redirect.') else: raise UnrewindableBodyError('Unable to rewind request body for redirect.')
[ "def", "rewind_body", "(", "prepared_request", ")", ":", "body_seek", "=", "getattr", "(", "prepared_request", ".", "body", ",", "'seek'", ",", "None", ")", "if", "(", "(", "body_seek", "is", "not", "None", ")", "and", "isinstance", "(", "prepared_request", ...
move file pointer back to its recorded starting position so it can be read again on redirect .
train
true
29,057
def ManifestFromXMLFile(filename_or_file): manifest = Manifest() manifest.parse(filename_or_file) return manifest
[ "def", "ManifestFromXMLFile", "(", "filename_or_file", ")", ":", "manifest", "=", "Manifest", "(", ")", "manifest", ".", "parse", "(", "filename_or_file", ")", "return", "manifest" ]
create and return manifest instance from file .
train
false
29,058
def captured_stdout(): return captured_output('stdout')
[ "def", "captured_stdout", "(", ")", ":", "return", "captured_output", "(", "'stdout'", ")" ]
a variation on support .
train
false
29,060
def GPGKeyCheck(value): value = value.replace(' ', '').replace(' DCTB ', '').strip() if (value in ('!CREATE', '!PASSWORD')): return value try: if (len(value) not in (8, 16, 40)): raise ValueError(_('Not a GPG key ID or fingerprint')) if (re.match('^[0-9A-F]+$', value.upper()) is None): raise ValueError(_('Not a GPG key ID or fingerprint')) except ValueError: try: return EmailCheck(value) except ValueError: raise ValueError(_('Not a GPG key ID or fingerprint')) return value.upper()
[ "def", "GPGKeyCheck", "(", "value", ")", ":", "value", "=", "value", ".", "replace", "(", "' '", ",", "''", ")", ".", "replace", "(", "' DCTB '", ",", "''", ")", ".", "strip", "(", ")", "if", "(", "value", "in", "(", "'!CREATE'", ",", "'!PASSWORD'"...
strip a gpg fingerprint of all spaces .
train
false
29,061
def enable_layer(r, **attr): if (r.component_name != 'layer_entity'): session.error = T('Incorrect parameters') redirect(URL(args=[r.id, 'layer_entity'])) ltable = s3db.gis_layer_config query = ((ltable.config_id == r.id) & (ltable.layer_id == r.component_id)) db(query).update(enabled=True) session.confirmation = T('Layer has been Enabled') redirect(URL(args=[r.id, 'layer_entity']))
[ "def", "enable_layer", "(", "r", ",", "**", "attr", ")", ":", "if", "(", "r", ".", "component_name", "!=", "'layer_entity'", ")", ":", "session", ".", "error", "=", "T", "(", "'Incorrect parameters'", ")", "redirect", "(", "URL", "(", "args", "=", "[",...
enable a layer designed to be a custom method called by an action button @todo: make this call an api function which can then also be used by cli scripts .
train
false
29,063
def test_filename(path): return os.path.join(test_dirname(), path)
[ "def", "test_filename", "(", "path", ")", ":", "return", "os", ".", "path", ".", "join", "(", "test_dirname", "(", ")", ",", "path", ")" ]
return an absolute path to a resource within orange .
train
false
29,064
def _test_logged_method(method_name, original_name): def _run_with_logging(self, *args, **kwargs): original = getattr(self, original_name) method = getattr(original, method_name) try: TEST_MESSAGE(method=method_name.decode('ascii')).write() return method(*args, **kwargs) except Exception: TEST_EXCEPTION(method=method_name.decode('ascii')).write() raise return _run_with_logging
[ "def", "_test_logged_method", "(", "method_name", ",", "original_name", ")", ":", "def", "_run_with_logging", "(", "self", ",", "*", "args", ",", "**", "kwargs", ")", ":", "original", "=", "getattr", "(", "self", ",", "original_name", ")", "method", "=", "...
decorator for logging message to eliot logger .
train
false
29,066
@py.test.mark.parametrize('item_name', [item.name for item in six._urllib_response_moved_attributes]) def test_move_items_urllib_response(item_name): if (sys.version_info[:2] >= (2, 6)): assert (item_name in dir(six.moves.urllib.response)) getattr(six.moves.urllib.response, item_name)
[ "@", "py", ".", "test", ".", "mark", ".", "parametrize", "(", "'item_name'", ",", "[", "item", ".", "name", "for", "item", "in", "six", ".", "_urllib_response_moved_attributes", "]", ")", "def", "test_move_items_urllib_response", "(", "item_name", ")", ":", ...
ensure that everything loads correctly .
train
false
29,067
def getManipulatedGeometryOutput(elementNode, geometryOutput, prefix): flippedGeometryOutput = triangle_mesh.getGeometryOutputCopy(geometryOutput) flip.flipPoints(elementNode, matrix.getVertexes(flippedGeometryOutput), prefix) if flip.getShouldReverse(elementNode, prefix): flippedFaces = face.getFaces(flippedGeometryOutput) for flippedFace in flippedFaces: flippedFace.vertexIndexes.reverse() return {'union': {'shapes': [flippedGeometryOutput, geometryOutput]}}
[ "def", "getManipulatedGeometryOutput", "(", "elementNode", ",", "geometryOutput", ",", "prefix", ")", ":", "flippedGeometryOutput", "=", "triangle_mesh", ".", "getGeometryOutputCopy", "(", "geometryOutput", ")", "flip", ".", "flipPoints", "(", "elementNode", ",", "mat...
get equated geometryoutput .
train
false
29,068
def CheckAltTokens(filename, clean_lines, linenum, error): line = clean_lines.elided[linenum] if Match('^\\s*#', line): return if ((line.find('/*') >= 0) or (line.find('*/') >= 0)): return for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line): error(filename, linenum, 'readability/alt_tokens', 2, ('Use operator %s instead of %s' % (_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1))))
[ "def", "CheckAltTokens", "(", "filename", ",", "clean_lines", ",", "linenum", ",", "error", ")", ":", "line", "=", "clean_lines", ".", "elided", "[", "linenum", "]", "if", "Match", "(", "'^\\\\s*#'", ",", "line", ")", ":", "return", "if", "(", "(", "li...
check alternative keywords being used in boolean expressions .
train
true
29,069
def certificate_get_all_by_user_and_project(context, user_id, project_id): return IMPL.certificate_get_all_by_user_and_project(context, user_id, project_id)
[ "def", "certificate_get_all_by_user_and_project", "(", "context", ",", "user_id", ",", "project_id", ")", ":", "return", "IMPL", ".", "certificate_get_all_by_user_and_project", "(", "context", ",", "user_id", ",", "project_id", ")" ]
get all certificates for a user and project .
train
false
29,070
@contextmanager def docutils_namespace(): try: _directives = copy(directives._directives) _roles = copy(roles._roles) (yield) finally: directives._directives = _directives roles._roles = _roles
[ "@", "contextmanager", "def", "docutils_namespace", "(", ")", ":", "try", ":", "_directives", "=", "copy", "(", "directives", ".", "_directives", ")", "_roles", "=", "copy", "(", "roles", ".", "_roles", ")", "(", "yield", ")", "finally", ":", "directives",...
create namespace for rest parsers .
train
false
29,071
def _CreateProjectObjects(target_list, target_dicts, options, msvs_version): global fixpath_prefix projects = {} for qualified_target in target_list: spec = target_dicts[qualified_target] if (spec['toolset'] != 'target'): raise GypError(('Multiple toolsets not supported in msvs build (target %s)' % qualified_target)) (proj_path, fixpath_prefix) = _GetPathOfProject(qualified_target, spec, options, msvs_version) guid = _GetGuidOfProject(proj_path, spec) overrides = _GetPlatformOverridesOfProject(spec) build_file = gyp.common.BuildFile(qualified_target) obj = MSVSNew.MSVSProject(proj_path, name=spec['target_name'], guid=guid, spec=spec, build_file=build_file, config_platform_overrides=overrides, fixpath_prefix=fixpath_prefix) if msvs_version.UsesVcxproj(): obj.set_msbuild_toolset(_GetMsbuildToolsetOfProject(proj_path, spec, msvs_version)) projects[qualified_target] = obj for project in projects.values(): if (not project.spec.get('msvs_external_builder')): deps = project.spec.get('dependencies', []) deps = [projects[d] for d in deps] project.set_dependencies(deps) return projects
[ "def", "_CreateProjectObjects", "(", "target_list", ",", "target_dicts", ",", "options", ",", "msvs_version", ")", ":", "global", "fixpath_prefix", "projects", "=", "{", "}", "for", "qualified_target", "in", "target_list", ":", "spec", "=", "target_dicts", "[", ...
create a msvsproject object for the targets found in target list .
train
false
29,072
@step(u'I answer a "([^"]*)" problem "([^"]*)ly"') def answer_problem_step(step, problem_type, correctness): input_problem_answer(step, problem_type, correctness) submit_problem(step)
[ "@", "step", "(", "u'I answer a \"([^\"]*)\" problem \"([^\"]*)ly\"'", ")", "def", "answer_problem_step", "(", "step", ",", "problem_type", ",", "correctness", ")", ":", "input_problem_answer", "(", "step", ",", "problem_type", ",", "correctness", ")", "submit_problem",...
mark a given problem type correct or incorrect .
train
false
29,073
def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True): d = attribute_mixing_dict(G, attribute, nodes) a = dict_to_numpy_array(d, mapping=mapping) if normalized: a = (a / a.sum()) return a
[ "def", "attribute_mixing_matrix", "(", "G", ",", "attribute", ",", "nodes", "=", "None", ",", "mapping", "=", "None", ",", "normalized", "=", "True", ")", ":", "d", "=", "attribute_mixing_dict", "(", "G", ",", "attribute", ",", "nodes", ")", "a", "=", ...
return mixing matrix for attribute .
train
false
29,074
def test_header_start_exception(): for readerclass in [ascii.NoHeader, ascii.SExtractor, ascii.Ipac, ascii.BaseReader, ascii.FixedWidthNoHeader, ascii.Cds, ascii.Daophot]: with pytest.raises(ValueError): reader = ascii.core._get_reader(readerclass, header_start=5)
[ "def", "test_header_start_exception", "(", ")", ":", "for", "readerclass", "in", "[", "ascii", ".", "NoHeader", ",", "ascii", ".", "SExtractor", ",", "ascii", ".", "Ipac", ",", "ascii", ".", "BaseReader", ",", "ascii", ".", "FixedWidthNoHeader", ",", "ascii"...
check certain readers throw an exception if header_start is set for certain readers it does not make sense to set the header_start .
train
false
29,075
@contextlib.contextmanager def MockEventNotification(response_method, native_filetype_completer=True): with patch(u'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync', return_value=MagicMock(return_value=True)): with patch(u'ycm.client.event_notification.JsonFromFuture', side_effect=response_method): with patch(u'ycm.youcompleteme.YouCompleteMe.FiletypeCompleterExistsForFiletype', return_value=native_filetype_completer): (yield)
[ "@", "contextlib", ".", "contextmanager", "def", "MockEventNotification", "(", "response_method", ",", "native_filetype_completer", "=", "True", ")", ":", "with", "patch", "(", "u'ycm.client.base_request.BaseRequest.PostDataToHandlerAsync'", ",", "return_value", "=", "Magic...
mock out the eventnotification client request object .
train
false
29,076
def locked(path, timeout=None): def decor(func): @functools.wraps(func) def wrapper(*args, **kwargs): lock = FileLock(path, timeout=timeout) lock.acquire() try: return func(*args, **kwargs) finally: lock.release() return wrapper return decor
[ "def", "locked", "(", "path", ",", "timeout", "=", "None", ")", ":", "def", "decor", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "**", "kwargs", ")", ":", "lock", "=", "FileLoc...
a context manager for locking an instance of a qmutex .
train
true
29,077
def function_serializer(function): try: return {'function': str(function), 'file': getfile(function), 'line': getsourcelines(function)[1]} except IOError: return {'function': str(function)} except TypeError: if isinstance(function, partial): return {'partial': function_serializer(function.func)} else: return {'function': str(function)}
[ "def", "function_serializer", "(", "function", ")", ":", "try", ":", "return", "{", "'function'", ":", "str", "(", "function", ")", ",", "'file'", ":", "getfile", "(", "function", ")", ",", "'line'", ":", "getsourcelines", "(", "function", ")", "[", "1",...
serialize the given function for logging by eliot .
train
false
29,078
def format_suffix_patterns(urlpatterns, suffix_required=False, allowed=None): suffix_kwarg = api_settings.FORMAT_SUFFIX_KWARG if allowed: if (len(allowed) == 1): allowed_pattern = allowed[0] else: allowed_pattern = ('(%s)' % '|'.join(allowed)) suffix_pattern = ('\\.(?P<%s>%s)$' % (suffix_kwarg, allowed_pattern)) else: suffix_pattern = ('\\.(?P<%s>[a-z0-9]+)$' % suffix_kwarg) return apply_suffix_patterns(urlpatterns, suffix_pattern, suffix_required)
[ "def", "format_suffix_patterns", "(", "urlpatterns", ",", "suffix_required", "=", "False", ",", "allowed", "=", "None", ")", ":", "suffix_kwarg", "=", "api_settings", ".", "FORMAT_SUFFIX_KWARG", "if", "allowed", ":", "if", "(", "len", "(", "allowed", ")", "=="...
supplement existing urlpatterns with corresponding patterns that also include a .
train
false
29,080
def tsplot(series, plotf, ax=None, **kwargs): if (ax is None): import matplotlib.pyplot as plt ax = plt.gca() (freq, series) = _maybe_resample(series, ax, kwargs) _decorate_axes(ax, freq, kwargs) ax._plot_data.append((series, plotf, kwargs)) lines = plotf(ax, series.index._mpl_repr(), series.values, **kwargs) format_dateaxis(ax, ax.freq) return lines
[ "def", "tsplot", "(", "series", ",", "plotf", ",", "ax", "=", "None", ",", "**", "kwargs", ")", ":", "if", "(", "ax", "is", "None", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "ax", "=", "plt", ".", "gca", "(", ")", "(", "freq...
plots a series on the given matplotlib axes or the current axes parameters axes : axes series : series notes supports same kwargs as axes .
train
true
29,081
def ovirt_full_argument_spec(**kwargs): spec = dict(auth=__get_auth_dict(), timeout=dict(default=180, type='int'), wait=dict(default=True, type='bool'), poll_interval=dict(default=3, type='int'), fetch_nested=dict(default=False, type='bool'), nested_attributes=dict(type='list')) spec.update(kwargs) return spec
[ "def", "ovirt_full_argument_spec", "(", "**", "kwargs", ")", ":", "spec", "=", "dict", "(", "auth", "=", "__get_auth_dict", "(", ")", ",", "timeout", "=", "dict", "(", "default", "=", "180", ",", "type", "=", "'int'", ")", ",", "wait", "=", "dict", "...
extend parameters of module with parameters which are common to all ovirt modules .
train
false
29,082
def new_schedule(): sched = OrderedDict() for (year, stype, week) in year_phase_week(): update_week(sched, year, stype, week) return sched
[ "def", "new_schedule", "(", ")", ":", "sched", "=", "OrderedDict", "(", ")", "for", "(", "year", ",", "stype", ",", "week", ")", "in", "year_phase_week", "(", ")", ":", "update_week", "(", "sched", ",", "year", ",", "stype", ",", "week", ")", "return...
builds an entire schedule from scratch .
train
false
29,083
def _runopenssl(pem, *args): if (os.name == 'posix'): command = ('openssl ' + ' '.join([(("'" + arg.replace("'", "'\\''")) + "'") for arg in args])) else: command = ('openssl ' + quoteArguments(args)) proc = Popen(native(command), shell=True, stdin=PIPE, stdout=PIPE) proc.stdin.write(pem) proc.stdin.close() output = proc.stdout.read() proc.stdout.close() proc.wait() return output
[ "def", "_runopenssl", "(", "pem", ",", "*", "args", ")", ":", "if", "(", "os", ".", "name", "==", "'posix'", ")", ":", "command", "=", "(", "'openssl '", "+", "' '", ".", "join", "(", "[", "(", "(", "\"'\"", "+", "arg", ".", "replace", "(", "\"...
run the command line openssl tool with the given arguments and write the given pem to its stdin .
train
false
29,084
def _retry(func): def wrapper(obj, *args, **kwargs): 'Wrapper for all query functions.' update_retries = 5 while (update_retries > 0): try: func(obj, *args, **kwargs) break except (OSError, TypeError, ValueError): update_retries -= 1 if (update_retries == 0): obj.set_state(STATE_OFF) return wrapper
[ "def", "_retry", "(", "func", ")", ":", "def", "wrapper", "(", "obj", ",", "*", "args", ",", "**", "kwargs", ")", ":", "update_retries", "=", "5", "while", "(", "update_retries", ">", "0", ")", ":", "try", ":", "func", "(", "obj", ",", "*", "args...
decorator to handle query retries .
train
false
29,085
def get_qos_specs(ctxt, spec_id): if (spec_id is None): msg = _('id cannot be None') raise exception.InvalidQoSSpecs(reason=msg) if (ctxt is None): ctxt = context.get_admin_context() return objects.QualityOfServiceSpecs.get_by_id(ctxt, spec_id)
[ "def", "get_qos_specs", "(", "ctxt", ",", "spec_id", ")", ":", "if", "(", "spec_id", "is", "None", ")", ":", "msg", "=", "_", "(", "'id cannot be None'", ")", "raise", "exception", ".", "InvalidQoSSpecs", "(", "reason", "=", "msg", ")", "if", "(", "ctx...
retrieves single qos specs by id .
train
false
29,089
@pytest.mark.django_db @pytest.mark.parametrize('show_all_categories', [True, False]) def test_category_links_plugin_with_customer(rf, show_all_categories): shop = get_default_shop() group = get_default_customer_group() customer = create_random_person() customer.groups.add(group) customer.save() request = rf.get('/') request.shop = get_default_shop() apply_request_middleware(request) request.customer = customer category = get_default_category() category.status = CategoryStatus.VISIBLE category.visibility = CategoryVisibility.VISIBLE_TO_GROUPS category.visibility_groups.add(group) category.shops.add(shop) category.save() vars = {'request': request} context = get_jinja_context(**vars) plugin = CategoryLinksPlugin({'categories': [category.pk], 'show_all_categories': show_all_categories}) assert category.is_visible(customer) assert (category in plugin.get_context_data(context)['categories']) customer_without_groups = create_random_person() customer_without_groups.groups.clear() assert (not category.is_visible(customer_without_groups)) request.customer = customer_without_groups context = get_jinja_context(**vars) assert (category not in plugin.get_context_data(context)['categories'])
[ "@", "pytest", ".", "mark", ".", "django_db", "@", "pytest", ".", "mark", ".", "parametrize", "(", "'show_all_categories'", ",", "[", "True", ",", "False", "]", ")", "def", "test_category_links_plugin_with_customer", "(", "rf", ",", "show_all_categories", ")", ...
test plugin for categories that is visible for certain group .
train
false
29,090
def open_session(bus): service_obj = bus_get_object(bus, SS_PATH) service_iface = dbus.Interface(service_obj, (SS_PREFIX + 'Service')) session = Session() try: (output, result) = service_iface.OpenSession(ALGORITHM_DH, dbus.ByteArray(int_to_bytes(session.my_public_key)), signature='sv') except dbus.exceptions.DBusException as e: if (e.get_dbus_name() != DBUS_NOT_SUPPORTED): raise (output, result) = service_iface.OpenSession(ALGORITHM_PLAIN, '', signature='sv') session.encrypted = False else: output = int_from_bytes(bytearray(output), 'big') session.set_server_public_key(output) session.object_path = result return session
[ "def", "open_session", "(", "bus", ")", ":", "service_obj", "=", "bus_get_object", "(", "bus", ",", "SS_PATH", ")", "service_iface", "=", "dbus", ".", "Interface", "(", "service_obj", ",", "(", "SS_PREFIX", "+", "'Service'", ")", ")", "session", "=", "Sess...
returns a new secret service session .
train
false
29,091
def frangi(image, scale_range=(1, 10), scale_step=2, beta1=0.5, beta2=15, black_ridges=True): (filtered, lambdas) = _frangi_hessian_common_filter(image, scale_range, scale_step, beta1, beta2) if black_ridges: filtered[(lambdas < 0)] = 0 else: filtered[(lambdas > 0)] = 0 return np.max(filtered, axis=0)
[ "def", "frangi", "(", "image", ",", "scale_range", "=", "(", "1", ",", "10", ")", ",", "scale_step", "=", "2", ",", "beta1", "=", "0.5", ",", "beta2", "=", "15", ",", "black_ridges", "=", "True", ")", ":", "(", "filtered", ",", "lambdas", ")", "=...
filter an image with the frangi filter .
train
false
29,092
def _EscapeEnvironmentVariableExpansion(s): s = s.replace('%', '%%') return s
[ "def", "_EscapeEnvironmentVariableExpansion", "(", "s", ")", ":", "s", "=", "s", ".", "replace", "(", "'%'", ",", "'%%'", ")", "return", "s" ]
escapes % characters .
train
false
29,093
def p_struct_declarator_2(t): pass
[ "def", "p_struct_declarator_2", "(", "t", ")", ":", "pass" ]
struct_declarator : declarator colon constant_expression .
train
false
29,095
def _flattenTree(request, root, write): stack = [_flattenElement(request, root, write, [], None, escapeForContent)] while stack: try: frame = stack[(-1)].gi_frame element = next(stack[(-1)]) except StopIteration: stack.pop() except Exception as e: stack.pop() roots = [] for generator in stack: roots.append(generator.gi_frame.f_locals['root']) roots.append(frame.f_locals['root']) raise FlattenerError(e, roots, extract_tb(exc_info()[2])) else: if isinstance(element, Deferred): def cbx(originalAndToFlatten): (original, toFlatten) = originalAndToFlatten stack.append(toFlatten) return original (yield element.addCallback(cbx)) else: stack.append(element)
[ "def", "_flattenTree", "(", "request", ",", "root", ",", "write", ")", ":", "stack", "=", "[", "_flattenElement", "(", "request", ",", "root", ",", "write", ",", "[", "]", ",", "None", ",", "escapeForContent", ")", "]", "while", "stack", ":", "try", ...
make c{root} into an iterable of l{bytes} and l{deferred} by doing a depth first traversal of the tree .
train
false
29,099
def succeed(result): d = Deferred() d.callback(result) return d
[ "def", "succeed", "(", "result", ")", ":", "d", "=", "Deferred", "(", ")", "d", ".", "callback", "(", "result", ")", "return", "d" ]
return a l{deferred} that has already had c{ .
train
false
29,100
def create_truefalse_cond(prompt='yes or no [default: no]? ', path=None): def truefalse_cond(visitor, node=None): 'Prompts the user for a true/false condition.' tf = TrueFalse(prompt=prompt, path=path) rtn = visitor.visit(tf) return rtn return truefalse_cond
[ "def", "create_truefalse_cond", "(", "prompt", "=", "'yes or no [default: no]? '", ",", "path", "=", "None", ")", ":", "def", "truefalse_cond", "(", "visitor", ",", "node", "=", "None", ")", ":", "tf", "=", "TrueFalse", "(", "prompt", "=", "prompt", ",", "...
this creates a basic condition function for use with nodes like while or other conditions .
train
false
29,102
def iterate(obj, opts): children = obj.get_children(**opts) if (not children): return [obj] traversal = deque() stack = deque([obj]) while stack: t = stack.popleft() traversal.append(t) for c in t.get_children(**opts): stack.append(c) return iter(traversal)
[ "def", "iterate", "(", "obj", ",", "opts", ")", ":", "children", "=", "obj", ".", "get_children", "(", "**", "opts", ")", "if", "(", "not", "children", ")", ":", "return", "[", "obj", "]", "traversal", "=", "deque", "(", ")", "stack", "=", "deque",...
traverse the given expression structure .
train
false
29,103
def pix2cm(pixels, monitor): if (not isinstance(monitor, monitors.Monitor)): msg = 'cm2pix requires a monitors.Monitor object as the second argument but received %s' raise ValueError((msg % str(type(monitor)))) scrWidthCm = monitor.getWidth() scrSizePix = monitor.getSizePix() if (scrSizePix is None): msg = 'Monitor %s has no known size in pixels (SEE MONITOR CENTER)' raise ValueError((msg % monitor.name)) if (scrWidthCm is None): msg = 'Monitor %s has no known width in cm (SEE MONITOR CENTER)' raise ValueError((msg % monitor.name)) return ((pixels * float(scrWidthCm)) / scrSizePix[0])
[ "def", "pix2cm", "(", "pixels", ",", "monitor", ")", ":", "if", "(", "not", "isinstance", "(", "monitor", ",", "monitors", ".", "Monitor", ")", ")", ":", "msg", "=", "'cm2pix requires a monitors.Monitor object as the second argument but received %s'", "raise", "Valu...
convert size in pixels to size in cm for a given monitor object .
train
false
29,105
def runWithJsonFile(expJsonFilePath, options, outputLabel, permWorkDir): if ('verbosityCount' in options): verbosity = options['verbosityCount'] del options['verbosityCount'] else: verbosity = 1 _setupInterruptHandling() with open(expJsonFilePath, 'r') as jsonFile: expJsonConfig = json.loads(jsonFile.read()) outDir = os.path.dirname(expJsonFilePath) return runWithConfig(expJsonConfig, options, outDir=outDir, outputLabel=outputLabel, permWorkDir=permWorkDir, verbosity=verbosity)
[ "def", "runWithJsonFile", "(", "expJsonFilePath", ",", "options", ",", "outputLabel", ",", "permWorkDir", ")", ":", "if", "(", "'verbosityCount'", "in", "options", ")", ":", "verbosity", "=", "options", "[", "'verbosityCount'", "]", "del", "options", "[", "'ve...
starts a swarm .
train
true
29,107
def _doktocsr(dok): (row, JA, A) = [list(i) for i in zip(*dok.row_list())] IA = ([0] * ((row[0] if row else 0) + 1)) for (i, r) in enumerate(row): IA.extend(([i] * (r - row[(i - 1)]))) IA.extend(([len(A)] * ((dok.rows - len(IA)) + 1))) shape = [dok.rows, dok.cols] return [A, JA, IA, shape]
[ "def", "_doktocsr", "(", "dok", ")", ":", "(", "row", ",", "JA", ",", "A", ")", "=", "[", "list", "(", "i", ")", "for", "i", "in", "zip", "(", "*", "dok", ".", "row_list", "(", ")", ")", "]", "IA", "=", "(", "[", "0", "]", "*", "(", "("...
converts a sparse matrix to compressed sparse row format .
train
false
29,108
def _find_tcl_tk_darwin_frameworks(binaries): tcl_root = tk_root = None for (nm, fnm) in binaries: if (nm == 'Tcl'): tcl_root = os.path.join(os.path.dirname(fnm), 'Resources/Scripts') elif (nm == 'Tk'): tk_root = os.path.join(os.path.dirname(fnm), 'Resources/Scripts') return (tcl_root, tk_root)
[ "def", "_find_tcl_tk_darwin_frameworks", "(", "binaries", ")", ":", "tcl_root", "=", "tk_root", "=", "None", "for", "(", "nm", ",", "fnm", ")", "in", "binaries", ":", "if", "(", "nm", "==", "'Tcl'", ")", ":", "tcl_root", "=", "os", ".", "path", ".", ...
get an os x-specific 2-tuple of the absolute paths of the top-level external data directories for both tcl and tk .
train
false
29,109
def set_http_port(port=80): _current = global_settings() if (_current['Global Settings']['HTTP_PORT']['VALUE'] == port): return True _xml = '<RIBCL VERSION="2.0">\n <LOGIN USER_LOGIN="adminname" PASSWORD="password">\n <RIB_INFO MODE="write">\n <MOD_GLOBAL_SETTINGS>\n <HTTP_PORT value="{0}"/>\n </MOD_GLOBAL_SETTINGS>\n </RIB_INFO>\n </LOGIN>\n </RIBCL>'.format(port) return __execute_cmd('Set_HTTP_Port', _xml)
[ "def", "set_http_port", "(", "port", "=", "80", ")", ":", "_current", "=", "global_settings", "(", ")", "if", "(", "_current", "[", "'Global Settings'", "]", "[", "'HTTP_PORT'", "]", "[", "'VALUE'", "]", "==", "port", ")", ":", "return", "True", "_xml", ...
configure the port http should listen on cli example: .
train
true
29,110
def rpad_ipv4_network(ip): return '.'.join(itertools.islice(itertools.chain(ip.split('.'), '0000'), 0, 4))
[ "def", "rpad_ipv4_network", "(", "ip", ")", ":", "return", "'.'", ".", "join", "(", "itertools", ".", "islice", "(", "itertools", ".", "chain", "(", "ip", ".", "split", "(", "'.'", ")", ",", "'0000'", ")", ",", "0", ",", "4", ")", ")" ]
returns an ip network address padded with zeros .
train
false
29,111
def drostie(): data = ['def drostie():\n "This function prints itself."\n data = ', '\n print data[0] + repr(data) + data[1]'] print ((data[0] + repr(data)) + data[1])
[ "def", "drostie", "(", ")", ":", "data", "=", "[", "'def drostie():\\n \"This function prints itself.\"\\n data = '", ",", "'\\n print data[0] + repr(data) + data[1]'", "]", "print", "(", "(", "data", "[", "0", "]", "+", "repr", "(", "data", ")", ")", "+", ...
this function prints itself .
train
false
29,113
def review_terms(request, url): group = get_object_or_404(Group, url=url) if (not group.terms): return redirect(reverse('groups:show_group', args=[group.url])) membership = get_object_or_404(GroupMembership, group=group, userprofile=request.user.userprofile, status=GroupMembership.PENDING_TERMS) membership_form = forms.TermsReviewForm((request.POST or None)) if membership_form.is_valid(): if (membership_form.cleaned_data['terms_accepted'] == 'True'): group.add_member(request.user.userprofile, GroupMembership.MEMBER) else: membership.delete() return redirect(reverse('groups:show_group', args=[group.url])) ctx = {'group': group, 'membership_form': membership_form} return render(request, 'groups/terms.html', ctx)
[ "def", "review_terms", "(", "request", ",", "url", ")", ":", "group", "=", "get_object_or_404", "(", "Group", ",", "url", "=", "url", ")", "if", "(", "not", "group", ".", "terms", ")", ":", "return", "redirect", "(", "reverse", "(", "'groups:show_group'"...
review group terms page .
train
false
29,114
def groovy_script(registry, xml_parent, data): gst = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.scripttrigger.groovy.GroovyScriptTrigger') gst.set('plugin', 'scripttrigger') mappings = [('system-script', 'groovySystemScript', False), ('script', 'groovyExpression', ''), ('script-file-path', 'groovyFilePath', ''), ('property-file-path', 'propertiesFilePath', ''), ('enable-concurrent', 'enableConcurrentBuild', False), ('cron', 'spec', '')] convert_mapping_to_xml(gst, data, mappings, fail_required=True) label = data.get('label') XML.SubElement(gst, 'labelRestriction').text = str(bool(label)).lower() if label: XML.SubElement(gst, 'triggerLabel').text = label
[ "def", "groovy_script", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "gst", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'org.jenkinsci.plugins.scripttrigger.groovy.GroovyScriptTrigger'", ")", "gst", ".", "set", "(", "'plugin'", ",", "'scr...
yaml: groovy-script triggers the job using a groovy script .
train
false
29,115
@task(ignore_result=False) @write def handle_file_validation_result(results, file_id, annotate=True): if annotate: results = annotate_validation_results(results) file_ = File.objects.get(pk=file_id) annotate_webext_incompatibilities(results=results, file_=file_, addon=file_.version.addon, version_string=file_.version.version, channel=file_.version.channel) return FileValidation.from_json(file_, results)
[ "@", "task", "(", "ignore_result", "=", "False", ")", "@", "write", "def", "handle_file_validation_result", "(", "results", ",", "file_id", ",", "annotate", "=", "True", ")", ":", "if", "annotate", ":", "results", "=", "annotate_validation_results", "(", "resu...
annotates a set of validation results .
train
false
29,117
def test_compound_model_with_nonstandard_broadcasting(): offx = Shift(1) offy = Shift(2) rot = AffineTransformation2D([[0, (-1)], [1, 0]]) m = ((offx & offy) | rot) (x, y) = m(0, 0) assert (x == (-2)) assert (y == 1) assert isinstance(x, float) assert isinstance(y, float) (x, y) = m([0, 1, 2], [0, 1, 2]) assert np.all((x == [(-2), (-3), (-4)])) assert np.all((y == [1, 2, 3]))
[ "def", "test_compound_model_with_nonstandard_broadcasting", "(", ")", ":", "offx", "=", "Shift", "(", "1", ")", "offy", "=", "Shift", "(", "2", ")", "rot", "=", "AffineTransformation2D", "(", "[", "[", "0", ",", "(", "-", "1", ")", "]", ",", "[", "1", ...
ensure that the standard_broadcasting flag is properly propagated when creating compound models .
train
false
29,118
def parse_extension(source, info): saved_pos = source.pos ch = source.get() if (ch == '<'): name = parse_name(source) group = info.open_group(name) source.expect('>') saved_flags = info.flags try: subpattern = _parse_pattern(source, info) source.expect(')') finally: info.flags = saved_flags source.ignore_space = bool((info.flags & VERBOSE)) info.close_group() return Group(info, group, subpattern) if (ch == '='): name = parse_name(source, allow_numeric=True) source.expect(')') if info.is_open_group(name): raise error('cannot refer to an open group', source.string, saved_pos) return make_ref_group(info, name, saved_pos) if ((ch == '>') or (ch == '&')): return parse_call_named_group(source, info, saved_pos) source.pos = saved_pos raise error('unknown extension', source.string, saved_pos)
[ "def", "parse_extension", "(", "source", ",", "info", ")", ":", "saved_pos", "=", "source", ".", "pos", "ch", "=", "source", ".", "get", "(", ")", "if", "(", "ch", "==", "'<'", ")", ":", "name", "=", "parse_name", "(", "source", ")", "group", "=", ...
parses a python extension .
train
false
29,119
def test_randimoize_corrmat_tails(): a = rs.randn(30) b = (a + (rs.rand(30) * 8)) c = rs.randn(30) d = [a, b, c] p_mat_b = algo.randomize_corrmat(d, 'both', False, random_seed=0) p_mat_u = algo.randomize_corrmat(d, 'upper', False, random_seed=0) p_mat_l = algo.randomize_corrmat(d, 'lower', False, random_seed=0) assert_equal(p_mat_b[(0, 1)], (p_mat_u[(0, 1)] * 2)) assert_equal(p_mat_l[(0, 1)], (1 - p_mat_u[(0, 1)]))
[ "def", "test_randimoize_corrmat_tails", "(", ")", ":", "a", "=", "rs", ".", "randn", "(", "30", ")", "b", "=", "(", "a", "+", "(", "rs", ".", "rand", "(", "30", ")", "*", "8", ")", ")", "c", "=", "rs", ".", "randn", "(", "30", ")", "d", "="...
test that the tail argument works .
train
false
29,120
def get_console(request, console_type, instance): if (console_type == 'AUTO'): check_consoles = CONSOLES else: try: check_consoles = {console_type: CONSOLES[console_type]} except KeyError: msg = (_('Console type "%s" not supported.') % console_type) raise exceptions.NotAvailable(msg) try: httpnotimplemented = nova_exception.HttpNotImplemented except AttributeError: httpnotimplemented = nova_exception.HTTPNotImplemented for (con_type, api_call) in check_consoles.items(): try: console = api_call(request, instance.id) except httpnotimplemented: continue except Exception: LOG.debug('Console not available', exc_info=True) continue if (con_type == 'SERIAL'): console_url = console.url else: console_url = ('%s&%s(%s)' % (console.url, urlencode({'title': getattr(instance, 'name', '')}), instance.id)) return (con_type, console_url) raise exceptions.NotAvailable(_('No available console found.'))
[ "def", "get_console", "(", "request", ",", "console_type", ",", "instance", ")", ":", "if", "(", "console_type", "==", "'AUTO'", ")", ":", "check_consoles", "=", "CONSOLES", "else", ":", "try", ":", "check_consoles", "=", "{", "console_type", ":", "CONSOLES"...
get a tuple of console url and console type .
train
true
29,122
@pytest.fixture(scope='function') def back_up_rc(request, user_config_path): user_config_path_backup = os.path.expanduser('~/.cookiecutterrc.backup') if os.path.exists(user_config_path): shutil.copy(user_config_path, user_config_path_backup) os.remove(user_config_path) def remove_test_rc(): '\n Remove the ~/.cookiecutterrc that has been created in the test.\n ' if os.path.exists(user_config_path): os.remove(user_config_path) def restore_original_rc(): '\n If it existed, restore the original ~/.cookiecutterrc\n ' if os.path.exists(user_config_path_backup): shutil.copy(user_config_path_backup, user_config_path) os.remove(user_config_path_backup) request.addfinalizer(restore_original_rc) request.addfinalizer(remove_test_rc)
[ "@", "pytest", ".", "fixture", "(", "scope", "=", "'function'", ")", "def", "back_up_rc", "(", "request", ",", "user_config_path", ")", ":", "user_config_path_backup", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.cookiecutterrc.backup'", ")", "if", "os...
back up an existing cookiecutter rc and restore it after the test .
train
false
29,124
def _cleaned(_pipeline_objects): pipeline_objects = copy.deepcopy(_pipeline_objects) for pipeline_object in pipeline_objects: if (pipeline_object['id'] == 'DefaultSchedule'): for field_object in pipeline_object['fields']: if (field_object['key'] == 'startDateTime'): start_date_time_string = field_object['stringValue'] start_date_time = datetime.datetime.strptime(start_date_time_string, '%Y-%m-%dT%H:%M:%S') field_object['stringValue'] = start_date_time.strftime('%H:%M:%S') return pipeline_objects
[ "def", "_cleaned", "(", "_pipeline_objects", ")", ":", "pipeline_objects", "=", "copy", ".", "deepcopy", "(", "_pipeline_objects", ")", "for", "pipeline_object", "in", "pipeline_objects", ":", "if", "(", "pipeline_object", "[", "'id'", "]", "==", "'DefaultSchedule...
return standardized pipeline objects to be used for comparing remove year .
train
true
29,125
def _insdc_location_string(location, rec_length): try: parts = location.parts if (location.strand == (-1)): return ('complement(%s(%s))' % (location.operator, ','.join((_insdc_location_string_ignoring_strand_and_subfeatures(p, rec_length) for p in parts[::(-1)])))) else: return ('%s(%s)' % (location.operator, ','.join((_insdc_location_string(p, rec_length) for p in parts)))) except AttributeError: loc = _insdc_location_string_ignoring_strand_and_subfeatures(location, rec_length) if (location.strand == (-1)): return ('complement(%s)' % loc) else: return loc
[ "def", "_insdc_location_string", "(", "location", ",", "rec_length", ")", ":", "try", ":", "parts", "=", "location", ".", "parts", "if", "(", "location", ".", "strand", "==", "(", "-", "1", ")", ")", ":", "return", "(", "'complement(%s(%s))'", "%", "(", ...
build a genbank/embl location from a featurelocation .
train
false
29,126
def _sigma_est_dwt(detail_coeffs, distribution='Gaussian'): detail_coeffs = detail_coeffs[np.nonzero(detail_coeffs)] if (distribution.lower() == 'gaussian'): denom = scipy.stats.norm.ppf(0.75) sigma = (np.median(np.abs(detail_coeffs)) / denom) else: raise ValueError('Only Gaussian noise estimation is currently supported') return sigma
[ "def", "_sigma_est_dwt", "(", "detail_coeffs", ",", "distribution", "=", "'Gaussian'", ")", ":", "detail_coeffs", "=", "detail_coeffs", "[", "np", ".", "nonzero", "(", "detail_coeffs", ")", "]", "if", "(", "distribution", ".", "lower", "(", ")", "==", "'gaus...
calculate the robust median estimator of the noise standard deviation .
train
false
29,127
@depends(HAS_HDPARM) def hpa(disks, size=None): hpa_data = {} for (disk, data) in hdparms(disks, 'N').items(): (visible, total, status) = data.values()[0] if ((visible == total) or ('disabled' in status)): hpa_data[disk] = {'total': total} else: hpa_data[disk] = {'total': total, 'visible': visible, 'hidden': (total - visible)} if (size is None): return hpa_data for (disk, data) in hpa_data.items(): try: size = (data['total'] - int(size)) except: if ('%' in size): size = int(size.strip('%')) size = ((100 - size) * data['total']) size /= 100 if (size <= 0): size = data['total'] _hdparm('--yes-i-know-what-i-am-doing -Np{0} {1}'.format(size, disk))
[ "@", "depends", "(", "HAS_HDPARM", ")", "def", "hpa", "(", "disks", ",", "size", "=", "None", ")", ":", "hpa_data", "=", "{", "}", "for", "(", "disk", ",", "data", ")", "in", "hdparms", "(", "disks", ",", "'N'", ")", ".", "items", "(", ")", ":"...
get/set host protected area settings t13 incits 346-2001 defines the beer and parties .
train
true
29,129
def STDDEV(ds, count, timeperiod=(- (2 ** 31)), nbdev=(-4e+37)): return call_talib_with_ds(ds, count, talib.STDDEV, timeperiod, nbdev)
[ "def", "STDDEV", "(", "ds", ",", "count", ",", "timeperiod", "=", "(", "-", "(", "2", "**", "31", ")", ")", ",", "nbdev", "=", "(", "-", "4e+37", ")", ")", ":", "return", "call_talib_with_ds", "(", "ds", ",", "count", ",", "talib", ".", "STDDEV",...
standard deviation .
train
false
29,130
def test_one(): from testapp import plugins eq_(plugins.plugin_began, True)
[ "def", "test_one", "(", ")", ":", "from", "testapp", "import", "plugins", "eq_", "(", "plugins", ".", "plugin_began", ",", "True", ")" ]
test that the test plugin was initialized .
train
false
29,131
def choose_account(accounts): labels = [acc.slug for acc in accounts] (code, index) = z_util(interfaces.IDisplay).menu('Please choose an account', labels, force_interactive=True) if (code == display_util.OK): return accounts[index] else: return None
[ "def", "choose_account", "(", "accounts", ")", ":", "labels", "=", "[", "acc", ".", "slug", "for", "acc", "in", "accounts", "]", "(", "code", ",", "index", ")", "=", "z_util", "(", "interfaces", ".", "IDisplay", ")", ".", "menu", "(", "'Please choose a...
choose an account .
train
false
29,132
def export_course_to_directory(course_key, root_dir): store = modulestore() course = store.get_course(course_key) if (course is None): raise CommandError('Invalid course_id') replacement_char = u'-' course_dir = replacement_char.join([course.id.org, course.id.course, course.id.run]) course_dir = re.sub('[^\\w\\.\\-]', replacement_char, course_dir) export_course_to_xml(store, None, course.id, root_dir, course_dir) export_dir = (path(root_dir) / course_dir) return export_dir
[ "def", "export_course_to_directory", "(", "course_key", ",", "root_dir", ")", ":", "store", "=", "modulestore", "(", ")", "course", "=", "store", ".", "get_course", "(", "course_key", ")", "if", "(", "course", "is", "None", ")", ":", "raise", "CommandError",...
export course into a directory .
train
false
29,133
def is_javascript_file(path): ext = os.path.splitext(path)[1].lower() return (ext in [u'.js', u'.javascript'])
[ "def", "is_javascript_file", "(", "path", ")", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "path", ")", "[", "1", "]", ".", "lower", "(", ")", "return", "(", "ext", "in", "[", "u'.js'", ",", "u'.javascript'", "]", ")" ]
return true if the given file path is a javascript file .
train
false
29,134
def eccentricity(jd): T = ((jd - jd1950) / 36525.0) p = ((-1.26e-07), (-4.193e-05), 0.01673011) return np.polyval(p, T)
[ "def", "eccentricity", "(", "jd", ")", ":", "T", "=", "(", "(", "jd", "-", "jd1950", ")", "/", "36525.0", ")", "p", "=", "(", "(", "-", "1.26e-07", ")", ",", "(", "-", "4.193e-05", ")", ",", "0.01673011", ")", "return", "np", ".", "polyval", "(...
eccentricity of the earths orbit at the requested julian date .
train
false
29,135
def load_matt_mahoney_text8_dataset(path='data/mm_test8/'): print 'Load or Download matt_mahoney_text8 Dataset> {}'.format(path) filename = 'text8.zip' url = 'http://mattmahoney.net/dc/' maybe_download_and_extract(filename, path, url, expected_bytes=31344016) with zipfile.ZipFile(os.path.join(path, filename)) as f: word_list = f.read(f.namelist()[0]).split() return word_list
[ "def", "load_matt_mahoney_text8_dataset", "(", "path", "=", "'data/mm_test8/'", ")", ":", "print", "'Load or Download matt_mahoney_text8 Dataset> {}'", ".", "format", "(", "path", ")", "filename", "=", "'text8.zip'", "url", "=", "'http://mattmahoney.net/dc/'", "maybe_downlo...
download a text file from matt mahoneys website if not present .
train
false
29,136
def type_description(name, types): return types[dereference_type(name)]
[ "def", "type_description", "(", "name", ",", "types", ")", ":", "return", "types", "[", "dereference_type", "(", "name", ")", "]" ]
returns a dictionary description the given type .
train
false
29,137
def test_user_legacy(script, data, virtualenv): virtualenv.system_site_packages = True script.pip('install', '-f', data.find_links, '--no-index', 'simple==1.0') script.pip('install', '-f', data.find_links, '--no-index', '--user', 'simple2==2.0') result = script.pip('list', '--user', '--format=legacy') assert ('simple (1.0)' not in result.stdout) assert ('simple2 (2.0)' in result.stdout), str(result)
[ "def", "test_user_legacy", "(", "script", ",", "data", ",", "virtualenv", ")", ":", "virtualenv", ".", "system_site_packages", "=", "True", "script", ".", "pip", "(", "'install'", ",", "'-f'", ",", "data", ".", "find_links", ",", "'--no-index'", ",", "'simpl...
test the behavior of --user flag in the list command .
train
false
29,138
def parse_feature_importances(filepath): lines = open(filepath, 'U').readlines() feature_IDs = [] scores = [] for line in lines[1:]: words = line.strip().split(' DCTB ') feature_IDs.append(words[0].strip()) scores.append(float(words[1].strip())) return (array(feature_IDs), array(scores))
[ "def", "parse_feature_importances", "(", "filepath", ")", ":", "lines", "=", "open", "(", "filepath", ",", "'U'", ")", ".", "readlines", "(", ")", "feature_IDs", "=", "[", "]", "scores", "=", "[", "]", "for", "line", "in", "lines", "[", "1", ":", "]"...
returns vector of feature ids .
train
false
29,139
def test_accept_custom_exception_text(): custom_converter = (lambda value: (value + ' converted')) custom_type = hug.types.accept(custom_converter, 'A string Value', 'Error occurred') assert (custom_type('bacon') == 'bacon converted') with pytest.raises(ValueError): custom_type(1)
[ "def", "test_accept_custom_exception_text", "(", ")", ":", "custom_converter", "=", "(", "lambda", "value", ":", "(", "value", "+", "' converted'", ")", ")", "custom_type", "=", "hug", ".", "types", ".", "accept", "(", "custom_converter", ",", "'A string Value'"...
tests to ensure its easy to custom the exception text using the accept wrapper .
train
false
29,140
def nomethod(cls): ctx.status = '405 Method Not Allowed' header('Content-Type', 'text/html') header('Allow', ', '.join([method for method in ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'] if hasattr(cls, method)])) return output('method not allowed')
[ "def", "nomethod", "(", "cls", ")", ":", "ctx", ".", "status", "=", "'405 Method Not Allowed'", "header", "(", "'Content-Type'", ",", "'text/html'", ")", "header", "(", "'Allow'", ",", "', '", ".", "join", "(", "[", "method", "for", "method", "in", "[", ...
returns a 405 method not allowed error for cls .
train
false
29,141
def _checkDependencies(): if conf.dependencies: checkDependencies()
[ "def", "_checkDependencies", "(", ")", ":", "if", "conf", ".", "dependencies", ":", "checkDependencies", "(", ")" ]
checks for missing dependencies .
train
false
29,142
def add_comments(comments): from r2.models.builder import write_comment_orders link_ids = [comment.link_id for comment in tup(comments)] links_by_id = Link._byID(link_ids) comments = tup(comments) comments_by_link_id = defaultdict(list) for comment in comments: comments_by_link_id[comment.link_id].append(comment) for (link_id, link_comments) in comments_by_link_id.iteritems(): link = links_by_id[link_id] timer = g.stats.get_timer('comment_tree.add.1') timer.start() write_comment_scores(link, link_comments) timer.intermediate('scores') CommentTree.add_comments(link, link_comments) timer.intermediate('update') write_comment_orders(link) timer.intermediate('write_order') timer.stop()
[ "def", "add_comments", "(", "comments", ")", ":", "from", "r2", ".", "models", ".", "builder", "import", "write_comment_orders", "link_ids", "=", "[", "comment", ".", "link_id", "for", "comment", "in", "tup", "(", "comments", ")", "]", "links_by_id", "=", ...
add comments to the commenttree and update scores .
train
false
29,143
def set_console_mode(mode, fd=1): hcon = STDHANDLES[fd] SetConsoleMode(hcon, mode)
[ "def", "set_console_mode", "(", "mode", ",", "fd", "=", "1", ")", ":", "hcon", "=", "STDHANDLES", "[", "fd", "]", "SetConsoleMode", "(", "hcon", ",", "mode", ")" ]
set the mode of the active console input .
train
false
29,144
def ignore_script(script): sid = script.get('id') output = script.get('output') if (sid in IGNORE_SCRIPTS_IDS): return True if (output in IGNORE_SCRIPTS.get(sid, [])): return True if (output in IGNORE_SCRIPT_OUTPUTS): return True if (IGNORE_SCRIPTS_REGEXP.get(sid) and (output is not None) and IGNORE_SCRIPTS_REGEXP[sid].search(output)): return True if ((output is not None) and any((expr.search(output) for expr in IGNORE_SCRIPT_OUTPUTS_REGEXP))): return True return False
[ "def", "ignore_script", "(", "script", ")", ":", "sid", "=", "script", ".", "get", "(", "'id'", ")", "output", "=", "script", ".", "get", "(", "'output'", ")", "if", "(", "sid", "in", "IGNORE_SCRIPTS_IDS", ")", ":", "return", "True", "if", "(", "outp...
predicate that decides whether an nmap script should be ignored or not .
train
false
29,146
def getOrientedLoops(loops): for (loopIndex, loop) in enumerate(loops): leftPoint = euclidean.getLeftPoint(loop) isInFilledRegion = euclidean.getIsInFilledRegion((loops[:loopIndex] + loops[(loopIndex + 1):]), leftPoint) if (isInFilledRegion == euclidean.isWiddershins(loop)): loop.reverse() return loops
[ "def", "getOrientedLoops", "(", "loops", ")", ":", "for", "(", "loopIndex", ",", "loop", ")", "in", "enumerate", "(", "loops", ")", ":", "leftPoint", "=", "euclidean", ".", "getLeftPoint", "(", "loop", ")", "isInFilledRegion", "=", "euclidean", ".", "getIs...
orient the loops which must be in descending order .
train
false
29,147
def runner_doc(*args): run_ = salt.runner.Runner(__opts__) docs = {} if (not args): for fun in run_.functions: docs[fun] = run_.functions[fun].__doc__ return _strip_rst(docs) for module in args: _use_fnmatch = False if ('*' in module): target_mod = module _use_fnmatch = True elif module: target_mod = ((module + '.') if (not module.endswith('.')) else module) else: target_mod = '' if _use_fnmatch: for fun in fnmatch.filter(run_.functions, target_mod): docs[fun] = run_.functions[fun].__doc__ else: for fun in run_.functions: if ((fun == module) or fun.startswith(target_mod)): docs[fun] = run_.functions[fun].__doc__ return _strip_rst(docs)
[ "def", "runner_doc", "(", "*", "args", ")", ":", "run_", "=", "salt", ".", "runner", ".", "Runner", "(", "__opts__", ")", "docs", "=", "{", "}", "if", "(", "not", "args", ")", ":", "for", "fun", "in", "run_", ".", "functions", ":", "docs", "[", ...
return the docstrings for all runners .
train
true
29,148
def test_add_accepts_to_naked_function_2(): def foo(int_1, int_2, int_3): pass t = time.time() for i in range(0, 10000): accepts(int, int, int)(foo) return (time.time() - t)
[ "def", "test_add_accepts_to_naked_function_2", "(", ")", ":", "def", "foo", "(", "int_1", ",", "int_2", ",", "int_3", ")", ":", "pass", "t", "=", "time", ".", "time", "(", ")", "for", "i", "in", "range", "(", "0", ",", "10000", ")", ":", "accepts", ...
adding accepts to a naked function: multi positional params .
train
false
29,149
def roots_laguerre(n, mu=False): return roots_genlaguerre(n, 0.0, mu=mu)
[ "def", "roots_laguerre", "(", "n", ",", "mu", "=", "False", ")", ":", "return", "roots_genlaguerre", "(", "n", ",", "0.0", ",", "mu", "=", "mu", ")" ]
gauss-laguerre quadrature .
train
false
29,151
def normalized_repr(obj, memo=None): if isinstance(obj, dict): return sorted_dict_repr(obj, memo) else: return repr(obj)
[ "def", "normalized_repr", "(", "obj", ",", "memo", "=", "None", ")", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "sorted_dict_repr", "(", "obj", ",", "memo", ")", "else", ":", "return", "repr", "(", "obj", ")" ]
return repr of obj .
train
false
29,153
@conf.commands.register def rdpcap(filename, count=(-1)): return PcapReader(filename).read_all(count=count)
[ "@", "conf", ".", "commands", ".", "register", "def", "rdpcap", "(", "filename", ",", "count", "=", "(", "-", "1", ")", ")", ":", "return", "PcapReader", "(", "filename", ")", ".", "read_all", "(", "count", "=", "count", ")" ]
read a pcap file and return a packet list count: read only <count> packets .
train
false
29,154
def workflow_entry_points(): default = default_entry_point() return chain([default], pkg_resources.iter_entry_points('orange.widgets.tutorials'), pkg_resources.iter_entry_points('orange.widgets.workflows'))
[ "def", "workflow_entry_points", "(", ")", ":", "default", "=", "default_entry_point", "(", ")", "return", "chain", "(", "[", "default", "]", ",", "pkg_resources", ".", "iter_entry_points", "(", "'orange.widgets.tutorials'", ")", ",", "pkg_resources", ".", "iter_en...
return an iterator over all example workflows .
train
false
29,156
def get_tree_size(start_path): if (not os.path.exists(start_path)): raise ValueError(('Incorrect path: %s' % start_path)) total_size = 0 for (dirpath, dirnames, filenames) in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size
[ "def", "get_tree_size", "(", "start_path", ")", ":", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "start_path", ")", ")", ":", "raise", "ValueError", "(", "(", "'Incorrect path: %s'", "%", "start_path", ")", ")", "total_size", "=", "0", "for"...
return size of filesystem tree .
train
false
29,157
def tmean(a, limits=None, inclusive=(True, True), axis=None): return trima(a, limits=limits, inclusive=inclusive).mean(axis=axis)
[ "def", "tmean", "(", "a", ",", "limits", "=", "None", ",", "inclusive", "=", "(", "True", ",", "True", ")", ",", "axis", "=", "None", ")", ":", "return", "trima", "(", "a", ",", "limits", "=", "limits", ",", "inclusive", "=", "inclusive", ")", "....
compute the trimmed mean .
train
false
29,158
def load_url_list(): if ('DIGITS_MODEL_STORE_URL' in os.environ): url_list = os.environ['DIGITS_MODEL_STORE_URL'] else: url_list = '' return validate(url_list).split(',')
[ "def", "load_url_list", "(", ")", ":", "if", "(", "'DIGITS_MODEL_STORE_URL'", "in", "os", ".", "environ", ")", ":", "url_list", "=", "os", ".", "environ", "[", "'DIGITS_MODEL_STORE_URL'", "]", "else", ":", "url_list", "=", "''", "return", "validate", "(", ...
return model store urls as a list verify if each url is valid .
train
false
29,159
def wep_send_deauths(iface, target, clients): global RUN_CONFIG cmd = ['aireplay-ng', '--ignore-negative-one', '--deauth', str(RUN_CONFIG.WPA_DEAUTH_COUNT), '-a', target.bssid, iface] call(cmd, stdout=DN, stderr=DN) for client in clients: cmd = ['aireplay-ng', '--ignore-negative-one', '--deauth', str(RUN_CONFIG.WPA_DEAUTH_COUNT), '-a', target.bssid, '-h', client.bssid, iface] call(cmd, stdout=DN, stderr=DN)
[ "def", "wep_send_deauths", "(", "iface", ",", "target", ",", "clients", ")", ":", "global", "RUN_CONFIG", "cmd", "=", "[", "'aireplay-ng'", ",", "'--ignore-negative-one'", ",", "'--deauth'", ",", "str", "(", "RUN_CONFIG", ".", "WPA_DEAUTH_COUNT", ")", ",", "'-...
sends deauth packets to broadcast and every client .
train
false
29,160
@contextlib.contextmanager def assure_cleanup(enter_func, exit_func, use_enter_return): enter_return = None try: if isinstance(enter_func, functools.partial): enter_func_name = enter_func.func.__name__ else: enter_func_name = enter_func.__name__ LOG.debug('Entering context. Function: %(func_name)s, use_enter_return: %(use)s.', {'func_name': enter_func_name, 'use': use_enter_return}) enter_return = enter_func() (yield enter_return) finally: if isinstance(exit_func, functools.partial): exit_func_name = exit_func.func.__name__ else: exit_func_name = exit_func.__name__ LOG.debug('Exiting context. Function: %(func_name)s, use_enter_return: %(use)s.', {'func_name': exit_func_name, 'use': use_enter_return}) if (enter_return is not None): if use_enter_return: ignore_exception(exit_func, enter_return) else: ignore_exception(exit_func)
[ "@", "contextlib", ".", "contextmanager", "def", "assure_cleanup", "(", "enter_func", ",", "exit_func", ",", "use_enter_return", ")", ":", "enter_return", "=", "None", "try", ":", "if", "isinstance", "(", "enter_func", ",", "functools", ".", "partial", ")", ":...
assures the resource is cleaned up .
train
false
29,161
def dmp_sqf_p(f, u, K): if dmp_zero_p(f, u): return True else: return (not dmp_degree(dmp_gcd(f, dmp_diff(f, 1, u, K), u, K), u))
[ "def", "dmp_sqf_p", "(", "f", ",", "u", ",", "K", ")", ":", "if", "dmp_zero_p", "(", "f", ",", "u", ")", ":", "return", "True", "else", ":", "return", "(", "not", "dmp_degree", "(", "dmp_gcd", "(", "f", ",", "dmp_diff", "(", "f", ",", "1", ",",...
return true if f is a square-free polynomial in k[x] .
train
false
29,162
def pick_flavor(flavors): for flavor_priority in ('m1.nano', 'm1.micro', 'm1.tiny', 'm1.small'): for flavor in flavors: if (flavor.name == flavor_priority): return flavor raise NoFlavorException()
[ "def", "pick_flavor", "(", "flavors", ")", ":", "for", "flavor_priority", "in", "(", "'m1.nano'", ",", "'m1.micro'", ",", "'m1.tiny'", ",", "'m1.small'", ")", ":", "for", "flavor", "in", "flavors", ":", "if", "(", "flavor", ".", "name", "==", "flavor_prior...
given a flavor list pick a reasonable one .
train
false
29,164
def s3_decode_iso_datetime(dtstr): DEFAULT = datetime.datetime.utcnow().replace(second=0, microsecond=0) dt = dateutil.parser.parse(dtstr, default=DEFAULT) if (dt.tzinfo is None): try: dt = dateutil.parser.parse((dtstr + ' +0000'), default=DEFAULT) except: dt = dateutil.parser.parse((dtstr + ' 00:00:00 +0000'), default=DEFAULT) return dt
[ "def", "s3_decode_iso_datetime", "(", "dtstr", ")", ":", "DEFAULT", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "replace", "(", "second", "=", "0", ",", "microsecond", "=", "0", ")", "dt", "=", "dateutil", ".", "parser", ".", "parse...
convert date/time string in iso-8601 format into a datetime object @note: this routine is named "iso" for consistency reasons .
train
false
29,166
def scalePoints(elementNode, points, prefix): scaleVector3Default = Vector3(1.0, 1.0, 1.0) scaleVector3 = matrix.getCumulativeVector3Remove(scaleVector3Default.copy(), elementNode, prefix) if (scaleVector3 == scaleVector3Default): return for point in points: point.x *= scaleVector3.x point.y *= scaleVector3.y point.z *= scaleVector3.z
[ "def", "scalePoints", "(", "elementNode", ",", "points", ",", "prefix", ")", ":", "scaleVector3Default", "=", "Vector3", "(", "1.0", ",", "1.0", ",", "1.0", ")", "scaleVector3", "=", "matrix", ".", "getCumulativeVector3Remove", "(", "scaleVector3Default", ".", ...
scale the points .
train
false
29,167
def example_number_for_type(region_code, num_type): if (region_code is None): return _example_number_anywhere_for_type(num_type) if (not _is_valid_region_code(region_code)): return None metadata = PhoneMetadata.metadata_for_region(region_code.upper()) desc = _number_desc_for_type(metadata, num_type) if (desc.example_number is not None): try: return parse(desc.example_number, region_code) except NumberParseException: pass return None
[ "def", "example_number_for_type", "(", "region_code", ",", "num_type", ")", ":", "if", "(", "region_code", "is", "None", ")", ":", "return", "_example_number_anywhere_for_type", "(", "num_type", ")", "if", "(", "not", "_is_valid_region_code", "(", "region_code", "...
gets a valid number for the specified region and number type .
train
true
29,168
def vm_snapshot_revert(vm_name, kwargs=None, call=None): if (call != 'action'): raise SaltCloudSystemExit('The vm_snapshot_revert action must be called with -a or --action.') if (kwargs is None): kwargs = {} snapshot_id = kwargs.get('snapshot_id', None) if (snapshot_id is None): raise SaltCloudSystemExit("The vm_snapshot_revert function requires a 'snapshot_id' to be provided.") (server, user, password) = _get_xml_rpc() auth = ':'.join([user, password]) vm_id = int(get_vm_id(kwargs={'name': vm_name})) response = server.one.vm.snapshotrevert(auth, vm_id, int(snapshot_id)) data = {'action': 'vm.snapshotrevert', 'snapshot_reverted': response[0], 'vm_id': response[1], 'error_code': response[2]} return data
[ "def", "vm_snapshot_revert", "(", "vm_name", ",", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "(", "call", "!=", "'action'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The vm_snapshot_revert action must be called with -a or --action.'", ")...
reverts a virtual machine to a snapshot .
train
true
29,169
@contextfunction def messaging_message_list(context, messages, skip_group=False, nomass=False): request = context['request'] response_format = 'html' if ('response_format' in context): response_format = context['response_format'] profile = request.user.profile return Markup(render_to_string('messaging/tags/message_list', {'messages': messages, 'profile': profile, 'skip_group': skip_group, 'nomass': nomass}, context_instance=RequestContext(request), response_format=response_format))
[ "@", "contextfunction", "def", "messaging_message_list", "(", "context", ",", "messages", ",", "skip_group", "=", "False", ",", "nomass", "=", "False", ")", ":", "request", "=", "context", "[", "'request'", "]", "response_format", "=", "'html'", "if", "(", "...
print a list of messages .
train
false
29,170
def disjoint_set_label(i, n, simplify=False): intersection = unicodedata.lookup('INTERSECTION') comp = 'c' def label_for_index(i): return chr((ord('A') + i)) if simplify: return ''.join((label_for_index(i) for (i, b) in enumerate(setkey(i, n)) if b)) else: return intersection.join(((label_for_index(i) + ('' if b else (('<sup>' + comp) + '</sup>'))) for (i, b) in enumerate(setkey(i, n))))
[ "def", "disjoint_set_label", "(", "i", ",", "n", ",", "simplify", "=", "False", ")", ":", "intersection", "=", "unicodedata", ".", "lookup", "(", "'INTERSECTION'", ")", "comp", "=", "'c'", "def", "label_for_index", "(", "i", ")", ":", "return", "chr", "(...
return a html formated label for a disjoint set indexed by i .
train
false
29,171
def xml_summary(registry, xml_parent, data): summary = XML.SubElement(xml_parent, 'hudson.plugins.summary__report.ACIPluginPublisher') summary.set('plugin', 'summary_report') mapping = [('files', 'name', None), ('shown-on-project-page', 'shownOnProjectPage', False)] helpers.convert_mapping_to_xml(summary, data, mapping, fail_required=True)
[ "def", "xml_summary", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "summary", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'hudson.plugins.summary__report.ACIPluginPublisher'", ")", "summary", ".", "set", "(", "'plugin'", ",", "'summary_re...
yaml: xml-summary adds support for the summary display plugin requires the jenkins :jenkins-wiki:summary display plugin <summary+display+plugin> .
train
false
29,172
def list_licenses(): KEY_PATTERN = re.compile('Key (.*)') keys = [] out = __salt__['cmd.run']('/sbin/emcpreg -list') for line in out.splitlines(): match = KEY_PATTERN.match(line) if (not match): continue keys.append({'key': match.group(1)}) return keys
[ "def", "list_licenses", "(", ")", ":", "KEY_PATTERN", "=", "re", ".", "compile", "(", "'Key (.*)'", ")", "keys", "=", "[", "]", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'/sbin/emcpreg -list'", ")", "for", "line", "in", "out", ".", "splitlines...
returns a list of applied powerpath license keys .
train
true
29,173
def serve_404_error(request, *args, **kwargs): access_warn(request, '404 not found') return render('404.mako', request, dict(uri=request.build_absolute_uri()), status=404)
[ "def", "serve_404_error", "(", "request", ",", "*", "args", ",", "**", "kwargs", ")", ":", "access_warn", "(", "request", ",", "'404 not found'", ")", "return", "render", "(", "'404.mako'", ",", "request", ",", "dict", "(", "uri", "=", "request", ".", "b...
registered handler for 404 .
train
false
29,174
def _maybe_convert_string_to_object(values): if isinstance(values, string_types): values = np.array([values], dtype=object) elif (isinstance(values, np.ndarray) and issubclass(values.dtype.type, (np.string_, np.unicode_))): values = values.astype(object) return values
[ "def", "_maybe_convert_string_to_object", "(", "values", ")", ":", "if", "isinstance", "(", "values", ",", "string_types", ")", ":", "values", "=", "np", ".", "array", "(", "[", "values", "]", ",", "dtype", "=", "object", ")", "elif", "(", "isinstance", ...
convert string-like and string-like array to convert object dtype .
train
false