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 |
|---|---|---|---|---|---|
31,232 | def skip_step():
global CONFIRM_STEPS
if CONFIRM_STEPS:
choice = raw_input('--- Confirm step? (y/N) [y] ')
if (choice.lower() == 'n'):
return True
return False
| [
"def",
"skip_step",
"(",
")",
":",
"global",
"CONFIRM_STEPS",
"if",
"CONFIRM_STEPS",
":",
"choice",
"=",
"raw_input",
"(",
"'--- Confirm step? (y/N) [y] '",
")",
"if",
"(",
"choice",
".",
"lower",
"(",
")",
"==",
"'n'",
")",
":",
"return",
"True",
"return",
... | asks for users response whether to run a step . | train | false |
31,235 | def fsplit(pred, objs):
t = []
f = []
for obj in objs:
if pred(obj):
t.append(obj)
else:
f.append(obj)
return (t, f)
| [
"def",
"fsplit",
"(",
"pred",
",",
"objs",
")",
":",
"t",
"=",
"[",
"]",
"f",
"=",
"[",
"]",
"for",
"obj",
"in",
"objs",
":",
"if",
"pred",
"(",
"obj",
")",
":",
"t",
".",
"append",
"(",
"obj",
")",
"else",
":",
"f",
".",
"append",
"(",
"... | split a list into two classes according to the predicate . | train | true |
31,236 | def bytescale(data, cmin=None, cmax=None, high=255, low=0):
if (data.dtype == uint8):
return data
if (high > 255):
raise ValueError('`high` should be less than or equal to 255.')
if (low < 0):
raise ValueError('`low` should be greater than or equal to 0.')
if (high < low):
raise ValueError('`high` should be greater than or equal to `low`.')
if (cmin is None):
cmin = data.min()
if (cmax is None):
cmax = data.max()
cscale = (cmax - cmin)
if (cscale < 0):
raise ValueError('`cmax` should be larger than `cmin`.')
elif (cscale == 0):
cscale = 1
scale = (float((high - low)) / cscale)
bytedata = (((data - cmin) * scale) + low)
return (bytedata.clip(low, high) + 0.5).astype(uint8)
| [
"def",
"bytescale",
"(",
"data",
",",
"cmin",
"=",
"None",
",",
"cmax",
"=",
"None",
",",
"high",
"=",
"255",
",",
"low",
"=",
"0",
")",
":",
"if",
"(",
"data",
".",
"dtype",
"==",
"uint8",
")",
":",
"return",
"data",
"if",
"(",
"high",
">",
... | byte scales an array . | train | true |
31,237 | def new(rsa_key):
return PKCS115_SigScheme(rsa_key)
| [
"def",
"new",
"(",
"rsa_key",
")",
":",
"return",
"PKCS115_SigScheme",
"(",
"rsa_key",
")"
] | create a new salsa20 cipher . | train | false |
31,239 | def exit_with_parsing_error():
print 'Invalid argument(s).'
usage()
sys.exit(2)
| [
"def",
"exit_with_parsing_error",
"(",
")",
":",
"print",
"'Invalid argument(s).'",
"usage",
"(",
")",
"sys",
".",
"exit",
"(",
"2",
")"
] | report invalid arguments and usage . | train | false |
31,241 | def precise_format_timedelta(delta, locale, threshold=0.85, decimals=2):
seconds = delta.total_seconds()
for (unit, secs_per_unit) in TIMEDELTA_UNITS:
value = (abs(seconds) / secs_per_unit)
if (value >= threshold):
plural_form = locale.plural_form(value)
pattern = None
for choice in ((unit + ':medium'), unit):
patterns = locale._data['unit_patterns'].get(choice)
if (patterns is not None):
pattern = patterns[plural_form]
break
if (pattern is None):
return u''
decimals = int(decimals)
format_string = (('%.' + str(decimals)) + 'f')
return pattern.replace('{0}', (format_string % value))
return u''
| [
"def",
"precise_format_timedelta",
"(",
"delta",
",",
"locale",
",",
"threshold",
"=",
"0.85",
",",
"decimals",
"=",
"2",
")",
":",
"seconds",
"=",
"delta",
".",
"total_seconds",
"(",
")",
"for",
"(",
"unit",
",",
"secs_per_unit",
")",
"in",
"TIMEDELTA_UNI... | like babel . | train | false |
31,242 | def get_ofs():
storage_backend = config['ofs.impl']
kw = {}
for (k, v) in config.items():
if ((not k.startswith('ofs.')) or (k == 'ofs.impl')):
continue
kw[k[4:]] = v
if ((storage_backend == 'pairtree') and ('storage_dir' in kw)):
create_pairtree_marker(kw['storage_dir'])
ofs = get_impl(storage_backend)(**kw)
return ofs
| [
"def",
"get_ofs",
"(",
")",
":",
"storage_backend",
"=",
"config",
"[",
"'ofs.impl'",
"]",
"kw",
"=",
"{",
"}",
"for",
"(",
"k",
",",
"v",
")",
"in",
"config",
".",
"items",
"(",
")",
":",
"if",
"(",
"(",
"not",
"k",
".",
"startswith",
"(",
"'o... | return a configured instance of the appropriate ofs driver . | train | false |
31,243 | def filter_kwargs(f, kwargs):
return keyfilter(op.contains(keywords(f)), kwargs)
| [
"def",
"filter_kwargs",
"(",
"f",
",",
"kwargs",
")",
":",
"return",
"keyfilter",
"(",
"op",
".",
"contains",
"(",
"keywords",
"(",
"f",
")",
")",
",",
"kwargs",
")"
] | return a dict of valid kwargs for f from a subset of kwargs examples . | train | false |
31,244 | @cli.command('display')
@processor
def display_cmd(images):
for image in images:
click.echo(('Displaying "%s"' % image.filename))
image.show()
(yield image)
| [
"@",
"cli",
".",
"command",
"(",
"'display'",
")",
"@",
"processor",
"def",
"display_cmd",
"(",
"images",
")",
":",
"for",
"image",
"in",
"images",
":",
"click",
".",
"echo",
"(",
"(",
"'Displaying \"%s\"'",
"%",
"image",
".",
"filename",
")",
")",
"im... | opens all images in an image viewer . | train | false |
31,245 | def _to_hass_color(color):
return list([int(c) for c in color])
| [
"def",
"_to_hass_color",
"(",
"color",
")",
":",
"return",
"list",
"(",
"[",
"int",
"(",
"c",
")",
"for",
"c",
"in",
"color",
"]",
")"
] | convert from color tuple to home assistant rgb list . | train | false |
31,246 | def _process_glsl_template(template, colors):
for i in range((len(colors) - 1), (-1), (-1)):
color = colors[i]
assert (len(color) == 4)
vec4_color = ('vec4(%.3f, %.3f, %.3f, %.3f)' % tuple(color))
template = template.replace(('$color_%d' % i), vec4_color)
return template
| [
"def",
"_process_glsl_template",
"(",
"template",
",",
"colors",
")",
":",
"for",
"i",
"in",
"range",
"(",
"(",
"len",
"(",
"colors",
")",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
",",
"(",
"-",
"1",
")",
")",
":",
"color",
"=",
"colors",
"[",
... | replace $color_i by color #i in the glsl template . | train | true |
31,247 | def _get_proxy_connection_details():
proxytype = get_proxy_type()
if (proxytype == 'esxi'):
details = __salt__['esxi.get_details']()
else:
raise CommandExecutionError("'{0}' proxy is not supported".format(proxytype))
return ((details.get('vcenter') if ('vcenter' in details) else details.get('host')), details.get('username'), details.get('password'), details.get('protocol'), details.get('port'), details.get('mechanism'), details.get('principal'), details.get('domain'))
| [
"def",
"_get_proxy_connection_details",
"(",
")",
":",
"proxytype",
"=",
"get_proxy_type",
"(",
")",
"if",
"(",
"proxytype",
"==",
"'esxi'",
")",
":",
"details",
"=",
"__salt__",
"[",
"'esxi.get_details'",
"]",
"(",
")",
"else",
":",
"raise",
"CommandExecution... | returns the connection details of the following proxies: esxi . | train | true |
31,248 | def amount_to_text(nbr, lang='fr', currency='euro'):
if (not _translate_funcs.has_key(lang)):
print ("WARNING: no translation function found for lang: '%s'" % (lang,))
lang = 'fr'
return _translate_funcs[lang](abs(nbr), currency)
| [
"def",
"amount_to_text",
"(",
"nbr",
",",
"lang",
"=",
"'fr'",
",",
"currency",
"=",
"'euro'",
")",
":",
"if",
"(",
"not",
"_translate_funcs",
".",
"has_key",
"(",
"lang",
")",
")",
":",
"print",
"(",
"\"WARNING: no translation function found for lang: '%s'\"",
... | converts an integer to its textual representation . | train | false |
31,249 | def discover_configs():
try:
config = os.environ['SENTRY_CONF']
except KeyError:
config = '~/.sentry'
config = os.path.expanduser(config)
if (config.endswith(('.py', '.conf')) or os.path.isfile(config)):
return (os.path.dirname(config), config, None)
return (config, os.path.join(config, DEFAULT_SETTINGS_OVERRIDE), os.path.join(config, DEFAULT_SETTINGS_CONF))
| [
"def",
"discover_configs",
"(",
")",
":",
"try",
":",
"config",
"=",
"os",
".",
"environ",
"[",
"'SENTRY_CONF'",
"]",
"except",
"KeyError",
":",
"config",
"=",
"'~/.sentry'",
"config",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"config",
")",
"if",
... | discover the locations of three configuration components: * config directory * optional python config file * optional yaml config . | train | false |
31,251 | def draw_shell(G, **kwargs):
nlist = kwargs.get('nlist', None)
if (nlist is not None):
del kwargs['nlist']
draw(G, shell_layout(G, nlist=nlist), **kwargs)
| [
"def",
"draw_shell",
"(",
"G",
",",
"**",
"kwargs",
")",
":",
"nlist",
"=",
"kwargs",
".",
"get",
"(",
"'nlist'",
",",
"None",
")",
"if",
"(",
"nlist",
"is",
"not",
"None",
")",
":",
"del",
"kwargs",
"[",
"'nlist'",
"]",
"draw",
"(",
"G",
",",
... | draw networkx graph with shell layout . | train | false |
31,252 | def _aggr_last(inList):
for elem in reversed(inList):
if (elem != SENTINEL_VALUE_FOR_MISSING_DATA):
return elem
return None
| [
"def",
"_aggr_last",
"(",
"inList",
")",
":",
"for",
"elem",
"in",
"reversed",
"(",
"inList",
")",
":",
"if",
"(",
"elem",
"!=",
"SENTINEL_VALUE_FOR_MISSING_DATA",
")",
":",
"return",
"elem",
"return",
"None"
] | returns last non-none element in the list . | train | false |
31,253 | def build_encoder_w2v(tparams, options):
opt_ret = dict()
trng = RandomStreams(1234)
embedding = tensor.tensor3('embedding', dtype='float32')
x_mask = tensor.matrix('x_mask', dtype='float32')
proj = get_layer(options['encoder'])[1](tparams, embedding, None, options, prefix='encoder', mask=x_mask)
ctx = proj[0][(-1)]
return (trng, embedding, x_mask, ctx)
| [
"def",
"build_encoder_w2v",
"(",
"tparams",
",",
"options",
")",
":",
"opt_ret",
"=",
"dict",
"(",
")",
"trng",
"=",
"RandomStreams",
"(",
"1234",
")",
"embedding",
"=",
"tensor",
".",
"tensor3",
"(",
"'embedding'",
",",
"dtype",
"=",
"'float32'",
")",
"... | computation graph for encoder . | train | false |
31,254 | def test_ast_bad_assert():
cant_compile(u'(assert)')
cant_compile(u'(assert 1 2 3)')
cant_compile(u'(assert 1 [1 2] 3)')
| [
"def",
"test_ast_bad_assert",
"(",
")",
":",
"cant_compile",
"(",
"u'(assert)'",
")",
"cant_compile",
"(",
"u'(assert 1 2 3)'",
")",
"cant_compile",
"(",
"u'(assert 1 [1 2] 3)'",
")"
] | make sure ast cant compile invalid assert . | train | false |
31,255 | def educateDashesOldSchool(str):
str = re.sub('---', '—', str)
str = re.sub('--', '–', str)
return str
| [
"def",
"educateDashesOldSchool",
"(",
"str",
")",
":",
"str",
"=",
"re",
".",
"sub",
"(",
"'---'",
",",
"'—'",
",",
"str",
")",
"str",
"=",
"re",
".",
"sub",
"(",
"'--'",
",",
"'–'",
",",
"str",
")",
"return",
"str"
] | parameter: string . | train | false |
31,256 | def _api_model_patch_replace(conn, restApiId, modelName, path, value):
response = conn.update_model(restApiId=restApiId, modelName=modelName, patchOperations=[{'op': 'replace', 'path': path, 'value': value}])
return response
| [
"def",
"_api_model_patch_replace",
"(",
"conn",
",",
"restApiId",
",",
"modelName",
",",
"path",
",",
"value",
")",
":",
"response",
"=",
"conn",
".",
"update_model",
"(",
"restApiId",
"=",
"restApiId",
",",
"modelName",
"=",
"modelName",
",",
"patchOperations... | the replace patch operation on a model resource . | train | true |
31,259 | @register_uncanonicalize
@gof.local_optimizer([T.MaxAndArgmax])
def local_max_and_argmax(node):
if isinstance(node.op, T.MaxAndArgmax):
axis = node.op.get_params(node)
if (len(node.outputs[1].clients) == 0):
new = CAReduce(scal.maximum, axis)(node.inputs[0])
return [new, None]
if (len(node.outputs[0].clients) == 0):
return [None, T._argmax(node.inputs[0], axis)]
| [
"@",
"register_uncanonicalize",
"@",
"gof",
".",
"local_optimizer",
"(",
"[",
"T",
".",
"MaxAndArgmax",
"]",
")",
"def",
"local_max_and_argmax",
"(",
"node",
")",
":",
"if",
"isinstance",
"(",
"node",
".",
"op",
",",
"T",
".",
"MaxAndArgmax",
")",
":",
"... | if we dont use the argmax . | train | false |
31,260 | def getHeaders(document):
return domhelpers.findElements(document, (lambda n, m=re.compile('h[23]$').match: m(n.nodeName)))
| [
"def",
"getHeaders",
"(",
"document",
")",
":",
"return",
"domhelpers",
".",
"findElements",
"(",
"document",
",",
"(",
"lambda",
"n",
",",
"m",
"=",
"re",
".",
"compile",
"(",
"'h[23]$'",
")",
".",
"match",
":",
"m",
"(",
"n",
".",
"nodeName",
")",
... | return all h2 and h3 nodes in the given document . | train | false |
31,261 | def print_log(text, *colors):
sys.stderr.write((sprint('{}: {}'.format(script_name, text), *colors) + '\n'))
| [
"def",
"print_log",
"(",
"text",
",",
"*",
"colors",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"(",
"sprint",
"(",
"'{}: {}'",
".",
"format",
"(",
"script_name",
",",
"text",
")",
",",
"*",
"colors",
")",
"+",
"'\\n'",
")",
")"
] | print a log message to standard error . | train | true |
31,262 | def fix_makefile(makefile):
if (not os.path.isfile(makefile)):
return
fin = open(makefile)
if 1:
lines = fin.readlines()
fin.close()
fout = open(makefile, 'w')
if 1:
for line in lines:
if line.startswith('PERL='):
continue
if line.startswith('CP='):
line = 'CP=copy\n'
if line.startswith('MKDIR='):
line = 'MKDIR=mkdir\n'
if line.startswith('CFLAG='):
line = line.strip()
for algo in ('RC5', 'MDC2', 'IDEA'):
noalgo = (' -DOPENSSL_NO_%s' % algo)
if (noalgo not in line):
line = (line + noalgo)
line = (line + '\n')
fout.write(line)
fout.close()
| [
"def",
"fix_makefile",
"(",
"makefile",
")",
":",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"makefile",
")",
")",
":",
"return",
"fin",
"=",
"open",
"(",
"makefile",
")",
"if",
"1",
":",
"lines",
"=",
"fin",
".",
"readlines",
"(",
... | fix some stuff in all makefiles . | train | false |
31,263 | def get_tagname(element):
try:
tagname = element.tag.split('}')[1]
except IndexError:
tagname = element.tag
return tagname
| [
"def",
"get_tagname",
"(",
"element",
")",
":",
"try",
":",
"tagname",
"=",
"element",
".",
"tag",
".",
"split",
"(",
"'}'",
")",
"[",
"1",
"]",
"except",
"IndexError",
":",
"tagname",
"=",
"element",
".",
"tag",
"return",
"tagname"
] | get tagname without namespace . | train | false |
31,264 | def Tm_Wallace(seq, check=True, strict=True):
seq = str(seq)
if check:
seq = _check(seq, 'Tm_Wallace')
melting_temp = ((2 * sum(map(seq.count, ('A', 'T', 'W')))) + (4 * sum(map(seq.count, ('C', 'G', 'S')))))
tmp = (((3 * sum(map(seq.count, ('K', 'M', 'N', 'R', 'Y')))) + ((10 / 3.0) * sum(map(seq.count, ('B', 'V'))))) + ((8 / 3.0) * sum(map(seq.count, ('D', 'H')))))
if (strict and tmp):
raise ValueError(('ambiguous bases B, D, H, K, M, N, R, V, Y not ' + 'allowed when strict=True'))
else:
melting_temp += tmp
return melting_temp
| [
"def",
"Tm_Wallace",
"(",
"seq",
",",
"check",
"=",
"True",
",",
"strict",
"=",
"True",
")",
":",
"seq",
"=",
"str",
"(",
"seq",
")",
"if",
"check",
":",
"seq",
"=",
"_check",
"(",
"seq",
",",
"'Tm_Wallace'",
")",
"melting_temp",
"=",
"(",
"(",
"... | calculate and return the tm using the wallace rule . | train | false |
31,265 | def build_queries_from(f, regex, cap_types, cap_pr, encoding=u'ascii'):
queries = []
for line in f:
matches = regex.match(line)
if matches:
query = reorder_to(list(zip(matches.groups(), cap_types)), cap_pr)
queries.append(query)
return queries
| [
"def",
"build_queries_from",
"(",
"f",
",",
"regex",
",",
"cap_types",
",",
"cap_pr",
",",
"encoding",
"=",
"u'ascii'",
")",
":",
"queries",
"=",
"[",
"]",
"for",
"line",
"in",
"f",
":",
"matches",
"=",
"regex",
".",
"match",
"(",
"line",
")",
"if",
... | returns a list of queries from the given file . | train | false |
31,266 | @contextlib.contextmanager
def TempChangeField(obj, field_name, new_value):
old_value = getattr(obj, field_name)
setattr(obj, field_name, new_value)
(yield old_value)
setattr(obj, field_name, old_value)
| [
"@",
"contextlib",
".",
"contextmanager",
"def",
"TempChangeField",
"(",
"obj",
",",
"field_name",
",",
"new_value",
")",
":",
"old_value",
"=",
"getattr",
"(",
"obj",
",",
"field_name",
")",
"setattr",
"(",
"obj",
",",
"field_name",
",",
"new_value",
")",
... | context manager to change a field value on an object temporarily . | train | false |
31,268 | @lru_cache()
def get_storage(storage_class=None, **kwargs):
return get_storage_class(storage_class)(**kwargs)
| [
"@",
"lru_cache",
"(",
")",
"def",
"get_storage",
"(",
"storage_class",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"return",
"get_storage_class",
"(",
"storage_class",
")",
"(",
"**",
"kwargs",
")"
] | imports the message storage class described by import_path . | train | false |
31,269 | def add_course_author(user, course):
global_admin = AdminFactory()
for role in (CourseStaffRole, CourseInstructorRole):
auth.add_users(global_admin, role(course.id), user)
| [
"def",
"add_course_author",
"(",
"user",
",",
"course",
")",
":",
"global_admin",
"=",
"AdminFactory",
"(",
")",
"for",
"role",
"in",
"(",
"CourseStaffRole",
",",
"CourseInstructorRole",
")",
":",
"auth",
".",
"add_users",
"(",
"global_admin",
",",
"role",
"... | add the user to the instructor group of the course so they will have the permissions to see it in studio . | train | false |
31,271 | def lowdata_fmt():
if (cherrypy.request.method.upper() != 'POST'):
return
data = cherrypy.request.unserialized_data
if (data and isinstance(data, collections.Mapping)):
if (('arg' in data) and (not isinstance(data['arg'], list))):
data['arg'] = [data['arg']]
cherrypy.request.lowstate = [data]
else:
cherrypy.serving.request.lowstate = data
| [
"def",
"lowdata_fmt",
"(",
")",
":",
"if",
"(",
"cherrypy",
".",
"request",
".",
"method",
".",
"upper",
"(",
")",
"!=",
"'POST'",
")",
":",
"return",
"data",
"=",
"cherrypy",
".",
"request",
".",
"unserialized_data",
"if",
"(",
"data",
"and",
"isinsta... | validate and format lowdata from incoming unserialized request data this tool requires that the hypermedia_in tool has already been run . | train | true |
31,272 | @task
def virtualenv_activate(requirements_revision=None):
assert (not is_old_env()), 'Active environment is old-style (directory, not symlink). Manual intervention required!'
req_rev = (requirements_revision or latest_requirements_revision())
assert virtualenv_verify(req_rev), ('Desired env revision %s invalid, cannot be made active' % req_rev)
env_dir = ('env.%s' % req_rev)
run(('echo "import sys; sys.setdefaultencoding(\'utf-8\')" > %s/viewfinder/lib/python2.7/sitecustomize.py' % env_dir))
run(('ln -T -s -f ~/env.%s ~/env' % req_rev))
fprint(('Environment at rev %s marked active.' % req_rev))
| [
"@",
"task",
"def",
"virtualenv_activate",
"(",
"requirements_revision",
"=",
"None",
")",
":",
"assert",
"(",
"not",
"is_old_env",
"(",
")",
")",
",",
"'Active environment is old-style (directory, not symlink). Manual intervention required!'",
"req_rev",
"=",
"(",
"requi... | make the virtual env at revision active . | train | false |
31,274 | def slices_from_chunks(chunks):
cumdims = [list(accumulate(add, ((0,) + bds[:(-1)]))) for bds in chunks]
shapes = product(*chunks)
starts = product(*cumdims)
return [tuple((slice(s, (s + dim)) for (s, dim) in zip(start, shape))) for (start, shape) in zip(starts, shapes)]
| [
"def",
"slices_from_chunks",
"(",
"chunks",
")",
":",
"cumdims",
"=",
"[",
"list",
"(",
"accumulate",
"(",
"add",
",",
"(",
"(",
"0",
",",
")",
"+",
"bds",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
")",
")",
"for",
"bds",
"in",
"chunks",
"]",
"... | translate chunks tuple to a set of slices in product order . | train | false |
31,275 | def tensor_dim(tensor, dim):
result = tensor.get_shape().as_list()[dim]
if (result is None):
result = tf.shape(tensor)[dim]
return result
| [
"def",
"tensor_dim",
"(",
"tensor",
",",
"dim",
")",
":",
"result",
"=",
"tensor",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"dim",
"]",
"if",
"(",
"result",
"is",
"None",
")",
":",
"result",
"=",
"tf",
".",
"shape",
"(",
"tensor... | returns int dimension if known at a graph build time else a tensor . | train | false |
31,277 | @main.command()
def bundles():
for bundle in sorted(bundles_module.bundles.keys()):
if bundle.startswith('.'):
continue
try:
ingestions = list(map(text_type, bundles_module.ingestions_for_bundle(bundle)))
except OSError as e:
if (e.errno != errno.ENOENT):
raise
ingestions = []
for timestamp in (ingestions or ['<no ingestions>']):
click.echo(('%s %s' % (bundle, timestamp)))
| [
"@",
"main",
".",
"command",
"(",
")",
"def",
"bundles",
"(",
")",
":",
"for",
"bundle",
"in",
"sorted",
"(",
"bundles_module",
".",
"bundles",
".",
"keys",
"(",
")",
")",
":",
"if",
"bundle",
".",
"startswith",
"(",
"'.'",
")",
":",
"continue",
"t... | list all of the available data bundles . | train | true |
31,278 | def select_option_by_text(select_browser_query, option_text):
def select_option(query, value):
' Get the first select element that matches the query and select the desired value. '
try:
select = Select(query.first.results[0])
select.select_by_visible_text(value)
return True
except StaleElementReferenceException:
return False
msg = 'Selected option {}'.format(option_text)
EmptyPromise((lambda : select_option(select_browser_query, option_text)), msg).fulfill()
| [
"def",
"select_option_by_text",
"(",
"select_browser_query",
",",
"option_text",
")",
":",
"def",
"select_option",
"(",
"query",
",",
"value",
")",
":",
"try",
":",
"select",
"=",
"Select",
"(",
"query",
".",
"first",
".",
"results",
"[",
"0",
"]",
")",
... | chooses an option within a select by text . | train | false |
31,279 | @snippet
def dataset_create(client, to_delete):
DATASET_NAME = ('dataset_create_%d' % (_millis(),))
dataset = client.dataset(DATASET_NAME)
dataset.create()
to_delete.append(dataset)
| [
"@",
"snippet",
"def",
"dataset_create",
"(",
"client",
",",
"to_delete",
")",
":",
"DATASET_NAME",
"=",
"(",
"'dataset_create_%d'",
"%",
"(",
"_millis",
"(",
")",
",",
")",
")",
"dataset",
"=",
"client",
".",
"dataset",
"(",
"DATASET_NAME",
")",
"dataset"... | create a dataset . | train | false |
31,280 | def gis_download_kml(record_id, filename, session_id_name, session_id, user_id=None):
if user_id:
auth.s3_impersonate(user_id)
result = gis.download_kml(record_id, filename, session_id_name, session_id)
db.commit()
return result
| [
"def",
"gis_download_kml",
"(",
"record_id",
",",
"filename",
",",
"session_id_name",
",",
"session_id",
",",
"user_id",
"=",
"None",
")",
":",
"if",
"user_id",
":",
"auth",
".",
"s3_impersonate",
"(",
"user_id",
")",
"result",
"=",
"gis",
".",
"download_kml... | download a kml file - will normally be done asynchronously if there is a worker alive . | train | false |
31,283 | @treeio_login_required
@handle_response_format
def field_edit(request, field_id, response_format='html'):
field = get_object_or_404(ItemField, pk=field_id)
if (not request.user.profile.has_permission(field, mode='w')):
return user_denied(request, message="You don't have access to this Field Type", response_format=response_format)
if request.POST:
if ('cancel' not in request.POST):
form = ItemFieldForm(request.POST, instance=field)
if form.is_valid():
item = form.save(request)
return HttpResponseRedirect(reverse('infrastructure_field_view', args=[item.id]))
else:
return HttpResponseRedirect(reverse('infrastructure_field_view', args=[item.id]))
else:
form = ItemFieldForm(instance=field)
context = _get_default_context(request)
context.update({'form': form, 'field': field})
return render_to_response('infrastructure/field_edit', context, context_instance=RequestContext(request), response_format=response_format)
| [
"@",
"treeio_login_required",
"@",
"handle_response_format",
"def",
"field_edit",
"(",
"request",
",",
"field_id",
",",
"response_format",
"=",
"'html'",
")",
":",
"field",
"=",
"get_object_or_404",
"(",
"ItemField",
",",
"pk",
"=",
"field_id",
")",
"if",
"(",
... | itemfield edit . | train | false |
31,284 | def _get_request_header(request, header_name, default=''):
if ((request is not None) and hasattr(request, 'META') and (header_name in request.META)):
return request.META[header_name]
else:
return default
| [
"def",
"_get_request_header",
"(",
"request",
",",
"header_name",
",",
"default",
"=",
"''",
")",
":",
"if",
"(",
"(",
"request",
"is",
"not",
"None",
")",
"and",
"hasattr",
"(",
"request",
",",
"'META'",
")",
"and",
"(",
"header_name",
"in",
"request",
... | helper method to get header values from a requests meta dict . | train | false |
31,285 | def restrict_to_dtype(dtype, message_template):
def processor(term_method, _, term_instance):
term_dtype = term_instance.dtype
if (term_dtype != dtype):
raise TypeError(message_template.format(method_name=term_method.__name__, expected_dtype=dtype.name, received_dtype=term_dtype))
return term_instance
return preprocess(self=processor)
| [
"def",
"restrict_to_dtype",
"(",
"dtype",
",",
"message_template",
")",
":",
"def",
"processor",
"(",
"term_method",
",",
"_",
",",
"term_instance",
")",
":",
"term_dtype",
"=",
"term_instance",
".",
"dtype",
"if",
"(",
"term_dtype",
"!=",
"dtype",
")",
":",... | a factory for decorators that restrict term methods to only be callable on terms with a specific dtype . | train | true |
31,286 | def organization_member_delete(context, data_dict=None):
_check_access('organization_member_delete', context, data_dict)
return _group_or_org_member_delete(context, data_dict)
| [
"def",
"organization_member_delete",
"(",
"context",
",",
"data_dict",
"=",
"None",
")",
":",
"_check_access",
"(",
"'organization_member_delete'",
",",
"context",
",",
"data_dict",
")",
"return",
"_group_or_org_member_delete",
"(",
"context",
",",
"data_dict",
")"
] | remove a user from an organization . | train | false |
31,287 | def in_interactive_session():
def check_main():
import __main__ as main
return ((not hasattr(main, '__file__')) or get_option('mode.sim_interactive'))
try:
return (__IPYTHON__ or check_main())
except:
return check_main()
| [
"def",
"in_interactive_session",
"(",
")",
":",
"def",
"check_main",
"(",
")",
":",
"import",
"__main__",
"as",
"main",
"return",
"(",
"(",
"not",
"hasattr",
"(",
"main",
",",
"'__file__'",
")",
")",
"or",
"get_option",
"(",
"'mode.sim_interactive'",
")",
... | check if were running in an interactive shell returns true if running under python/ipython interactive shell . | train | false |
31,288 | def disable_urllib3_warning():
try:
import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()
except Exception:
pass
| [
"def",
"disable_urllib3_warning",
"(",
")",
":",
"try",
":",
"import",
"requests",
".",
"packages",
".",
"urllib3",
"requests",
".",
"packages",
".",
"urllib3",
".",
"disable_warnings",
"(",
")",
"except",
"Exception",
":",
"pass"
] | URL#insecurerequestwarning insecureplatformwarning 警告的临时解决方案 . | train | false |
31,289 | def _sconnect(host=None, port=None, password=None):
if (host is None):
host = __salt__['config.option']('redis_sentinel.host', 'localhost')
if (port is None):
port = __salt__['config.option']('redis_sentinel.port', 26379)
if (password is None):
password = __salt__['config.option']('redis_sentinel.password')
return redis.StrictRedis(host, port, password=password)
| [
"def",
"_sconnect",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"(",
"host",
"is",
"None",
")",
":",
"host",
"=",
"__salt__",
"[",
"'config.option'",
"]",
"(",
"'redis_sentinel.host'",
",",
"'localh... | returns an instance of the redis client . | train | false |
31,290 | def parse_break_str(txt):
txt = txt.strip()
if (len(txt.split()) == 2):
(n, units) = txt.split()
else:
(n, units) = (1, txt)
units = units.rstrip(u's')
n = int(n)
return (n, units)
| [
"def",
"parse_break_str",
"(",
"txt",
")",
":",
"txt",
"=",
"txt",
".",
"strip",
"(",
")",
"if",
"(",
"len",
"(",
"txt",
".",
"split",
"(",
")",
")",
"==",
"2",
")",
":",
"(",
"n",
",",
"units",
")",
"=",
"txt",
".",
"split",
"(",
")",
"els... | parses 10 weeks into tuple . | train | false |
31,291 | def _find_lang(langdict, lang, script, region):
full_locale = _full_locale(lang, script, region)
if ((full_locale in _LOCALE_NORMALIZATION_MAP) and (_LOCALE_NORMALIZATION_MAP[full_locale] in langdict)):
return langdict[_LOCALE_NORMALIZATION_MAP[full_locale]]
if (full_locale in langdict):
return langdict[full_locale]
if (script is not None):
lang_script = ('%s_%s' % (lang, script))
if (lang_script in langdict):
return langdict[lang_script]
if (region is not None):
lang_region = ('%s_%s' % (lang, region))
if (lang_region in langdict):
return langdict[lang_region]
if (lang in langdict):
return langdict[lang]
if _may_fall_back_to_english(lang):
return langdict.get('en', None)
else:
return None
| [
"def",
"_find_lang",
"(",
"langdict",
",",
"lang",
",",
"script",
",",
"region",
")",
":",
"full_locale",
"=",
"_full_locale",
"(",
"lang",
",",
"script",
",",
"region",
")",
"if",
"(",
"(",
"full_locale",
"in",
"_LOCALE_NORMALIZATION_MAP",
")",
"and",
"("... | return the entry in the dictionary for the given language information . | train | true |
31,292 | def insert_key(key, v, trie):
if ((not key) or has_key(key, trie)):
return
for char in key:
branch = _get_child_branch(trie, char)
if (not branch):
new_branch = [char]
trie.append(new_branch)
trie = new_branch
else:
trie = branch
trie.append((key, v))
| [
"def",
"insert_key",
"(",
"key",
",",
"v",
",",
"trie",
")",
":",
"if",
"(",
"(",
"not",
"key",
")",
"or",
"has_key",
"(",
"key",
",",
"trie",
")",
")",
":",
"return",
"for",
"char",
"in",
"key",
":",
"branch",
"=",
"_get_child_branch",
"(",
"tri... | insert a pair into trie . | train | false |
31,294 | def bindir_rel(*args):
return os.path.join(CONF.bindir, *args)
| [
"def",
"bindir_rel",
"(",
"*",
"args",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"CONF",
".",
"bindir",
",",
"*",
"args",
")"
] | return a path relative to $bindir . | train | false |
31,295 | def appendArgs(url, args):
if hasattr(args, 'items'):
args = args.items()
args.sort()
else:
args = list(args)
if (len(args) == 0):
return url
if ('?' in url):
sep = '&'
else:
sep = '?'
i = 0
for (k, v) in args:
if (type(k) is not str):
k = k.encode('UTF-8')
if (type(v) is not str):
v = v.encode('UTF-8')
args[i] = (k, v)
i += 1
return ('%s%s%s' % (url, sep, urlencode(args)))
| [
"def",
"appendArgs",
"(",
"url",
",",
"args",
")",
":",
"if",
"hasattr",
"(",
"args",
",",
"'items'",
")",
":",
"args",
"=",
"args",
".",
"items",
"(",
")",
"args",
".",
"sort",
"(",
")",
"else",
":",
"args",
"=",
"list",
"(",
"args",
")",
"if"... | append query arguments to a http(s) url . | train | true |
31,297 | def proxy_functions(proxy):
if proxy:
return {'proxy_functions': proxy['rest_sample.fns']()}
| [
"def",
"proxy_functions",
"(",
"proxy",
")",
":",
"if",
"proxy",
":",
"return",
"{",
"'proxy_functions'",
":",
"proxy",
"[",
"'rest_sample.fns'",
"]",
"(",
")",
"}"
] | the loader will execute functions with one argument and pass a reference to the proxymodules lazyloader object . | train | false |
31,299 | @frappe.whitelist()
def mark_attendance(students_present, students_absent, course_schedule=None, student_batch=None, date=None):
present = json.loads(students_present)
absent = json.loads(students_absent)
for d in present:
make_attendance_records(d[u'student'], d[u'student_name'], u'Present', course_schedule, student_batch, date)
for d in absent:
make_attendance_records(d[u'student'], d[u'student_name'], u'Absent', course_schedule, student_batch, date)
frappe.db.commit()
frappe.msgprint(_(u'Attendance has been marked successfully.'))
| [
"@",
"frappe",
".",
"whitelist",
"(",
")",
"def",
"mark_attendance",
"(",
"students_present",
",",
"students_absent",
",",
"course_schedule",
"=",
"None",
",",
"student_batch",
"=",
"None",
",",
"date",
"=",
"None",
")",
":",
"present",
"=",
"json",
".",
"... | creates multiple attendance records . | train | false |
31,301 | def _CopyMatchScorerToScorerSpecProtocolBuffer(match_scorer, limit, pb):
if isinstance(match_scorer, RescoringMatchScorer):
pb.set_scorer(search_service_pb.ScorerSpec.RESCORING_MATCH_SCORER)
elif isinstance(match_scorer, MatchScorer):
pb.set_scorer(search_service_pb.ScorerSpec.MATCH_SCORER)
else:
raise TypeError(('match_scorer must be a MatchScorer or RescoringMatchRescorer, got %s' % match_scorer.__class__.__name__))
pb.set_limit(limit)
return pb
| [
"def",
"_CopyMatchScorerToScorerSpecProtocolBuffer",
"(",
"match_scorer",
",",
"limit",
",",
"pb",
")",
":",
"if",
"isinstance",
"(",
"match_scorer",
",",
"RescoringMatchScorer",
")",
":",
"pb",
".",
"set_scorer",
"(",
"search_service_pb",
".",
"ScorerSpec",
".",
... | copies a matchscorer to a search_service_pb . | train | false |
31,302 | @get('/task/new')
def task_new():
taskid = hexencode(os.urandom(8))
remote_addr = request.remote_addr
DataStore.tasks[taskid] = Task(taskid, remote_addr)
logger.debug(("Created new task: '%s'" % taskid))
return jsonize({'success': True, 'taskid': taskid})
| [
"@",
"get",
"(",
"'/task/new'",
")",
"def",
"task_new",
"(",
")",
":",
"taskid",
"=",
"hexencode",
"(",
"os",
".",
"urandom",
"(",
"8",
")",
")",
"remote_addr",
"=",
"request",
".",
"remote_addr",
"DataStore",
".",
"tasks",
"[",
"taskid",
"]",
"=",
"... | create new task id . | train | false |
31,303 | def api_get_manageable_snapshots(*args, **kwargs):
snap_id = 'ffffffff-0000-ffff-0000-ffffffffffff'
snaps = [{'reference': {'source-name': ('snapshot-%s' % snap_id)}, 'size': 4, 'extra_info': 'qos_setting:high', 'safe_to_manage': False, 'reason_not_safe': 'snapshot in use', 'cinder_id': snap_id, 'source_reference': {'source-name': 'volume-00000000-ffff-0000-ffff-000000'}}, {'reference': {'source-name': 'mysnap'}, 'size': 5, 'extra_info': 'qos_setting:low', 'safe_to_manage': True, 'reason_not_safe': None, 'cinder_id': None, 'source_reference': {'source-name': 'myvol'}}]
return snaps
| [
"def",
"api_get_manageable_snapshots",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"snap_id",
"=",
"'ffffffff-0000-ffff-0000-ffffffffffff'",
"snaps",
"=",
"[",
"{",
"'reference'",
":",
"{",
"'source-name'",
":",
"(",
"'snapshot-%s'",
"%",
"snap_id",
")",
"}... | replacement for cinder . | train | false |
31,304 | def test_image_equals_mask():
assert_close(reconstruction(np.ones((7, 5)), np.ones((7, 5))), 1)
| [
"def",
"test_image_equals_mask",
"(",
")",
":",
"assert_close",
"(",
"reconstruction",
"(",
"np",
".",
"ones",
"(",
"(",
"7",
",",
"5",
")",
")",
",",
"np",
".",
"ones",
"(",
"(",
"7",
",",
"5",
")",
")",
")",
",",
"1",
")"
] | test reconstruction where the image and mask are the same . | train | false |
31,305 | def _buildElementNsmap(using_elements):
thisMap = {}
for e in using_elements:
thisMap[e.attrib['prefix']] = e.attrib['namespace']
return thisMap
| [
"def",
"_buildElementNsmap",
"(",
"using_elements",
")",
":",
"thisMap",
"=",
"{",
"}",
"for",
"e",
"in",
"using_elements",
":",
"thisMap",
"[",
"e",
".",
"attrib",
"[",
"'prefix'",
"]",
"]",
"=",
"e",
".",
"attrib",
"[",
"'namespace'",
"]",
"return",
... | build a namespace map for an admx element . | train | true |
31,307 | @click.command()
@click.option('--count', default=2, callback=validate_count, help='A positive even number.')
@click.option('--foo', help='A mysterious parameter.')
@click.option('--url', help='A URL', type=URL())
@click.version_option()
def cli(count, foo, url):
if ((foo is not None) and (foo != 'wat')):
raise click.BadParameter('If a value is provided it needs to be the value "wat".', param_hint=['--foo'])
click.echo(('count: %s' % count))
click.echo(('foo: %s' % foo))
click.echo(('url: %s' % repr(url)))
| [
"@",
"click",
".",
"command",
"(",
")",
"@",
"click",
".",
"option",
"(",
"'--count'",
",",
"default",
"=",
"2",
",",
"callback",
"=",
"validate_count",
",",
"help",
"=",
"'A positive even number.'",
")",
"@",
"click",
".",
"option",
"(",
"'--foo'",
",",... | prints a list of medias . | train | false |
31,308 | def clean_headers(headers):
clean = {}
try:
for (k, v) in six.iteritems(headers):
if (not isinstance(k, six.binary_type)):
k = str(k)
if (not isinstance(v, six.binary_type)):
v = str(v)
clean[_helpers._to_bytes(k)] = _helpers._to_bytes(v)
except UnicodeEncodeError:
from oauth2client.client import NonAsciiHeaderError
raise NonAsciiHeaderError(k, ': ', v)
return clean
| [
"def",
"clean_headers",
"(",
"headers",
")",
":",
"clean",
"=",
"{",
"}",
"try",
":",
"for",
"(",
"k",
",",
"v",
")",
"in",
"six",
".",
"iteritems",
"(",
"headers",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"k",
",",
"six",
".",
"binary_type... | forces header keys and values to be strings . | train | true |
31,309 | def _printOneTrainingVector(x):
print ''.join((('1' if (k != 0) else '.') for k in x))
| [
"def",
"_printOneTrainingVector",
"(",
"x",
")",
":",
"print",
"''",
".",
"join",
"(",
"(",
"(",
"'1'",
"if",
"(",
"k",
"!=",
"0",
")",
"else",
"'.'",
")",
"for",
"k",
"in",
"x",
")",
")"
] | print a single vector succinctly . | train | false |
31,310 | def cached_blog_entries(blog_fetcher=_blog_entries, key_prefix=KEY_PREFIX):
blog_lock = CacheLock((key_prefix + LOCK_KEYNAME))
if cache.get((key_prefix + FRESHNESS_KEYNAME)):
entries = cache.get((key_prefix + DATA_KEYNAME))
if entries:
return entries
try:
with blog_lock:
entries = blog_fetcher()
except CacheLockInUse:
return cache.get((key_prefix + DATA_KEYNAME))
cache.set((key_prefix + FRESHNESS_KEYNAME), 'yay', BLOG_ENTRY_CACHE_TIMEOUT)
cache.set((key_prefix + DATA_KEYNAME), entries, STALENESS_TOLERANCE)
return entries
| [
"def",
"cached_blog_entries",
"(",
"blog_fetcher",
"=",
"_blog_entries",
",",
"key_prefix",
"=",
"KEY_PREFIX",
")",
":",
"blog_lock",
"=",
"CacheLock",
"(",
"(",
"key_prefix",
"+",
"LOCK_KEYNAME",
")",
")",
"if",
"cache",
".",
"get",
"(",
"(",
"key_prefix",
... | return a cached copy of blog entries that weve fetched . | train | false |
31,311 | def dos_to_long(path):
if (not ((os.name == 'nt') and ('~' in path) and os.path.exists(path))):
return path
from ctypes import create_unicode_buffer, windll
buf = create_unicode_buffer(500)
windll.kernel32.GetLongPathNameW(path.decode('mbcs'), buf, 500)
return buf.value.encode('mbcs')
| [
"def",
"dos_to_long",
"(",
"path",
")",
":",
"if",
"(",
"not",
"(",
"(",
"os",
".",
"name",
"==",
"'nt'",
")",
"and",
"(",
"'~'",
"in",
"path",
")",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
")",
":",
"return",
"path",
"... | convert windows paths in dos format to long format . | train | false |
31,312 | def _instructor_dash_url(course_key, section=None):
url = reverse('instructor_dashboard', kwargs={'course_id': unicode(course_key)})
if (section is not None):
url += u'#view-{section}'.format(section=section)
return url
| [
"def",
"_instructor_dash_url",
"(",
"course_key",
",",
"section",
"=",
"None",
")",
":",
"url",
"=",
"reverse",
"(",
"'instructor_dashboard'",
",",
"kwargs",
"=",
"{",
"'course_id'",
":",
"unicode",
"(",
"course_key",
")",
"}",
")",
"if",
"(",
"section",
"... | return the url for a section in the instructor dashboard . | train | false |
31,313 | def _build_requested_filter(requested_filter):
all_filters = {'Images': ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/tiff', 'image/tif', 'image/x-icon'], 'Documents': ['application/pdf', 'text/plain', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'application/vnd.openxmlformats-officedocument.presentationml.template', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'application/msword', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint']}
requested_file_types = all_filters.get(requested_filter, None)
where = ["JSON.stringify(this.contentType).toUpperCase() == JSON.stringify('{}').toUpperCase()".format(req_filter) for req_filter in requested_file_types]
filter_params = {'$where': ' || '.join(where)}
return filter_params
| [
"def",
"_build_requested_filter",
"(",
"requested_filter",
")",
":",
"all_filters",
"=",
"{",
"'Images'",
":",
"[",
"'image/png'",
",",
"'image/jpeg'",
",",
"'image/jpg'",
",",
"'image/gif'",
",",
"'image/tiff'",
",",
"'image/tif'",
",",
"'image/x-icon'",
"]",
","... | returns requested filter_params string . | train | false |
31,314 | def get_course_tag(user, course_id, key):
try:
record = UserCourseTag.objects.get(user=user, course_id=course_id, key=key)
return record.value
except UserCourseTag.DoesNotExist:
return None
| [
"def",
"get_course_tag",
"(",
"user",
",",
"course_id",
",",
"key",
")",
":",
"try",
":",
"record",
"=",
"UserCourseTag",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"user",
",",
"course_id",
"=",
"course_id",
",",
"key",
"=",
"key",
")",
"return",
... | gets the value of the users course tag for the specified key in the specified course_id . | train | false |
31,316 | def get_real_social_auth_object(request):
running_pipeline = get(request)
if (running_pipeline and ('social' in running_pipeline['kwargs'])):
social = running_pipeline['kwargs']['social']
if isinstance(social, dict):
social = UserSocialAuth.objects.get(uid=social.get('uid', ''))
return social
| [
"def",
"get_real_social_auth_object",
"(",
"request",
")",
":",
"running_pipeline",
"=",
"get",
"(",
"request",
")",
"if",
"(",
"running_pipeline",
"and",
"(",
"'social'",
"in",
"running_pipeline",
"[",
"'kwargs'",
"]",
")",
")",
":",
"social",
"=",
"running_p... | at times . | train | false |
31,317 | def java_jar(name, srcs=[], deps=[], prebuilt=False, pre_build=False, **kwargs):
target = JavaJarTarget(name, srcs, deps, (prebuilt or pre_build), blade.blade, kwargs)
if pre_build:
console.warning(('//%s:%s: "pre_build" has been deprecated, please use "prebuilt"' % (target.path, target.name)))
blade.blade.register_target(target)
| [
"def",
"java_jar",
"(",
"name",
",",
"srcs",
"=",
"[",
"]",
",",
"deps",
"=",
"[",
"]",
",",
"prebuilt",
"=",
"False",
",",
"pre_build",
"=",
"False",
",",
"**",
"kwargs",
")",
":",
"target",
"=",
"JavaJarTarget",
"(",
"name",
",",
"srcs",
",",
"... | define java_jar target . | train | false |
31,318 | def serverFactoryFor(protocol):
factory = ServerFactory()
factory.protocol = protocol
return factory
| [
"def",
"serverFactoryFor",
"(",
"protocol",
")",
":",
"factory",
"=",
"ServerFactory",
"(",
")",
"factory",
".",
"protocol",
"=",
"protocol",
"return",
"factory"
] | helper function which provides the signature l{serverfactory} should provide . | train | false |
31,319 | def find_lemmata(tokens):
for token in tokens:
(word, pos, lemma) = (token[0], token[1], token[0])
if pos.startswith(('DT',)):
lemma = singularize(word, pos='DT')
if pos.startswith('JJ'):
lemma = predicative(word)
if (pos == 'NNS'):
lemma = singularize(word)
if pos.startswith(('VB', 'MD')):
lemma = (conjugate(word, INFINITIVE) or word)
token.append(lemma.lower())
return tokens
| [
"def",
"find_lemmata",
"(",
"tokens",
")",
":",
"for",
"token",
"in",
"tokens",
":",
"(",
"word",
",",
"pos",
",",
"lemma",
")",
"=",
"(",
"token",
"[",
"0",
"]",
",",
"token",
"[",
"1",
"]",
",",
"token",
"[",
"0",
"]",
")",
"if",
"pos",
"."... | annotates the tokens with lemmata for plural nouns and conjugated verbs . | train | true |
31,320 | def mvnormcdf(upper, mu, cov, lower=None, **kwds):
upper = np.array(upper)
if (lower is None):
lower = ((- np.ones(upper.shape)) * np.inf)
else:
lower = np.array(lower)
cov = np.array(cov)
stdev = np.sqrt(np.diag(cov))
lower = ((lower - mu) / stdev)
upper = ((upper - mu) / stdev)
divrow = np.atleast_2d(stdev)
corr = ((cov / divrow) / divrow.T)
return mvstdnormcdf(lower, upper, corr, **kwds)
| [
"def",
"mvnormcdf",
"(",
"upper",
",",
"mu",
",",
"cov",
",",
"lower",
"=",
"None",
",",
"**",
"kwds",
")",
":",
"upper",
"=",
"np",
".",
"array",
"(",
"upper",
")",
"if",
"(",
"lower",
"is",
"None",
")",
":",
"lower",
"=",
"(",
"(",
"-",
"np... | multivariate normal cumulative distribution function this is a wrapper for scipy . | train | false |
31,323 | def percent(args=None):
if (__grains__['kernel'] == 'Linux'):
cmd = 'df -P'
elif (__grains__['kernel'] == 'OpenBSD'):
cmd = 'df -kP'
else:
cmd = 'df'
ret = {}
out = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
for line in out:
if (not line):
continue
if line.startswith('Filesystem'):
continue
comps = line.split()
while (not comps[1].isdigit()):
comps[0] = '{0} {1}'.format(comps[0], comps[1])
comps.pop(1)
try:
if (__grains__['kernel'] == 'Darwin'):
ret[comps[8]] = comps[4]
else:
ret[comps[5]] = comps[4]
except IndexError:
log.error('Problem parsing disk usage information')
ret = {}
if (args and (args not in ret)):
log.error("Problem parsing disk usage information: Partition '{0}' does not exist!".format(args))
ret = {}
elif args:
return ret[args]
return ret
| [
"def",
"percent",
"(",
"args",
"=",
"None",
")",
":",
"if",
"(",
"__grains__",
"[",
"'kernel'",
"]",
"==",
"'Linux'",
")",
":",
"cmd",
"=",
"'df -P'",
"elif",
"(",
"__grains__",
"[",
"'kernel'",
"]",
"==",
"'OpenBSD'",
")",
":",
"cmd",
"=",
"'df -kP'... | return partition information for volumes mounted on this minion cli example: . | train | true |
31,325 | def bonferroni_correction(pvals):
return (array(pvals, dtype=float) * len(pvals))
| [
"def",
"bonferroni_correction",
"(",
"pvals",
")",
":",
"return",
"(",
"array",
"(",
"pvals",
",",
"dtype",
"=",
"float",
")",
"*",
"len",
"(",
"pvals",
")",
")"
] | p-value correction with bonferroni method . | train | false |
31,326 | def mulmatscaler(matlist, scaler, K):
return [mulrowscaler(row, scaler, K) for row in matlist]
| [
"def",
"mulmatscaler",
"(",
"matlist",
",",
"scaler",
",",
"K",
")",
":",
"return",
"[",
"mulrowscaler",
"(",
"row",
",",
"scaler",
",",
"K",
")",
"for",
"row",
"in",
"matlist",
"]"
] | performs scaler matrix multiplication one row at at time . | train | false |
31,327 | def key_exists(key_id, region=None, key=None, keyid=None, profile=None):
conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)
r = {}
try:
key = conn.describe_key(key_id)
r['result'] = True
except boto.exception.BotoServerError as e:
if isinstance(e, boto.kms.exceptions.NotFoundException):
r['result'] = False
return r
r['error'] = __utils__['boto.get_error'](e)
return r
| [
"def",
"key_exists",
"(",
"key_id",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",... | check for the existence of a key . | train | true |
31,328 | def dyad_completion(w):
w = tuple((Fraction(v) for v in w))
d = max((v.denominator for v in w))
p = next_pow2(d)
if (p == d):
return w
else:
return (tuple((Fraction((v * d), p) for v in w)) + (Fraction((p - d), p),))
| [
"def",
"dyad_completion",
"(",
"w",
")",
":",
"w",
"=",
"tuple",
"(",
"(",
"Fraction",
"(",
"v",
")",
"for",
"v",
"in",
"w",
")",
")",
"d",
"=",
"max",
"(",
"(",
"v",
".",
"denominator",
"for",
"v",
"in",
"w",
")",
")",
"p",
"=",
"next_pow2",... | return the dyadic completion of w . | train | false |
31,329 | @slow_test
@requires_sklearn_0_15
def test_cov_estimation_on_raw_reg():
raw = read_raw_fif(raw_fname, preload=True)
raw.info['sfreq'] /= 10.0
raw = RawArray(raw._data[:, ::10].copy(), raw.info)
cov_mne = read_cov(erm_cov_fname)
with warnings.catch_warnings(record=True):
warnings.simplefilter('always')
cov = compute_raw_covariance(raw, tstep=5.0, method='diagonal_fixed')
assert_snr(cov.data, cov_mne.data, 5)
| [
"@",
"slow_test",
"@",
"requires_sklearn_0_15",
"def",
"test_cov_estimation_on_raw_reg",
"(",
")",
":",
"raw",
"=",
"read_raw_fif",
"(",
"raw_fname",
",",
"preload",
"=",
"True",
")",
"raw",
".",
"info",
"[",
"'sfreq'",
"]",
"/=",
"10.0",
"raw",
"=",
"RawArr... | test estimation from raw with regularization . | train | false |
31,330 | def path_to_file_uri(abspath):
return path.path_to_uri(abspath)
| [
"def",
"path_to_file_uri",
"(",
"abspath",
")",
":",
"return",
"path",
".",
"path_to_uri",
"(",
"abspath",
")"
] | convert absolute path to file uri . | train | false |
31,331 | def update_subnet(subnet, name, profile=None):
conn = _auth(profile)
return conn.update_subnet(subnet, name)
| [
"def",
"update_subnet",
"(",
"subnet",
",",
"name",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"update_subnet",
"(",
"subnet",
",",
"name",
")"
] | updates a subnet cli example: . | train | true |
31,333 | def test_huber_scaling_invariant():
rng = np.random.RandomState(0)
(X, y) = make_regression_with_outliers()
huber = HuberRegressor(fit_intercept=False, alpha=0.0, max_iter=100)
huber.fit(X, y)
n_outliers_mask_1 = huber.outliers_
assert_false(np.all(n_outliers_mask_1))
huber.fit(X, (2.0 * y))
n_outliers_mask_2 = huber.outliers_
assert_array_equal(n_outliers_mask_2, n_outliers_mask_1)
huber.fit((2.0 * X), (2.0 * y))
n_outliers_mask_3 = huber.outliers_
assert_array_equal(n_outliers_mask_3, n_outliers_mask_1)
| [
"def",
"test_huber_scaling_invariant",
"(",
")",
":",
"rng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"0",
")",
"(",
"X",
",",
"y",
")",
"=",
"make_regression_with_outliers",
"(",
")",
"huber",
"=",
"HuberRegressor",
"(",
"fit_intercept",
"=",
"F... | test that outliers filtering is scaling independent . | train | false |
31,334 | def get_selection_rect(img, sr, target):
left_border = ((abs((sr.left() - target.left())) / target.width()) * img.width())
top_border = ((abs((sr.top() - target.top())) / target.height()) * img.height())
right_border = ((abs((target.right() - sr.right())) / target.width()) * img.width())
bottom_border = ((abs((target.bottom() - sr.bottom())) / target.height()) * img.height())
return (left_border, top_border, ((img.width() - left_border) - right_border), ((img.height() - top_border) - bottom_border))
| [
"def",
"get_selection_rect",
"(",
"img",
",",
"sr",
",",
"target",
")",
":",
"left_border",
"=",
"(",
"(",
"abs",
"(",
"(",
"sr",
".",
"left",
"(",
")",
"-",
"target",
".",
"left",
"(",
")",
")",
")",
"/",
"target",
".",
"width",
"(",
")",
")",... | given selection rect return the corresponding rectangle in the underlying image as left . | train | false |
31,336 | def get_request_stats():
return {'ip': get_real_ip(), 'platform': request.user_agent.platform, 'browser': request.user_agent.browser, 'version': request.user_agent.version, 'language': request.user_agent.language}
| [
"def",
"get_request_stats",
"(",
")",
":",
"return",
"{",
"'ip'",
":",
"get_real_ip",
"(",
")",
",",
"'platform'",
":",
"request",
".",
"user_agent",
".",
"platform",
",",
"'browser'",
":",
"request",
".",
"user_agent",
".",
"browser",
",",
"'version'",
":... | get ip . | train | false |
31,337 | def discover(uri):
result = DiscoveryResult(uri)
resp = fetchers.fetch(uri, headers={'Accept': YADIS_ACCEPT_HEADER})
if (resp.status not in (200, 206)):
raise DiscoveryFailure(('HTTP Response status from identity URL host is not 200. Got status %r' % (resp.status,)), resp)
result.normalized_uri = resp.final_url
result.content_type = resp.headers.get('content-type')
result.xrds_uri = whereIsYadis(resp)
if (result.xrds_uri and result.usedYadisLocation()):
resp = fetchers.fetch(result.xrds_uri)
if (resp.status not in (200, 206)):
exc = DiscoveryFailure(('HTTP Response status from Yadis host is not 200. Got status %r' % (resp.status,)), resp)
exc.identity_url = result.normalized_uri
raise exc
result.content_type = resp.headers.get('content-type')
result.response_text = resp.body
return result
| [
"def",
"discover",
"(",
"uri",
")",
":",
"result",
"=",
"DiscoveryResult",
"(",
"uri",
")",
"resp",
"=",
"fetchers",
".",
"fetch",
"(",
"uri",
",",
"headers",
"=",
"{",
"'Accept'",
":",
"YADIS_ACCEPT_HEADER",
"}",
")",
"if",
"(",
"resp",
".",
"status",... | discover services for a given uri . | train | true |
31,339 | def extract_arguments(text):
regexp = re.compile('\\/\\w*(@\\w*)*\\s*([\\s\\S]*)', re.IGNORECASE)
result = regexp.match(text)
return (result.group(2) if is_command(text) else None)
| [
"def",
"extract_arguments",
"(",
"text",
")",
":",
"regexp",
"=",
"re",
".",
"compile",
"(",
"'\\\\/\\\\w*(@\\\\w*)*\\\\s*([\\\\s\\\\S]*)'",
",",
"re",
".",
"IGNORECASE",
")",
"result",
"=",
"regexp",
".",
"match",
"(",
"text",
")",
"return",
"(",
"result",
... | returns the argument after the command . | train | true |
31,340 | def cmpfiles(a, b, common, shallow=True):
res = ([], [], [])
for x in common:
ax = os.path.join(a, x)
bx = os.path.join(b, x)
res[_cmp(ax, bx, shallow)].append(x)
return res
| [
"def",
"cmpfiles",
"(",
"a",
",",
"b",
",",
"common",
",",
"shallow",
"=",
"True",
")",
":",
"res",
"=",
"(",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
")",
"for",
"x",
"in",
"common",
":",
"ax",
"=",
"os",
".",
"path",
".",
"join",
"(",
"a... | compare common files in two directories . | train | false |
31,341 | def blackbody_lambda(in_x, temperature):
if (getattr(in_x, u'unit', None) is None):
in_x = u.Quantity(in_x, u.AA)
bb_nu = (blackbody_nu(in_x, temperature) * u.sr)
flux = bb_nu.to(FLAM, u.spectral_density(in_x))
return (flux / u.sr)
| [
"def",
"blackbody_lambda",
"(",
"in_x",
",",
"temperature",
")",
":",
"if",
"(",
"getattr",
"(",
"in_x",
",",
"u'unit'",
",",
"None",
")",
"is",
"None",
")",
":",
"in_x",
"=",
"u",
".",
"Quantity",
"(",
"in_x",
",",
"u",
".",
"AA",
")",
"bb_nu",
... | like :func:blackbody_nu but for :math:b_{lambda}(t) . | train | false |
31,344 | def sentence_ribes(references, hypothesis, alpha=0.25, beta=0.1):
best_ribes = (-1.0)
for reference in references:
worder = word_rank_alignment(reference, hypothesis)
nkt = kendall_tau(worder)
bp = min(1.0, math.exp((1.0 - (len(reference) / len(hypothesis)))))
p1 = (len(worder) / len(hypothesis))
_ribes = ((nkt * (p1 ** alpha)) * (bp ** beta))
if (_ribes > best_ribes):
best_ribes = _ribes
return best_ribes
| [
"def",
"sentence_ribes",
"(",
"references",
",",
"hypothesis",
",",
"alpha",
"=",
"0.25",
",",
"beta",
"=",
"0.1",
")",
":",
"best_ribes",
"=",
"(",
"-",
"1.0",
")",
"for",
"reference",
"in",
"references",
":",
"worder",
"=",
"word_rank_alignment",
"(",
... | the ribes from hideki isozaki . | train | false |
31,347 | def lazy_loading_proxy_for_interface(interface, loader):
class LazyLoadingProxy(proxyForInterface(interface, '_original'), ):
_cached_original = None
def __init__(self):
'\n The initializer of a class generated by ``proxyForInterface``\n expects the wrapped "original" object as an argument. Overrride\n that here.\n '
@property
def _original(self):
if (self._cached_original is None):
self._cached_original = loader()
return self._cached_original
return LazyLoadingProxy()
| [
"def",
"lazy_loading_proxy_for_interface",
"(",
"interface",
",",
"loader",
")",
":",
"class",
"LazyLoadingProxy",
"(",
"proxyForInterface",
"(",
"interface",
",",
"'_original'",
")",
",",
")",
":",
"_cached_original",
"=",
"None",
"def",
"__init__",
"(",
"self",
... | create a proxy for an interface which builds the wrapped object lazily . | train | false |
31,348 | def catalogue_pre_save(instance, sender, **kwargs):
record = None
try:
catalogue = get_catalogue()
record = catalogue.get_record(instance.uuid)
except EnvironmentError as err:
msg = ('Could not connect to catalogue to save information for layer "%s"' % instance.name)
LOGGER.warn(msg, err)
raise err
if (record is None):
return
| [
"def",
"catalogue_pre_save",
"(",
"instance",
",",
"sender",
",",
"**",
"kwargs",
")",
":",
"record",
"=",
"None",
"try",
":",
"catalogue",
"=",
"get_catalogue",
"(",
")",
"record",
"=",
"catalogue",
".",
"get_record",
"(",
"instance",
".",
"uuid",
")",
... | send information to catalogue . | train | false |
31,349 | def combine_repeated_headers(kvset):
def set_pop(set, item):
set.remove(item)
return item
headers = defaultdict(list)
keys = set()
for (key, value) in kvset:
headers[key].append(value)
keys.add(key)
return [(set_pop(keys, k), '\x00'.join(headers[k])) for (k, v) in kvset if (k in keys)]
| [
"def",
"combine_repeated_headers",
"(",
"kvset",
")",
":",
"def",
"set_pop",
"(",
"set",
",",
"item",
")",
":",
"set",
".",
"remove",
"(",
"item",
")",
"return",
"item",
"headers",
"=",
"defaultdict",
"(",
"list",
")",
"keys",
"=",
"set",
"(",
")",
"... | given a list of key-value pairs . | train | false |
31,350 | def _get_proctoring_requirements(course_key):
from edx_proctoring.api import get_all_exams_for_course
requirements = []
for exam in get_all_exams_for_course(unicode(course_key)):
if (exam['is_proctored'] and exam['is_active'] and (not exam['is_practice_exam'])):
try:
usage_key = UsageKey.from_string(exam['content_id'])
proctor_block = modulestore().get_item(usage_key)
except (InvalidKeyError, ItemNotFoundError):
LOGGER.info("Invalid content_id '%s' for proctored block '%s'", exam['content_id'], exam['exam_name'])
proctor_block = None
if proctor_block:
requirements.append({'namespace': 'proctored_exam', 'name': exam['content_id'], 'display_name': exam['exam_name'], 'start_date': (proctor_block.start if proctor_block.start else None), 'criteria': {}})
if requirements:
log_msg = "Registering the following as 'proctored_exam' credit requirements: {log_msg}".format(log_msg=requirements)
LOGGER.info(log_msg)
return requirements
| [
"def",
"_get_proctoring_requirements",
"(",
"course_key",
")",
":",
"from",
"edx_proctoring",
".",
"api",
"import",
"get_all_exams_for_course",
"requirements",
"=",
"[",
"]",
"for",
"exam",
"in",
"get_all_exams_for_course",
"(",
"unicode",
"(",
"course_key",
")",
")... | will return list of requirements regarding any exams that have been marked as proctored exams . | train | false |
31,351 | def test_lex_line_counting_multi():
entries = tokenize('\n(foo (one two))\n(foo bar)\n')
entry = entries[0]
assert (entry.start_line == 2)
assert (entry.start_column == 1)
assert (entry.end_line == 2)
assert (entry.end_column == 15)
entry = entries[1]
assert (entry.start_line == 3)
assert (entry.start_column == 1)
assert (entry.end_line == 3)
assert (entry.end_column == 9)
| [
"def",
"test_lex_line_counting_multi",
"(",
")",
":",
"entries",
"=",
"tokenize",
"(",
"'\\n(foo (one two))\\n(foo bar)\\n'",
")",
"entry",
"=",
"entries",
"[",
"0",
"]",
"assert",
"(",
"entry",
".",
"start_line",
"==",
"2",
")",
"assert",
"(",
"entry",
".",
... | make sure we can do multi-line tokenization . | train | false |
31,352 | def is_singleton(rdtype):
if _singletons.has_key(rdtype):
return True
return False
| [
"def",
"is_singleton",
"(",
"rdtype",
")",
":",
"if",
"_singletons",
".",
"has_key",
"(",
"rdtype",
")",
":",
"return",
"True",
"return",
"False"
] | true if the type is a singleton . | train | false |
31,355 | def s3_meta_fields():
s3_meta_approved_by = S3ReusableField('approved_by', 'integer', readable=False, writable=False, requires=None, represent=s3_auth_user_represent)
fields = (s3_meta_uuid(), s3_meta_mci(), s3_meta_deletion_status(), s3_meta_deletion_fk(), s3_meta_deletion_rb(), s3_meta_created_on(), s3_meta_modified_on(), s3_meta_approved_by())
fields = ((fields + s3_authorstamp()) + s3_ownerstamp())
return fields
| [
"def",
"s3_meta_fields",
"(",
")",
":",
"s3_meta_approved_by",
"=",
"S3ReusableField",
"(",
"'approved_by'",
",",
"'integer'",
",",
"readable",
"=",
"False",
",",
"writable",
"=",
"False",
",",
"requires",
"=",
"None",
",",
"represent",
"=",
"s3_auth_user_repres... | normal meta-fields added to every table . | train | false |
31,356 | def get_platform():
if (os.name == 'nt'):
prefix = ' bit ('
i = sys.version.find(prefix)
if (i == (-1)):
return sys.platform
j = sys.version.find(')', i)
look = sys.version[(i + len(prefix)):j].lower()
if (look == 'amd64'):
return 'win-amd64'
if (look == 'itanium'):
return 'win-ia64'
return sys.platform
if ('_PYTHON_HOST_PLATFORM' in os.environ):
return os.environ['_PYTHON_HOST_PLATFORM']
if ((os.name != 'posix') or (not hasattr(os, 'uname'))):
return sys.platform
(osname, host, release, version, machine) = os.uname()
osname = osname.lower().replace('/', '')
machine = machine.replace(' ', '_')
machine = machine.replace('/', '-')
if (osname[:5] == 'linux'):
return ('%s-%s' % (osname, machine))
elif (osname[:5] == 'sunos'):
if (release[0] >= '5'):
osname = 'solaris'
release = ('%d.%s' % ((int(release[0]) - 3), release[2:]))
bitness = {2147483647: '32bit', 9223372036854775807: '64bit'}
machine += ('.%s' % bitness[sys.maxsize])
elif (osname[:4] == 'irix'):
return ('%s-%s' % (osname, release))
elif (osname[:3] == 'aix'):
return ('%s-%s.%s' % (osname, version, release))
elif (osname[:6] == 'cygwin'):
osname = 'cygwin'
rel_re = re.compile('[\\d.]+', re.ASCII)
m = rel_re.match(release)
if m:
release = m.group()
elif (osname[:6] == 'darwin'):
import _osx_support, distutils.sysconfig
(osname, release, machine) = _osx_support.get_platform_osx(distutils.sysconfig.get_config_vars(), osname, release, machine)
return ('%s-%s-%s' % (osname, release, machine))
| [
"def",
"get_platform",
"(",
")",
":",
"if",
"(",
"os",
".",
"name",
"==",
"'nt'",
")",
":",
"prefix",
"=",
"' bit ('",
"i",
"=",
"sys",
".",
"version",
".",
"find",
"(",
"prefix",
")",
"if",
"(",
"i",
"==",
"(",
"-",
"1",
")",
")",
":",
"retu... | whats the platform? example: linux is a platform . | train | false |
31,357 | def CreateRPC(service='datastore_v3', deadline=None, callback=None, read_policy=None):
assert (service == 'datastore_v3')
conn = _GetConnection()
config = None
if (deadline is not None):
config = datastore_rpc.Configuration(deadline=deadline)
rpc = conn._create_rpc(config)
rpc.callback = callback
if (read_policy is not None):
rpc.read_policy = read_policy
return rpc
| [
"def",
"CreateRPC",
"(",
"service",
"=",
"'datastore_v3'",
",",
"deadline",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"read_policy",
"=",
"None",
")",
":",
"assert",
"(",
"service",
"==",
"'datastore_v3'",
")",
"conn",
"=",
"_GetConnection",
"(",
")"... | creates a rpc instance for the given service . | train | false |
31,358 | def literals(choices, prefix='', suffix=''):
return '|'.join((((prefix + re.escape(c)) + suffix) for c in choices.split()))
| [
"def",
"literals",
"(",
"choices",
",",
"prefix",
"=",
"''",
",",
"suffix",
"=",
"''",
")",
":",
"return",
"'|'",
".",
"join",
"(",
"(",
"(",
"(",
"prefix",
"+",
"re",
".",
"escape",
"(",
"c",
")",
")",
"+",
"suffix",
")",
"for",
"c",
"in",
"... | create a regex from a space-separated list of literal choices . | train | true |
31,359 | def read_certificates(glob_path):
ret = {}
for path in glob.glob(glob_path):
if os.path.isfile(path):
try:
ret[path] = read_certificate(certificate=path)
except ValueError:
pass
return ret
| [
"def",
"read_certificates",
"(",
"glob_path",
")",
":",
"ret",
"=",
"{",
"}",
"for",
"path",
"in",
"glob",
".",
"glob",
"(",
"glob_path",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"try",
":",
"ret",
"[",
"path",
"]"... | returns a dict containing details of a all certificates matching a glob glob_path: a path to certificates to be read and returned . | train | false |
31,360 | def _slurp(filename):
with open(filename) as f:
return f.read()
| [
"def",
"_slurp",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")"
] | read in the entire contents of a file . | train | false |
31,361 | def _get_creation_time(m):
try:
return m.creation_time
except AttributeError:
try:
return m.datetime
except AttributeError:
return datetime.datetime(1970, 1, 1, 0, 0, 0)
| [
"def",
"_get_creation_time",
"(",
"m",
")",
":",
"try",
":",
"return",
"m",
".",
"creation_time",
"except",
"AttributeError",
":",
"try",
":",
"return",
"m",
".",
"datetime",
"except",
"AttributeError",
":",
"return",
"datetime",
".",
"datetime",
"(",
"1970"... | compatibility shim . | train | false |
31,364 | def change_USE_SUBTITLES(use_subtitles):
use_subtitles = checkbox_to_value(use_subtitles)
if (sickbeard.USE_SUBTITLES == use_subtitles):
return
sickbeard.USE_SUBTITLES = use_subtitles
if sickbeard.USE_SUBTITLES:
if (not sickbeard.subtitlesFinderScheduler.enable):
logger.log(u'Starting SUBTITLESFINDER thread', logger.INFO)
sickbeard.subtitlesFinderScheduler.silent = False
sickbeard.subtitlesFinderScheduler.enable = True
else:
logger.log(u'Unable to start SUBTITLESFINDER thread. Already running', logger.INFO)
else:
sickbeard.subtitlesFinderScheduler.enable = False
sickbeard.subtitlesFinderScheduler.silent = True
logger.log(u'Stopping SUBTITLESFINDER thread', logger.INFO)
| [
"def",
"change_USE_SUBTITLES",
"(",
"use_subtitles",
")",
":",
"use_subtitles",
"=",
"checkbox_to_value",
"(",
"use_subtitles",
")",
"if",
"(",
"sickbeard",
".",
"USE_SUBTITLES",
"==",
"use_subtitles",
")",
":",
"return",
"sickbeard",
".",
"USE_SUBTITLES",
"=",
"u... | enable/disable subtitle searcher todo: make this return true/false on success/failure . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.