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 |
|---|---|---|---|---|---|
26,760 | def strategy_connected_sequential_bfs(G, colors):
return strategy_connected_sequential(G, colors, 'bfs')
| [
"def",
"strategy_connected_sequential_bfs",
"(",
"G",
",",
"colors",
")",
":",
"return",
"strategy_connected_sequential",
"(",
"G",
",",
"colors",
",",
"'bfs'",
")"
] | returns an iterable over nodes in g in the order given by a breadth-first traversal . | train | false |
26,761 | def all_repositories(number=(-1), etag=None):
return gh.all_repositories(number, etag)
| [
"def",
"all_repositories",
"(",
"number",
"=",
"(",
"-",
"1",
")",
",",
"etag",
"=",
"None",
")",
":",
"return",
"gh",
".",
"all_repositories",
"(",
"number",
",",
"etag",
")"
] | iterate over every repository in the order they were created . | train | false |
26,762 | @world.absorb
def css_fill(css_selector, text, index=0):
wait_for_visible(css_selector, index=index)
retry_on_exception((lambda : css_find(css_selector)[index].fill(text)))
wait_for((lambda _: css_has_value(css_selector, text, index=index)))
return True
| [
"@",
"world",
".",
"absorb",
"def",
"css_fill",
"(",
"css_selector",
",",
"text",
",",
"index",
"=",
"0",
")",
":",
"wait_for_visible",
"(",
"css_selector",
",",
"index",
"=",
"index",
")",
"retry_on_exception",
"(",
"(",
"lambda",
":",
"css_find",
"(",
... | set the value of the element to the specified text . | train | false |
26,763 | def get_original_file(filediff, request, encoding_list):
data = ''
if (not filediff.is_new):
repository = filediff.diffset.repository
data = repository.get_file(filediff.source_file, filediff.source_revision, base_commit_id=filediff.diffset.base_commit_id, request=request)
(encoding, data) = convert_to_unicode(data, encoding_list)
data = convert_line_endings(data)
data = data.encode(encoding)
if (filediff.parent_diff and ((not filediff.extra_data) or (not filediff.extra_data.get(u'parent_moved', False)))):
data = patch(filediff.parent_diff, data, filediff.source_file, request)
return data
| [
"def",
"get_original_file",
"(",
"filediff",
",",
"request",
",",
"encoding_list",
")",
":",
"data",
"=",
"''",
"if",
"(",
"not",
"filediff",
".",
"is_new",
")",
":",
"repository",
"=",
"filediff",
".",
"diffset",
".",
"repository",
"data",
"=",
"repositor... | get a file either from the cache or the scm . | train | false |
26,764 | def _name_matches(name, matches):
for m in matches:
if name.endswith(m):
return True
if name.lower().endswith(('_' + m.lower())):
return True
if (name.lower() == m.lower()):
return True
return False
| [
"def",
"_name_matches",
"(",
"name",
",",
"matches",
")",
":",
"for",
"m",
"in",
"matches",
":",
"if",
"name",
".",
"endswith",
"(",
"m",
")",
":",
"return",
"True",
"if",
"name",
".",
"lower",
"(",
")",
".",
"endswith",
"(",
"(",
"'_'",
"+",
"m"... | helper function to see if given name has any of the patterns in given matches . | train | true |
26,765 | def error_endpoint(error):
headers = None
if error.response:
headers = error.response.headers
response = {config.STATUS: config.STATUS_ERR, config.ERROR: {'code': error.code, 'message': error.description}}
return send_response(None, (response, None, None, error.code, headers))
| [
"def",
"error_endpoint",
"(",
"error",
")",
":",
"headers",
"=",
"None",
"if",
"error",
".",
"response",
":",
"headers",
"=",
"error",
".",
"response",
".",
"headers",
"response",
"=",
"{",
"config",
".",
"STATUS",
":",
"config",
".",
"STATUS_ERR",
",",
... | response returned when an error is raised by the api (e . | train | false |
26,768 | def list_cache_opts():
return [(g, copy.deepcopy(o)) for (g, o) in _cache_opts]
| [
"def",
"list_cache_opts",
"(",
")",
":",
"return",
"[",
"(",
"g",
",",
"copy",
".",
"deepcopy",
"(",
"o",
")",
")",
"for",
"(",
"g",
",",
"o",
")",
"in",
"_cache_opts",
"]"
] | return a list of oslo_config options available in glance cache service . | train | false |
26,769 | def defer_to_events_queue(fn, *args, **kwargs):
deferred.defer(fn, _queue=QUEUE_NAME_EVENTS, *args, **kwargs)
| [
"def",
"defer_to_events_queue",
"(",
"fn",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"deferred",
".",
"defer",
"(",
"fn",
",",
"_queue",
"=",
"QUEUE_NAME_EVENTS",
",",
"*",
"args",
",",
"**",
"kwargs",
")"
] | adds a new task to the deferred queue for processing events . | train | false |
26,770 | def _nova_to_osvif_route(route):
obj = objects.route.Route(cidr=route['cidr'])
if (route['interface'] is not None):
obj.interface = route['interface']
if ((route['gateway'] is not None) and (route['gateway']['address'] is not None)):
obj.gateway = route['gateway']['address']
return obj
| [
"def",
"_nova_to_osvif_route",
"(",
"route",
")",
":",
"obj",
"=",
"objects",
".",
"route",
".",
"Route",
"(",
"cidr",
"=",
"route",
"[",
"'cidr'",
"]",
")",
"if",
"(",
"route",
"[",
"'interface'",
"]",
"is",
"not",
"None",
")",
":",
"obj",
".",
"i... | convert nova route object into os_vif object . | train | false |
26,772 | def create_table(context, data_dict):
datastore_fields = [{'id': '_id', 'type': 'serial primary key'}, {'id': '_full_text', 'type': 'tsvector'}]
extra_fields = []
supplied_fields = data_dict.get('fields', [])
check_fields(context, supplied_fields)
field_ids = _pluck('id', supplied_fields)
records = data_dict.get('records')
for field in supplied_fields:
if ('type' not in field):
if ((not records) or (field['id'] not in records[0])):
raise ValidationError({'fields': [u'"{0}" type not guessable'.format(field['id'])]})
field['type'] = _guess_type(records[0][field['id']])
unique_fields = set([f['id'] for f in supplied_fields])
if (not (len(unique_fields) == len(supplied_fields))):
raise ValidationError({'field': ['Duplicate column names are not supported']})
if records:
if (not isinstance(records[0], dict)):
raise ValidationError({'records': ['The first row is not a json object']})
supplied_field_ids = records[0].keys()
for field_id in supplied_field_ids:
if (field_id not in field_ids):
extra_fields.append({'id': field_id, 'type': _guess_type(records[0][field_id])})
fields = ((datastore_fields + supplied_fields) + extra_fields)
sql_fields = u', '.join([u'"{0}" {1}'.format(f['id'], f['type']) for f in fields])
sql_string = u'CREATE TABLE "{0}" ({1});'.format(data_dict['resource_id'], sql_fields)
context['connection'].execute(sql_string.replace('%', '%%'))
| [
"def",
"create_table",
"(",
"context",
",",
"data_dict",
")",
":",
"datastore_fields",
"=",
"[",
"{",
"'id'",
":",
"'_id'",
",",
"'type'",
":",
"'serial primary key'",
"}",
",",
"{",
"'id'",
":",
"'_full_text'",
",",
"'type'",
":",
"'tsvector'",
"}",
"]",
... | create a table in the database . | train | false |
26,773 | def corner_moravec(image, window_size=1):
return _corner_moravec(image, window_size)
| [
"def",
"corner_moravec",
"(",
"image",
",",
"window_size",
"=",
"1",
")",
":",
"return",
"_corner_moravec",
"(",
"image",
",",
"window_size",
")"
] | compute moravec corner measure response image . | train | false |
26,774 | def weak_date(date):
return ((datetime.strptime(date, RFC1123_DATE_FORMAT) + timedelta(seconds=1)) if date else None)
| [
"def",
"weak_date",
"(",
"date",
")",
":",
"return",
"(",
"(",
"datetime",
".",
"strptime",
"(",
"date",
",",
"RFC1123_DATE_FORMAT",
")",
"+",
"timedelta",
"(",
"seconds",
"=",
"1",
")",
")",
"if",
"date",
"else",
"None",
")"
] | returns a rfc-1123 string corresponding to a datetime value plus a 1 second timedelta . | train | false |
26,775 | def unique_v2(lst):
dd = defaultdict(int)
unique_list = []
for val in lst:
dd[val] += 1
for val in lst:
if (dd[val] == 1):
unique_list.append(val)
return unique_list
| [
"def",
"unique_v2",
"(",
"lst",
")",
":",
"dd",
"=",
"defaultdict",
"(",
"int",
")",
"unique_list",
"=",
"[",
"]",
"for",
"val",
"in",
"lst",
":",
"dd",
"[",
"val",
"]",
"+=",
"1",
"for",
"val",
"in",
"lst",
":",
"if",
"(",
"dd",
"[",
"val",
... | returns a list of all unique elements in the input list "lst . | train | false |
26,776 | def decorator(caller, _func=None):
if (_func is not None):
return decorate(_func, caller)
if inspect.isclass(caller):
name = caller.__name__.lower()
doc = ('decorator(%s) converts functions/generators into factories of %s objects' % (caller.__name__, caller.__name__))
elif inspect.isfunction(caller):
if (caller.__name__ == '<lambda>'):
name = '_lambda_'
else:
name = caller.__name__
doc = caller.__doc__
else:
name = caller.__class__.__name__.lower()
doc = caller.__call__.__doc__
evaldict = dict(_call_=caller, _decorate_=decorate)
return FunctionMaker.create(('%s(func)' % name), 'return _decorate_(func, _call_)', evaldict, doc=doc, module=caller.__module__, __wrapped__=caller)
| [
"def",
"decorator",
"(",
"caller",
",",
"_func",
"=",
"None",
")",
":",
"if",
"(",
"_func",
"is",
"not",
"None",
")",
":",
"return",
"decorate",
"(",
"_func",
",",
"caller",
")",
"if",
"inspect",
".",
"isclass",
"(",
"caller",
")",
":",
"name",
"="... | general purpose decorator factory: takes a caller function as input and returns a decorator with the same attributes . | train | true |
26,779 | def copy_recursively(source_dir, target_dir):
shutil.copytree(source_dir, target_dir)
| [
"def",
"copy_recursively",
"(",
"source_dir",
",",
"target_dir",
")",
":",
"shutil",
".",
"copytree",
"(",
"source_dir",
",",
"target_dir",
")"
] | recursively copy a source directory to a target directory . | train | false |
26,780 | def check_build():
build_dirs = ['build', 'build/doctrees', 'build/html', 'build/latex', 'build/texinfo', '_static', '_templates']
for d in build_dirs:
try:
os.mkdir(d)
except OSError:
pass
| [
"def",
"check_build",
"(",
")",
":",
"build_dirs",
"=",
"[",
"'build'",
",",
"'build/doctrees'",
",",
"'build/html'",
",",
"'build/latex'",
",",
"'build/texinfo'",
",",
"'_static'",
",",
"'_templates'",
"]",
"for",
"d",
"in",
"build_dirs",
":",
"try",
":",
"... | create target build directories if necessary . | train | false |
26,781 | @utils.arg('server', metavar='<server>', help=_('Name or ID of server.'))
def do_unshelve(cs, args):
_find_server(cs, args.server).unshelve()
| [
"@",
"utils",
".",
"arg",
"(",
"'server'",
",",
"metavar",
"=",
"'<server>'",
",",
"help",
"=",
"_",
"(",
"'Name or ID of server.'",
")",
")",
"def",
"do_unshelve",
"(",
"cs",
",",
"args",
")",
":",
"_find_server",
"(",
"cs",
",",
"args",
".",
"server"... | unshelve a server . | train | false |
26,782 | def to_native_string(string, encoding='ascii'):
if isinstance(string, builtin_str):
out = string
elif is_py2:
out = string.encode(encoding)
else:
out = string.decode(encoding)
return out
| [
"def",
"to_native_string",
"(",
"string",
",",
"encoding",
"=",
"'ascii'",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"builtin_str",
")",
":",
"out",
"=",
"string",
"elif",
"is_py2",
":",
"out",
"=",
"string",
".",
"encode",
"(",
"encoding",
")",
... | given a string object . | train | true |
26,783 | def test_kl():
init_mode = theano.config.compute_test_value
theano.config.compute_test_value = 'raise'
try:
mlp = MLP(layers=[Sigmoid(dim=10, layer_name='Y', irange=0.1)], nvis=10)
X = mlp.get_input_space().make_theano_batch()
Y = mlp.get_output_space().make_theano_batch()
X.tag.test_value = np.random.random(get_debug_values(X)[0].shape).astype(theano.config.floatX)
Y_hat = mlp.fprop(X)
ave = kl(Y, Y_hat, 1)
Y.tag.test_value[2][3] = 1.1
np.testing.assert_raises(ValueError, kl, Y, Y_hat, 1)
Y.tag.test_value[2][3] = (-0.1)
np.testing.assert_raises(ValueError, kl, Y, Y_hat, 1)
finally:
theano.config.compute_test_value = init_mode
| [
"def",
"test_kl",
"(",
")",
":",
"init_mode",
"=",
"theano",
".",
"config",
".",
"compute_test_value",
"theano",
".",
"config",
".",
"compute_test_value",
"=",
"'raise'",
"try",
":",
"mlp",
"=",
"MLP",
"(",
"layers",
"=",
"[",
"Sigmoid",
"(",
"dim",
"=",... | test whether function kl() has properly processed the input . | train | false |
26,788 | def ensure_installed(installable_context, install_func, auto_init):
parent_path = installable_context.parent_path
desc = installable_context.installable_description
def _check():
if (not installable_context.is_installed()):
if auto_init:
if installable_context.can_install():
if install_func(installable_context):
installed = False
log.warning(('%s installation requested and failed.' % desc))
else:
installed = installable_context.is_installed()
if (not installed):
log.warning(('%s installation requested, seemed to succeed, but not found.' % desc))
else:
installed = False
else:
installed = False
log.warning('%s not installed and auto-installation disabled.', desc)
else:
installed = True
return installed
if (not os.path.lexists(parent_path)):
os.mkdir(parent_path)
try:
if (auto_init and os.access(parent_path, os.W_OK)):
with FileLock(os.path.join(parent_path, desc.lower())):
return _check()
else:
return _check()
except FileLockException:
return ensure_installed(installable_context, auto_init)
| [
"def",
"ensure_installed",
"(",
"installable_context",
",",
"install_func",
",",
"auto_init",
")",
":",
"parent_path",
"=",
"installable_context",
".",
"parent_path",
"desc",
"=",
"installable_context",
".",
"installable_description",
"def",
"_check",
"(",
")",
":",
... | make sure target is installed - handle multiple processes potentially attempting installation . | train | false |
26,789 | def build_selection_spec(client_factory, name):
sel_spec = client_factory.create('ns0:SelectionSpec')
sel_spec.name = name
return sel_spec
| [
"def",
"build_selection_spec",
"(",
"client_factory",
",",
"name",
")",
":",
"sel_spec",
"=",
"client_factory",
".",
"create",
"(",
"'ns0:SelectionSpec'",
")",
"sel_spec",
".",
"name",
"=",
"name",
"return",
"sel_spec"
] | builds the selection spec . | train | false |
26,790 | def _makeAccept(key):
return sha1(('%s%s' % (key, _WS_GUID))).digest().encode('base64').strip()
| [
"def",
"_makeAccept",
"(",
"key",
")",
":",
"return",
"sha1",
"(",
"(",
"'%s%s'",
"%",
"(",
"key",
",",
"_WS_GUID",
")",
")",
")",
".",
"digest",
"(",
")",
".",
"encode",
"(",
"'base64'",
")",
".",
"strip",
"(",
")"
] | create an b{accept} response for a given key . | train | false |
26,793 | def _calc_shared_phylotypes_pairwise(otu_table, i, j):
shared_phylos = logical_and(otu_table.data(i, 'sample'), otu_table.data(j, 'sample'))
return shared_phylos.sum()
| [
"def",
"_calc_shared_phylotypes_pairwise",
"(",
"otu_table",
",",
"i",
",",
"j",
")",
":",
"shared_phylos",
"=",
"logical_and",
"(",
"otu_table",
".",
"data",
"(",
"i",
",",
"'sample'",
")",
",",
"otu_table",
".",
"data",
"(",
"j",
",",
"'sample'",
")",
... | calculate shared otus between two samples in column i and j . | train | false |
26,794 | @login_required
@view
def display_person_edit_name(request, name_edit_mode):
data = get_personal_data(request.user.get_profile())
data['name_edit_mode'] = name_edit_mode
data['editable'] = True
return (request, 'profile/main.html', data)
| [
"@",
"login_required",
"@",
"view",
"def",
"display_person_edit_name",
"(",
"request",
",",
"name_edit_mode",
")",
":",
"data",
"=",
"get_personal_data",
"(",
"request",
".",
"user",
".",
"get_profile",
"(",
")",
")",
"data",
"[",
"'name_edit_mode'",
"]",
"=",... | show a little edit form for first name and last name . | train | false |
26,795 | def _gf_div(f, g, p):
ring = f.ring
(densequo, denserem) = gf_div(f.to_dense(), g.to_dense(), p, ring.domain)
return (ring.from_dense(densequo), ring.from_dense(denserem))
| [
"def",
"_gf_div",
"(",
"f",
",",
"g",
",",
"p",
")",
":",
"ring",
"=",
"f",
".",
"ring",
"(",
"densequo",
",",
"denserem",
")",
"=",
"gf_div",
"(",
"f",
".",
"to_dense",
"(",
")",
",",
"g",
".",
"to_dense",
"(",
")",
",",
"p",
",",
"ring",
... | compute frac f g modulo p for two univariate polynomials over mathbb z_p . | train | false |
26,796 | def is_select(status):
if (not status):
return False
return (status.split(None, 1)[0].lower() == u'select')
| [
"def",
"is_select",
"(",
"status",
")",
":",
"if",
"(",
"not",
"status",
")",
":",
"return",
"False",
"return",
"(",
"status",
".",
"split",
"(",
"None",
",",
"1",
")",
"[",
"0",
"]",
".",
"lower",
"(",
")",
"==",
"u'select'",
")"
] | returns true if the first word in status is select . | train | false |
26,797 | def gmetric_write(NAME, VAL, TYPE, UNITS, SLOPE, TMAX, DMAX, GROUP):
packer = Packer()
HOSTNAME = 'test'
SPOOF = 0
packer.pack_int(128)
packer.pack_string(HOSTNAME)
packer.pack_string(NAME)
packer.pack_int(SPOOF)
packer.pack_string(TYPE)
packer.pack_string(NAME)
packer.pack_string(UNITS)
packer.pack_int(slope_str2int[SLOPE])
packer.pack_uint(int(TMAX))
packer.pack_uint(int(DMAX))
if (GROUP == ''):
packer.pack_int(0)
else:
packer.pack_int(1)
packer.pack_string('GROUP')
packer.pack_string(GROUP)
data = Packer()
data.pack_int((128 + 5))
data.pack_string(HOSTNAME)
data.pack_string(NAME)
data.pack_int(SPOOF)
data.pack_string('%s')
data.pack_string(str(VAL))
return (packer.get_buffer(), data.get_buffer())
| [
"def",
"gmetric_write",
"(",
"NAME",
",",
"VAL",
",",
"TYPE",
",",
"UNITS",
",",
"SLOPE",
",",
"TMAX",
",",
"DMAX",
",",
"GROUP",
")",
":",
"packer",
"=",
"Packer",
"(",
")",
"HOSTNAME",
"=",
"'test'",
"SPOOF",
"=",
"0",
"packer",
".",
"pack_int",
... | arguments are in all upper-case to match xml . | train | true |
26,798 | def get_serving_url(blob_key, size=None, crop=False, secure_url=None, filename=None, rpc=None):
rpc = get_serving_url_async(blob_key, size, crop, secure_url, filename, rpc)
return rpc.get_result()
| [
"def",
"get_serving_url",
"(",
"blob_key",
",",
"size",
"=",
"None",
",",
"crop",
"=",
"False",
",",
"secure_url",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"rpc",
"=",
"None",
")",
":",
"rpc",
"=",
"get_serving_url_async",
"(",
"blob_key",
",",
... | obtain a url that will serve the underlying image . | train | false |
26,799 | def buf_lookup_c_code(proto, defin, name, nd):
if (nd == 1):
proto.putln(('#define %s(type, buf, i0, s0) ((type)buf + i0)' % name))
else:
args = ', '.join([('i%d, s%d' % (i, i)) for i in range(nd)])
offset = ' + '.join([('i%d * s%d' % (i, i)) for i in range((nd - 1))])
proto.putln(('#define %s(type, buf, %s) ((type)((char*)buf + %s) + i%d)' % (name, args, offset, (nd - 1))))
| [
"def",
"buf_lookup_c_code",
"(",
"proto",
",",
"defin",
",",
"name",
",",
"nd",
")",
":",
"if",
"(",
"nd",
"==",
"1",
")",
":",
"proto",
".",
"putln",
"(",
"(",
"'#define %s(type, buf, i0, s0) ((type)buf + i0)'",
"%",
"name",
")",
")",
"else",
":",
"args... | similar to strided lookup . | train | false |
26,800 | def _clear_ignore(endpoint_props):
return dict(((prop_name, prop_val) for (prop_name, prop_val) in six.iteritems(endpoint_props) if ((prop_name not in _DO_NOT_COMPARE_FIELDS) and (prop_val is not None))))
| [
"def",
"_clear_ignore",
"(",
"endpoint_props",
")",
":",
"return",
"dict",
"(",
"(",
"(",
"prop_name",
",",
"prop_val",
")",
"for",
"(",
"prop_name",
",",
"prop_val",
")",
"in",
"six",
".",
"iteritems",
"(",
"endpoint_props",
")",
"if",
"(",
"(",
"prop_n... | both _clear_dict and _ignore_keys in a single iteration . | train | true |
26,801 | def set_virt_cpus(self, num):
if ((num == '') or (num is None)):
self.virt_cpus = 1
return
if (num == '<<inherit>>'):
self.virt_cpus = '<<inherit>>'
return
try:
num = int(str(num))
except:
raise CX(_(('invalid number of virtual CPUs (%s)' % num)))
self.virt_cpus = num
| [
"def",
"set_virt_cpus",
"(",
"self",
",",
"num",
")",
":",
"if",
"(",
"(",
"num",
"==",
"''",
")",
"or",
"(",
"num",
"is",
"None",
")",
")",
":",
"self",
".",
"virt_cpus",
"=",
"1",
"return",
"if",
"(",
"num",
"==",
"'<<inherit>>'",
")",
":",
"... | for virt only . | train | false |
26,802 | def sort_from_strings(model_cls, sort_parts):
if (not sort_parts):
sort = query.NullSort()
elif (len(sort_parts) == 1):
sort = construct_sort_part(model_cls, sort_parts[0])
else:
sort = query.MultipleSort()
for part in sort_parts:
sort.add_sort(construct_sort_part(model_cls, part))
return sort
| [
"def",
"sort_from_strings",
"(",
"model_cls",
",",
"sort_parts",
")",
":",
"if",
"(",
"not",
"sort_parts",
")",
":",
"sort",
"=",
"query",
".",
"NullSort",
"(",
")",
"elif",
"(",
"len",
"(",
"sort_parts",
")",
"==",
"1",
")",
":",
"sort",
"=",
"const... | create a sort from a list of sort criteria . | train | false |
26,804 | def test_shipping_method_without_shipping(request_cart_with_item, client, monkeypatch):
monkeypatch.setattr('saleor.checkout.core.Checkout.is_shipping_required', False)
response = client.get(reverse('checkout:shipping-method'))
assert (response.status_code == 302)
assert (get_redirect_location(response) == reverse('checkout:summary'))
| [
"def",
"test_shipping_method_without_shipping",
"(",
"request_cart_with_item",
",",
"client",
",",
"monkeypatch",
")",
":",
"monkeypatch",
".",
"setattr",
"(",
"'saleor.checkout.core.Checkout.is_shipping_required'",
",",
"False",
")",
"response",
"=",
"client",
".",
"get"... | user tries to get shipping method step in checkout without shipping - if is redirected to summary step . | train | false |
26,805 | def pathmatch(pattern, filename):
symbols = {'?': '[^/]', '?/': '[^/]/', '*': '[^/]+', '*/': '[^/]+/', '**/': '(?:.+/)*?', '**': '(?:.+/)*?[^/]+'}
buf = []
for (idx, part) in enumerate(re.split('([?*]+/?)', pattern)):
if (idx % 2):
buf.append(symbols[part])
elif part:
buf.append(re.escape(part))
match = re.match((''.join(buf) + '$'), filename.replace(os.sep, '/'))
return (match is not None)
| [
"def",
"pathmatch",
"(",
"pattern",
",",
"filename",
")",
":",
"symbols",
"=",
"{",
"'?'",
":",
"'[^/]'",
",",
"'?/'",
":",
"'[^/]/'",
",",
"'*'",
":",
"'[^/]+'",
",",
"'*/'",
":",
"'[^/]+/'",
",",
"'**/'",
":",
"'(?:.+/)*?'",
",",
"'**'",
":",
"'(?:... | extended pathname pattern matching . | train | false |
26,806 | def maybe_show_progress(it, show_progress, **kwargs):
if show_progress:
return click.progressbar(it, **kwargs)
return CallbackManager((lambda it=it: it))
| [
"def",
"maybe_show_progress",
"(",
"it",
",",
"show_progress",
",",
"**",
"kwargs",
")",
":",
"if",
"show_progress",
":",
"return",
"click",
".",
"progressbar",
"(",
"it",
",",
"**",
"kwargs",
")",
"return",
"CallbackManager",
"(",
"(",
"lambda",
"it",
"="... | optionally show a progress bar for the given iterator . | train | true |
26,809 | def setLogRecordFactory(factory):
global _LOG_RECORD_FACTORY
_LOG_RECORD_FACTORY = factory
| [
"def",
"setLogRecordFactory",
"(",
"factory",
")",
":",
"global",
"_LOG_RECORD_FACTORY",
"_LOG_RECORD_FACTORY",
"=",
"factory"
] | set the factory to be used when instantiating a log record . | train | false |
26,810 | def fake_loads_json_error(content, *args, **kwargs):
raise json.JSONDecodeError('Using simplejson & you gave me bad JSON.', '', 0)
| [
"def",
"fake_loads_json_error",
"(",
"content",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"raise",
"json",
".",
"JSONDecodeError",
"(",
"'Using simplejson & you gave me bad JSON.'",
",",
"''",
",",
"0",
")"
] | callable to generate a fake jsondecodeerror . | train | false |
26,811 | def parse_ns_headers(ns_headers):
known_attrs = ('expires', 'domain', 'path', 'secure', 'version', 'port', 'max-age')
result = []
for ns_header in ns_headers:
pairs = []
version_set = False
for (ii, param) in enumerate(ns_header.split(';')):
param = param.strip()
(key, sep, val) = param.partition('=')
key = key.strip()
if (not key):
if (ii == 0):
break
else:
continue
val = (val.strip() if sep else None)
if (ii != 0):
lc = key.lower()
if (lc in known_attrs):
key = lc
if (key == 'version'):
if (val is not None):
val = _strip_quotes(val)
version_set = True
elif (key == 'expires'):
if (val is not None):
val = http2time(_strip_quotes(val))
pairs.append((key, val))
if pairs:
if (not version_set):
pairs.append(('version', '0'))
result.append(pairs)
return result
| [
"def",
"parse_ns_headers",
"(",
"ns_headers",
")",
":",
"known_attrs",
"=",
"(",
"'expires'",
",",
"'domain'",
",",
"'path'",
",",
"'secure'",
",",
"'version'",
",",
"'port'",
",",
"'max-age'",
")",
"result",
"=",
"[",
"]",
"for",
"ns_header",
"in",
"ns_he... | ad-hoc parser for netscape protocol cookie-attributes . | train | false |
26,812 | def _overwrite_special_dates(midnight_utcs, opens_or_closes, special_opens_or_closes):
if (not len(special_opens_or_closes)):
return
(len_m, len_oc) = (len(midnight_utcs), len(opens_or_closes))
if (len_m != len_oc):
raise ValueError(('Found misaligned dates while building calendar.\nExpected midnight_utcs to be the same length as open_or_closes,\nbut len(midnight_utcs)=%d, len(open_or_closes)=%d' % len_m), len_oc)
indexer = midnight_utcs.get_indexer(special_opens_or_closes.normalize())
if ((-1) in indexer):
bad_dates = list(special_opens_or_closes[(indexer == (-1))])
raise ValueError(('Special dates %s are not trading days.' % bad_dates))
opens_or_closes.values[indexer] = special_opens_or_closes.values
| [
"def",
"_overwrite_special_dates",
"(",
"midnight_utcs",
",",
"opens_or_closes",
",",
"special_opens_or_closes",
")",
":",
"if",
"(",
"not",
"len",
"(",
"special_opens_or_closes",
")",
")",
":",
"return",
"(",
"len_m",
",",
"len_oc",
")",
"=",
"(",
"len",
"(",... | overwrite dates in open_or_closes with corresponding dates in special_opens_or_closes . | train | true |
26,813 | def parse_dict_header(value):
result = {}
for item in _parse_list_header(value):
if ('=' not in item):
result[item] = None
continue
(name, value) = item.split('=', 1)
if (value[:1] == value[(-1):] == '"'):
value = unquote_header_value(value[1:(-1)])
result[name] = value
return result
| [
"def",
"parse_dict_header",
"(",
"value",
")",
":",
"result",
"=",
"{",
"}",
"for",
"item",
"in",
"_parse_list_header",
"(",
"value",
")",
":",
"if",
"(",
"'='",
"not",
"in",
"item",
")",
":",
"result",
"[",
"item",
"]",
"=",
"None",
"continue",
"(",... | parse lists of key . | train | true |
26,814 | def Mean(xs):
return np.mean(xs)
| [
"def",
"Mean",
"(",
"xs",
")",
":",
"return",
"np",
".",
"mean",
"(",
"xs",
")"
] | computes mean . | train | false |
26,816 | def _pick_bads(event, params):
bads = params['info']['bads']
params['info']['bads'] = _select_bads(event, params, bads)
params['update_fun']()
params['plot_fun']()
| [
"def",
"_pick_bads",
"(",
"event",
",",
"params",
")",
":",
"bads",
"=",
"params",
"[",
"'info'",
"]",
"[",
"'bads'",
"]",
"params",
"[",
"'info'",
"]",
"[",
"'bads'",
"]",
"=",
"_select_bads",
"(",
"event",
",",
"params",
",",
"bads",
")",
"params",... | select components on click . | train | false |
26,817 | @unbox(types.Set)
def unbox_set(typ, obj, c):
size = c.pyapi.set_size(obj)
errorptr = cgutils.alloca_once_value(c.builder, cgutils.false_bit)
setptr = cgutils.alloca_once(c.builder, c.context.get_value_type(typ))
ptr = c.pyapi.object_get_private_data(obj)
with c.builder.if_else(cgutils.is_not_null(c.builder, ptr)) as (has_meminfo, otherwise):
with has_meminfo:
inst = setobj.SetInstance.from_meminfo(c.context, c.builder, typ, ptr)
if typ.reflected:
inst.parent = obj
c.builder.store(inst.value, setptr)
with otherwise:
_python_set_to_native(typ, obj, c, size, setptr, errorptr)
def cleanup():
c.pyapi.object_reset_private_data(obj)
return NativeValue(c.builder.load(setptr), is_error=c.builder.load(errorptr), cleanup=cleanup)
| [
"@",
"unbox",
"(",
"types",
".",
"Set",
")",
"def",
"unbox_set",
"(",
"typ",
",",
"obj",
",",
"c",
")",
":",
"size",
"=",
"c",
".",
"pyapi",
".",
"set_size",
"(",
"obj",
")",
"errorptr",
"=",
"cgutils",
".",
"alloca_once_value",
"(",
"c",
".",
"b... | convert set *obj* to a native set . | train | false |
26,818 | def lat2hemi(lat):
return (((lat >= 0) and 'N') or 'S')
| [
"def",
"lat2hemi",
"(",
"lat",
")",
":",
"return",
"(",
"(",
"(",
"lat",
">=",
"0",
")",
"and",
"'N'",
")",
"or",
"'S'",
")"
] | convert latitude to single-letter hemisphere . | train | false |
26,820 | def _make_agent_name(base):
if base:
if ('pyrax' in base):
return base
else:
return ('%s %s' % (USER_AGENT, base))
else:
return USER_AGENT
| [
"def",
"_make_agent_name",
"(",
"base",
")",
":",
"if",
"base",
":",
"if",
"(",
"'pyrax'",
"in",
"base",
")",
":",
"return",
"base",
"else",
":",
"return",
"(",
"'%s %s'",
"%",
"(",
"USER_AGENT",
",",
"base",
")",
")",
"else",
":",
"return",
"USER_AG... | appends pyrax information to the underlying librarys user agent . | train | false |
26,821 | def extend_year_spans(spans, spanlen, start=1900, end=2014):
extended_spans = spans[:]
for (x, y) in pairwise(spans):
for span_from in range((x['to'] + 1), y['from'], spanlen):
extended_spans.append({'from': span_from})
for span_from in range((spans[0]['from'] - spanlen), start, (- spanlen)):
extended_spans.append({'from': span_from})
for span_from in range((spans[(-1)]['to'] + 1), end, spanlen):
extended_spans.append({'from': span_from})
complete_year_spans(extended_spans)
return extended_spans
| [
"def",
"extend_year_spans",
"(",
"spans",
",",
"spanlen",
",",
"start",
"=",
"1900",
",",
"end",
"=",
"2014",
")",
":",
"extended_spans",
"=",
"spans",
"[",
":",
"]",
"for",
"(",
"x",
",",
"y",
")",
"in",
"pairwise",
"(",
"spans",
")",
":",
"for",
... | add new spans to given spans list so that every year of [start . | train | false |
26,822 | def format_json_object(obj):
return oslo_serialization.jsonutils.dumps(obj, sort_keys=True, indent=3)
| [
"def",
"format_json_object",
"(",
"obj",
")",
":",
"return",
"oslo_serialization",
".",
"jsonutils",
".",
"dumps",
"(",
"obj",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"3",
")"
] | formats json object to make it readable by proper indentation . | train | false |
26,824 | def utf8decode(value):
return value.decode('utf-8')
| [
"def",
"utf8decode",
"(",
"value",
")",
":",
"return",
"value",
".",
"decode",
"(",
"'utf-8'",
")"
] | returns utf-8 representation of the supplied 8-bit string representation . | train | false |
26,825 | def _retry_get_url(url, num_retries=10, timeout=5):
for i in range(0, num_retries):
try:
result = requests.get(url, timeout=timeout, proxies={'http': ''})
if hasattr(result, 'text'):
return result.text
elif hasattr(result, 'content'):
return result.content
else:
return ''
except requests.exceptions.HTTPError as exc:
return ''
except Exception as exc:
pass
log.warning('Caught exception reading from URL. Retry no. {0}'.format(i))
log.warning(pprint.pformat(exc))
time.sleep((2 ** i))
log.error('Failed to read from URL for {0} times. Giving up.'.format(num_retries))
return ''
| [
"def",
"_retry_get_url",
"(",
"url",
",",
"num_retries",
"=",
"10",
",",
"timeout",
"=",
"5",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"num_retries",
")",
":",
"try",
":",
"result",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"timeout"... | retry grabbing a url . | train | true |
26,828 | def PmfProbLess(pmf1, pmf2):
total = 0.0
for (v1, p1) in pmf1.Items():
for (v2, p2) in pmf2.Items():
if (v1 < v2):
total += (p1 * p2)
return total
| [
"def",
"PmfProbLess",
"(",
"pmf1",
",",
"pmf2",
")",
":",
"total",
"=",
"0.0",
"for",
"(",
"v1",
",",
"p1",
")",
"in",
"pmf1",
".",
"Items",
"(",
")",
":",
"for",
"(",
"v2",
",",
"p2",
")",
"in",
"pmf2",
".",
"Items",
"(",
")",
":",
"if",
"... | probability that a value from pmf1 is less than a value from pmf2 . | train | true |
26,830 | def floating_ebtables_rules(fixed_ip, network):
return ([('PREROUTING --logical-in %s -p ipv4 --ip-src %s ! --ip-dst %s -j redirect --redirect-target ACCEPT' % (network['bridge'], fixed_ip, network['cidr']))], 'nat')
| [
"def",
"floating_ebtables_rules",
"(",
"fixed_ip",
",",
"network",
")",
":",
"return",
"(",
"[",
"(",
"'PREROUTING --logical-in %s -p ipv4 --ip-src %s ! --ip-dst %s -j redirect --redirect-target ACCEPT'",
"%",
"(",
"network",
"[",
"'bridge'",
"]",
",",
"fixed_ip",
",",
"n... | makes sure only in-network traffic is bridged . | train | false |
26,831 | def _get_process_info(proc):
cmd = salt.utils.to_str((proc.CommandLine or ''))
name = salt.utils.to_str(proc.Name)
info = dict(cmd=cmd, name=name, **_get_process_owner(proc))
return info
| [
"def",
"_get_process_info",
"(",
"proc",
")",
":",
"cmd",
"=",
"salt",
".",
"utils",
".",
"to_str",
"(",
"(",
"proc",
".",
"CommandLine",
"or",
"''",
")",
")",
"name",
"=",
"salt",
".",
"utils",
".",
"to_str",
"(",
"proc",
".",
"Name",
")",
"info",... | return process information . | train | false |
26,833 | def DictReader(file_obj, columns=None):
footer = _read_footer(file_obj)
keys = (columns if columns else [s.name for s in footer.schema if s.type])
for row in reader(file_obj, columns):
(yield OrderedDict(zip(keys, row)))
| [
"def",
"DictReader",
"(",
"file_obj",
",",
"columns",
"=",
"None",
")",
":",
"footer",
"=",
"_read_footer",
"(",
"file_obj",
")",
"keys",
"=",
"(",
"columns",
"if",
"columns",
"else",
"[",
"s",
".",
"name",
"for",
"s",
"in",
"footer",
".",
"schema",
... | reader for a parquet file object . | train | true |
26,834 | def _grid_in_property(field_name, docstring, read_only=False, closed_only=False):
def getter(self):
if (closed_only and (not self._closed)):
raise AttributeError(('can only get %r on a closed file' % field_name))
if (field_name == 'length'):
return self._file.get(field_name, 0)
return self._file.get(field_name, None)
def setter(self, value):
if self._closed:
self._coll.files.update_one({'_id': self._file['_id']}, {'$set': {field_name: value}})
self._file[field_name] = value
if read_only:
docstring += '\n\nThis attribute is read-only.'
elif closed_only:
docstring = ('%s\n\n%s' % (docstring, 'This attribute is read-only and can only be read after :meth:`close` has been called.'))
if ((not read_only) and (not closed_only)):
return property(getter, setter, doc=docstring)
return property(getter, doc=docstring)
| [
"def",
"_grid_in_property",
"(",
"field_name",
",",
"docstring",
",",
"read_only",
"=",
"False",
",",
"closed_only",
"=",
"False",
")",
":",
"def",
"getter",
"(",
"self",
")",
":",
"if",
"(",
"closed_only",
"and",
"(",
"not",
"self",
".",
"_closed",
")",... | create a gridin property . | train | true |
26,836 | def _get_revno(git_dir):
describe = _run_shell_command(('git --git-dir=%s describe --always' % git_dir))
if ('-' in describe):
return describe.rsplit('-', 2)[(-2)]
revlist = _run_shell_command(('git --git-dir=%s rev-list --abbrev-commit HEAD' % git_dir))
return len(revlist.splitlines())
| [
"def",
"_get_revno",
"(",
"git_dir",
")",
":",
"describe",
"=",
"_run_shell_command",
"(",
"(",
"'git --git-dir=%s describe --always'",
"%",
"git_dir",
")",
")",
"if",
"(",
"'-'",
"in",
"describe",
")",
":",
"return",
"describe",
".",
"rsplit",
"(",
"'-'",
"... | return the number of commits since the most recent tag . | train | false |
26,837 | def install_package(package, src, dst):
unpack_tarball(src, dst)
run_scripts((dst + package.name), scripts=['getscript', 'postinst'])
| [
"def",
"install_package",
"(",
"package",
",",
"src",
",",
"dst",
")",
":",
"unpack_tarball",
"(",
"src",
",",
"dst",
")",
"run_scripts",
"(",
"(",
"dst",
"+",
"package",
".",
"name",
")",
",",
"scripts",
"=",
"[",
"'getscript'",
",",
"'postinst'",
"]"... | install package if not already installed . | train | false |
26,839 | def slice_X(X, start=None, stop=None):
if isinstance(X, list):
if hasattr(start, '__len__'):
if hasattr(start, 'shape'):
start = start.tolist()
return [x[start] for x in X]
else:
return [x[start:stop] for x in X]
elif hasattr(start, '__len__'):
if hasattr(start, 'shape'):
start = start.tolist()
return X[start]
else:
return X[start:stop]
| [
"def",
"slice_X",
"(",
"X",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"list",
")",
":",
"if",
"hasattr",
"(",
"start",
",",
"'__len__'",
")",
":",
"if",
"hasattr",
"(",
"start",
",",
"'shape... | this takes an array-like . | train | false |
26,842 | def bartlett(M):
return bartlett_(M)
| [
"def",
"bartlett",
"(",
"M",
")",
":",
"return",
"bartlett_",
"(",
"M",
")"
] | return a bartlett window . | train | false |
26,843 | def result_check(expected, got, ulp_tol=5, abs_tol=0.0):
if (got == expected):
return None
failure = 'not equal'
if (isinstance(expected, float) and isinstance(got, int)):
got = float(got)
elif (isinstance(got, float) and isinstance(expected, int)):
expected = float(expected)
if (isinstance(expected, float) and isinstance(got, float)):
if (math.isnan(expected) and math.isnan(got)):
failure = None
elif (math.isinf(expected) or math.isinf(got)):
pass
else:
failure = ulp_abs_check(expected, got, ulp_tol, abs_tol)
if (failure is not None):
fail_fmt = 'expected {!r}, got {!r}'
fail_msg = fail_fmt.format(expected, got)
fail_msg += ' ({})'.format(failure)
return fail_msg
else:
return None
| [
"def",
"result_check",
"(",
"expected",
",",
"got",
",",
"ulp_tol",
"=",
"5",
",",
"abs_tol",
"=",
"0.0",
")",
":",
"if",
"(",
"got",
"==",
"expected",
")",
":",
"return",
"None",
"failure",
"=",
"'not equal'",
"if",
"(",
"isinstance",
"(",
"expected",... | compare arguments expected and got . | train | false |
26,844 | @depends(HAS_PYVMOMI)
def vmotion_enable(host, username, password, protocol=None, port=None, host_names=None, device='vmk0'):
service_instance = salt.utils.vmware.get_service_instance(host=host, username=username, password=password, protocol=protocol, port=port)
host_names = _check_hosts(service_instance, host, host_names)
ret = {}
for host_name in host_names:
host_ref = _get_host_ref(service_instance, host, host_name=host_name)
vmotion_system = host_ref.configManager.vmotionSystem
try:
vmotion_system.SelectVnic(device)
except vim.fault.HostConfigFault as err:
msg = 'vsphere.vmotion_disable failed: {0}'.format(err)
log.debug(msg)
ret.update({host_name: {'Error': msg, 'VMotion Enabled': False}})
continue
ret.update({host_name: {'VMotion Enabled': True}})
return ret
| [
"@",
"depends",
"(",
"HAS_PYVMOMI",
")",
"def",
"vmotion_enable",
"(",
"host",
",",
"username",
",",
"password",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"host_names",
"=",
"None",
",",
"device",
"=",
"'vmk0'",
")",
":",
"service_inst... | enable vmotion for a given host or list of host_names . | train | true |
26,845 | def Conv2d(net, n_filter=32, filter_size=(3, 3), strides=(1, 1), act=None, padding='SAME', W_init=tf.truncated_normal_initializer(stddev=0.02), b_init=tf.constant_initializer(value=0.0), W_init_args={}, b_init_args={}, name='conv2d'):
if (act is None):
act = tf.identity
net = Conv2dLayer(net, act=act, shape=[filter_size[0], filter_size[1], int(net.outputs.get_shape()[(-1)]), n_filter], strides=[1, strides[0], strides[1], 1], padding=padding, W_init=W_init, W_init_args=W_init_args, b_init=b_init, b_init_args=b_init_args, name=name)
return net
| [
"def",
"Conv2d",
"(",
"net",
",",
"n_filter",
"=",
"32",
",",
"filter_size",
"=",
"(",
"3",
",",
"3",
")",
",",
"strides",
"=",
"(",
"1",
",",
"1",
")",
",",
"act",
"=",
"None",
",",
"padding",
"=",
"'SAME'",
",",
"W_init",
"=",
"tf",
".",
"t... | wrapper for :class:conv2dlayer . | train | false |
26,848 | def _init_cachedir_tag():
cachedir_tag = os.path.join(cache(), 'CACHEDIR.TAG')
if (not os.path.exists(cachedir_tag)):
try:
with open(cachedir_tag, 'w', encoding='utf-8') as f:
f.write('Signature: 8a477f597d28d172789f06886806bc55\n')
f.write('# This file is a cache directory tag created by qutebrowser.\n')
f.write('# For information about cache directory tags, see:\n')
f.write('# http://www.brynosaurus.com/cachedir/\n')
except OSError:
log.init.exception('Failed to create CACHEDIR.TAG')
| [
"def",
"_init_cachedir_tag",
"(",
")",
":",
"cachedir_tag",
"=",
"os",
".",
"path",
".",
"join",
"(",
"cache",
"(",
")",
",",
"'CACHEDIR.TAG'",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"cachedir_tag",
")",
")",
":",
"try",
":",
... | create cachedir . | train | false |
26,849 | def pwnstallerGenerateRunwrc():
code = '#include "resource.h"\n'
code += '#define APSTUDIO_READONLY_SYMBOLS\n'
code += '#include "windows.h"\n'
code += '#undef APSTUDIO_READONLY_SYMBOLS\n'
code += '#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)\n'
code += '#ifdef _WIN32\n'
code += 'LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL\n'
code += '#pragma code_page(1252)\n'
code += '#endif\n'
iconPath = (settings.VEIL_EVASION_PATH + '/modules/common/source/icons/')
code += ('IDI_ICON1 ICON DISCARDABLE "./icons/%s"\n' % random.choice(os.listdir(iconPath)))
code += '#endif\n'
return code
| [
"def",
"pwnstallerGenerateRunwrc",
"(",
")",
":",
"code",
"=",
"'#include \"resource.h\"\\n'",
"code",
"+=",
"'#define APSTUDIO_READONLY_SYMBOLS\\n'",
"code",
"+=",
"'#include \"windows.h\"\\n'",
"code",
"+=",
"'#undef APSTUDIO_READONLY_SYMBOLS\\n'",
"code",
"+=",
"'#if !define... | generate pwnstallers runw . | train | false |
26,851 | def get_appsettings(config_uri, name=None, options=None, appconfig=appconfig):
(path, section) = _getpathsec(config_uri, name)
config_name = ('config:%s' % path)
here_dir = os.getcwd()
return appconfig(config_name, name=section, relative_to=here_dir, global_conf=options)
| [
"def",
"get_appsettings",
"(",
"config_uri",
",",
"name",
"=",
"None",
",",
"options",
"=",
"None",
",",
"appconfig",
"=",
"appconfig",
")",
":",
"(",
"path",
",",
"section",
")",
"=",
"_getpathsec",
"(",
"config_uri",
",",
"name",
")",
"config_name",
"=... | return a dictionary representing the key/value pairs in an app section within the file represented by config_uri . | train | false |
26,852 | def load_openerp_module(module_name):
global loaded
if (module_name in loaded):
return
initialize_sys_path()
try:
__import__(('odoo.addons.' + module_name))
info = load_information_from_description_file(module_name)
if info['post_load']:
getattr(sys.modules[('odoo.addons.' + module_name)], info['post_load'])()
except Exception as e:
msg = ("Couldn't load module %s" % module_name)
_logger.critical(msg)
_logger.critical(e)
raise
else:
loaded.append(module_name)
| [
"def",
"load_openerp_module",
"(",
"module_name",
")",
":",
"global",
"loaded",
"if",
"(",
"module_name",
"in",
"loaded",
")",
":",
"return",
"initialize_sys_path",
"(",
")",
"try",
":",
"__import__",
"(",
"(",
"'odoo.addons.'",
"+",
"module_name",
")",
")",
... | load an openerp module . | train | false |
26,853 | def resource_auth(resource):
resource_def = app.config['DOMAIN'][resource]
if callable(resource_def['authentication']):
resource_def['authentication'] = resource_def['authentication']()
return resource_def['authentication']
| [
"def",
"resource_auth",
"(",
"resource",
")",
":",
"resource_def",
"=",
"app",
".",
"config",
"[",
"'DOMAIN'",
"]",
"[",
"resource",
"]",
"if",
"callable",
"(",
"resource_def",
"[",
"'authentication'",
"]",
")",
":",
"resource_def",
"[",
"'authentication'",
... | ensure resource auth is an instance and its state is preserved between calls . | train | false |
26,854 | def find_pure_symbol_int_repr(symbols, unknown_clauses):
all_symbols = set().union(*unknown_clauses)
found_pos = all_symbols.intersection(symbols)
found_neg = all_symbols.intersection([(- s) for s in symbols])
for p in found_pos:
if ((- p) not in found_neg):
return (p, True)
for p in found_neg:
if ((- p) not in found_pos):
return ((- p), False)
return (None, None)
| [
"def",
"find_pure_symbol_int_repr",
"(",
"symbols",
",",
"unknown_clauses",
")",
":",
"all_symbols",
"=",
"set",
"(",
")",
".",
"union",
"(",
"*",
"unknown_clauses",
")",
"found_pos",
"=",
"all_symbols",
".",
"intersection",
"(",
"symbols",
")",
"found_neg",
"... | same as find_pure_symbol . | train | false |
26,855 | def stub_out_registry_server(stubs, **kwargs):
def fake_get_connection_type(client):
'\n Returns the proper connection type\n '
DEFAULT_REGISTRY_PORT = 9191
if ((client.port == DEFAULT_REGISTRY_PORT) and (client.host == '0.0.0.0')):
return FakeRegistryConnection
def fake_image_iter(self):
for i in self.response.app_iter:
(yield i)
stubs.Set(glance.common.client.BaseClient, 'get_connection_type', fake_get_connection_type)
| [
"def",
"stub_out_registry_server",
"(",
"stubs",
",",
"**",
"kwargs",
")",
":",
"def",
"fake_get_connection_type",
"(",
"client",
")",
":",
"DEFAULT_REGISTRY_PORT",
"=",
"9191",
"if",
"(",
"(",
"client",
".",
"port",
"==",
"DEFAULT_REGISTRY_PORT",
")",
"and",
... | mocks calls to 127 . | train | false |
26,856 | def cross(vec1, vec2):
if (not isinstance(vec1, (Vector, Dyadic))):
raise TypeError('Cross product is between two vectors')
return (vec1 ^ vec2)
| [
"def",
"cross",
"(",
"vec1",
",",
"vec2",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"vec1",
",",
"(",
"Vector",
",",
"Dyadic",
")",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Cross product is between two vectors'",
")",
"return",
"(",
"vec1",
"^",
... | from: URL . | train | false |
26,857 | def oo_flatten(data):
if (not isinstance(data, list)):
raise errors.AnsibleFilterError('|failed expects to flatten a List')
return [item for sublist in data for item in sublist]
| [
"def",
"oo_flatten",
"(",
"data",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"data",
",",
"list",
")",
")",
":",
"raise",
"errors",
".",
"AnsibleFilterError",
"(",
"'|failed expects to flatten a List'",
")",
"return",
"[",
"item",
"for",
"sublist",
"in",... | this filter plugin will flatten a list of lists . | train | false |
26,858 | def constraint(**conditions):
return IMPL.constraint(**conditions)
| [
"def",
"constraint",
"(",
"**",
"conditions",
")",
":",
"return",
"IMPL",
".",
"constraint",
"(",
"**",
"conditions",
")"
] | return a constraint object suitable for use with some updates . | train | false |
26,859 | def getModuleWithDirectoryPath(directoryPath, fileName):
if (fileName == ''):
print 'The file name in getModule in archive was empty.'
return None
originalSystemPath = sys.path[:]
try:
sys.path.insert(0, directoryPath)
folderPluginsModule = __import__(fileName)
sys.path = originalSystemPath
return folderPluginsModule
except:
sys.path = originalSystemPath
print ''
print 'Exception traceback in getModuleWithDirectoryPath in archive:'
traceback.print_exc(file=sys.stdout)
print ''
print ('That error means; could not import a module with the fileName ' + fileName)
print ('and an absolute directory name of ' + directoryPath)
print ''
return None
| [
"def",
"getModuleWithDirectoryPath",
"(",
"directoryPath",
",",
"fileName",
")",
":",
"if",
"(",
"fileName",
"==",
"''",
")",
":",
"print",
"'The file name in getModule in archive was empty.'",
"return",
"None",
"originalSystemPath",
"=",
"sys",
".",
"path",
"[",
":... | get the module from the filename and folder name . | train | false |
26,860 | def _create_figure(height_inches):
fig = matplotlib.figure.Figure(figsize=(_FIGURE_WIDTH_IN, (height_inches + _FIGURE_BOTTOM_PADDING_IN)), dpi=_FIGURE_DPI, facecolor='white')
fig.subplots_adjust(bottom=(float(_FIGURE_BOTTOM_PADDING_IN) / height_inches))
return (fig, (fig.get_figheight() * _FIGURE_DPI))
| [
"def",
"_create_figure",
"(",
"height_inches",
")",
":",
"fig",
"=",
"matplotlib",
".",
"figure",
".",
"Figure",
"(",
"figsize",
"=",
"(",
"_FIGURE_WIDTH_IN",
",",
"(",
"height_inches",
"+",
"_FIGURE_BOTTOM_PADDING_IN",
")",
")",
",",
"dpi",
"=",
"_FIGURE_DPI"... | creates an instance of matplotlib . | train | false |
26,861 | def test_urlencoded():
test_data = BytesIO('foo=baz&foo=bar&name=John+Doe')
assert (hug.input_format.urlencoded(test_data) == {'name': 'John Doe', 'foo': ['baz', 'bar']})
| [
"def",
"test_urlencoded",
"(",
")",
":",
"test_data",
"=",
"BytesIO",
"(",
"'foo=baz&foo=bar&name=John+Doe'",
")",
"assert",
"(",
"hug",
".",
"input_format",
".",
"urlencoded",
"(",
"test_data",
")",
"==",
"{",
"'name'",
":",
"'John Doe'",
",",
"'foo'",
":",
... | ensure that urlencoded input format works as intended . | train | false |
26,862 | def on_course_publish(course_key):
from openedx.core.djangoapps.credit import api, tasks
if api.is_credit_course(course_key):
tasks.update_credit_course_requirements.delay(unicode(course_key))
log.info(u'Added task to update credit requirements for course "%s" to the task queue', course_key)
| [
"def",
"on_course_publish",
"(",
"course_key",
")",
":",
"from",
"openedx",
".",
"core",
".",
"djangoapps",
".",
"credit",
"import",
"api",
",",
"tasks",
"if",
"api",
".",
"is_credit_course",
"(",
"course_key",
")",
":",
"tasks",
".",
"update_credit_course_req... | will receive a delegated course_published signal from cms/djangoapps/contentstore/signals . | train | false |
26,863 | def get_connection_helper(reactor, address, username, port):
try:
agentEndpoint = UNIXClientEndpoint(reactor, os.environ['SSH_AUTH_SOCK'])
except KeyError:
agentEndpoint = None
return _NewConnectionHelper(reactor, address, port, None, username, keys=None, password=None, agentEndpoint=agentEndpoint, knownHosts=KnownHostsFile.fromPath(FilePath('/dev/null')), ui=ConsoleUI((lambda : _ReadFile('yes'))))
| [
"def",
"get_connection_helper",
"(",
"reactor",
",",
"address",
",",
"username",
",",
"port",
")",
":",
"try",
":",
"agentEndpoint",
"=",
"UNIXClientEndpoint",
"(",
"reactor",
",",
"os",
".",
"environ",
"[",
"'SSH_AUTH_SOCK'",
"]",
")",
"except",
"KeyError",
... | get a :class:twisted . | train | false |
26,864 | def get_matching_activity_dicts(query_string, search_cursor):
collection_ids = []
if (not search_cursor):
(collection_ids, _) = collection_services.get_collection_ids_matching_query(query_string)
(exp_ids, new_search_cursor) = exp_services.get_exploration_ids_matching_query(query_string, cursor=search_cursor)
activity_list = []
activity_list = summary_services.get_displayable_collection_summary_dicts_matching_ids(collection_ids)
activity_list += summary_services.get_displayable_exp_summary_dicts_matching_ids(exp_ids)
if (len(activity_list) == feconf.DEFAULT_QUERY_LIMIT):
logging.error(('%s activities were fetched to load the library page. You may be running up against the default query limits.' % feconf.DEFAULT_QUERY_LIMIT))
return (activity_list, new_search_cursor)
| [
"def",
"get_matching_activity_dicts",
"(",
"query_string",
",",
"search_cursor",
")",
":",
"collection_ids",
"=",
"[",
"]",
"if",
"(",
"not",
"search_cursor",
")",
":",
"(",
"collection_ids",
",",
"_",
")",
"=",
"collection_services",
".",
"get_collection_ids_matc... | given a query string and a search cursor . | train | false |
26,865 | def escape_query(search_strings):
result = []
for search_string in search_strings:
result.append(search_string)
short_query = re.sub(u"'", u'', search_string)
if (search_string != short_query):
result.append(short_query)
very_short_query = re.sub(u"'[a-z]", u'', search_string)
if (short_query != very_short_query):
result.append(very_short_query)
return result
| [
"def",
"escape_query",
"(",
"search_strings",
")",
":",
"result",
"=",
"[",
"]",
"for",
"search_string",
"in",
"search_strings",
":",
"result",
".",
"append",
"(",
"search_string",
")",
"short_query",
"=",
"re",
".",
"sub",
"(",
"u\"'\"",
",",
"u''",
",",
... | escaping some expression greys -> greys + greys + grey . | train | false |
26,866 | def getSelectedPluginName(plugins):
for plugin in plugins:
if plugin.value:
return plugin.name
return ''
| [
"def",
"getSelectedPluginName",
"(",
"plugins",
")",
":",
"for",
"plugin",
"in",
"plugins",
":",
"if",
"plugin",
".",
"value",
":",
"return",
"plugin",
".",
"name",
"return",
"''"
] | get the selected plugin name . | train | false |
26,867 | def get_current_request():
return RequestCache.get_current_request()
| [
"def",
"get_current_request",
"(",
")",
":",
"return",
"RequestCache",
".",
"get_current_request",
"(",
")"
] | return current request instance . | train | false |
26,868 | def command_py2to3(args):
from lib2to3.main import main
args2 = []
if command_py2to3_work_around3k:
if args.no_diffs:
args2.append('--no-diffs')
if args.write:
args2.append('-w')
if args.nobackups:
args2.append('-n')
args2.extend(args.sources)
sys.exit(main('lib2to3.fixes', args=args2))
| [
"def",
"command_py2to3",
"(",
"args",
")",
":",
"from",
"lib2to3",
".",
"main",
"import",
"main",
"args2",
"=",
"[",
"]",
"if",
"command_py2to3_work_around3k",
":",
"if",
"args",
".",
"no_diffs",
":",
"args2",
".",
"append",
"(",
"'--no-diffs'",
")",
"if",... | apply 2to3 tool to python sources . | train | false |
26,869 | def api_snapshot_get(self, context, snp_id):
snapshot = {'id': fake.SNAPSHOT_ID, 'progress': '100%', 'volume_id': fake.VOLUME_ID, 'project_id': fake.PROJECT_ID, 'status': fields.SnapshotStatus.AVAILABLE}
if (snp_id == snapshot_id):
snapshot_objct = fake_snapshot.fake_snapshot_obj(context, **snapshot)
return snapshot_objct
else:
raise exception.SnapshotNotFound(snapshot_id=snp_id)
| [
"def",
"api_snapshot_get",
"(",
"self",
",",
"context",
",",
"snp_id",
")",
":",
"snapshot",
"=",
"{",
"'id'",
":",
"fake",
".",
"SNAPSHOT_ID",
",",
"'progress'",
":",
"'100%'",
",",
"'volume_id'",
":",
"fake",
".",
"VOLUME_ID",
",",
"'project_id'",
":",
... | replacement for cinder . | train | false |
26,870 | def GetLineWidth(line):
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if (unicodedata.east_asian_width(uc) in ('W', 'F')):
width += 2
elif (not unicodedata.combining(uc)):
width += 1
return width
else:
return len(line)
| [
"def",
"GetLineWidth",
"(",
"line",
")",
":",
"if",
"isinstance",
"(",
"line",
",",
"unicode",
")",
":",
"width",
"=",
"0",
"for",
"uc",
"in",
"unicodedata",
".",
"normalize",
"(",
"'NFC'",
",",
"line",
")",
":",
"if",
"(",
"unicodedata",
".",
"east_... | determines the width of the line in column positions . | train | true |
26,871 | def dotted_getattr(obj, name):
return reduce(getattr, name.split('.'), obj)
| [
"def",
"dotted_getattr",
"(",
"obj",
",",
"name",
")",
":",
"return",
"reduce",
"(",
"getattr",
",",
"name",
".",
"split",
"(",
"'.'",
")",
",",
"obj",
")"
] | getattr like function accepting a dotted name for attribute lookup . | train | false |
26,872 | def cleaner(env_path):
if os.path.exists(env_path):
shutil.rmtree(env_path)
| [
"def",
"cleaner",
"(",
"env_path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"env_path",
")",
":",
"shutil",
".",
"rmtree",
"(",
"env_path",
")"
] | checks that an environment path exists and . | train | false |
26,876 | def parse_nick_modes(mode_string):
return _parse_modes(mode_string, '')
| [
"def",
"parse_nick_modes",
"(",
"mode_string",
")",
":",
"return",
"_parse_modes",
"(",
"mode_string",
",",
"''",
")"
] | parse a nick mode string . | train | false |
26,880 | def rgb2luv(rgb):
return xyz2luv(rgb2xyz(rgb))
| [
"def",
"rgb2luv",
"(",
"rgb",
")",
":",
"return",
"xyz2luv",
"(",
"rgb2xyz",
"(",
"rgb",
")",
")"
] | rgb to cie-luv color space conversion . | train | false |
26,881 | def test_ros_init():
ratio = 'auto'
ros = RandomOverSampler(ratio=ratio, random_state=RND_SEED)
assert_equal(ros.random_state, RND_SEED)
| [
"def",
"test_ros_init",
"(",
")",
":",
"ratio",
"=",
"'auto'",
"ros",
"=",
"RandomOverSampler",
"(",
"ratio",
"=",
"ratio",
",",
"random_state",
"=",
"RND_SEED",
")",
"assert_equal",
"(",
"ros",
".",
"random_state",
",",
"RND_SEED",
")"
] | test the initialisation of the object . | train | false |
26,883 | def mutex():
mutex_num = [50, 50, 50, 500, 500, 500, 1000, 1000, 1000]
locks = [10000, 25000, 50000, 10000, 25000, 50000, 10000, 25000, 50000]
mutex_locks = []
mutex_locks.extend(locks)
mutex_loops = [2500, 5000, 10000, 10000, 2500, 5000, 5000, 10000, 2500]
test_command = 'sysbench --num-threads=250 --test=mutex '
test_command += '--mutex-num={0} --mutex-locks={1} --mutex-loops={2} run '
result = None
ret_val = {}
for (num, locks, loops) in zip(mutex_num, mutex_locks, mutex_loops):
key = 'Mutex: {0} Locks: {1} Loops: {2}'.format(num, locks, loops)
run_command = test_command.format(num, locks, loops)
result = __salt__['cmd.run'](run_command)
ret_val[key] = _parser(result)
return ret_val
| [
"def",
"mutex",
"(",
")",
":",
"mutex_num",
"=",
"[",
"50",
",",
"50",
",",
"50",
",",
"500",
",",
"500",
",",
"500",
",",
"1000",
",",
"1000",
",",
"1000",
"]",
"locks",
"=",
"[",
"10000",
",",
"25000",
",",
"50000",
",",
"10000",
",",
"2500... | tests the implementation of mutex cli examples: . | train | true |
26,885 | def B64HexEncode(s, padding=True):
encoded = base64.b64encode(s)
translated = encoded.translate(_std_to_b64hex)
if padding:
return translated
else:
return translated.rstrip('=')
| [
"def",
"B64HexEncode",
"(",
"s",
",",
"padding",
"=",
"True",
")",
":",
"encoded",
"=",
"base64",
".",
"b64encode",
"(",
"s",
")",
"translated",
"=",
"encoded",
".",
"translate",
"(",
"_std_to_b64hex",
")",
"if",
"padding",
":",
"return",
"translated",
"... | encode a string using base64 with extended hex alphabet . | train | false |
26,886 | def compile_isolated(func, args, return_type=None, flags=DEFAULT_FLAGS, locals={}):
from .targets.registry import cpu_target
typingctx = typing.Context()
targetctx = cpu.CPUContext(typingctx)
with cpu_target.nested_context(typingctx, targetctx):
return compile_extra(typingctx, targetctx, func, args, return_type, flags, locals)
| [
"def",
"compile_isolated",
"(",
"func",
",",
"args",
",",
"return_type",
"=",
"None",
",",
"flags",
"=",
"DEFAULT_FLAGS",
",",
"locals",
"=",
"{",
"}",
")",
":",
"from",
".",
"targets",
".",
"registry",
"import",
"cpu_target",
"typingctx",
"=",
"typing",
... | compile the function in an isolated environment . | train | false |
26,888 | def send_mail_template(subject, template, addr_from, addr_to, context=None, attachments=None, fail_silently=None, addr_bcc=None, headers=None):
if (context is None):
context = {}
if (attachments is None):
attachments = []
if (fail_silently is None):
fail_silently = settings.EMAIL_FAIL_SILENTLY
context.update(context_settings())
if (isinstance(addr_to, str) or isinstance(addr_to, bytes)):
addr_to = [addr_to]
if ((addr_bcc is not None) and (isinstance(addr_bcc, str) or isinstance(addr_bcc, bytes))):
addr_bcc = [addr_bcc]
render = (lambda type: loader.get_template((u'%s.%s' % (template, type))).render(Context(context)))
msg = EmailMultiAlternatives(subject, render(u'txt'), addr_from, addr_to, addr_bcc, headers=headers)
msg.attach_alternative(render(u'html'), u'text/html')
for attachment in attachments:
msg.attach(*attachment)
msg.send(fail_silently=fail_silently)
| [
"def",
"send_mail_template",
"(",
"subject",
",",
"template",
",",
"addr_from",
",",
"addr_to",
",",
"context",
"=",
"None",
",",
"attachments",
"=",
"None",
",",
"fail_silently",
"=",
"None",
",",
"addr_bcc",
"=",
"None",
",",
"headers",
"=",
"None",
")",... | send email rendering text and html versions for the specified template name using the context dictionary passed in . | train | true |
26,889 | def col_download_unread(cols_selected):
submissions = []
for sid in cols_selected:
id = Source.query.filter((Source.filesystem_id == sid)).one().id
submissions += Submission.query.filter((Submission.downloaded == False), (Submission.source_id == id)).all()
if (submissions == []):
flash('No unread submissions in collections selected!', 'error')
return redirect(url_for('index'))
return download('unread', submissions)
| [
"def",
"col_download_unread",
"(",
"cols_selected",
")",
":",
"submissions",
"=",
"[",
"]",
"for",
"sid",
"in",
"cols_selected",
":",
"id",
"=",
"Source",
".",
"query",
".",
"filter",
"(",
"(",
"Source",
".",
"filesystem_id",
"==",
"sid",
")",
")",
".",
... | download all unread submissions from all selected sources . | train | false |
26,890 | def eval_master_func(opts):
if ('__master_func_evaluated' not in opts):
mod_fun = opts['master']
(mod, fun) = mod_fun.split('.')
try:
master_mod = salt.loader.raw_mod(opts, mod, fun)
if (not master_mod):
raise KeyError
opts['master'] = master_mod[mod_fun]()
if ((not isinstance(opts['master'], str)) and (not isinstance(opts['master'], list))):
raise TypeError
opts['__master_func_evaluated'] = True
except KeyError:
log.error('Failed to load module {0}'.format(mod_fun))
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
except TypeError:
log.error('{0} returned from {1} is not a string or a list'.format(opts['master'], mod_fun))
sys.exit(salt.defaults.exitcodes.EX_GENERIC)
log.info('Evaluated master from module: {0}'.format(mod_fun))
| [
"def",
"eval_master_func",
"(",
"opts",
")",
":",
"if",
"(",
"'__master_func_evaluated'",
"not",
"in",
"opts",
")",
":",
"mod_fun",
"=",
"opts",
"[",
"'master'",
"]",
"(",
"mod",
",",
"fun",
")",
"=",
"mod_fun",
".",
"split",
"(",
"'.'",
")",
"try",
... | evaluate master function if master type is func and save it result in opts[master] . | train | true |
26,891 | def _servicegroup_get_server(sg_name, s_name, s_port=None, **connection_args):
ret = None
servers = _servicegroup_get_servers(sg_name, **connection_args)
if (servers is None):
return None
for server in servers:
if (server.get_servername() == s_name):
if ((s_port is not None) and (s_port != server.get_port())):
ret = None
ret = server
return ret
| [
"def",
"_servicegroup_get_server",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
"=",
"None",
",",
"**",
"connection_args",
")",
":",
"ret",
"=",
"None",
"servers",
"=",
"_servicegroup_get_servers",
"(",
"sg_name",
",",
"**",
"connection_args",
")",
"if",
"(",... | returns a member of a service group or none . | train | true |
26,892 | def global_conf_callback(preloaded_app_conf, global_conf):
replication_concurrency = int((preloaded_app_conf.get('replication_concurrency') or 4))
if replication_concurrency:
global_conf['replication_semaphore'] = [multiprocessing.BoundedSemaphore(replication_concurrency)]
| [
"def",
"global_conf_callback",
"(",
"preloaded_app_conf",
",",
"global_conf",
")",
":",
"replication_concurrency",
"=",
"int",
"(",
"(",
"preloaded_app_conf",
".",
"get",
"(",
"'replication_concurrency'",
")",
"or",
"4",
")",
")",
"if",
"replication_concurrency",
":... | callback for swift . | train | false |
26,893 | def remove_js_css(content):
r = re.compile('<script.*?</script>', ((re.I | re.M) | re.S))
s = r.sub('', content)
r = re.compile('<style.*?</style>', ((re.I | re.M) | re.S))
s = r.sub('', s)
r = re.compile('<!--.*?-->', ((re.I | re.M) | re.S))
s = r.sub('', s)
r = re.compile('<meta.*?>', ((re.I | re.M) | re.S))
s = r.sub('', s)
r = re.compile('<ins.*?</ins>', ((re.I | re.M) | re.S))
s = r.sub('', s)
return s
| [
"def",
"remove_js_css",
"(",
"content",
")",
":",
"r",
"=",
"re",
".",
"compile",
"(",
"'<script.*?</script>'",
",",
"(",
"(",
"re",
".",
"I",
"|",
"re",
".",
"M",
")",
"|",
"re",
".",
"S",
")",
")",
"s",
"=",
"r",
".",
"sub",
"(",
"''",
",",... | remove the the javascript and the stylesheet and the comment content . | train | false |
26,894 | def sort_method(node, settings=None):
attr = 'name'
if (settings and hasattr(settings, 'attr') and settings.attr):
attr = settings.attr
reverse = False
if (settings and hasattr(settings, 'reverse')):
reverse = settings.reverse
if (not isinstance(attr, list)):
attr = [attr]
filter_ = partial(filter_method, settings=settings)
excluder_ = partial(attributes_checker, attributes=attr)
resources = filter((lambda x: (excluder_(x) and filter_(x))), node.walk_resources())
return sorted(resources, key=attrgetter(*attr), reverse=reverse)
| [
"def",
"sort_method",
"(",
"node",
",",
"settings",
"=",
"None",
")",
":",
"attr",
"=",
"'name'",
"if",
"(",
"settings",
"and",
"hasattr",
"(",
"settings",
",",
"'attr'",
")",
"and",
"settings",
".",
"attr",
")",
":",
"attr",
"=",
"settings",
".",
"a... | sorts the resources in the given node based on the given settings . | train | false |
26,895 | def plan_server(action, parms, interval):
__SCHED.add_single_task(action, '', (interval * 60), kronos.method.sequential, parms, None)
| [
"def",
"plan_server",
"(",
"action",
",",
"parms",
",",
"interval",
")",
":",
"__SCHED",
".",
"add_single_task",
"(",
"action",
",",
"''",
",",
"(",
"interval",
"*",
"60",
")",
",",
"kronos",
".",
"method",
".",
"sequential",
",",
"parms",
",",
"None",... | plan to re-activate server after interval minutes . | train | false |
26,899 | def LCF_graph(n, shift_list, repeats, create_using=None):
if ((create_using is not None) and create_using.is_directed()):
raise NetworkXError('Directed Graph not supported')
if (n <= 0):
return empty_graph(0, create_using)
G = cycle_graph(n, create_using)
G.name = 'LCF_graph'
nodes = sorted(list(G))
n_extra_edges = (repeats * len(shift_list))
if (n_extra_edges < 1):
return G
for i in range(n_extra_edges):
shift = shift_list[(i % len(shift_list))]
v1 = nodes[(i % n)]
v2 = nodes[((i + shift) % n)]
G.add_edge(v1, v2)
return G
| [
"def",
"LCF_graph",
"(",
"n",
",",
"shift_list",
",",
"repeats",
",",
"create_using",
"=",
"None",
")",
":",
"if",
"(",
"(",
"create_using",
"is",
"not",
"None",
")",
"and",
"create_using",
".",
"is_directed",
"(",
")",
")",
":",
"raise",
"NetworkXError"... | return the cubic graph specified in lcf notation . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.