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
27,297
def _get_branch_option(**kwargs): branch = kwargs.get('branch', '') ret = [] if branch: log.info("Adding branch '%s'", branch) ret.append("--branch='{0}'".format(branch)) return ret
[ "def", "_get_branch_option", "(", "**", "kwargs", ")", ":", "branch", "=", "kwargs", ".", "get", "(", "'branch'", ",", "''", ")", "ret", "=", "[", "]", "if", "branch", ":", "log", ".", "info", "(", "\"Adding branch '%s'\"", ",", "branch", ")", "ret", ...
returns a list of --branch option to be used in the yum command .
train
false
27,299
def object_id_validator(key, activity_dict, errors, context): activity_type = activity_dict[('activity_type',)] if object_id_validators.has_key(activity_type): object_id = activity_dict[('object_id',)] return object_id_validators[activity_type](object_id, context) else: raise Invalid(('There is no object_id va...
[ "def", "object_id_validator", "(", "key", ",", "activity_dict", ",", "errors", ",", "context", ")", ":", "activity_type", "=", "activity_dict", "[", "(", "'activity_type'", ",", ")", "]", "if", "object_id_validators", ".", "has_key", "(", "activity_type", ")", ...
validate the object_id value of an activity_dict .
train
false
27,300
def getGeometryPath(subName=''): return getJoinedPath(getFabmetheusUtilitiesPath('geometry'), subName)
[ "def", "getGeometryPath", "(", "subName", "=", "''", ")", ":", "return", "getJoinedPath", "(", "getFabmetheusUtilitiesPath", "(", "'geometry'", ")", ",", "subName", ")" ]
get the geometry directory path .
train
false
27,302
def test_install_folder_using_relative_path(script): script.scratch_path.join('initools').mkdir() script.scratch_path.join('initools', 'mock').mkdir() pkg_path = ((script.scratch_path / 'initools') / 'mock') pkg_path.join('setup.py').write(mock100_setup_py) result = script.pip('install', (Path('initools') / 'mock'...
[ "def", "test_install_folder_using_relative_path", "(", "script", ")", ":", "script", ".", "scratch_path", ".", "join", "(", "'initools'", ")", ".", "mkdir", "(", ")", "script", ".", "scratch_path", ".", "join", "(", "'initools'", ",", "'mock'", ")", ".", "mk...
test installing a folder using pip install folder1/folder2 .
train
false
27,305
def test_not_browsing_error(hist): with pytest.raises(ValueError) as error1: hist.nextitem() assert (str(error1.value) == 'Currently not browsing history') with pytest.raises(ValueError) as error2: hist.previtem() assert (str(error2.value) == 'Currently not browsing history')
[ "def", "test_not_browsing_error", "(", "hist", ")", ":", "with", "pytest", ".", "raises", "(", "ValueError", ")", "as", "error1", ":", "hist", ".", "nextitem", "(", ")", "assert", "(", "str", "(", "error1", ".", "value", ")", "==", "'Currently not browsing...
test that next/previtem throws a valueerror .
train
false
27,306
def encode_region(name): for (tag, (language, region, iso639, iso3166)) in LANGUAGE_REGION.items(): if (region == name.capitalize()): return iso3166
[ "def", "encode_region", "(", "name", ")", ":", "for", "(", "tag", ",", "(", "language", ",", "region", ",", "iso639", ",", "iso3166", ")", ")", "in", "LANGUAGE_REGION", ".", "items", "(", ")", ":", "if", "(", "region", "==", "name", ".", "capitalize"...
returns the region code for the given region name .
train
false
27,309
def set_autocommit(autocommit, using=None): return get_connection(using).set_autocommit(autocommit)
[ "def", "set_autocommit", "(", "autocommit", ",", "using", "=", "None", ")", ":", "return", "get_connection", "(", "using", ")", ".", "set_autocommit", "(", "autocommit", ")" ]
set the autocommit status of the connection .
train
false
27,310
def xstrip(filename): while xisabs(filename): if re.match('\\w:[\\\\/]', filename): filename = re.sub('^\\w+:[\\\\/]+', '', filename) elif re.match('[\\\\/]', filename): filename = re.sub('^[\\\\/]+', '', filename) return filename
[ "def", "xstrip", "(", "filename", ")", ":", "while", "xisabs", "(", "filename", ")", ":", "if", "re", ".", "match", "(", "'\\\\w:[\\\\\\\\/]'", ",", "filename", ")", ":", "filename", "=", "re", ".", "sub", "(", "'^\\\\w+:[\\\\\\\\/]+'", ",", "''", ",", ...
make relative path out of absolute by stripping prefixes used on linux .
train
false
27,311
def print_proto(d, parent=(), indent=0): for (m, sd) in sorted(d.items(), cmp=(lambda x, y: cmp(x[0], y[0]))): full_name_l = (parent + (m,)) full_name = '$'.join(full_name_l) is_message_or_group = (full_name in messages_info) if is_message_or_group: print_message(m, sd, parent, indent) else: print_prot...
[ "def", "print_proto", "(", "d", ",", "parent", "=", "(", ")", ",", "indent", "=", "0", ")", ":", "for", "(", "m", ",", "sd", ")", "in", "sorted", "(", "d", ".", "items", "(", ")", ",", "cmp", "=", "(", "lambda", "x", ",", "y", ":", "cmp", ...
display all protos .
train
false
27,313
def delete_hc(kwargs=None, call=None): if (call != 'function'): raise SaltCloudSystemExit('The delete_hc function must be called with -f or --function.') if ((not kwargs) or ('name' not in kwargs)): log.error('A name must be specified when deleting a health check.') return False name = kwargs['name'] conn = g...
[ "def", "delete_hc", "(", "kwargs", "=", "None", ",", "call", "=", "None", ")", ":", "if", "(", "call", "!=", "'function'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The delete_hc function must be called with -f or --function.'", ")", "if", "(", "(", "not"...
permanently delete a health check .
train
true
27,314
def _dotrig(a, b): return ((a.func == b.func) and ((a.has(TrigonometricFunction) and b.has(TrigonometricFunction)) or (a.has(HyperbolicFunction) and b.has(HyperbolicFunction))))
[ "def", "_dotrig", "(", "a", ",", "b", ")", ":", "return", "(", "(", "a", ".", "func", "==", "b", ".", "func", ")", "and", "(", "(", "a", ".", "has", "(", "TrigonometricFunction", ")", "and", "b", ".", "has", "(", "TrigonometricFunction", ")", ")"...
helper to tell whether a and b have the same sorts of symbols in them -- no need to test hyperbolic patterns against expressions that have no hyperbolics in them .
train
false
27,316
def test_any(): assert (not hug.validate.any(hug.validate.contains_one_of('last', 'year'), hug.validate.contains_one_of('first', 'place'))(TEST_SCHEMA)) assert hug.validate.any(hug.validate.contains_one_of('last', 'year'), hug.validate.contains_one_of('no', 'way'))(TEST_SCHEMA)
[ "def", "test_any", "(", ")", ":", "assert", "(", "not", "hug", ".", "validate", ".", "any", "(", "hug", ".", "validate", ".", "contains_one_of", "(", "'last'", ",", "'year'", ")", ",", "hug", ".", "validate", ".", "contains_one_of", "(", "'first'", ","...
test to ensure hugs any validation function works as expected to combine validators .
train
false
27,317
def parse_hl_lines(expr): if (not expr): return [] try: return list(map(int, expr.split())) except ValueError: return []
[ "def", "parse_hl_lines", "(", "expr", ")", ":", "if", "(", "not", "expr", ")", ":", "return", "[", "]", "try", ":", "return", "list", "(", "map", "(", "int", ",", "expr", ".", "split", "(", ")", ")", ")", "except", "ValueError", ":", "return", "[...
support our syntax for emphasizing certain lines of code .
train
false
27,318
def source_hashed(source_filename, prepared_options, thumbnail_extension, **kwargs): source_sha = hashlib.sha1(source_filename.encode(u'utf-8')).digest() source_hash = base64.urlsafe_b64encode(source_sha[:9]).decode(u'utf-8') parts = u':'.join(prepared_options[1:]) parts_sha = hashlib.sha1(parts.encode(u'utf-8')).d...
[ "def", "source_hashed", "(", "source_filename", ",", "prepared_options", ",", "thumbnail_extension", ",", "**", "kwargs", ")", ":", "source_sha", "=", "hashlib", ".", "sha1", "(", "source_filename", ".", "encode", "(", "u'utf-8'", ")", ")", ".", "digest", "(",...
generate a thumbnail filename of the source filename and options separately hashed .
train
true
27,319
def timer(*func, **kwargs): key = kwargs.get('key', None) test_only = kwargs.get('test_only', True) def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): if (test_only and (not settings.IN_TEST_SUITE)): return func(*args, **kw) else: name = (key if key else ('%s.%s' % (func.__module...
[ "def", "timer", "(", "*", "func", ",", "**", "kwargs", ")", ":", "key", "=", "kwargs", ".", "get", "(", "'key'", ",", "None", ")", "test_only", "=", "kwargs", ".", "get", "(", "'test_only'", ",", "True", ")", "def", "decorator", "(", "func", ")", ...
wrapper around dog_stats_api .
train
false
27,320
def _set_bundle_properties(bundle, root, namespace): bundle.name = root.get('name')
[ "def", "_set_bundle_properties", "(", "bundle", ",", "root", ",", "namespace", ")", ":", "bundle", ".", "name", "=", "root", ".", "get", "(", "'name'", ")" ]
get bundle properties from bundle xml set properties on bundle with attributes from xml etree root .
train
false
27,324
def X_n(n, a, x): (n, a, x) = map(S, [n, a, x]) C = sqrt((2 / a)) return (C * sin((((pi * n) * x) / a)))
[ "def", "X_n", "(", "n", ",", "a", ",", "x", ")", ":", "(", "n", ",", "a", ",", "x", ")", "=", "map", "(", "S", ",", "[", "n", ",", "a", ",", "x", "]", ")", "C", "=", "sqrt", "(", "(", "2", "/", "a", ")", ")", "return", "(", "C", "...
returns the wavefunction x_{n} for an infinite 1d box n the "principal" quantum number .
train
false
27,326
def inspect_response(response, spider): Shell(spider.crawler).start(response=response)
[ "def", "inspect_response", "(", "response", ",", "spider", ")", ":", "Shell", "(", "spider", ".", "crawler", ")", ".", "start", "(", "response", "=", "response", ")" ]
open a shell to inspect the given response .
train
false
27,327
@requires_sklearn def test_gat_plot_diagonal(): gat = _get_data() gat.plot_diagonal() del gat.scores_ assert_raises(RuntimeError, gat.plot)
[ "@", "requires_sklearn", "def", "test_gat_plot_diagonal", "(", ")", ":", "gat", "=", "_get_data", "(", ")", "gat", ".", "plot_diagonal", "(", ")", "del", "gat", ".", "scores_", "assert_raises", "(", "RuntimeError", ",", "gat", ".", "plot", ")" ]
test gat diagonal plot .
train
false
27,328
@pytest.mark.parametrize('parallel', [True, False]) def test_lstrip_whitespace(parallel, read_basic): text = ('\n 1, 2, DCTB 3\n A, DCTB DCTB B, C\n a, b, c\n' + ' \n') table = read_basic(text, delimiter=',', parallel=parallel) expected = Table([['A', 'a'], ['B', 'b'], ['C', 'c']], names=('1', '2', '3...
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'parallel'", ",", "[", "True", ",", "False", "]", ")", "def", "test_lstrip_whitespace", "(", "parallel", ",", "read_basic", ")", ":", "text", "=", "(", "'\\n 1, 2, DCTB 3\\n A, DCTB DCTB B, C\\n a, ...
test to make sure the reader ignores whitespace at the beginning of fields .
train
false
27,329
@utils.arg('host', metavar='<host>', help='Name of host.') @utils.arg('--target_host', metavar='<target_host>', default=None, help=_('Name of target host. If no host is specified the scheduler will select a target.')) @utils.arg('--on-shared-storage', dest='on_shared_storage', action='store_true', default=False, help=_...
[ "@", "utils", ".", "arg", "(", "'host'", ",", "metavar", "=", "'<host>'", ",", "help", "=", "'Name of host.'", ")", "@", "utils", ".", "arg", "(", "'--target_host'", ",", "metavar", "=", "'<target_host>'", ",", "default", "=", "None", ",", "help", "=", ...
evacuate all instances from failed host .
train
false
27,330
def print_octave_code(expr, **settings): print(octave_code(expr, **settings))
[ "def", "print_octave_code", "(", "expr", ",", "**", "settings", ")", ":", "print", "(", "octave_code", "(", "expr", ",", "**", "settings", ")", ")" ]
prints the octave representation of the given expression .
train
false
27,332
def update_user_details(backend, details, response, user=None, is_new=False, *args, **kwargs): if (user is None): return changed = False for (name, value) in six.iteritems(details): if (not _ignore_field(name, is_new)): if (value and (value != getattr(user, name, None))): setattr(user, name, value) ch...
[ "def", "update_user_details", "(", "backend", ",", "details", ",", "response", ",", "user", "=", "None", ",", "is_new", "=", "False", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "(", "user", "is", "None", ")", ":", "return", "changed", "="...
update user details using data from provider .
train
false
27,333
def sum_signs(exprs): is_pos = all([expr.is_positive() for expr in exprs]) is_neg = all([expr.is_negative() for expr in exprs]) return (is_pos, is_neg)
[ "def", "sum_signs", "(", "exprs", ")", ":", "is_pos", "=", "all", "(", "[", "expr", ".", "is_positive", "(", ")", "for", "expr", "in", "exprs", "]", ")", "is_neg", "=", "all", "(", "[", "expr", ".", "is_negative", "(", ")", "for", "expr", "in", "...
give the sign resulting from summing a list of expressions .
train
false
27,335
def equivalent(term1, term2, subs=None): head_type = type(term1) if (type(term2) != head_type): return False elif (head_type not in (tuple, list)): try: return ((term1 is term2) or (term1 == term2)) except: return False pot1 = preorder_traversal(term1) pot2 = preorder_traversal(term2) subs = ({} if (s...
[ "def", "equivalent", "(", "term1", ",", "term2", ",", "subs", "=", "None", ")", ":", "head_type", "=", "type", "(", "term1", ")", "if", "(", "type", "(", "term2", ")", "!=", "head_type", ")", ":", "return", "False", "elif", "(", "head_type", "not", ...
determine if two terms are equivalent .
train
false
27,336
def get_document_content(xml_node): pretty_indent(xml_node) return tostring(xml_node, 'utf-8')
[ "def", "get_document_content", "(", "xml_node", ")", ":", "pretty_indent", "(", "xml_node", ")", "return", "tostring", "(", "xml_node", ",", "'utf-8'", ")" ]
print nicely formatted xml to a string .
train
false
27,337
def literal_compile(s): return str(s.compile(compile_kwargs={'literal_binds': True}))
[ "def", "literal_compile", "(", "s", ")", ":", "return", "str", "(", "s", ".", "compile", "(", "compile_kwargs", "=", "{", "'literal_binds'", ":", "True", "}", ")", ")" ]
compile a sql expression with bind params inlined as literals .
train
false
27,338
def get_pid_from_file(program_name, pid_files_dir=None): pidfile_path = get_pid_path(program_name, pid_files_dir) if (not os.path.exists(pidfile_path)): return None pidfile = open(get_pid_path(program_name, pid_files_dir), 'r') try: pid = int(pidfile.readline()) except IOError: if (not os.path.exists(pidfile...
[ "def", "get_pid_from_file", "(", "program_name", ",", "pid_files_dir", "=", "None", ")", ":", "pidfile_path", "=", "get_pid_path", "(", "program_name", ",", "pid_files_dir", ")", "if", "(", "not", "os", ".", "path", ".", "exists", "(", "pidfile_path", ")", "...
reads the pid from <program_name> .
train
false
27,339
def _create_local_srs(host_ref): create_sr(name_label='Local storage ISO', type='iso', other_config={'i18n-original-value-name_label': 'Local storage ISO', 'i18n-key': 'local-storage-iso'}, physical_size=80000, physical_utilisation=40000, virtual_allocation=80000, host_ref=host_ref) return create_sr(name_label='Local...
[ "def", "_create_local_srs", "(", "host_ref", ")", ":", "create_sr", "(", "name_label", "=", "'Local storage ISO'", ",", "type", "=", "'iso'", ",", "other_config", "=", "{", "'i18n-original-value-name_label'", ":", "'Local storage ISO'", ",", "'i18n-key'", ":", "'loc...
create an sr that looks like the one created on the local disk by default by the xenserver installer .
train
false
27,340
def test_conv_str_choices_valid(): param = inspect.Parameter('foo', inspect.Parameter.POSITIONAL_ONLY) converted = argparser.type_conv(param, str, 'val1', str_choices=['val1', 'val2']) assert (converted == 'val1')
[ "def", "test_conv_str_choices_valid", "(", ")", ":", "param", "=", "inspect", ".", "Parameter", "(", "'foo'", ",", "inspect", ".", "Parameter", ".", "POSITIONAL_ONLY", ")", "converted", "=", "argparser", ".", "type_conv", "(", "param", ",", "str", ",", "'val...
calling str type with str_choices and valid value .
train
false
27,341
def popular_tags_for_model(model, count=10): content_type = ContentType.objects.get_for_model(model) return Tag.objects.filter(taggit_taggeditem_items__content_type=content_type).annotate(item_count=Count(u'taggit_taggeditem_items')).order_by(u'-item_count')[:count]
[ "def", "popular_tags_for_model", "(", "model", ",", "count", "=", "10", ")", ":", "content_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "model", ")", "return", "Tag", ".", "objects", ".", "filter", "(", "taggit_taggeditem_items__content_...
return a queryset of the most frequently used tags used on this model class .
train
false
27,342
@world.absorb def wait_for_visible(css_selector, index=0, timeout=GLOBAL_WAIT_FOR_TIMEOUT): wait_for(func=(lambda _: css_visible(css_selector, index)), timeout=timeout, timeout_msg='Timed out waiting for {} to be visible.'.format(css_selector))
[ "@", "world", ".", "absorb", "def", "wait_for_visible", "(", "css_selector", ",", "index", "=", "0", ",", "timeout", "=", "GLOBAL_WAIT_FOR_TIMEOUT", ")", ":", "wait_for", "(", "func", "=", "(", "lambda", "_", ":", "css_visible", "(", "css_selector", ",", "...
wait for the element to be visible in the dom .
train
false
27,346
def addGradientListToDocstring(): def dec(fn): if (fn.__doc__ is not None): fn.__doc__ = (fn.__doc__ + str(Gradients.keys()).strip('[').strip(']')) return fn return dec
[ "def", "addGradientListToDocstring", "(", ")", ":", "def", "dec", "(", "fn", ")", ":", "if", "(", "fn", ".", "__doc__", "is", "not", "None", ")", ":", "fn", ".", "__doc__", "=", "(", "fn", ".", "__doc__", "+", "str", "(", "Gradients", ".", "keys", ...
decorator to add list of current pre-defined gradients to the end of a function docstring .
train
false
27,348
def sign_file(file_obj, server): endpoint = get_endpoint(server) if (not endpoint): log.info(u'Not signing file {0}: no active endpoint'.format(file_obj.pk)) return if (not os.path.exists(file_obj.file_path)): log.info(u"File {0} doesn't exist on disk".format(file_obj.file_path)) return if (file_obj.version...
[ "def", "sign_file", "(", "file_obj", ",", "server", ")", ":", "endpoint", "=", "get_endpoint", "(", "server", ")", "if", "(", "not", "endpoint", ")", ":", "log", ".", "info", "(", "u'Not signing file {0}: no active endpoint'", ".", "format", "(", "file_obj", ...
sign a file .
train
false
27,349
def set_serv_parms(service, args): import _winreg uargs = [] for arg in args: uargs.append(unicoder(arg)) try: key = _winreg.CreateKey(_winreg.HKEY_LOCAL_MACHINE, (_SERVICE_KEY + service)) _winreg.SetValueEx(key, _SERVICE_PARM, None, _winreg.REG_MULTI_SZ, uargs) _winreg.CloseKey(key) except WindowsError: ...
[ "def", "set_serv_parms", "(", "service", ",", "args", ")", ":", "import", "_winreg", "uargs", "=", "[", "]", "for", "arg", "in", "args", ":", "uargs", ".", "append", "(", "unicoder", "(", "arg", ")", ")", "try", ":", "key", "=", "_winreg", ".", "Cr...
set the service command line parameters in registry .
train
false
27,350
@cache_permission def can_update_translation(user, project): return check_permission(user, project, 'trans.update_translation')
[ "@", "cache_permission", "def", "can_update_translation", "(", "user", ",", "project", ")", ":", "return", "check_permission", "(", "user", ",", "project", ",", "'trans.update_translation'", ")" ]
checks whether user can update translation repository .
train
false
27,351
def tridi_inverse_iteration(d, e, w, x0=None, rtol=1e-08): eig_diag = (d - w) if (x0 is None): x0 = np.random.randn(len(d)) x_prev = np.zeros_like(x0) norm_x = np.linalg.norm(x0) x0 /= norm_x while (np.linalg.norm((np.abs(x0) - np.abs(x_prev))) > rtol): x_prev = x0.copy() tridisolve(eig_diag, e, x0) norm_...
[ "def", "tridi_inverse_iteration", "(", "d", ",", "e", ",", "w", ",", "x0", "=", "None", ",", "rtol", "=", "1e-08", ")", ":", "eig_diag", "=", "(", "d", "-", "w", ")", "if", "(", "x0", "is", "None", ")", ":", "x0", "=", "np", ".", "random", "....
perform an inverse iteration .
train
true
27,352
def filter_none_values(value): result = dict([(k, v) for (k, v) in value.items() if (v != 'None')]) return result
[ "def", "filter_none_values", "(", "value", ")", ":", "result", "=", "dict", "(", "[", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "value", ".", "items", "(", ")", "if", "(", "v", "!=", "'None'", ")", "]", ")", "return", "re...
filter out string "none" values from the provided dict .
train
false
27,355
def _common_path(p1, p2): while (p1 and p2): if (p1 == p2): return p1 if (len(p1) > len(p2)): p1 = os.path.dirname(p1) else: p2 = os.path.dirname(p2) return ''
[ "def", "_common_path", "(", "p1", ",", "p2", ")", ":", "while", "(", "p1", "and", "p2", ")", ":", "if", "(", "p1", "==", "p2", ")", ":", "return", "p1", "if", "(", "len", "(", "p1", ")", ">", "len", "(", "p2", ")", ")", ":", "p1", "=", "o...
returns the longest path common to p1 and p2 .
train
false
27,356
def mutating(func): @functools.wraps(func) def wrapped(self, req, *args, **kwargs): if req.context.read_only: msg = _('Read-only access') LOG.debug(msg) raise exc.HTTPForbidden(msg, request=req, content_type='text/plain') return func(self, req, *args, **kwargs) return wrapped
[ "def", "mutating", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapped", "(", "self", ",", "req", ",", "*", "args", ",", "**", "kwargs", ")", ":", "if", "req", ".", "context", ".", "read_only", ":", "msg", "="...
decorator to enforce read-only logic .
train
false
27,358
def get_page_instance(context): possible_names = [PAGE_TEMPLATE_VAR, u'self'] for name in possible_names: if (name in context): page = context[name] if isinstance(page, Page): return page
[ "def", "get_page_instance", "(", "context", ")", ":", "possible_names", "=", "[", "PAGE_TEMPLATE_VAR", ",", "u'self'", "]", "for", "name", "in", "possible_names", ":", "if", "(", "name", "in", "context", ")", ":", "page", "=", "context", "[", "name", "]", ...
given a template context .
train
false
27,359
def getLoopsFromCorrectMesh(edges, faces, vertexes, z): remainingEdgeTable = getRemainingEdgeTable(edges, vertexes, z) remainingValues = remainingEdgeTable.values() for edge in remainingValues: if (len(edge.faceIndexes) < 2): print 'This should never happen, there is a hole in the triangle mesh, each edge shoul...
[ "def", "getLoopsFromCorrectMesh", "(", "edges", ",", "faces", ",", "vertexes", ",", "z", ")", ":", "remainingEdgeTable", "=", "getRemainingEdgeTable", "(", "edges", ",", "vertexes", ",", "z", ")", "remainingValues", "=", "remainingEdgeTable", ".", "values", "(",...
get loops from a carve of a correct mesh .
train
false
27,361
def create_model_tables(models, **create_table_kwargs): for m in sort_models_topologically(models): m.create_table(**create_table_kwargs)
[ "def", "create_model_tables", "(", "models", ",", "**", "create_table_kwargs", ")", ":", "for", "m", "in", "sort_models_topologically", "(", "models", ")", ":", "m", ".", "create_table", "(", "**", "create_table_kwargs", ")" ]
create tables for all given models .
train
false
27,363
def get_s3_content_and_delete(bucket, path, with_key=False): if is_botocore(): import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path) e...
[ "def", "get_s3_content_and_delete", "(", "bucket", ",", "path", ",", "with_key", "=", "False", ")", ":", "if", "is_botocore", "(", ")", ":", "import", "botocore", ".", "session", "session", "=", "botocore", ".", "session", ".", "get_session", "(", ")", "cl...
get content from s3 key .
train
false
27,364
def logdet_symm(m, check_symm=False): from scipy import linalg if check_symm: if (not np.all((m == m.T))): raise ValueError('m is not symmetric.') (c, _) = linalg.cho_factor(m, lower=True) return (2 * np.sum(np.log(c.diagonal())))
[ "def", "logdet_symm", "(", "m", ",", "check_symm", "=", "False", ")", ":", "from", "scipy", "import", "linalg", "if", "check_symm", ":", "if", "(", "not", "np", ".", "all", "(", "(", "m", "==", "m", ".", "T", ")", ")", ")", ":", "raise", "ValueEr...
return log(det(m)) asserting positive definiteness of m .
train
false
27,365
def safe_no_dnn_algo_bwd(algo): if algo: raise RuntimeError('The option `dnn.conv.algo_bwd` has been removed and should not be used anymore. Please use the options `dnn.conv.algo_bwd_filter` and `dnn.conv.algo_bwd_data` instead.') return True
[ "def", "safe_no_dnn_algo_bwd", "(", "algo", ")", ":", "if", "algo", ":", "raise", "RuntimeError", "(", "'The option `dnn.conv.algo_bwd` has been removed and should not be used anymore. Please use the options `dnn.conv.algo_bwd_filter` and `dnn.conv.algo_bwd_data` instead.'", ")", "return...
make sure the user is not attempting to use dnn .
train
false
27,366
def time_to_epoch(t): if isinstance(t, int): return t elif (isinstance(t, tuple) or isinstance(t, time.struct_time)): return int(time.mktime(t)) elif hasattr(t, 'timetuple'): return int(time.mktime(t.timetuple())) elif hasattr(t, 'strftime'): return int(t.strftime('%s')) elif (isinstance(t, str) or isinsta...
[ "def", "time_to_epoch", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "int", ")", ":", "return", "t", "elif", "(", "isinstance", "(", "t", ",", "tuple", ")", "or", "isinstance", "(", "t", ",", "time", ".", "struct_time", ")", ")", ":", "...
convert time specified in a variety of forms into unix epoch time .
train
false
27,367
def unique_id(name): return '{0}-{1}-{2}'.format(name, int(time.time()), random.randint(0, 10000))
[ "def", "unique_id", "(", "name", ")", ":", "return", "'{0}-{1}-{2}'", ".", "format", "(", "name", ",", "int", "(", "time", ".", "time", "(", ")", ")", ",", "random", ".", "randint", "(", "0", ",", "10000", ")", ")" ]
generates an unique id .
train
false
27,369
def test_basic_call_on_method_registering_without_decorator_coroutine(): class API(object, ): def __init__(self): hug.call()(self.hello_world_method) @asyncio.coroutine def hello_world_method(self): return 'Hello World!' api_instance = API() assert (loop.run_until_complete(api_instance.hello_world_method...
[ "def", "test_basic_call_on_method_registering_without_decorator_coroutine", "(", ")", ":", "class", "API", "(", "object", ",", ")", ":", "def", "__init__", "(", "self", ")", ":", "hug", ".", "call", "(", ")", "(", "self", ".", "hello_world_method", ")", "@", ...
test to ensure instance method calling via async works as expected .
train
false
27,371
def json_to_dict(x): if (x.find('callback') > (-1)): pos_lb = x.find('{') pos_rb = x.find('}') x = x[pos_lb:(pos_rb + 1)] try: if (type(x) != str): x = x.decode('utf-8') return json.loads(x, encoding='utf-8') except: return x
[ "def", "json_to_dict", "(", "x", ")", ":", "if", "(", "x", ".", "find", "(", "'callback'", ")", ">", "(", "-", "1", ")", ")", ":", "pos_lb", "=", "x", ".", "find", "(", "'{'", ")", "pos_rb", "=", "x", ".", "find", "(", "'}'", ")", "x", "=",...
oauthresponse class cant parse the json data with content-type - text/html and because of a rubbish api .
train
false
27,372
def get_framework_by_id(framework_id): for fw in get_frameworks(): if (fw.get_id() == framework_id): return fw return None
[ "def", "get_framework_by_id", "(", "framework_id", ")", ":", "for", "fw", "in", "get_frameworks", "(", ")", ":", "if", "(", "fw", ".", "get_id", "(", ")", "==", "framework_id", ")", ":", "return", "fw", "return", "None" ]
return framework instance associated with given id .
train
false
27,374
def delete_file(path, fileName=None): if fileName: path = os.path.join(path, fileName) if os.path.isfile(path): os.remove(path)
[ "def", "delete_file", "(", "path", ",", "fileName", "=", "None", ")", ":", "if", "fileName", ":", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "fileName", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "os",...
delete file from public folder .
train
false
27,376
def secure_cookie(): return (request.environ['wsgi.url_scheme'] == 'https')
[ "def", "secure_cookie", "(", ")", ":", "return", "(", "request", ".", "environ", "[", "'wsgi.url_scheme'", "]", "==", "'https'", ")" ]
return true if cookie should have secure attribute .
train
false
27,377
def print_tag(tag, decode, outstream=sys.stdout): outstream.write((('Tagger: ' + decode(tag.tagger)) + '\n')) outstream.write((('Date: ' + decode(tag.tag_time)) + '\n')) outstream.write('\n') outstream.write((decode(tag.message) + '\n')) outstream.write('\n')
[ "def", "print_tag", "(", "tag", ",", "decode", ",", "outstream", "=", "sys", ".", "stdout", ")", ":", "outstream", ".", "write", "(", "(", "(", "'Tagger: '", "+", "decode", "(", "tag", ".", "tagger", ")", ")", "+", "'\\n'", ")", ")", "outstream", "...
write a human-readable tag .
train
false
27,378
def sqrtm(M): r = real_if_close(expm2((0.5 * logm(M))), 1e-08) return ((r + r.T) / 2)
[ "def", "sqrtm", "(", "M", ")", ":", "r", "=", "real_if_close", "(", "expm2", "(", "(", "0.5", "*", "logm", "(", "M", ")", ")", ")", ",", "1e-08", ")", "return", "(", "(", "r", "+", "r", ".", "T", ")", "/", "2", ")" ]
returns the symmetric semi-definite positive square root of a matrix .
train
false
27,379
def distrib_family(): distrib = distrib_id() if (distrib in ['Debian', 'Ubuntu', 'LinuxMint', 'elementary OS']): return 'debian' elif (distrib in ['RHEL', 'CentOS', 'SLES', 'Fedora']): return 'redhat' elif (distrib in ['SunOS']): return 'sun' elif (distrib in ['Gentoo']): return 'gentoo' elif (distrib in ...
[ "def", "distrib_family", "(", ")", ":", "distrib", "=", "distrib_id", "(", ")", "if", "(", "distrib", "in", "[", "'Debian'", ",", "'Ubuntu'", ",", "'LinuxMint'", ",", "'elementary OS'", "]", ")", ":", "return", "'debian'", "elif", "(", "distrib", "in", "...
get the distribution family .
train
false
27,380
def test_mark_done_invariant(): seg = make_segment(1, explicit=True) with pytest.raises(exception.UserCritical): seg.mark_done()
[ "def", "test_mark_done_invariant", "(", ")", ":", "seg", "=", "make_segment", "(", "1", ",", "explicit", "=", "True", ")", "with", "pytest", ".", "raises", "(", "exception", ".", "UserCritical", ")", ":", "seg", ".", "mark_done", "(", ")" ]
check explicit segments cannot be .
train
false
27,381
def _find_chordality_breaker(G, s=None, treewidth_bound=sys.maxsize): unnumbered = set(G) if (s is None): s = random.choice(list(unnumbered)) unnumbered.remove(s) numbered = set([s]) current_treewidth = (-1) while unnumbered: v = _max_cardinality_node(G, unnumbered, numbered) unnumbered.remove(v) numbered...
[ "def", "_find_chordality_breaker", "(", "G", ",", "s", "=", "None", ",", "treewidth_bound", "=", "sys", ".", "maxsize", ")", ":", "unnumbered", "=", "set", "(", "G", ")", "if", "(", "s", "is", "None", ")", ":", "s", "=", "random", ".", "choice", "(...
given a graph g .
train
false
27,382
def select_template(template_name_list): not_found = [] for template_name in template_name_list: try: return get_template(template_name) except TemplateDoesNotExist as e: if (e.args[0] not in not_found): not_found.append(e.args[0]) continue raise TemplateDoesNotExist(', '.join(not_found))
[ "def", "select_template", "(", "template_name_list", ")", ":", "not_found", "=", "[", "]", "for", "template_name", "in", "template_name_list", ":", "try", ":", "return", "get_template", "(", "template_name", ")", "except", "TemplateDoesNotExist", "as", "e", ":", ...
try to load one of the given templates .
train
false
27,383
def define_service(service_descriptor, module): class_dict = {'__module__': module.__name__} class_name = service_descriptor.name.encode('utf-8') for method_descriptor in (service_descriptor.methods or []): request_definition = messages.find_definition(method_descriptor.request_type, module) response_definition ...
[ "def", "define_service", "(", "service_descriptor", ",", "module", ")", ":", "class_dict", "=", "{", "'__module__'", ":", "module", ".", "__name__", "}", "class_name", "=", "service_descriptor", ".", "name", ".", "encode", "(", "'utf-8'", ")", "for", "method_d...
define a new service proxy .
train
false
27,384
def mae(actual, predicted): return np.mean(ae(actual, predicted))
[ "def", "mae", "(", "actual", ",", "predicted", ")", ":", "return", "np", ".", "mean", "(", "ae", "(", "actual", ",", "predicted", ")", ")" ]
computes the mean absolute error .
train
false
27,385
def get_course_about_section(request, course, section_key): html_sections = {'short_description', 'description', 'key_dates', 'video', 'course_staff_short', 'course_staff_extended', 'requirements', 'syllabus', 'textbook', 'faq', 'more_info', 'overview', 'effort', 'end_date', 'prerequisites', 'ocw_links'} if (section_...
[ "def", "get_course_about_section", "(", "request", ",", "course", ",", "section_key", ")", ":", "html_sections", "=", "{", "'short_description'", ",", "'description'", ",", "'key_dates'", ",", "'video'", ",", "'course_staff_short'", ",", "'course_staff_extended'", ","...
this returns the snippet of html to be rendered on the course about page .
train
false
27,388
def is_valid_ipv4_prefix(ipv4_prefix): if (not isinstance(ipv4_prefix, str)): return False tokens = ipv4_prefix.split('/') if (len(tokens) != 2): return False return (is_valid_ipv4(tokens[0]) and is_valid_ip_prefix(tokens[1], 32))
[ "def", "is_valid_ipv4_prefix", "(", "ipv4_prefix", ")", ":", "if", "(", "not", "isinstance", "(", "ipv4_prefix", ",", "str", ")", ")", ":", "return", "False", "tokens", "=", "ipv4_prefix", ".", "split", "(", "'/'", ")", "if", "(", "len", "(", "tokens", ...
returns true if *ipv4_prefix* is a valid prefix with mask .
train
true
27,389
def encode_language(name): for (tag, (language, region, iso639, iso3166)) in LANGUAGE_REGION.items(): if (language == name.capitalize()): return iso639
[ "def", "encode_language", "(", "name", ")", ":", "for", "(", "tag", ",", "(", "language", ",", "region", ",", "iso639", ",", "iso3166", ")", ")", "in", "LANGUAGE_REGION", ".", "items", "(", ")", ":", "if", "(", "language", "==", "name", ".", "capital...
returns the language code for the given language name .
train
false
27,390
def polygon_bounds(points): (minx, miny) = (points[0][0], points[0][1]) (maxx, maxy) = (minx, miny) for p in points: minx = min(minx, p[0]) maxx = max(maxx, p[0]) miny = min(miny, p[1]) maxy = max(maxy, p[1]) return (minx, miny, (maxx - minx), (maxy - miny))
[ "def", "polygon_bounds", "(", "points", ")", ":", "(", "minx", ",", "miny", ")", "=", "(", "points", "[", "0", "]", "[", "0", "]", ",", "points", "[", "0", "]", "[", "1", "]", ")", "(", "maxx", ",", "maxy", ")", "=", "(", "minx", ",", "miny...
return bounding box of a polygon in form .
train
true
27,391
def get_zendesk(): zendesk_url = settings.ZENDESK_URL zendesk_email = settings.ZENDESK_USER_EMAIL zendesk_password = settings.ZENDESK_USER_PASSWORD if ((not zendesk_url) or (not zendesk_email) or (not zendesk_password)): log.error('Zendesk settings error: please set ZENDESK_URL, ZENDESK_USER_EMAIL and ZENDESK_USE...
[ "def", "get_zendesk", "(", ")", ":", "zendesk_url", "=", "settings", ".", "ZENDESK_URL", "zendesk_email", "=", "settings", ".", "ZENDESK_USER_EMAIL", "zendesk_password", "=", "settings", ".", "ZENDESK_USER_PASSWORD", "if", "(", "(", "not", "zendesk_url", ")", "or"...
instantiate and return a zendesk client .
train
false
27,392
def next_month(t): now = time.localtime(t) month = (now.tm_mon + 1) year = now.tm_year if (month > 12): month = 1 year += 1 ntime = (year, month, 1, 0, 0, 0, 0, 0, now[8]) return time.mktime(ntime)
[ "def", "next_month", "(", "t", ")", ":", "now", "=", "time", ".", "localtime", "(", "t", ")", "month", "=", "(", "now", ".", "tm_mon", "+", "1", ")", "year", "=", "now", ".", "tm_year", "if", "(", "month", ">", "12", ")", ":", "month", "=", "...
return timestamp for start of next month .
train
false
27,393
def all_timeseries_index_generator(k=10): make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex] for make_index_func in make_index_funcs: (yield make_index_func(k=k))
[ "def", "all_timeseries_index_generator", "(", "k", "=", "10", ")", ":", "make_index_funcs", "=", "[", "makeDateIndex", ",", "makePeriodIndex", ",", "makeTimedeltaIndex", "]", "for", "make_index_func", "in", "make_index_funcs", ":", "(", "yield", "make_index_func", "...
generator which can be iterated over to get instances of all the classes which represent time-seires .
train
false
27,394
def test_badapp(): def badapp(environ, start_response): start_response('200 OK', []) raise HTTPBadRequest('Do not do this at home.') newapp = HTTPExceptionHandler(badapp) assert ('Bad Request' in ''.join(newapp({'HTTP_ACCEPT': 'text/html'}, (lambda a, b, c=None: None))))
[ "def", "test_badapp", "(", ")", ":", "def", "badapp", "(", "environ", ",", "start_response", ")", ":", "start_response", "(", "'200 OK'", ",", "[", "]", ")", "raise", "HTTPBadRequest", "(", "'Do not do this at home.'", ")", "newapp", "=", "HTTPExceptionHandler",...
verify that the middleware handles previously-started responses .
train
false
27,396
def smembers(key, host=None, port=None, db=None, password=None): server = _connect(host, port, db, password) return list(server.smembers(key))
[ "def", "smembers", "(", "key", ",", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_connect", "(", "host", ",", "port", ",", "db", ",", "password", ")", "return", "li...
get members in a redis set cli example: .
train
true
27,398
def is_x86_architecture(): if ('86' in platform.machine()): return True else: return False
[ "def", "is_x86_architecture", "(", ")", ":", "if", "(", "'86'", "in", "platform", ".", "machine", "(", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
return true if the architecture is x86 .
train
false
27,399
@jingo.register.function def showing(query, pager): format_opts = (pager.start_index(), pager.end_index(), pager.paginator.count) query = escape(query) if query: showing = _(u'Showing {0} - {1} of {2} results for <strong>{3}</strong>').format(*(format_opts + (query,))) else: showing = _(u'Showing {0} - {1} of {...
[ "@", "jingo", ".", "register", ".", "function", "def", "showing", "(", "query", ",", "pager", ")", ":", "format_opts", "=", "(", "pager", ".", "start_index", "(", ")", ",", "pager", ".", "end_index", "(", ")", ",", "pager", ".", "paginator", ".", "co...
writes a string that tells the user what they are seeing in terms of search results .
train
false
27,403
def start_flask_app(host, port): app.run(host=host, port=port) app.config['DEBUG'] = False app.config['TESTING'] = False
[ "def", "start_flask_app", "(", "host", ",", "port", ")", ":", "app", ".", "run", "(", "host", "=", "host", ",", "port", "=", "port", ")", "app", ".", "config", "[", "'DEBUG'", "]", "=", "False", "app", ".", "config", "[", "'TESTING'", "]", "=", "...
runs the server .
train
false
27,404
def test_sobel_horizontal(): (i, j) = np.mgrid[(-5):6, (-5):6] image = (i >= 0).astype(float) result = (filters.sobel(image) * np.sqrt(2)) i[(np.abs(j) == 5)] = 10000 assert_allclose(result[(i == 0)], 1) assert np.all((result[(np.abs(i) > 1)] == 0))
[ "def", "test_sobel_horizontal", "(", ")", ":", "(", "i", ",", "j", ")", "=", "np", ".", "mgrid", "[", "(", "-", "5", ")", ":", "6", ",", "(", "-", "5", ")", ":", "6", "]", "image", "=", "(", "i", ">=", "0", ")", ".", "astype", "(", "float...
sobel on a horizontal edge should be a horizontal line .
train
false
27,405
def get_precision(currency): global _cache if (_cache is None): _cache = _generate_cache() return _cache[currency]
[ "def", "get_precision", "(", "currency", ")", ":", "global", "_cache", "if", "(", "_cache", "is", "None", ")", ":", "_cache", "=", "_generate_cache", "(", ")", "return", "_cache", "[", "currency", "]" ]
get precision for a given field .
train
false
27,406
def _GetMimeType(file_name): extension_index = file_name.rfind('.') if (extension_index == (-1)): extension = '' else: extension = file_name[(extension_index + 1):].lower() if (extension in EXTENSION_BLACKLIST): raise InvalidAttachmentTypeError(('Extension %s is not supported.' % extension)) mime_type = EXTE...
[ "def", "_GetMimeType", "(", "file_name", ")", ":", "extension_index", "=", "file_name", ".", "rfind", "(", "'.'", ")", "if", "(", "extension_index", "==", "(", "-", "1", ")", ")", ":", "extension", "=", "''", "else", ":", "extension", "=", "file_name", ...
determine mime-type from file name .
train
false
27,407
def test_lwta_yaml(): limited_epoch_train(os.path.join(pylearn2.__path__[0], 'models/tests/lwta.yaml'))
[ "def", "test_lwta_yaml", "(", ")", ":", "limited_epoch_train", "(", "os", ".", "path", ".", "join", "(", "pylearn2", ".", "__path__", "[", "0", "]", ",", "'models/tests/lwta.yaml'", ")", ")" ]
test simple model on random data .
train
false
27,408
def monitor_folders(registry, xml_parent, data): ft = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.fstrigger.triggers.FolderContentTrigger') ft.set('plugin', 'fstrigger') mappings = [('path', 'path', ''), ('cron', 'spec', '')] convert_mapping_to_xml(ft, data, mappings, fail_required=True) includes = data.get(...
[ "def", "monitor_folders", "(", "registry", ",", "xml_parent", ",", "data", ")", ":", "ft", "=", "XML", ".", "SubElement", "(", "xml_parent", ",", "'org.jenkinsci.plugins.fstrigger.triggers.FolderContentTrigger'", ")", "ft", ".", "set", "(", "'plugin'", ",", "'fstr...
yaml: monitor-folders configure jenkins to monitor folders .
train
false
27,412
def absolute_symlink(source_path, target_path): if (not os.path.isabs(source_path)): raise ValueError(u'Path for source : {} must be absolute'.format(source_path)) if (not os.path.isabs(target_path)): raise ValueError(u'Path for link : {} must be absolute'.format(target_path)) if (source_path == target_path): ...
[ "def", "absolute_symlink", "(", "source_path", ",", "target_path", ")", ":", "if", "(", "not", "os", ".", "path", ".", "isabs", "(", "source_path", ")", ")", ":", "raise", "ValueError", "(", "u'Path for source : {} must be absolute'", ".", "format", "(", "sour...
create a symlink at target pointing to source using the absolute path .
train
true
27,413
def srs_output(func, argtypes): func.argtypes = argtypes func.restype = c_void_p func.errcheck = check_srs return func
[ "def", "srs_output", "(", "func", ",", "argtypes", ")", ":", "func", ".", "argtypes", "=", "argtypes", "func", ".", "restype", "=", "c_void_p", "func", ".", "errcheck", "=", "check_srs", "return", "func" ]
generates a ctypes prototype for the given function with the given c arguments that returns a pointer to an ogr spatial reference system .
train
false
27,414
def cifarnet_arg_scope(weight_decay=0.004): with slim.arg_scope([slim.conv2d], weights_initializer=tf.truncated_normal_initializer(stddev=0.05), activation_fn=tf.nn.relu): with slim.arg_scope([slim.fully_connected], biases_initializer=tf.constant_initializer(0.1), weights_initializer=trunc_normal(0.04), weights_regu...
[ "def", "cifarnet_arg_scope", "(", "weight_decay", "=", "0.004", ")", ":", "with", "slim", ".", "arg_scope", "(", "[", "slim", ".", "conv2d", "]", ",", "weights_initializer", "=", "tf", ".", "truncated_normal_initializer", "(", "stddev", "=", "0.05", ")", ","...
defines the default cifarnet argument scope .
train
false
27,415
def _without_most_central_edges(G, most_valuable_edge): original_num_components = nx.number_connected_components(G) num_new_components = original_num_components while (num_new_components <= original_num_components): edge = most_valuable_edge(G) G.remove_edge(*edge) new_components = tuple(nx.connected_component...
[ "def", "_without_most_central_edges", "(", "G", ",", "most_valuable_edge", ")", ":", "original_num_components", "=", "nx", ".", "number_connected_components", "(", "G", ")", "num_new_components", "=", "original_num_components", "while", "(", "num_new_components", "<=", ...
returns the connected components of the graph that results from repeatedly removing the most "valuable" edge in the graph .
train
false
27,417
def intranges_contain(int_, ranges): tuple_ = (int_, int_) pos = bisect.bisect_left(ranges, tuple_) if (pos > 0): (left, right) = ranges[(pos - 1)] if (left <= int_ < right): return True if (pos < len(ranges)): (left, _) = ranges[pos] if (left == int_): return True return False
[ "def", "intranges_contain", "(", "int_", ",", "ranges", ")", ":", "tuple_", "=", "(", "int_", ",", "int_", ")", "pos", "=", "bisect", ".", "bisect_left", "(", "ranges", ",", "tuple_", ")", "if", "(", "pos", ">", "0", ")", ":", "(", "left", ",", "...
determine if int_ falls into one of the ranges in ranges .
train
true
27,418
def setDefaultFetcher(fetcher, wrap_exceptions=True): global _default_fetcher if ((fetcher is None) or (not wrap_exceptions)): _default_fetcher = fetcher else: _default_fetcher = ExceptionWrappingFetcher(fetcher)
[ "def", "setDefaultFetcher", "(", "fetcher", ",", "wrap_exceptions", "=", "True", ")", ":", "global", "_default_fetcher", "if", "(", "(", "fetcher", "is", "None", ")", "or", "(", "not", "wrap_exceptions", ")", ")", ":", "_default_fetcher", "=", "fetcher", "el...
set the default fetcher .
train
true
27,420
def comment_requirement(req): return any(((ign in req) for ign in COMMENT_REQUIREMENTS))
[ "def", "comment_requirement", "(", "req", ")", ":", "return", "any", "(", "(", "(", "ign", "in", "req", ")", "for", "ign", "in", "COMMENT_REQUIREMENTS", ")", ")" ]
some requirements dont install on all systems .
train
false
27,421
def image_snapshot_delete(call=None, kwargs=None): if (call != 'function'): raise SaltCloudSystemExit('The image_snapshot_delete function must be called with -f or --function.') if (kwargs is None): kwargs = {} image_id = kwargs.get('image_id', None) image_name = kwargs.get('image_name', None) snapshot_id = kw...
[ "def", "image_snapshot_delete", "(", "call", "=", "None", ",", "kwargs", "=", "None", ")", ":", "if", "(", "call", "!=", "'function'", ")", ":", "raise", "SaltCloudSystemExit", "(", "'The image_snapshot_delete function must be called with -f or --function.'", ")", "if...
deletes a snapshot from the image .
train
true
27,422
@register.filter(is_safe=False) def unlocalize(value): return force_text(value)
[ "@", "register", ".", "filter", "(", "is_safe", "=", "False", ")", "def", "unlocalize", "(", "value", ")", ":", "return", "force_text", "(", "value", ")" ]
forces a value to be rendered as a non-localized value .
train
false
27,425
def read_var(*args): ret = {} try: for arg in args: log.debug('Querying: %s', arg) cmd = '{0} {1} {2}'.format(_TRAFFICLINE, '-r', arg) ret[arg] = _subprocess(cmd) except KeyError: pass return ret
[ "def", "read_var", "(", "*", "args", ")", ":", "ret", "=", "{", "}", "try", ":", "for", "arg", "in", "args", ":", "log", ".", "debug", "(", "'Querying: %s'", ",", "arg", ")", "cmd", "=", "'{0} {1} {2}'", ".", "format", "(", "_TRAFFICLINE", ",", "'-...
read variable definitions from the traffic_line command .
train
false
27,426
def include_enabled_extensions(settings): from django.db.models.loading import load_app from django.db import DatabaseError from reviewboard.extensions.base import get_extension_manager try: manager = get_extension_manager() except DatabaseError: return for extension in manager.get_enabled_extensions(): loa...
[ "def", "include_enabled_extensions", "(", "settings", ")", ":", "from", "django", ".", "db", ".", "models", ".", "loading", "import", "load_app", "from", "django", ".", "db", "import", "DatabaseError", "from", "reviewboard", ".", "extensions", ".", "base", "im...
this adds enabled extensions to the installed_apps cache so that operations like syncdb and evolve will take extensions into consideration .
train
false
27,427
@pytest.mark.parametrize('value', ['foo\\bar', 'fo\xc3\xb6\r\nb\xc3\xa4r', 'fo\xc3\xb6\\r\\nb\xc3\xa4r', 'fo\xc3\xb6\r\n\\r\\nb\xc3\xa4r', 'nfo\xc3\xb6\nb\xc3\xa4r', 'nfo\xc3\xb6\\nb\xc3\xa4r', 'fo\xc3\xb6\n\\nb\xc3\xa4r']) def test_multistringwidget_decompress_strings(value): widget = MultiStringWidget() assert (wid...
[ "@", "pytest", ".", "mark", ".", "parametrize", "(", "'value'", ",", "[", "'foo\\\\bar'", ",", "'fo\\xc3\\xb6\\r\\nb\\xc3\\xa4r'", ",", "'fo\\xc3\\xb6\\\\r\\\\nb\\xc3\\xa4r'", ",", "'fo\\xc3\\xb6\\r\\n\\\\r\\\\nb\\xc3\\xa4r'", ",", "'nfo\\xc3\\xb6\\nb\\xc3\\xa4r'", ",", "'nfo...
tests units multistringwidget decompresses string values .
train
false
27,428
def add_classifier_layer(net, num_outputs): net_classifier = Network((net.sizes + [num_outputs])) net_classifier.weights[:(-1)] = net.weights net_classifier.biases[:(-1)] = net.biases return net_classifier
[ "def", "add_classifier_layer", "(", "net", ",", "num_outputs", ")", ":", "net_classifier", "=", "Network", "(", "(", "net", ".", "sizes", "+", "[", "num_outputs", "]", ")", ")", "net_classifier", ".", "weights", "[", ":", "(", "-", "1", ")", "]", "=", ...
return the network net .
train
false
27,429
def extract_bits(data, shift, length): bitmask = (((1 << length) - 1) << shift) return ((data & bitmask) >> shift)
[ "def", "extract_bits", "(", "data", ",", "shift", ",", "length", ")", ":", "bitmask", "=", "(", "(", "(", "1", "<<", "length", ")", "-", "1", ")", "<<", "shift", ")", "return", "(", "(", "data", "&", "bitmask", ")", ">>", "shift", ")" ]
extract a portion of a bit string .
train
false
27,430
def plane(individual): return (individual[0],)
[ "def", "plane", "(", "individual", ")", ":", "return", "(", "individual", "[", "0", "]", ",", ")" ]
plane test objective function .
train
false
27,431
def build_header(prim, webdir=''): try: uptime = calc_age(sabnzbd.START) except: uptime = '-' if prim: color = sabnzbd.WEB_COLOR else: color = sabnzbd.WEB_COLOR2 if (not color): color = '' header = {'T': Ttemplate, 'Tspec': Tspec, 'Tx': Ttemplate, 'version': sabnzbd.__version__, 'paused': (Downloader.do...
[ "def", "build_header", "(", "prim", ",", "webdir", "=", "''", ")", ":", "try", ":", "uptime", "=", "calc_age", "(", "sabnzbd", ".", "START", ")", "except", ":", "uptime", "=", "'-'", "if", "prim", ":", "color", "=", "sabnzbd", ".", "WEB_COLOR", "else...
build a header from a list of fields .
train
false
27,433
@plugins.command('new') @click.argument('plugin_identifier', callback=check_cookiecutter) @click.option('--template', '-t', type=click.STRING, default='https://github.com/sh4nks/cookiecutter-flaskbb-plugin', help='Path to a cookiecutter template or to a valid git repo.') def new_plugin(plugin_identifier, template): ou...
[ "@", "plugins", ".", "command", "(", "'new'", ")", "@", "click", ".", "argument", "(", "'plugin_identifier'", ",", "callback", "=", "check_cookiecutter", ")", "@", "click", ".", "option", "(", "'--template'", ",", "'-t'", ",", "type", "=", "click", ".", ...
creates a new plugin based on the cookiecutter plugin template .
train
false
27,434
def define_enum(enum_descriptor, module_name): enum_values = (enum_descriptor.values or []) class_dict = dict(((value.name, value.number) for value in enum_values)) class_dict['__module__'] = module_name return type(str(enum_descriptor.name), (messages.Enum,), class_dict)
[ "def", "define_enum", "(", "enum_descriptor", ",", "module_name", ")", ":", "enum_values", "=", "(", "enum_descriptor", ".", "values", "or", "[", "]", ")", "class_dict", "=", "dict", "(", "(", "(", "value", ".", "name", ",", "value", ".", "number", ")", ...
define enum class from descriptor .
train
false
27,436
def get_constr_expr(lh_op, rh_op): if (rh_op is None): return lh_op else: return sum_expr([lh_op, neg_expr(rh_op)])
[ "def", "get_constr_expr", "(", "lh_op", ",", "rh_op", ")", ":", "if", "(", "rh_op", "is", "None", ")", ":", "return", "lh_op", "else", ":", "return", "sum_expr", "(", "[", "lh_op", ",", "neg_expr", "(", "rh_op", ")", "]", ")" ]
returns the operator in the constraint .
train
false
27,437
def quality(mime_type, ranges): parsed_ranges = map(parse_media_range, ranges.split(',')) return quality_parsed(mime_type, parsed_ranges)
[ "def", "quality", "(", "mime_type", ",", "ranges", ")", ":", "parsed_ranges", "=", "map", "(", "parse_media_range", ",", "ranges", ".", "split", "(", "','", ")", ")", "return", "quality_parsed", "(", "mime_type", ",", "parsed_ranges", ")" ]
returns the quality q of a mime-type when compared against the media-ranges in ranges .
train
false
27,438
def awscli_initialize(cli): cli.register('building-command-table.main', add_s3) cli.register('building-command-table.sync', register_sync_strategies)
[ "def", "awscli_initialize", "(", "cli", ")", ":", "cli", ".", "register", "(", "'building-command-table.main'", ",", "add_s3", ")", "cli", ".", "register", "(", "'building-command-table.sync'", ",", "register_sync_strategies", ")" ]
this function is require to use the plugin .
train
false
27,439
def is_prerequisite(course_key, prereq_content_key): return (get_gating_milestone(course_key, prereq_content_key, 'fulfills') is not None)
[ "def", "is_prerequisite", "(", "course_key", ",", "prereq_content_key", ")", ":", "return", "(", "get_gating_milestone", "(", "course_key", ",", "prereq_content_key", ",", "'fulfills'", ")", "is", "not", "None", ")" ]
returns true if there is at least one coursecontentmilestone which the given course content fulfills arguments: course_key : the course key prereq_content_key : the prerequisite content usage key returns: bool: true if the course content fulfills a coursecontentmilestone .
train
false