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 |
|---|---|---|---|---|---|
39,976 | def get_path_dir_files(dirName, nzbName, proc_type):
path = u''
dirs = []
files = []
if (((dirName == sickbeard.TV_DOWNLOAD_DIR) and (not nzbName)) or (proc_type == u'manual')):
for (path, dirs, files) in ek(os.walk, dirName):
break
else:
(path, dirs) = ek(os.path.split, dirName)
if ((not ((nzbName is None) or nzbName.endswith(u'.nzb'))) and ek(os.path.isfile, ek(os.path.join, dirName, nzbName))):
dirs = []
files = [ek(os.path.join, dirName, nzbName)]
else:
dirs = [dirs]
files = []
return (path, dirs, files)
| [
"def",
"get_path_dir_files",
"(",
"dirName",
",",
"nzbName",
",",
"proc_type",
")",
":",
"path",
"=",
"u''",
"dirs",
"=",
"[",
"]",
"files",
"=",
"[",
"]",
"if",
"(",
"(",
"(",
"dirName",
"==",
"sickbeard",
".",
"TV_DOWNLOAD_DIR",
")",
"and",
"(",
"not",
"nzbName",
")",
")",
"or",
"(",
"proc_type",
"==",
"u'manual'",
")",
")",
":",
"for",
"(",
"path",
",",
"dirs",
",",
"files",
")",
"in",
"ek",
"(",
"os",
".",
"walk",
",",
"dirName",
")",
":",
"break",
"else",
":",
"(",
"path",
",",
"dirs",
")",
"=",
"ek",
"(",
"os",
".",
"path",
".",
"split",
",",
"dirName",
")",
"if",
"(",
"(",
"not",
"(",
"(",
"nzbName",
"is",
"None",
")",
"or",
"nzbName",
".",
"endswith",
"(",
"u'.nzb'",
")",
")",
")",
"and",
"ek",
"(",
"os",
".",
"path",
".",
"isfile",
",",
"ek",
"(",
"os",
".",
"path",
".",
"join",
",",
"dirName",
",",
"nzbName",
")",
")",
")",
":",
"dirs",
"=",
"[",
"]",
"files",
"=",
"[",
"ek",
"(",
"os",
".",
"path",
".",
"join",
",",
"dirName",
",",
"nzbName",
")",
"]",
"else",
":",
"dirs",
"=",
"[",
"dirs",
"]",
"files",
"=",
"[",
"]",
"return",
"(",
"path",
",",
"dirs",
",",
"files",
")"
] | get files in a path . | train | false |
39,978 | def valid_value(value, quote=default_cookie_quote, unquote=default_unquote):
if (value is None):
return False
encoded = encode_cookie_value(value, quote=quote)
decoded = parse_string(encoded, unquote=unquote)
decoded_normalized = (normalize('NFKD', decoded) if (not isinstance(decoded, bytes)) else decoded)
value_normalized = (normalize('NFKD', value) if (not isinstance(value, bytes)) else value)
if (decoded_normalized == value_normalized):
return True
return False
| [
"def",
"valid_value",
"(",
"value",
",",
"quote",
"=",
"default_cookie_quote",
",",
"unquote",
"=",
"default_unquote",
")",
":",
"if",
"(",
"value",
"is",
"None",
")",
":",
"return",
"False",
"encoded",
"=",
"encode_cookie_value",
"(",
"value",
",",
"quote",
"=",
"quote",
")",
"decoded",
"=",
"parse_string",
"(",
"encoded",
",",
"unquote",
"=",
"unquote",
")",
"decoded_normalized",
"=",
"(",
"normalize",
"(",
"'NFKD'",
",",
"decoded",
")",
"if",
"(",
"not",
"isinstance",
"(",
"decoded",
",",
"bytes",
")",
")",
"else",
"decoded",
")",
"value_normalized",
"=",
"(",
"normalize",
"(",
"'NFKD'",
",",
"value",
")",
"if",
"(",
"not",
"isinstance",
"(",
"value",
",",
"bytes",
")",
")",
"else",
"value",
")",
"if",
"(",
"decoded_normalized",
"==",
"value_normalized",
")",
":",
"return",
"True",
"return",
"False"
] | validate a cookie value string . | train | true |
39,979 | def selectDialect(protocol, dialect):
protocol._selectDialect(dialect)
| [
"def",
"selectDialect",
"(",
"protocol",
",",
"dialect",
")",
":",
"protocol",
".",
"_selectDialect",
"(",
"dialect",
")"
] | dictate a banana dialect to use . | train | false |
39,980 | def _base64_unicode(value):
as_bytes = base64.b64encode(value)
return as_bytes.decode('ascii')
| [
"def",
"_base64_unicode",
"(",
"value",
")",
":",
"as_bytes",
"=",
"base64",
".",
"b64encode",
"(",
"value",
")",
"return",
"as_bytes",
".",
"decode",
"(",
"'ascii'",
")"
] | helper to base64 encode and make json serializable . | train | false |
39,981 | def cos(x):
return tf.cos(x)
| [
"def",
"cos",
"(",
"x",
")",
":",
"return",
"tf",
".",
"cos",
"(",
"x",
")"
] | elementwise cos function . | train | false |
39,982 | @require_GET
def wiki_rows(request, readout_slug):
product = _get_product(request)
readout = _kb_readout(request, readout_slug, READOUTS, locale=request.GET.get('locale'), mode=smart_int(request.GET.get('mode'), None), product=product)
max_rows = smart_int(request.GET.get('max'), fallback=None)
return HttpResponse(readout.render(max_rows=max_rows))
| [
"@",
"require_GET",
"def",
"wiki_rows",
"(",
"request",
",",
"readout_slug",
")",
":",
"product",
"=",
"_get_product",
"(",
"request",
")",
"readout",
"=",
"_kb_readout",
"(",
"request",
",",
"readout_slug",
",",
"READOUTS",
",",
"locale",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"'locale'",
")",
",",
"mode",
"=",
"smart_int",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"'mode'",
")",
",",
"None",
")",
",",
"product",
"=",
"product",
")",
"max_rows",
"=",
"smart_int",
"(",
"request",
".",
"GET",
".",
"get",
"(",
"'max'",
")",
",",
"fallback",
"=",
"None",
")",
"return",
"HttpResponse",
"(",
"readout",
".",
"render",
"(",
"max_rows",
"=",
"max_rows",
")",
")"
] | return the table contents html for the given readout and mode . | train | false |
39,983 | def _plot_boot_kde(ax, x, boot_data, color, **kwargs):
kwargs.pop('data')
_ts_kde(ax, x, boot_data, color, **kwargs)
| [
"def",
"_plot_boot_kde",
"(",
"ax",
",",
"x",
",",
"boot_data",
",",
"color",
",",
"**",
"kwargs",
")",
":",
"kwargs",
".",
"pop",
"(",
"'data'",
")",
"_ts_kde",
"(",
"ax",
",",
"x",
",",
"boot_data",
",",
"color",
",",
"**",
"kwargs",
")"
] | plot the kernal density estimate of the bootstrap distribution . | train | false |
39,984 | @then(u'the command output should contain {count:d} times')
def step_command_output_should_contain_multiple_times(context, count):
assert (context.text is not None), 'REQUIRE: multi-line text'
step_command_output_should_contain_text_multiple_times(context, context.text, count)
| [
"@",
"then",
"(",
"u'the command output should contain {count:d} times'",
")",
"def",
"step_command_output_should_contain_multiple_times",
"(",
"context",
",",
"count",
")",
":",
"assert",
"(",
"context",
".",
"text",
"is",
"not",
"None",
")",
",",
"'REQUIRE: multi-line text'",
"step_command_output_should_contain_text_multiple_times",
"(",
"context",
",",
"context",
".",
"text",
",",
"count",
")"
] | example: when i run "behave . | train | false |
39,986 | def _get_pygments_extensions():
import pygments.lexers as lexers
extensions = []
for lx in lexers.get_all_lexers():
lexer_exts = lx[2]
if lexer_exts:
other_exts = [le for le in lexer_exts if (not le.startswith('*'))]
lexer_exts = [le[1:] for le in lexer_exts if le.startswith('*')]
lexer_exts = [le for le in lexer_exts if (not le.endswith('_*'))]
extensions = ((extensions + list(lexer_exts)) + list(other_exts))
return sorted(list(set(extensions)))
| [
"def",
"_get_pygments_extensions",
"(",
")",
":",
"import",
"pygments",
".",
"lexers",
"as",
"lexers",
"extensions",
"=",
"[",
"]",
"for",
"lx",
"in",
"lexers",
".",
"get_all_lexers",
"(",
")",
":",
"lexer_exts",
"=",
"lx",
"[",
"2",
"]",
"if",
"lexer_exts",
":",
"other_exts",
"=",
"[",
"le",
"for",
"le",
"in",
"lexer_exts",
"if",
"(",
"not",
"le",
".",
"startswith",
"(",
"'*'",
")",
")",
"]",
"lexer_exts",
"=",
"[",
"le",
"[",
"1",
":",
"]",
"for",
"le",
"in",
"lexer_exts",
"if",
"le",
".",
"startswith",
"(",
"'*'",
")",
"]",
"lexer_exts",
"=",
"[",
"le",
"for",
"le",
"in",
"lexer_exts",
"if",
"(",
"not",
"le",
".",
"endswith",
"(",
"'_*'",
")",
")",
"]",
"extensions",
"=",
"(",
"(",
"extensions",
"+",
"list",
"(",
"lexer_exts",
")",
")",
"+",
"list",
"(",
"other_exts",
")",
")",
"return",
"sorted",
"(",
"list",
"(",
"set",
"(",
"extensions",
")",
")",
")"
] | return all file type extensions supported by pygments . | train | true |
39,987 | @pytest.fixture
def record_xml_property(request):
request.node.warn(code='C3', message='record_xml_property is an experimental feature')
xml = getattr(request.config, '_xml', None)
if (xml is not None):
node_reporter = xml.node_reporter(request.node.nodeid)
return node_reporter.add_property
else:
def add_property_noop(name, value):
pass
return add_property_noop
| [
"@",
"pytest",
".",
"fixture",
"def",
"record_xml_property",
"(",
"request",
")",
":",
"request",
".",
"node",
".",
"warn",
"(",
"code",
"=",
"'C3'",
",",
"message",
"=",
"'record_xml_property is an experimental feature'",
")",
"xml",
"=",
"getattr",
"(",
"request",
".",
"config",
",",
"'_xml'",
",",
"None",
")",
"if",
"(",
"xml",
"is",
"not",
"None",
")",
":",
"node_reporter",
"=",
"xml",
".",
"node_reporter",
"(",
"request",
".",
"node",
".",
"nodeid",
")",
"return",
"node_reporter",
".",
"add_property",
"else",
":",
"def",
"add_property_noop",
"(",
"name",
",",
"value",
")",
":",
"pass",
"return",
"add_property_noop"
] | add extra xml properties to the tag for the calling test . | train | false |
39,988 | def decipher_shift(msg, key, symbols=None):
return encipher_shift(msg, (- key), symbols)
| [
"def",
"decipher_shift",
"(",
"msg",
",",
"key",
",",
"symbols",
"=",
"None",
")",
":",
"return",
"encipher_shift",
"(",
"msg",
",",
"(",
"-",
"key",
")",
",",
"symbols",
")"
] | return the text by shifting the characters of msg to the left by the amount given by key . | train | false |
39,989 | def dump(object_, file_, parameters=None, use_cpickle=False, protocol=DEFAULT_PROTOCOL, **kwargs):
if use_cpickle:
pickler = cPickle.Pickler
else:
pickler = _PicklerWithWarning
with closing(tarfile.TarFile(fileobj=file_, mode='w')) as tar_file:
external_objects = {}
def _save_parameters(f):
renamer = _Renamer()
named_parameters = {renamer(p): p for p in parameters}
numpy.savez(f, **{n: p.get_value() for (n, p) in named_parameters.items()})
for (name, p) in named_parameters.items():
array_ = p.container.storage[0]
external_objects[id(array_)] = _mangle_parameter_name(p, name)
if parameters:
_taradd(_save_parameters, tar_file, '_parameters')
if (object_ is not None):
save_object = _SaveObject(pickler, object_, external_objects, protocol, **kwargs)
_taradd(save_object, tar_file, '_pkl')
| [
"def",
"dump",
"(",
"object_",
",",
"file_",
",",
"parameters",
"=",
"None",
",",
"use_cpickle",
"=",
"False",
",",
"protocol",
"=",
"DEFAULT_PROTOCOL",
",",
"**",
"kwargs",
")",
":",
"if",
"use_cpickle",
":",
"pickler",
"=",
"cPickle",
".",
"Pickler",
"else",
":",
"pickler",
"=",
"_PicklerWithWarning",
"with",
"closing",
"(",
"tarfile",
".",
"TarFile",
"(",
"fileobj",
"=",
"file_",
",",
"mode",
"=",
"'w'",
")",
")",
"as",
"tar_file",
":",
"external_objects",
"=",
"{",
"}",
"def",
"_save_parameters",
"(",
"f",
")",
":",
"renamer",
"=",
"_Renamer",
"(",
")",
"named_parameters",
"=",
"{",
"renamer",
"(",
"p",
")",
":",
"p",
"for",
"p",
"in",
"parameters",
"}",
"numpy",
".",
"savez",
"(",
"f",
",",
"**",
"{",
"n",
":",
"p",
".",
"get_value",
"(",
")",
"for",
"(",
"n",
",",
"p",
")",
"in",
"named_parameters",
".",
"items",
"(",
")",
"}",
")",
"for",
"(",
"name",
",",
"p",
")",
"in",
"named_parameters",
".",
"items",
"(",
")",
":",
"array_",
"=",
"p",
".",
"container",
".",
"storage",
"[",
"0",
"]",
"external_objects",
"[",
"id",
"(",
"array_",
")",
"]",
"=",
"_mangle_parameter_name",
"(",
"p",
",",
"name",
")",
"if",
"parameters",
":",
"_taradd",
"(",
"_save_parameters",
",",
"tar_file",
",",
"'_parameters'",
")",
"if",
"(",
"object_",
"is",
"not",
"None",
")",
":",
"save_object",
"=",
"_SaveObject",
"(",
"pickler",
",",
"object_",
",",
"external_objects",
",",
"protocol",
",",
"**",
"kwargs",
")",
"_taradd",
"(",
"save_object",
",",
"tar_file",
",",
"'_pkl'",
")"
] | print out a text representation of a code object . | train | false |
39,992 | def pot_for_column(cls, column, summary=False):
if summary:
return 'flavor'
elif column.info.get('ripped'):
return 'ripped'
elif column.name.endswith('effect'):
return 'effects'
else:
return 'misc'
| [
"def",
"pot_for_column",
"(",
"cls",
",",
"column",
",",
"summary",
"=",
"False",
")",
":",
"if",
"summary",
":",
"return",
"'flavor'",
"elif",
"column",
".",
"info",
".",
"get",
"(",
"'ripped'",
")",
":",
"return",
"'ripped'",
"elif",
"column",
".",
"name",
".",
"endswith",
"(",
"'effect'",
")",
":",
"return",
"'effects'",
"else",
":",
"return",
"'misc'"
] | translatable texts get categorized into different pot files to help translators prioritize . | train | false |
39,996 | def _set_custom_selection(params):
chs = params['fig_selection'].lasso.selection
if (len(chs) == 0):
return
labels = [l._text for l in params['fig_selection'].radio.labels]
inds = np.in1d(params['raw'].ch_names, chs)
params['selections']['Custom'] = np.where(inds)[0]
_set_radio_button(labels.index('Custom'), params=params)
| [
"def",
"_set_custom_selection",
"(",
"params",
")",
":",
"chs",
"=",
"params",
"[",
"'fig_selection'",
"]",
".",
"lasso",
".",
"selection",
"if",
"(",
"len",
"(",
"chs",
")",
"==",
"0",
")",
":",
"return",
"labels",
"=",
"[",
"l",
".",
"_text",
"for",
"l",
"in",
"params",
"[",
"'fig_selection'",
"]",
".",
"radio",
".",
"labels",
"]",
"inds",
"=",
"np",
".",
"in1d",
"(",
"params",
"[",
"'raw'",
"]",
".",
"ch_names",
",",
"chs",
")",
"params",
"[",
"'selections'",
"]",
"[",
"'Custom'",
"]",
"=",
"np",
".",
"where",
"(",
"inds",
")",
"[",
"0",
"]",
"_set_radio_button",
"(",
"labels",
".",
"index",
"(",
"'Custom'",
")",
",",
"params",
"=",
"params",
")"
] | set custom selection by lasso selector . | train | false |
39,997 | def _parse_credentials(username, password, database, options):
mechanism = options.get('authmechanism', 'DEFAULT')
if ((username is None) and (mechanism != 'MONGODB-X509')):
return None
source = options.get('authsource', (database or 'admin'))
return _build_credentials_tuple(mechanism, source, username, password, options)
| [
"def",
"_parse_credentials",
"(",
"username",
",",
"password",
",",
"database",
",",
"options",
")",
":",
"mechanism",
"=",
"options",
".",
"get",
"(",
"'authmechanism'",
",",
"'DEFAULT'",
")",
"if",
"(",
"(",
"username",
"is",
"None",
")",
"and",
"(",
"mechanism",
"!=",
"'MONGODB-X509'",
")",
")",
":",
"return",
"None",
"source",
"=",
"options",
".",
"get",
"(",
"'authsource'",
",",
"(",
"database",
"or",
"'admin'",
")",
")",
"return",
"_build_credentials_tuple",
"(",
"mechanism",
",",
"source",
",",
"username",
",",
"password",
",",
"options",
")"
] | parse authentication credentials . | train | true |
39,998 | @utils.synchronized(SERIAL_LOCK)
def acquire_port(host):
(start, stop) = _get_port_range()
for port in six.moves.range(start, stop):
if ((host, port) in ALLOCATED_PORTS):
continue
try:
_verify_port(host, port)
ALLOCATED_PORTS.add((host, port))
return port
except exception.SocketPortInUseException as e:
LOG.warning(e.format_message())
raise exception.SocketPortRangeExhaustedException(host=host)
| [
"@",
"utils",
".",
"synchronized",
"(",
"SERIAL_LOCK",
")",
"def",
"acquire_port",
"(",
"host",
")",
":",
"(",
"start",
",",
"stop",
")",
"=",
"_get_port_range",
"(",
")",
"for",
"port",
"in",
"six",
".",
"moves",
".",
"range",
"(",
"start",
",",
"stop",
")",
":",
"if",
"(",
"(",
"host",
",",
"port",
")",
"in",
"ALLOCATED_PORTS",
")",
":",
"continue",
"try",
":",
"_verify_port",
"(",
"host",
",",
"port",
")",
"ALLOCATED_PORTS",
".",
"add",
"(",
"(",
"host",
",",
"port",
")",
")",
"return",
"port",
"except",
"exception",
".",
"SocketPortInUseException",
"as",
"e",
":",
"LOG",
".",
"warning",
"(",
"e",
".",
"format_message",
"(",
")",
")",
"raise",
"exception",
".",
"SocketPortRangeExhaustedException",
"(",
"host",
"=",
"host",
")"
] | returns a free tcp port on host . | train | false |
39,999 | def get_spinner(msg):
s = spinner.Spinner()
log.info(msg, extra=dict(__nonewline__=True))
s.start()
return s
| [
"def",
"get_spinner",
"(",
"msg",
")",
":",
"s",
"=",
"spinner",
".",
"Spinner",
"(",
")",
"log",
".",
"info",
"(",
"msg",
",",
"extra",
"=",
"dict",
"(",
"__nonewline__",
"=",
"True",
")",
")",
"s",
".",
"start",
"(",
")",
"return",
"s"
] | logs a status msg . | train | false |
40,001 | def apiname(funcname):
if funcname.startswith('gl'):
return funcname
elif funcname.startswith('_'):
return (('_gl' + funcname[1].upper()) + funcname[2:])
else:
return (('gl' + funcname[0].upper()) + funcname[1:])
| [
"def",
"apiname",
"(",
"funcname",
")",
":",
"if",
"funcname",
".",
"startswith",
"(",
"'gl'",
")",
":",
"return",
"funcname",
"elif",
"funcname",
".",
"startswith",
"(",
"'_'",
")",
":",
"return",
"(",
"(",
"'_gl'",
"+",
"funcname",
"[",
"1",
"]",
".",
"upper",
"(",
")",
")",
"+",
"funcname",
"[",
"2",
":",
"]",
")",
"else",
":",
"return",
"(",
"(",
"'gl'",
"+",
"funcname",
"[",
"0",
"]",
".",
"upper",
"(",
")",
")",
"+",
"funcname",
"[",
"1",
":",
"]",
")"
] | define what name the api uses . | train | false |
40,002 | def _get_text(nodes):
return ''.join([n.data for n in nodes if (n.nodeType == n.TEXT_NODE)])
| [
"def",
"_get_text",
"(",
"nodes",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"n",
".",
"data",
"for",
"n",
"in",
"nodes",
"if",
"(",
"n",
".",
"nodeType",
"==",
"n",
".",
"TEXT_NODE",
")",
"]",
")"
] | dom utility routine for getting contents of text nodes . | train | false |
40,003 | def p_unary_expression_1(t):
pass
| [
"def",
"p_unary_expression_1",
"(",
"t",
")",
":",
"pass"
] | unary_expression : postfix_expression . | train | false |
40,004 | def guess_all_extensions(type, strict=True):
init()
return guess_all_extensions(type, strict)
| [
"def",
"guess_all_extensions",
"(",
"type",
",",
"strict",
"=",
"True",
")",
":",
"init",
"(",
")",
"return",
"guess_all_extensions",
"(",
"type",
",",
"strict",
")"
] | guess the extensions for a file based on its mime type . | train | false |
40,005 | @cleanup
def test_determinism_all():
_determinism_check(format=u'ps')
| [
"@",
"cleanup",
"def",
"test_determinism_all",
"(",
")",
":",
"_determinism_check",
"(",
"format",
"=",
"u'ps'",
")"
] | test for reproducible ps output . | train | false |
40,006 | def obj_attrs(msg_):
if isinstance(msg_, StringifyMixin):
itr = msg_.stringify_attrs()
else:
itr = obj_python_attrs(msg_)
for (k, v) in itr:
if (k.endswith('_') and (k[:(-1)] in _RESERVED_KEYWORD)):
assert isinstance(msg_, StringifyMixin)
k = k[:(-1)]
(yield (k, v))
| [
"def",
"obj_attrs",
"(",
"msg_",
")",
":",
"if",
"isinstance",
"(",
"msg_",
",",
"StringifyMixin",
")",
":",
"itr",
"=",
"msg_",
".",
"stringify_attrs",
"(",
")",
"else",
":",
"itr",
"=",
"obj_python_attrs",
"(",
"msg_",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"itr",
":",
"if",
"(",
"k",
".",
"endswith",
"(",
"'_'",
")",
"and",
"(",
"k",
"[",
":",
"(",
"-",
"1",
")",
"]",
"in",
"_RESERVED_KEYWORD",
")",
")",
":",
"assert",
"isinstance",
"(",
"msg_",
",",
"StringifyMixin",
")",
"k",
"=",
"k",
"[",
":",
"(",
"-",
"1",
")",
"]",
"(",
"yield",
"(",
"k",
",",
"v",
")",
")"
] | similar to obj_python_attrs() but deals with python reserved keywords . | train | true |
40,008 | @removals.remove(message='keystoneclient auth plugins are deprecated. Use keystoneauth.', version='2.1.0', removal_version='3.0.0')
def get_available_plugin_names():
mgr = stevedore.ExtensionManager(namespace=PLUGIN_NAMESPACE, invoke_on_load=False)
return frozenset(mgr.names())
| [
"@",
"removals",
".",
"remove",
"(",
"message",
"=",
"'keystoneclient auth plugins are deprecated. Use keystoneauth.'",
",",
"version",
"=",
"'2.1.0'",
",",
"removal_version",
"=",
"'3.0.0'",
")",
"def",
"get_available_plugin_names",
"(",
")",
":",
"mgr",
"=",
"stevedore",
".",
"ExtensionManager",
"(",
"namespace",
"=",
"PLUGIN_NAMESPACE",
",",
"invoke_on_load",
"=",
"False",
")",
"return",
"frozenset",
"(",
"mgr",
".",
"names",
"(",
")",
")"
] | get the names of all the plugins that are available on the system . | train | false |
40,011 | def get_ip_nonlocal_bind(namespace=None):
cmd = ['sysctl', '-bn', IP_NONLOCAL_BIND]
ip_wrapper = IPWrapper(namespace)
return int(ip_wrapper.netns.execute(cmd, run_as_root=True))
| [
"def",
"get_ip_nonlocal_bind",
"(",
"namespace",
"=",
"None",
")",
":",
"cmd",
"=",
"[",
"'sysctl'",
",",
"'-bn'",
",",
"IP_NONLOCAL_BIND",
"]",
"ip_wrapper",
"=",
"IPWrapper",
"(",
"namespace",
")",
"return",
"int",
"(",
"ip_wrapper",
".",
"netns",
".",
"execute",
"(",
"cmd",
",",
"run_as_root",
"=",
"True",
")",
")"
] | get kernel option value of ip_nonlocal_bind in given namespace . | train | false |
40,012 | def find_available_plugins(loaded=False):
active_plugins = set()
for plugin_func in plugin_store.values():
for (plugin, func) in plugin_func:
active_plugins.add(plugin)
d = {}
for plugin in plugin_provides:
if ((not loaded) or (plugin in active_plugins)):
d[plugin] = [f for f in plugin_provides[plugin] if (not f.startswith('_'))]
return d
| [
"def",
"find_available_plugins",
"(",
"loaded",
"=",
"False",
")",
":",
"active_plugins",
"=",
"set",
"(",
")",
"for",
"plugin_func",
"in",
"plugin_store",
".",
"values",
"(",
")",
":",
"for",
"(",
"plugin",
",",
"func",
")",
"in",
"plugin_func",
":",
"active_plugins",
".",
"add",
"(",
"plugin",
")",
"d",
"=",
"{",
"}",
"for",
"plugin",
"in",
"plugin_provides",
":",
"if",
"(",
"(",
"not",
"loaded",
")",
"or",
"(",
"plugin",
"in",
"active_plugins",
")",
")",
":",
"d",
"[",
"plugin",
"]",
"=",
"[",
"f",
"for",
"f",
"in",
"plugin_provides",
"[",
"plugin",
"]",
"if",
"(",
"not",
"f",
".",
"startswith",
"(",
"'_'",
")",
")",
"]",
"return",
"d"
] | list available plugins . | train | false |
40,013 | def decode_deflate(content):
try:
try:
return zlib.decompress(content)
except zlib.error:
return zlib.decompress(content, (-15))
except zlib.error:
return None
| [
"def",
"decode_deflate",
"(",
"content",
")",
":",
"try",
":",
"try",
":",
"return",
"zlib",
".",
"decompress",
"(",
"content",
")",
"except",
"zlib",
".",
"error",
":",
"return",
"zlib",
".",
"decompress",
"(",
"content",
",",
"(",
"-",
"15",
")",
")",
"except",
"zlib",
".",
"error",
":",
"return",
"None"
] | returns decompressed data for deflate . | train | false |
40,014 | def average_precision_score(y_true, y_score, average='macro', sample_weight=None):
def _binary_average_precision(y_true, y_score, sample_weight=None):
(precision, recall, thresholds) = precision_recall_curve(y_true, y_score, sample_weight=sample_weight)
return auc(recall, precision)
return _average_binary_score(_binary_average_precision, y_true, y_score, average, sample_weight=sample_weight)
| [
"def",
"average_precision_score",
"(",
"y_true",
",",
"y_score",
",",
"average",
"=",
"'macro'",
",",
"sample_weight",
"=",
"None",
")",
":",
"def",
"_binary_average_precision",
"(",
"y_true",
",",
"y_score",
",",
"sample_weight",
"=",
"None",
")",
":",
"(",
"precision",
",",
"recall",
",",
"thresholds",
")",
"=",
"precision_recall_curve",
"(",
"y_true",
",",
"y_score",
",",
"sample_weight",
"=",
"sample_weight",
")",
"return",
"auc",
"(",
"recall",
",",
"precision",
")",
"return",
"_average_binary_score",
"(",
"_binary_average_precision",
",",
"y_true",
",",
"y_score",
",",
"average",
",",
"sample_weight",
"=",
"sample_weight",
")"
] | compute average precision from prediction scores this score corresponds to the area under the precision-recall curve . | train | false |
40,015 | @printing_func
def extract_scala_imports(source_files_content):
packages = set()
import_re = re.compile(u'^import ([^;]*);?$')
for filecontent in source_files_content.dependencies:
for line in filecontent.content.splitlines():
match = import_re.search(line)
if match:
packages.add(match.group(1).rsplit(u'.', 1)[0])
return ImportedJVMPackages([JVMPackageName(p) for p in packages])
| [
"@",
"printing_func",
"def",
"extract_scala_imports",
"(",
"source_files_content",
")",
":",
"packages",
"=",
"set",
"(",
")",
"import_re",
"=",
"re",
".",
"compile",
"(",
"u'^import ([^;]*);?$'",
")",
"for",
"filecontent",
"in",
"source_files_content",
".",
"dependencies",
":",
"for",
"line",
"in",
"filecontent",
".",
"content",
".",
"splitlines",
"(",
")",
":",
"match",
"=",
"import_re",
".",
"search",
"(",
"line",
")",
"if",
"match",
":",
"packages",
".",
"add",
"(",
"match",
".",
"group",
"(",
"1",
")",
".",
"rsplit",
"(",
"u'.'",
",",
"1",
")",
"[",
"0",
"]",
")",
"return",
"ImportedJVMPackages",
"(",
"[",
"JVMPackageName",
"(",
"p",
")",
"for",
"p",
"in",
"packages",
"]",
")"
] | a toy example of dependency inference . | train | false |
40,016 | def test_pdf1():
r = S3Request(prefix='pr', name='person')
T = current.T
from s3.s3export import S3Exporter
exporter = S3Exporter().pdf
return exporter(r.resource, request=r, method='list', pdf_title=T('PDF Test Card I'), pdf_header=header, pdf_callback=body_1, pdf_footer=footer)
| [
"def",
"test_pdf1",
"(",
")",
":",
"r",
"=",
"S3Request",
"(",
"prefix",
"=",
"'pr'",
",",
"name",
"=",
"'person'",
")",
"T",
"=",
"current",
".",
"T",
"from",
"s3",
".",
"s3export",
"import",
"S3Exporter",
"exporter",
"=",
"S3Exporter",
"(",
")",
".",
"pdf",
"return",
"exporter",
"(",
"r",
".",
"resource",
",",
"request",
"=",
"r",
",",
"method",
"=",
"'list'",
",",
"pdf_title",
"=",
"T",
"(",
"'PDF Test Card I'",
")",
",",
"pdf_header",
"=",
"header",
",",
"pdf_callback",
"=",
"body_1",
",",
"pdf_footer",
"=",
"footer",
")"
] | generate a test pdf that will demonstrate s3rl_pdf functionality . | train | false |
40,018 | def test_scriptinfo(test_apps):
obj = ScriptInfo(app_import_path='cliapp.app:testapp')
assert (obj.load_app().name == 'testapp')
assert (obj.load_app().name == 'testapp')
def create_app(info):
return Flask('createapp')
obj = ScriptInfo(create_app=create_app)
app = obj.load_app()
assert (app.name == 'createapp')
assert (obj.load_app() == app)
| [
"def",
"test_scriptinfo",
"(",
"test_apps",
")",
":",
"obj",
"=",
"ScriptInfo",
"(",
"app_import_path",
"=",
"'cliapp.app:testapp'",
")",
"assert",
"(",
"obj",
".",
"load_app",
"(",
")",
".",
"name",
"==",
"'testapp'",
")",
"assert",
"(",
"obj",
".",
"load_app",
"(",
")",
".",
"name",
"==",
"'testapp'",
")",
"def",
"create_app",
"(",
"info",
")",
":",
"return",
"Flask",
"(",
"'createapp'",
")",
"obj",
"=",
"ScriptInfo",
"(",
"create_app",
"=",
"create_app",
")",
"app",
"=",
"obj",
".",
"load_app",
"(",
")",
"assert",
"(",
"app",
".",
"name",
"==",
"'createapp'",
")",
"assert",
"(",
"obj",
".",
"load_app",
"(",
")",
"==",
"app",
")"
] | test of scriptinfo . | train | false |
40,019 | def detect_properties(path):
vision_client = vision.Client()
with io.open(path, 'rb') as image_file:
content = image_file.read()
image = vision_client.image(content=content)
properties = image.detect_properties()
print 'Properties:'
for prop in properties:
color = prop.colors[0]
print 'fraction: {}'.format(color.pixel_fraction)
print 'r: {}'.format(color.color.red)
print 'g: {}'.format(color.color.green)
print 'b: {}'.format(color.color.blue)
| [
"def",
"detect_properties",
"(",
"path",
")",
":",
"vision_client",
"=",
"vision",
".",
"Client",
"(",
")",
"with",
"io",
".",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"image_file",
":",
"content",
"=",
"image_file",
".",
"read",
"(",
")",
"image",
"=",
"vision_client",
".",
"image",
"(",
"content",
"=",
"content",
")",
"properties",
"=",
"image",
".",
"detect_properties",
"(",
")",
"print",
"'Properties:'",
"for",
"prop",
"in",
"properties",
":",
"color",
"=",
"prop",
".",
"colors",
"[",
"0",
"]",
"print",
"'fraction: {}'",
".",
"format",
"(",
"color",
".",
"pixel_fraction",
")",
"print",
"'r: {}'",
".",
"format",
"(",
"color",
".",
"color",
".",
"red",
")",
"print",
"'g: {}'",
".",
"format",
"(",
"color",
".",
"color",
".",
"green",
")",
"print",
"'b: {}'",
".",
"format",
"(",
"color",
".",
"color",
".",
"blue",
")"
] | detects image properties in the file . | train | false |
40,020 | def _snapper_pre(opts, jid):
snapper_pre = None
try:
if ((not opts['test']) and __opts__.get('snapper_states')):
snapper_pre = __salt__['snapper.create_snapshot'](config=__opts__.get('snapper_states_config', 'root'), snapshot_type='pre', description='Salt State run for jid {0}'.format(jid), __pub_jid=jid)
except Exception:
log.error('Failed to create snapper pre snapshot for jid: {0}'.format(jid))
return snapper_pre
| [
"def",
"_snapper_pre",
"(",
"opts",
",",
"jid",
")",
":",
"snapper_pre",
"=",
"None",
"try",
":",
"if",
"(",
"(",
"not",
"opts",
"[",
"'test'",
"]",
")",
"and",
"__opts__",
".",
"get",
"(",
"'snapper_states'",
")",
")",
":",
"snapper_pre",
"=",
"__salt__",
"[",
"'snapper.create_snapshot'",
"]",
"(",
"config",
"=",
"__opts__",
".",
"get",
"(",
"'snapper_states_config'",
",",
"'root'",
")",
",",
"snapshot_type",
"=",
"'pre'",
",",
"description",
"=",
"'Salt State run for jid {0}'",
".",
"format",
"(",
"jid",
")",
",",
"__pub_jid",
"=",
"jid",
")",
"except",
"Exception",
":",
"log",
".",
"error",
"(",
"'Failed to create snapper pre snapshot for jid: {0}'",
".",
"format",
"(",
"jid",
")",
")",
"return",
"snapper_pre"
] | create a snapper pre snapshot . | train | true |
40,021 | def test_oldstyle_eq():
class x:
pass
inst = type(x())
global cmpCalled
cmpCalled = False
class C:
def __init__(self, value):
self.value = value
def __cmp__(self, other):
global cmpCalled
cmpCalled = True
return (self.value - other.value)
class D:
def __init__(self, value):
self.value = value
def __cmp__(self, other):
global cmpCalled
cmpCalled = True
return (self.value - other.value)
class C2(C, ):
pass
class D2(D, ):
pass
AreEqual(inst.__eq__(C(3.0), C(4.5)), NotImplemented)
AreEqual(inst.__eq__(C(3.0), C2(4.5)), NotImplemented)
AreEqual(inst.__eq__(C(3.0), D(4.5)), NotImplemented)
AreEqual(cmpCalled, False)
| [
"def",
"test_oldstyle_eq",
"(",
")",
":",
"class",
"x",
":",
"pass",
"inst",
"=",
"type",
"(",
"x",
"(",
")",
")",
"global",
"cmpCalled",
"cmpCalled",
"=",
"False",
"class",
"C",
":",
"def",
"__init__",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"value",
"=",
"value",
"def",
"__cmp__",
"(",
"self",
",",
"other",
")",
":",
"global",
"cmpCalled",
"cmpCalled",
"=",
"True",
"return",
"(",
"self",
".",
"value",
"-",
"other",
".",
"value",
")",
"class",
"D",
":",
"def",
"__init__",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"value",
"=",
"value",
"def",
"__cmp__",
"(",
"self",
",",
"other",
")",
":",
"global",
"cmpCalled",
"cmpCalled",
"=",
"True",
"return",
"(",
"self",
".",
"value",
"-",
"other",
".",
"value",
")",
"class",
"C2",
"(",
"C",
",",
")",
":",
"pass",
"class",
"D2",
"(",
"D",
",",
")",
":",
"pass",
"AreEqual",
"(",
"inst",
".",
"__eq__",
"(",
"C",
"(",
"3.0",
")",
",",
"C",
"(",
"4.5",
")",
")",
",",
"NotImplemented",
")",
"AreEqual",
"(",
"inst",
".",
"__eq__",
"(",
"C",
"(",
"3.0",
")",
",",
"C2",
"(",
"4.5",
")",
")",
",",
"NotImplemented",
")",
"AreEqual",
"(",
"inst",
".",
"__eq__",
"(",
"C",
"(",
"3.0",
")",
",",
"D",
"(",
"4.5",
")",
")",
",",
"NotImplemented",
")",
"AreEqual",
"(",
"cmpCalled",
",",
"False",
")"
] | old style __eq__ shouldnt call __cmp__ . | train | false |
40,022 | def figlegend(*args, **kwargs):
return gcf().legend(*args, **kwargs)
| [
"def",
"figlegend",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"gcf",
"(",
")",
".",
"legend",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | place a legend in the figure . | train | false |
40,023 | def activate_pipeline(pipeline_id, region=None, key=None, keyid=None, profile=None):
client = _get_client(region, key, keyid, profile)
r = {}
try:
client.activate_pipeline(pipelineId=pipeline_id)
r['result'] = True
except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e:
r['error'] = str(e)
return r
| [
"def",
"activate_pipeline",
"(",
"pipeline_id",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"client",
"=",
"_get_client",
"(",
"region",
",",
"key",
",",
"keyid",
",",
"profile",
")",
"r",
"=",
"{",
"}",
"try",
":",
"client",
".",
"activate_pipeline",
"(",
"pipelineId",
"=",
"pipeline_id",
")",
"r",
"[",
"'result'",
"]",
"=",
"True",
"except",
"(",
"botocore",
".",
"exceptions",
".",
"BotoCoreError",
",",
"botocore",
".",
"exceptions",
".",
"ClientError",
")",
"as",
"e",
":",
"r",
"[",
"'error'",
"]",
"=",
"str",
"(",
"e",
")",
"return",
"r"
] | start processing pipeline tasks . | train | true |
40,024 | def ball(radius, dtype=np.uint8):
n = ((2 * radius) + 1)
(Z, Y, X) = np.mgrid[(- radius):radius:(n * 1j), (- radius):radius:(n * 1j), (- radius):radius:(n * 1j)]
s = (((X ** 2) + (Y ** 2)) + (Z ** 2))
return np.array((s <= (radius * radius)), dtype=dtype)
| [
"def",
"ball",
"(",
"radius",
",",
"dtype",
"=",
"np",
".",
"uint8",
")",
":",
"n",
"=",
"(",
"(",
"2",
"*",
"radius",
")",
"+",
"1",
")",
"(",
"Z",
",",
"Y",
",",
"X",
")",
"=",
"np",
".",
"mgrid",
"[",
"(",
"-",
"radius",
")",
":",
"radius",
":",
"(",
"n",
"*",
"1j",
")",
",",
"(",
"-",
"radius",
")",
":",
"radius",
":",
"(",
"n",
"*",
"1j",
")",
",",
"(",
"-",
"radius",
")",
":",
"radius",
":",
"(",
"n",
"*",
"1j",
")",
"]",
"s",
"=",
"(",
"(",
"(",
"X",
"**",
"2",
")",
"+",
"(",
"Y",
"**",
"2",
")",
")",
"+",
"(",
"Z",
"**",
"2",
")",
")",
"return",
"np",
".",
"array",
"(",
"(",
"s",
"<=",
"(",
"radius",
"*",
"radius",
")",
")",
",",
"dtype",
"=",
"dtype",
")"
] | generates a ball-shaped structuring element . | train | false |
40,025 | def rackspace_provisioner(username, key, region, keyname):
from libcloud.compute.providers import get_driver, Provider
driver = get_driver(Provider.RACKSPACE)(key=username, secret=key, region=region)
provisioner = LibcloudProvisioner(driver=driver, keyname=keyname, image_names=IMAGE_NAMES, create_node_arguments=(lambda **kwargs: {'ex_config_drive': 'true'}), provision=provision_rackspace, default_size='performance1-8', get_default_user=get_default_username)
return provisioner
| [
"def",
"rackspace_provisioner",
"(",
"username",
",",
"key",
",",
"region",
",",
"keyname",
")",
":",
"from",
"libcloud",
".",
"compute",
".",
"providers",
"import",
"get_driver",
",",
"Provider",
"driver",
"=",
"get_driver",
"(",
"Provider",
".",
"RACKSPACE",
")",
"(",
"key",
"=",
"username",
",",
"secret",
"=",
"key",
",",
"region",
"=",
"region",
")",
"provisioner",
"=",
"LibcloudProvisioner",
"(",
"driver",
"=",
"driver",
",",
"keyname",
"=",
"keyname",
",",
"image_names",
"=",
"IMAGE_NAMES",
",",
"create_node_arguments",
"=",
"(",
"lambda",
"**",
"kwargs",
":",
"{",
"'ex_config_drive'",
":",
"'true'",
"}",
")",
",",
"provision",
"=",
"provision_rackspace",
",",
"default_size",
"=",
"'performance1-8'",
",",
"get_default_user",
"=",
"get_default_username",
")",
"return",
"provisioner"
] | create a libcloudprovisioner for provisioning nodes on rackspace . | train | false |
40,027 | def run_on_app_servers(command):
log.info(('Running %s on app servers' % command))
ret_val = 0
if getattr(settings, 'MULTIPLE_APP_SERVERS', None):
for server in settings.MULTIPLE_APP_SERVERS:
ret = os.system(('ssh %s@%s %s' % (SYNC_USER, server, command)))
if (ret != 0):
ret_val = ret
return ret_val
else:
ret = os.system(command)
return ret
| [
"def",
"run_on_app_servers",
"(",
"command",
")",
":",
"log",
".",
"info",
"(",
"(",
"'Running %s on app servers'",
"%",
"command",
")",
")",
"ret_val",
"=",
"0",
"if",
"getattr",
"(",
"settings",
",",
"'MULTIPLE_APP_SERVERS'",
",",
"None",
")",
":",
"for",
"server",
"in",
"settings",
".",
"MULTIPLE_APP_SERVERS",
":",
"ret",
"=",
"os",
".",
"system",
"(",
"(",
"'ssh %s@%s %s'",
"%",
"(",
"SYNC_USER",
",",
"server",
",",
"command",
")",
")",
")",
"if",
"(",
"ret",
"!=",
"0",
")",
":",
"ret_val",
"=",
"ret",
"return",
"ret_val",
"else",
":",
"ret",
"=",
"os",
".",
"system",
"(",
"command",
")",
"return",
"ret"
] | a helper to copy a single file across app servers . | train | false |
40,028 | def job_get_by_idx(job_idx):
try:
job = Job.objects.get(pk=job_idx)
return job
except Job.DoesNotExist:
return None
| [
"def",
"job_get_by_idx",
"(",
"job_idx",
")",
":",
"try",
":",
"job",
"=",
"Job",
".",
"objects",
".",
"get",
"(",
"pk",
"=",
"job_idx",
")",
"return",
"job",
"except",
"Job",
".",
"DoesNotExist",
":",
"return",
"None"
] | return a job based on its idx . | train | false |
40,029 | def collector():
setuptools_incompat = ('report', 'prepareTest', 'prepareTestLoader', 'prepareTestRunner', 'setOutputStream')
plugins = RestrictedPluginManager(exclude=setuptools_incompat)
conf = Config(files=all_config_files(), plugins=plugins)
conf.configure(argv=['collector'])
loader = defaultTestLoader(conf)
if conf.testNames:
suite = loader.loadTestsFromNames(conf.testNames)
else:
suite = loader.loadTestsFromNames(('.',))
return FinalizingSuiteWrapper(suite, plugins.finalize)
| [
"def",
"collector",
"(",
")",
":",
"setuptools_incompat",
"=",
"(",
"'report'",
",",
"'prepareTest'",
",",
"'prepareTestLoader'",
",",
"'prepareTestRunner'",
",",
"'setOutputStream'",
")",
"plugins",
"=",
"RestrictedPluginManager",
"(",
"exclude",
"=",
"setuptools_incompat",
")",
"conf",
"=",
"Config",
"(",
"files",
"=",
"all_config_files",
"(",
")",
",",
"plugins",
"=",
"plugins",
")",
"conf",
".",
"configure",
"(",
"argv",
"=",
"[",
"'collector'",
"]",
")",
"loader",
"=",
"defaultTestLoader",
"(",
"conf",
")",
"if",
"conf",
".",
"testNames",
":",
"suite",
"=",
"loader",
".",
"loadTestsFromNames",
"(",
"conf",
".",
"testNames",
")",
"else",
":",
"suite",
"=",
"loader",
".",
"loadTestsFromNames",
"(",
"(",
"'.'",
",",
")",
")",
"return",
"FinalizingSuiteWrapper",
"(",
"suite",
",",
"plugins",
".",
"finalize",
")"
] | testsuite replacement entry point . | train | true |
40,030 | def list_keys(hive, key=None, use_32bit_registry=False):
if PY2:
local_hive = _mbcs_to_unicode(hive)
local_key = _unicode_to_mbcs(key)
else:
local_hive = hive
local_key = key
registry = Registry()
hkey = registry.hkeys[local_hive]
access_mask = registry.registry_32[use_32bit_registry]
subkeys = []
try:
handle = _winreg.OpenKey(hkey, local_key, 0, access_mask)
for i in range(_winreg.QueryInfoKey(handle)[0]):
subkey = _winreg.EnumKey(handle, i)
if PY2:
subkeys.append(_mbcs_to_unicode(subkey))
else:
subkeys.append(subkey)
handle.Close()
except WindowsError as exc:
log.debug(exc)
log.debug(u'Cannot find key: {0}\\{1}'.format(hive, key))
return (False, u'Cannot find key: {0}\\{1}'.format(hive, key))
return subkeys
| [
"def",
"list_keys",
"(",
"hive",
",",
"key",
"=",
"None",
",",
"use_32bit_registry",
"=",
"False",
")",
":",
"if",
"PY2",
":",
"local_hive",
"=",
"_mbcs_to_unicode",
"(",
"hive",
")",
"local_key",
"=",
"_unicode_to_mbcs",
"(",
"key",
")",
"else",
":",
"local_hive",
"=",
"hive",
"local_key",
"=",
"key",
"registry",
"=",
"Registry",
"(",
")",
"hkey",
"=",
"registry",
".",
"hkeys",
"[",
"local_hive",
"]",
"access_mask",
"=",
"registry",
".",
"registry_32",
"[",
"use_32bit_registry",
"]",
"subkeys",
"=",
"[",
"]",
"try",
":",
"handle",
"=",
"_winreg",
".",
"OpenKey",
"(",
"hkey",
",",
"local_key",
",",
"0",
",",
"access_mask",
")",
"for",
"i",
"in",
"range",
"(",
"_winreg",
".",
"QueryInfoKey",
"(",
"handle",
")",
"[",
"0",
"]",
")",
":",
"subkey",
"=",
"_winreg",
".",
"EnumKey",
"(",
"handle",
",",
"i",
")",
"if",
"PY2",
":",
"subkeys",
".",
"append",
"(",
"_mbcs_to_unicode",
"(",
"subkey",
")",
")",
"else",
":",
"subkeys",
".",
"append",
"(",
"subkey",
")",
"handle",
".",
"Close",
"(",
")",
"except",
"WindowsError",
"as",
"exc",
":",
"log",
".",
"debug",
"(",
"exc",
")",
"log",
".",
"debug",
"(",
"u'Cannot find key: {0}\\\\{1}'",
".",
"format",
"(",
"hive",
",",
"key",
")",
")",
"return",
"(",
"False",
",",
"u'Cannot find key: {0}\\\\{1}'",
".",
"format",
"(",
"hive",
",",
"key",
")",
")",
"return",
"subkeys"
] | list the keys available . | train | false |
40,032 | def create_expected_df_for_factor_compute(start_date, sids, tuples, end_date):
df = pd.DataFrame(tuples, columns=[SID_FIELD_NAME, 'estimate', 'knowledge_date'])
df = df.pivot_table(columns=SID_FIELD_NAME, values='estimate', index='knowledge_date')
df = df.reindex(pd.date_range(start_date, end_date))
df.index = df.index.rename('knowledge_date')
df['at_date'] = end_date.tz_localize('utc')
df = df.set_index(['at_date', df.index.tz_localize('utc')]).ffill()
new_sids = (set(sids) - set(df.columns))
df = df.reindex(columns=df.columns.union(new_sids))
return df
| [
"def",
"create_expected_df_for_factor_compute",
"(",
"start_date",
",",
"sids",
",",
"tuples",
",",
"end_date",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"tuples",
",",
"columns",
"=",
"[",
"SID_FIELD_NAME",
",",
"'estimate'",
",",
"'knowledge_date'",
"]",
")",
"df",
"=",
"df",
".",
"pivot_table",
"(",
"columns",
"=",
"SID_FIELD_NAME",
",",
"values",
"=",
"'estimate'",
",",
"index",
"=",
"'knowledge_date'",
")",
"df",
"=",
"df",
".",
"reindex",
"(",
"pd",
".",
"date_range",
"(",
"start_date",
",",
"end_date",
")",
")",
"df",
".",
"index",
"=",
"df",
".",
"index",
".",
"rename",
"(",
"'knowledge_date'",
")",
"df",
"[",
"'at_date'",
"]",
"=",
"end_date",
".",
"tz_localize",
"(",
"'utc'",
")",
"df",
"=",
"df",
".",
"set_index",
"(",
"[",
"'at_date'",
",",
"df",
".",
"index",
".",
"tz_localize",
"(",
"'utc'",
")",
"]",
")",
".",
"ffill",
"(",
")",
"new_sids",
"=",
"(",
"set",
"(",
"sids",
")",
"-",
"set",
"(",
"df",
".",
"columns",
")",
")",
"df",
"=",
"df",
".",
"reindex",
"(",
"columns",
"=",
"df",
".",
"columns",
".",
"union",
"(",
"new_sids",
")",
")",
"return",
"df"
] | given a list of tuples of new data we get for each sid on each critical date . | train | false |
40,034 | def remove_gateway_router(router, profile=None):
conn = _auth(profile)
return conn.remove_gateway_router(router)
| [
"def",
"remove_gateway_router",
"(",
"router",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_auth",
"(",
"profile",
")",
"return",
"conn",
".",
"remove_gateway_router",
"(",
"router",
")"
] | removes an external network gateway from the specified router cli example: . | train | false |
40,035 | def _CopySortOptionsToProtocolBuffer(sort_options, params):
for expression in sort_options.expressions:
sort_spec_pb = params.add_sort_spec()
_CopySortExpressionToProtocolBuffer(expression, sort_spec_pb)
if sort_options.match_scorer:
scorer_spec = params.mutable_scorer_spec()
_CopyMatchScorerToScorerSpecProtocolBuffer(sort_options.match_scorer, sort_options.limit, scorer_spec)
scorer_spec.set_limit(sort_options.limit)
else:
params.mutable_scorer_spec().set_limit(sort_options.limit)
| [
"def",
"_CopySortOptionsToProtocolBuffer",
"(",
"sort_options",
",",
"params",
")",
":",
"for",
"expression",
"in",
"sort_options",
".",
"expressions",
":",
"sort_spec_pb",
"=",
"params",
".",
"add_sort_spec",
"(",
")",
"_CopySortExpressionToProtocolBuffer",
"(",
"expression",
",",
"sort_spec_pb",
")",
"if",
"sort_options",
".",
"match_scorer",
":",
"scorer_spec",
"=",
"params",
".",
"mutable_scorer_spec",
"(",
")",
"_CopyMatchScorerToScorerSpecProtocolBuffer",
"(",
"sort_options",
".",
"match_scorer",
",",
"sort_options",
".",
"limit",
",",
"scorer_spec",
")",
"scorer_spec",
".",
"set_limit",
"(",
"sort_options",
".",
"limit",
")",
"else",
":",
"params",
".",
"mutable_scorer_spec",
"(",
")",
".",
"set_limit",
"(",
"sort_options",
".",
"limit",
")"
] | copies the sortoptions into the searchparams proto buf . | train | false |
40,036 | def worker_claim_for_cleanup(context, claimer_id, orm_worker):
return IMPL.worker_claim_for_cleanup(context, claimer_id, orm_worker)
| [
"def",
"worker_claim_for_cleanup",
"(",
"context",
",",
"claimer_id",
",",
"orm_worker",
")",
":",
"return",
"IMPL",
".",
"worker_claim_for_cleanup",
"(",
"context",
",",
"claimer_id",
",",
"orm_worker",
")"
] | claim a worker entry for cleanup . | train | false |
40,037 | def karate_club_graph():
all_members = set(range(34))
club1 = {0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12, 13, 16, 17, 19, 21}
G = nx.Graph()
G.add_nodes_from(all_members)
G.name = "Zachary's Karate Club"
zacharydat = '0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0\n1 0 1 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0\n1 1 0 1 0 0 0 1 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0\n1 1 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1\n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\n1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\n0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\n1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\n1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 1 1\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1\n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1\n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 1\n0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\n1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 1 1\n0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 0 0 0 0 0 1 1 1 0 1\n0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 0 0 1 1 1 1 1 1 1 0'
for (row, line) in enumerate(zacharydat.split('\n')):
thisrow = [int(b) for b in line.split()]
for (col, entry) in enumerate(thisrow):
if (entry == 1):
G.add_edge(row, col)
for v in G:
G.node[v]['club'] = ('Mr. Hi' if (v in club1) else 'Officer')
return G
| [
"def",
"karate_club_graph",
"(",
")",
":",
"all_members",
"=",
"set",
"(",
"range",
"(",
"34",
")",
")",
"club1",
"=",
"{",
"0",
",",
"1",
",",
"2",
",",
"3",
",",
"4",
",",
"5",
",",
"6",
",",
"7",
",",
"8",
",",
"10",
",",
"11",
",",
"12",
",",
"13",
",",
"16",
",",
"17",
",",
"19",
",",
"21",
"}",
"G",
"=",
"nx",
".",
"Graph",
"(",
")",
"G",
".",
"add_nodes_from",
"(",
"all_members",
")",
"G",
".",
"name",
"=",
"\"Zachary's Karate Club\"",
"zacharydat",
"=",
"'0 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0\\n1 0 1 1 0 0 0 1 0 0 0 0 0 1 0 0 0 1 0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0\\n1 1 0 1 0 0 0 1 1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 1 0\\n1 1 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 0 0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1\\n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\\n1 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\\n0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\\n1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\\n1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 0 0 1 1\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 1 0 0\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 1 0 0\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 1\\n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 1\\n0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1\\n0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 1 1\\n0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\\n1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 0 0 1 0 0 0 1 1\\n0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 1 0 0 1 0 1 0 1 1 0 0 0 0 0 1 1 1 0 1\\n0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 1 0 0 1 1 1 0 1 1 0 0 1 1 1 1 1 1 1 0'",
"for",
"(",
"row",
",",
"line",
")",
"in",
"enumerate",
"(",
"zacharydat",
".",
"split",
"(",
"'\\n'",
")",
")",
":",
"thisrow",
"=",
"[",
"int",
"(",
"b",
")",
"for",
"b",
"in",
"line",
".",
"split",
"(",
")",
"]",
"for",
"(",
"col",
",",
"entry",
")",
"in",
"enumerate",
"(",
"thisrow",
")",
":",
"if",
"(",
"entry",
"==",
"1",
")",
":",
"G",
".",
"add_edge",
"(",
"row",
",",
"col",
")",
"for",
"v",
"in",
"G",
":",
"G",
".",
"node",
"[",
"v",
"]",
"[",
"'club'",
"]",
"=",
"(",
"'Mr. Hi'",
"if",
"(",
"v",
"in",
"club1",
")",
"else",
"'Officer'",
")",
"return",
"G"
] | return zacharys karate club graph . | train | false |
40,038 | def tuple_to_qfont(tup):
if (not (isinstance(tup, tuple) and (len(tup) == 4) and font_is_installed(tup[0]) and isinstance(tup[1], int) and isinstance(tup[2], bool) and isinstance(tup[3], bool))):
return None
font = QtGui.QFont()
(family, size, italic, bold) = tup
font.setFamily(family)
font.setPointSize(size)
font.setItalic(italic)
font.setBold(bold)
return font
| [
"def",
"tuple_to_qfont",
"(",
"tup",
")",
":",
"if",
"(",
"not",
"(",
"isinstance",
"(",
"tup",
",",
"tuple",
")",
"and",
"(",
"len",
"(",
"tup",
")",
"==",
"4",
")",
"and",
"font_is_installed",
"(",
"tup",
"[",
"0",
"]",
")",
"and",
"isinstance",
"(",
"tup",
"[",
"1",
"]",
",",
"int",
")",
"and",
"isinstance",
"(",
"tup",
"[",
"2",
"]",
",",
"bool",
")",
"and",
"isinstance",
"(",
"tup",
"[",
"3",
"]",
",",
"bool",
")",
")",
")",
":",
"return",
"None",
"font",
"=",
"QtGui",
".",
"QFont",
"(",
")",
"(",
"family",
",",
"size",
",",
"italic",
",",
"bold",
")",
"=",
"tup",
"font",
".",
"setFamily",
"(",
"family",
")",
"font",
".",
"setPointSize",
"(",
"size",
")",
"font",
".",
"setItalic",
"(",
"italic",
")",
"font",
".",
"setBold",
"(",
"bold",
")",
"return",
"font"
] | create a qfont from tuple: . | train | true |
40,040 | def is_visible_to_specific_content_groups(xblock):
if (not xblock.group_access):
return False
for partition in get_user_partition_info(xblock):
if any((g['selected'] for g in partition['groups'])):
return True
return False
| [
"def",
"is_visible_to_specific_content_groups",
"(",
"xblock",
")",
":",
"if",
"(",
"not",
"xblock",
".",
"group_access",
")",
":",
"return",
"False",
"for",
"partition",
"in",
"get_user_partition_info",
"(",
"xblock",
")",
":",
"if",
"any",
"(",
"(",
"g",
"[",
"'selected'",
"]",
"for",
"g",
"in",
"partition",
"[",
"'groups'",
"]",
")",
")",
":",
"return",
"True",
"return",
"False"
] | returns true if this xblock has visibility limited to specific content groups . | train | false |
40,041 | def get_num_host_queue_entries(**filter_data):
return models.HostQueueEntry.query_count(filter_data)
| [
"def",
"get_num_host_queue_entries",
"(",
"**",
"filter_data",
")",
":",
"return",
"models",
".",
"HostQueueEntry",
".",
"query_count",
"(",
"filter_data",
")"
] | get the number of host queue entries associated with this job . | train | false |
40,045 | def ts_lls(y, params, df):
print(y, params, df)
(mu, sigma2) = params.T
df = (df * 1.0)
lls = ((gammaln(((df + 1) / 2.0)) - gammaln((df / 2.0))) - (0.5 * np.log((df * np.pi))))
lls -= ((((df + 1.0) / 2.0) * np.log((1.0 + ((((y - mu) ** 2) / df) / sigma2)))) + (0.5 * np.log(sigma2)))
return lls
| [
"def",
"ts_lls",
"(",
"y",
",",
"params",
",",
"df",
")",
":",
"print",
"(",
"y",
",",
"params",
",",
"df",
")",
"(",
"mu",
",",
"sigma2",
")",
"=",
"params",
".",
"T",
"df",
"=",
"(",
"df",
"*",
"1.0",
")",
"lls",
"=",
"(",
"(",
"gammaln",
"(",
"(",
"(",
"df",
"+",
"1",
")",
"/",
"2.0",
")",
")",
"-",
"gammaln",
"(",
"(",
"df",
"/",
"2.0",
")",
")",
")",
"-",
"(",
"0.5",
"*",
"np",
".",
"log",
"(",
"(",
"df",
"*",
"np",
".",
"pi",
")",
")",
")",
")",
"lls",
"-=",
"(",
"(",
"(",
"(",
"df",
"+",
"1.0",
")",
"/",
"2.0",
")",
"*",
"np",
".",
"log",
"(",
"(",
"1.0",
"+",
"(",
"(",
"(",
"(",
"y",
"-",
"mu",
")",
"**",
"2",
")",
"/",
"df",
")",
"/",
"sigma2",
")",
")",
")",
")",
"+",
"(",
"0.5",
"*",
"np",
".",
"log",
"(",
"sigma2",
")",
")",
")",
"return",
"lls"
] | t loglikelihood given observations and mean mu and variance sigma2 = 1 parameters y : array . | train | false |
40,047 | @open_file(1, mode='w')
def write_yaml(G, path, encoding='UTF-8', **kwds):
try:
import yaml
except ImportError:
raise ImportError('write_yaml() requires PyYAML: http://pyyaml.org/')
yaml.dump(G, path, **kwds)
| [
"@",
"open_file",
"(",
"1",
",",
"mode",
"=",
"'w'",
")",
"def",
"write_yaml",
"(",
"G",
",",
"path",
",",
"encoding",
"=",
"'UTF-8'",
",",
"**",
"kwds",
")",
":",
"try",
":",
"import",
"yaml",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'write_yaml() requires PyYAML: http://pyyaml.org/'",
")",
"yaml",
".",
"dump",
"(",
"G",
",",
"path",
",",
"**",
"kwds",
")"
] | write graph g in yaml format to path . | train | false |
40,048 | def setChecksum(command):
if (len(command) < 8):
raise LabJackException('Command does not contain enough bytes.')
try:
a = command[1]
a = ((a & 120) >> 3)
if (a == 15):
command = setChecksum16(command)
command = setChecksum8(command, 6)
return command
else:
command = setChecksum8(command, len(command))
return command
except LabJackException as e:
raise e
except Exception as e:
raise LabJackException(('SetChecksum Exception:' + str(e)))
| [
"def",
"setChecksum",
"(",
"command",
")",
":",
"if",
"(",
"len",
"(",
"command",
")",
"<",
"8",
")",
":",
"raise",
"LabJackException",
"(",
"'Command does not contain enough bytes.'",
")",
"try",
":",
"a",
"=",
"command",
"[",
"1",
"]",
"a",
"=",
"(",
"(",
"a",
"&",
"120",
")",
">>",
"3",
")",
"if",
"(",
"a",
"==",
"15",
")",
":",
"command",
"=",
"setChecksum16",
"(",
"command",
")",
"command",
"=",
"setChecksum8",
"(",
"command",
",",
"6",
")",
"return",
"command",
"else",
":",
"command",
"=",
"setChecksum8",
"(",
"command",
",",
"len",
"(",
"command",
")",
")",
"return",
"command",
"except",
"LabJackException",
"as",
"e",
":",
"raise",
"e",
"except",
"Exception",
"as",
"e",
":",
"raise",
"LabJackException",
"(",
"(",
"'SetChecksum Exception:'",
"+",
"str",
"(",
"e",
")",
")",
")"
] | returns a command with checksums places in the proper locations for windows . | train | false |
40,049 | def kegg_info(database):
return _q('info', database)
| [
"def",
"kegg_info",
"(",
"database",
")",
":",
"return",
"_q",
"(",
"'info'",
",",
"database",
")"
] | kegg info - displays the current statistics of a given database . | train | false |
40,050 | def lmbda(v, x):
if (not (isscalar(v) and isscalar(x))):
raise ValueError('arguments must be scalars.')
if (v < 0):
raise ValueError('argument must be > 0.')
n = int(v)
v0 = (v - n)
if (n < 1):
n1 = 1
else:
n1 = n
v1 = (n1 + v0)
if (v != floor(v)):
(vm, vl, dl) = specfun.lamv(v1, x)
else:
(vm, vl, dl) = specfun.lamn(v1, x)
return (vl[:(n + 1)], dl[:(n + 1)])
| [
"def",
"lmbda",
"(",
"v",
",",
"x",
")",
":",
"if",
"(",
"not",
"(",
"isscalar",
"(",
"v",
")",
"and",
"isscalar",
"(",
"x",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"'arguments must be scalars.'",
")",
"if",
"(",
"v",
"<",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'argument must be > 0.'",
")",
"n",
"=",
"int",
"(",
"v",
")",
"v0",
"=",
"(",
"v",
"-",
"n",
")",
"if",
"(",
"n",
"<",
"1",
")",
":",
"n1",
"=",
"1",
"else",
":",
"n1",
"=",
"n",
"v1",
"=",
"(",
"n1",
"+",
"v0",
")",
"if",
"(",
"v",
"!=",
"floor",
"(",
"v",
")",
")",
":",
"(",
"vm",
",",
"vl",
",",
"dl",
")",
"=",
"specfun",
".",
"lamv",
"(",
"v1",
",",
"x",
")",
"else",
":",
"(",
"vm",
",",
"vl",
",",
"dl",
")",
"=",
"specfun",
".",
"lamn",
"(",
"v1",
",",
"x",
")",
"return",
"(",
"vl",
"[",
":",
"(",
"n",
"+",
"1",
")",
"]",
",",
"dl",
"[",
":",
"(",
"n",
"+",
"1",
")",
"]",
")"
] | jahnke-emden lambda function . | train | false |
40,051 | @register.inclusion_tag(u'shop/includes/order_totals.html', takes_context=True)
def order_totals(context):
return _order_totals(context)
| [
"@",
"register",
".",
"inclusion_tag",
"(",
"u'shop/includes/order_totals.html'",
",",
"takes_context",
"=",
"True",
")",
"def",
"order_totals",
"(",
"context",
")",
":",
"return",
"_order_totals",
"(",
"context",
")"
] | html version of order_totals . | train | false |
40,052 | def get_obj_doc(obj):
doc = (getattr(obj, u'__doc__', u'') or u'')
if (not isinstance(doc, unicode)):
doc = unicode(doc, u'utf-8')
return doc
| [
"def",
"get_obj_doc",
"(",
"obj",
")",
":",
"doc",
"=",
"(",
"getattr",
"(",
"obj",
",",
"u'__doc__'",
",",
"u''",
")",
"or",
"u''",
")",
"if",
"(",
"not",
"isinstance",
"(",
"doc",
",",
"unicode",
")",
")",
":",
"doc",
"=",
"unicode",
"(",
"doc",
",",
"u'utf-8'",
")",
"return",
"doc"
] | return __doc__ of the given object as unicode . | train | false |
40,054 | def extension_header_def(header_type):
def f(cls):
_extension_headers[header_type] = cls
cls.TYPE = header_type
return cls
return f
| [
"def",
"extension_header_def",
"(",
"header_type",
")",
":",
"def",
"f",
"(",
"cls",
")",
":",
"_extension_headers",
"[",
"header_type",
"]",
"=",
"cls",
"cls",
".",
"TYPE",
"=",
"header_type",
"return",
"cls",
"return",
"f"
] | extension header decorator . | train | false |
40,057 | def set_node_attributes(G, name, values):
if (not isinstance(values, dict)):
values = dict(zip_longest(G, [], fillvalue=values))
for (node, value) in values.items():
G.node[node][name] = value
| [
"def",
"set_node_attributes",
"(",
"G",
",",
"name",
",",
"values",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"values",
",",
"dict",
")",
")",
":",
"values",
"=",
"dict",
"(",
"zip_longest",
"(",
"G",
",",
"[",
"]",
",",
"fillvalue",
"=",
"values",
")",
")",
"for",
"(",
"node",
",",
"value",
")",
"in",
"values",
".",
"items",
"(",
")",
":",
"G",
".",
"node",
"[",
"node",
"]",
"[",
"name",
"]",
"=",
"value"
] | sets node attributes from a given value or dictionary of values . | train | false |
40,058 | def check_can_access(node, user, key=None, api_node=None):
if (user is None):
return False
if ((not node.can_view(Auth(user=user))) and (api_node != node)):
if (key in node.private_link_keys_deleted):
status.push_status_message('The view-only links you used are expired.', trust=False)
raise HTTPError(http.FORBIDDEN, data={'message_long': 'User has restricted access to this page. If this should not have occurred and the issue persists, please report it to <a href="mailto:support@osf.io">support@osf.io</a>.'})
return True
| [
"def",
"check_can_access",
"(",
"node",
",",
"user",
",",
"key",
"=",
"None",
",",
"api_node",
"=",
"None",
")",
":",
"if",
"(",
"user",
"is",
"None",
")",
":",
"return",
"False",
"if",
"(",
"(",
"not",
"node",
".",
"can_view",
"(",
"Auth",
"(",
"user",
"=",
"user",
")",
")",
")",
"and",
"(",
"api_node",
"!=",
"node",
")",
")",
":",
"if",
"(",
"key",
"in",
"node",
".",
"private_link_keys_deleted",
")",
":",
"status",
".",
"push_status_message",
"(",
"'The view-only links you used are expired.'",
",",
"trust",
"=",
"False",
")",
"raise",
"HTTPError",
"(",
"http",
".",
"FORBIDDEN",
",",
"data",
"=",
"{",
"'message_long'",
":",
"'User has restricted access to this page. If this should not have occurred and the issue persists, please report it to <a href=\"mailto:support@osf.io\">support@osf.io</a>.'",
"}",
")",
"return",
"True"
] | view helper that returns whether a given user can access a node . | train | false |
40,059 | @decorators.memoize
def _check_vmadm():
return salt.utils.which('vmadm')
| [
"@",
"decorators",
".",
"memoize",
"def",
"_check_vmadm",
"(",
")",
":",
"return",
"salt",
".",
"utils",
".",
"which",
"(",
"'vmadm'",
")"
] | looks to see if vmadm is present on the system . | train | false |
40,061 | @public
def content(f, *gens, **args):
options.allowed_flags(args, ['polys'])
try:
(F, opt) = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('content', 1, exc)
return F.content()
| [
"@",
"public",
"def",
"content",
"(",
"f",
",",
"*",
"gens",
",",
"**",
"args",
")",
":",
"options",
".",
"allowed_flags",
"(",
"args",
",",
"[",
"'polys'",
"]",
")",
"try",
":",
"(",
"F",
",",
"opt",
")",
"=",
"poly_from_expr",
"(",
"f",
",",
"*",
"gens",
",",
"**",
"args",
")",
"except",
"PolificationFailed",
"as",
"exc",
":",
"raise",
"ComputationFailed",
"(",
"'content'",
",",
"1",
",",
"exc",
")",
"return",
"F",
".",
"content",
"(",
")"
] | retrieve the *figure* for a plotly plot file . | train | false |
40,062 | def _BoolConverter(s):
return py3compat.CONFIGPARSER_BOOLEAN_STATES[s.lower()]
| [
"def",
"_BoolConverter",
"(",
"s",
")",
":",
"return",
"py3compat",
".",
"CONFIGPARSER_BOOLEAN_STATES",
"[",
"s",
".",
"lower",
"(",
")",
"]"
] | option value converter for a boolean . | train | false |
40,063 | def log_ormcache_stats(sig=None, frame=None):
from odoo.modules.registry import Registry
import threading
me = threading.currentThread()
me_dbname = me.dbname
entries = defaultdict(int)
for (dbname, reg) in Registry.registries.iteritems():
for key in reg.cache.iterkeys():
entries[((dbname,) + key[:2])] += 1
for (key, count) in sorted(entries.items()):
(dbname, model_name, method) = key
me.dbname = dbname
stat = STAT[key]
_logger.info('%6d entries, %6d hit, %6d miss, %6d err, %4.1f%% ratio, for %s.%s', count, stat.hit, stat.miss, stat.err, stat.ratio, model_name, method.__name__)
me.dbname = me_dbname
| [
"def",
"log_ormcache_stats",
"(",
"sig",
"=",
"None",
",",
"frame",
"=",
"None",
")",
":",
"from",
"odoo",
".",
"modules",
".",
"registry",
"import",
"Registry",
"import",
"threading",
"me",
"=",
"threading",
".",
"currentThread",
"(",
")",
"me_dbname",
"=",
"me",
".",
"dbname",
"entries",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"(",
"dbname",
",",
"reg",
")",
"in",
"Registry",
".",
"registries",
".",
"iteritems",
"(",
")",
":",
"for",
"key",
"in",
"reg",
".",
"cache",
".",
"iterkeys",
"(",
")",
":",
"entries",
"[",
"(",
"(",
"dbname",
",",
")",
"+",
"key",
"[",
":",
"2",
"]",
")",
"]",
"+=",
"1",
"for",
"(",
"key",
",",
"count",
")",
"in",
"sorted",
"(",
"entries",
".",
"items",
"(",
")",
")",
":",
"(",
"dbname",
",",
"model_name",
",",
"method",
")",
"=",
"key",
"me",
".",
"dbname",
"=",
"dbname",
"stat",
"=",
"STAT",
"[",
"key",
"]",
"_logger",
".",
"info",
"(",
"'%6d entries, %6d hit, %6d miss, %6d err, %4.1f%% ratio, for %s.%s'",
",",
"count",
",",
"stat",
".",
"hit",
",",
"stat",
".",
"miss",
",",
"stat",
".",
"err",
",",
"stat",
".",
"ratio",
",",
"model_name",
",",
"method",
".",
"__name__",
")",
"me",
".",
"dbname",
"=",
"me_dbname"
] | log statistics of ormcache usage by database . | train | false |
40,064 | @aborts
def test_require_key_exists_empty_list():
require('hosts')
| [
"@",
"aborts",
"def",
"test_require_key_exists_empty_list",
"(",
")",
":",
"require",
"(",
"'hosts'",
")"
] | when given a single existing key but the value is an empty list . | train | false |
40,066 | def randomByteString(len):
ll = int(((len / 8) + int(((len % 8) > 0))))
return ''.join([struct.pack('!Q', random.getrandbits(64)) for _ in xrange(0, ll)])[:len]
| [
"def",
"randomByteString",
"(",
"len",
")",
":",
"ll",
"=",
"int",
"(",
"(",
"(",
"len",
"/",
"8",
")",
"+",
"int",
"(",
"(",
"(",
"len",
"%",
"8",
")",
">",
"0",
")",
")",
")",
")",
"return",
"''",
".",
"join",
"(",
"[",
"struct",
".",
"pack",
"(",
"'!Q'",
",",
"random",
".",
"getrandbits",
"(",
"64",
")",
")",
"for",
"_",
"in",
"xrange",
"(",
"0",
",",
"ll",
")",
"]",
")",
"[",
":",
"len",
"]"
] | generate a string of random bytes . | train | false |
40,067 | def create_suggestion(exploration_id, author_id, exploration_version, state_name, description, suggestion_content):
thread_id = _create_models_for_thread_and_first_message(exploration_id, state_name, author_id, description, DEFAULT_SUGGESTION_THREAD_INITIAL_MESSAGE, True)
feedback_models.SuggestionModel.create(exploration_id, thread_id, author_id, exploration_version, state_name, description, suggestion_content)
full_thread_id = feedback_models.FeedbackThreadModel.generate_full_thread_id(exploration_id, thread_id)
subscription_services.subscribe_to_thread(author_id, full_thread_id)
_enqueue_suggestion_email_task(exploration_id, thread_id)
| [
"def",
"create_suggestion",
"(",
"exploration_id",
",",
"author_id",
",",
"exploration_version",
",",
"state_name",
",",
"description",
",",
"suggestion_content",
")",
":",
"thread_id",
"=",
"_create_models_for_thread_and_first_message",
"(",
"exploration_id",
",",
"state_name",
",",
"author_id",
",",
"description",
",",
"DEFAULT_SUGGESTION_THREAD_INITIAL_MESSAGE",
",",
"True",
")",
"feedback_models",
".",
"SuggestionModel",
".",
"create",
"(",
"exploration_id",
",",
"thread_id",
",",
"author_id",
",",
"exploration_version",
",",
"state_name",
",",
"description",
",",
"suggestion_content",
")",
"full_thread_id",
"=",
"feedback_models",
".",
"FeedbackThreadModel",
".",
"generate_full_thread_id",
"(",
"exploration_id",
",",
"thread_id",
")",
"subscription_services",
".",
"subscribe_to_thread",
"(",
"author_id",
",",
"full_thread_id",
")",
"_enqueue_suggestion_email_task",
"(",
"exploration_id",
",",
"thread_id",
")"
] | creates a new suggestionmodel and the corresponding feedbackthreadmodel domain object . | train | false |
40,068 | def validate_user(user, device, token):
res = {'message': 'User key is invalid', 'result': False}
parameters = dict()
parameters['user'] = user
parameters['token'] = token
if device:
parameters['device'] = device
response = query(function='validate_user', method='POST', header_dict={'Content-Type': 'application/x-www-form-urlencoded'}, data=_urlencode(parameters))
if response['res']:
if ('message' in response):
_message = response.get('message', '')
if ('status' in _message):
if (_message.get('dict', {}).get('status', None) == 1):
res['result'] = True
res['message'] = 'User key is valid.'
else:
res['result'] = False
res['message'] = ''.join(_message.get('dict', {}).get('errors'))
return res
| [
"def",
"validate_user",
"(",
"user",
",",
"device",
",",
"token",
")",
":",
"res",
"=",
"{",
"'message'",
":",
"'User key is invalid'",
",",
"'result'",
":",
"False",
"}",
"parameters",
"=",
"dict",
"(",
")",
"parameters",
"[",
"'user'",
"]",
"=",
"user",
"parameters",
"[",
"'token'",
"]",
"=",
"token",
"if",
"device",
":",
"parameters",
"[",
"'device'",
"]",
"=",
"device",
"response",
"=",
"query",
"(",
"function",
"=",
"'validate_user'",
",",
"method",
"=",
"'POST'",
",",
"header_dict",
"=",
"{",
"'Content-Type'",
":",
"'application/x-www-form-urlencoded'",
"}",
",",
"data",
"=",
"_urlencode",
"(",
"parameters",
")",
")",
"if",
"response",
"[",
"'res'",
"]",
":",
"if",
"(",
"'message'",
"in",
"response",
")",
":",
"_message",
"=",
"response",
".",
"get",
"(",
"'message'",
",",
"''",
")",
"if",
"(",
"'status'",
"in",
"_message",
")",
":",
"if",
"(",
"_message",
".",
"get",
"(",
"'dict'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'status'",
",",
"None",
")",
"==",
"1",
")",
":",
"res",
"[",
"'result'",
"]",
"=",
"True",
"res",
"[",
"'message'",
"]",
"=",
"'User key is valid.'",
"else",
":",
"res",
"[",
"'result'",
"]",
"=",
"False",
"res",
"[",
"'message'",
"]",
"=",
"''",
".",
"join",
"(",
"_message",
".",
"get",
"(",
"'dict'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'errors'",
")",
")",
"return",
"res"
] | send a message to a pushover user or group . | train | true |
40,070 | def pure_nash_brute(g):
return list(pure_nash_brute_gen(g))
| [
"def",
"pure_nash_brute",
"(",
"g",
")",
":",
"return",
"list",
"(",
"pure_nash_brute_gen",
"(",
"g",
")",
")"
] | find all pure nash equilibria of a normal form game by brute force . | train | false |
40,072 | def de_mean_matrix(A):
(nr, nc) = shape(A)
(column_means, _) = scale(A)
return make_matrix(nr, nc, (lambda i, j: (A[i][j] - column_means[j])))
| [
"def",
"de_mean_matrix",
"(",
"A",
")",
":",
"(",
"nr",
",",
"nc",
")",
"=",
"shape",
"(",
"A",
")",
"(",
"column_means",
",",
"_",
")",
"=",
"scale",
"(",
"A",
")",
"return",
"make_matrix",
"(",
"nr",
",",
"nc",
",",
"(",
"lambda",
"i",
",",
"j",
":",
"(",
"A",
"[",
"i",
"]",
"[",
"j",
"]",
"-",
"column_means",
"[",
"j",
"]",
")",
")",
")"
] | returns the result of subtracting from every value in a the mean value of its column . | train | false |
40,073 | def _makeHDB2(ACK, NAK):
SAB = 1
DAB = 1
PFB = 0
HDB2val = ((((((DAB & 3) * pow(2, 6)) | ((SAB & 3) * pow(2, 4))) | ((PFB & 3) * pow(2, 2))) | ((ACK & 1) * pow(2, 1))) | (NAK & 1))
return HDB2val
| [
"def",
"_makeHDB2",
"(",
"ACK",
",",
"NAK",
")",
":",
"SAB",
"=",
"1",
"DAB",
"=",
"1",
"PFB",
"=",
"0",
"HDB2val",
"=",
"(",
"(",
"(",
"(",
"(",
"(",
"DAB",
"&",
"3",
")",
"*",
"pow",
"(",
"2",
",",
"6",
")",
")",
"|",
"(",
"(",
"SAB",
"&",
"3",
")",
"*",
"pow",
"(",
"2",
",",
"4",
")",
")",
")",
"|",
"(",
"(",
"PFB",
"&",
"3",
")",
"*",
"pow",
"(",
"2",
",",
"2",
")",
")",
")",
"|",
"(",
"(",
"ACK",
"&",
"1",
")",
"*",
"pow",
"(",
"2",
",",
"1",
")",
")",
")",
"|",
"(",
"NAK",
"&",
"1",
")",
")",
"return",
"HDB2val"
] | encode header byte 2 . | train | false |
40,074 | def gitbucket(parser, xml_parent, data):
gitbucket = XML.SubElement(xml_parent, 'org.jenkinsci.plugins.gitbucket.GitBucketProjectProperty')
gitbucket.set('plugin', 'gitbucket')
mapping = [('url', 'url', None), ('link-enabled', 'linkEnabled', False)]
helpers.convert_mapping_to_xml(gitbucket, data, mapping, fail_required=True)
| [
"def",
"gitbucket",
"(",
"parser",
",",
"xml_parent",
",",
"data",
")",
":",
"gitbucket",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'org.jenkinsci.plugins.gitbucket.GitBucketProjectProperty'",
")",
"gitbucket",
".",
"set",
"(",
"'plugin'",
",",
"'gitbucket'",
")",
"mapping",
"=",
"[",
"(",
"'url'",
",",
"'url'",
",",
"None",
")",
",",
"(",
"'link-enabled'",
",",
"'linkEnabled'",
",",
"False",
")",
"]",
"helpers",
".",
"convert_mapping_to_xml",
"(",
"gitbucket",
",",
"data",
",",
"mapping",
",",
"fail_required",
"=",
"True",
")"
] | yaml: gitbucket integrate gitbucket to jenkins . | train | false |
40,075 | def get_compiler_path():
given_binary = os.environ.get('SOLC_BINARY')
if given_binary:
return given_binary
for path in os.getenv('PATH', '').split(os.pathsep):
path = path.strip('"')
executable_path = os.path.join(path, BINARY)
if (os.path.isfile(executable_path) and os.access(executable_path, os.X_OK)):
return executable_path
return None
| [
"def",
"get_compiler_path",
"(",
")",
":",
"given_binary",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SOLC_BINARY'",
")",
"if",
"given_binary",
":",
"return",
"given_binary",
"for",
"path",
"in",
"os",
".",
"getenv",
"(",
"'PATH'",
",",
"''",
")",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"path",
"=",
"path",
".",
"strip",
"(",
"'\"'",
")",
"executable_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"BINARY",
")",
"if",
"(",
"os",
".",
"path",
".",
"isfile",
"(",
"executable_path",
")",
"and",
"os",
".",
"access",
"(",
"executable_path",
",",
"os",
".",
"X_OK",
")",
")",
":",
"return",
"executable_path",
"return",
"None"
] | return the path to the solc compiler . | train | true |
40,076 | def _moved_global(old_name, new_module=None, new_name=None):
assert (new_module or new_name)
if isinstance(new_module, _MovedGlobals):
new_module = new_module._mg__old_ref
old_module = inspect.getmodule(inspect.stack()[1][0])
new_module = (new_module or old_module)
new_name = (new_name or old_name)
_MovedGlobals._mg__moves[(old_module, old_name)] = (new_module, new_name)
| [
"def",
"_moved_global",
"(",
"old_name",
",",
"new_module",
"=",
"None",
",",
"new_name",
"=",
"None",
")",
":",
"assert",
"(",
"new_module",
"or",
"new_name",
")",
"if",
"isinstance",
"(",
"new_module",
",",
"_MovedGlobals",
")",
":",
"new_module",
"=",
"new_module",
".",
"_mg__old_ref",
"old_module",
"=",
"inspect",
".",
"getmodule",
"(",
"inspect",
".",
"stack",
"(",
")",
"[",
"1",
"]",
"[",
"0",
"]",
")",
"new_module",
"=",
"(",
"new_module",
"or",
"old_module",
")",
"new_name",
"=",
"(",
"new_name",
"or",
"old_name",
")",
"_MovedGlobals",
".",
"_mg__moves",
"[",
"(",
"old_module",
",",
"old_name",
")",
"]",
"=",
"(",
"new_module",
",",
"new_name",
")"
] | deprecate a single attribute in a module . | train | false |
40,077 | def _AppendSubtypeRec(node, subtype, force=True):
if isinstance(node, pytree.Leaf):
_AppendTokenSubtype(node, subtype)
return
for child in node.children:
_AppendSubtypeRec(child, subtype, force=force)
| [
"def",
"_AppendSubtypeRec",
"(",
"node",
",",
"subtype",
",",
"force",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"pytree",
".",
"Leaf",
")",
":",
"_AppendTokenSubtype",
"(",
"node",
",",
"subtype",
")",
"return",
"for",
"child",
"in",
"node",
".",
"children",
":",
"_AppendSubtypeRec",
"(",
"child",
",",
"subtype",
",",
"force",
"=",
"force",
")"
] | append the leafs in the node to the given subtype . | train | false |
40,079 | def form_view(request):
if (request.method == 'POST'):
form = TestForm(request.POST)
if form.is_valid():
t = Template('Valid POST data.', name='Valid POST Template')
c = Context()
else:
t = Template('Invalid POST data. {{ form.errors }}', name='Invalid POST Template')
c = Context({'form': form})
else:
form = TestForm(request.GET)
t = Template('Viewing base form. {{ form }}.', name='Form GET Template')
c = Context({'form': form})
return HttpResponse(t.render(c))
| [
"def",
"form_view",
"(",
"request",
")",
":",
"if",
"(",
"request",
".",
"method",
"==",
"'POST'",
")",
":",
"form",
"=",
"TestForm",
"(",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"t",
"=",
"Template",
"(",
"'Valid POST data.'",
",",
"name",
"=",
"'Valid POST Template'",
")",
"c",
"=",
"Context",
"(",
")",
"else",
":",
"t",
"=",
"Template",
"(",
"'Invalid POST data. {{ form.errors }}'",
",",
"name",
"=",
"'Invalid POST Template'",
")",
"c",
"=",
"Context",
"(",
"{",
"'form'",
":",
"form",
"}",
")",
"else",
":",
"form",
"=",
"TestForm",
"(",
"request",
".",
"GET",
")",
"t",
"=",
"Template",
"(",
"'Viewing base form. {{ form }}.'",
",",
"name",
"=",
"'Form GET Template'",
")",
"c",
"=",
"Context",
"(",
"{",
"'form'",
":",
"form",
"}",
")",
"return",
"HttpResponse",
"(",
"t",
".",
"render",
"(",
"c",
")",
")"
] | a view that tests a simple form . | train | false |
40,081 | def _check_olecf(data):
offset = 512
if data.startswith('\xec\xa5\xc1\x00', offset):
return 'application/msword'
elif ('Microsoft Excel' in data):
return 'application/vnd.ms-excel'
elif _ppt_pattern.match(data, offset):
return 'application/vnd.ms-powerpoint'
return False
| [
"def",
"_check_olecf",
"(",
"data",
")",
":",
"offset",
"=",
"512",
"if",
"data",
".",
"startswith",
"(",
"'\\xec\\xa5\\xc1\\x00'",
",",
"offset",
")",
":",
"return",
"'application/msword'",
"elif",
"(",
"'Microsoft Excel'",
"in",
"data",
")",
":",
"return",
"'application/vnd.ms-excel'",
"elif",
"_ppt_pattern",
".",
"match",
"(",
"data",
",",
"offset",
")",
":",
"return",
"'application/vnd.ms-powerpoint'",
"return",
"False"
] | pre-ooxml office formats are ole compound files which all use the same file signature and should have a subheader at offset 512 . | train | false |
40,082 | def _get_signed_query_params(credentials, expiration, string_to_sign):
if (not isinstance(credentials, google.auth.credentials.Signing)):
auth_uri = 'http://google-cloud-python.readthedocs.io/en/latest/google-cloud-auth.html#setting-up-a-service-account'
raise AttributeError(('you need a private key to sign credentials.the credentials you are currently using %s just contains a token. see %s for more details.' % (type(credentials), auth_uri)))
signature_bytes = credentials.sign_bytes(string_to_sign)
signature = base64.b64encode(signature_bytes)
service_account_name = credentials.signer_email
return {'GoogleAccessId': service_account_name, 'Expires': str(expiration), 'Signature': signature}
| [
"def",
"_get_signed_query_params",
"(",
"credentials",
",",
"expiration",
",",
"string_to_sign",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"credentials",
",",
"google",
".",
"auth",
".",
"credentials",
".",
"Signing",
")",
")",
":",
"auth_uri",
"=",
"'http://google-cloud-python.readthedocs.io/en/latest/google-cloud-auth.html#setting-up-a-service-account'",
"raise",
"AttributeError",
"(",
"(",
"'you need a private key to sign credentials.the credentials you are currently using %s just contains a token. see %s for more details.'",
"%",
"(",
"type",
"(",
"credentials",
")",
",",
"auth_uri",
")",
")",
")",
"signature_bytes",
"=",
"credentials",
".",
"sign_bytes",
"(",
"string_to_sign",
")",
"signature",
"=",
"base64",
".",
"b64encode",
"(",
"signature_bytes",
")",
"service_account_name",
"=",
"credentials",
".",
"signer_email",
"return",
"{",
"'GoogleAccessId'",
":",
"service_account_name",
",",
"'Expires'",
":",
"str",
"(",
"expiration",
")",
",",
"'Signature'",
":",
"signature",
"}"
] | gets query parameters for creating a signed url . | train | false |
40,083 | def quota_get_per_project_resources():
return IMPL.quota_get_per_project_resources()
| [
"def",
"quota_get_per_project_resources",
"(",
")",
":",
"return",
"IMPL",
".",
"quota_get_per_project_resources",
"(",
")"
] | retrieve the names of resources whose quotas are calculated on a per-project rather than a per-user basis . | train | false |
40,085 | def condition_not_db_filter(model, field, value, auto_none=True):
result = (~ condition_db_filter(model, field, value))
if (auto_none and ((isinstance(value, collections.Iterable) and (not isinstance(value, six.string_types)) and (None not in value)) or (value is not None))):
orm_field = getattr(model, field)
result = or_(result, orm_field.is_(None))
return result
| [
"def",
"condition_not_db_filter",
"(",
"model",
",",
"field",
",",
"value",
",",
"auto_none",
"=",
"True",
")",
":",
"result",
"=",
"(",
"~",
"condition_db_filter",
"(",
"model",
",",
"field",
",",
"value",
")",
")",
"if",
"(",
"auto_none",
"and",
"(",
"(",
"isinstance",
"(",
"value",
",",
"collections",
".",
"Iterable",
")",
"and",
"(",
"not",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
")",
"and",
"(",
"None",
"not",
"in",
"value",
")",
")",
"or",
"(",
"value",
"is",
"not",
"None",
")",
")",
")",
":",
"orm_field",
"=",
"getattr",
"(",
"model",
",",
"field",
")",
"result",
"=",
"or_",
"(",
"result",
",",
"orm_field",
".",
"is_",
"(",
"None",
")",
")",
"return",
"result"
] | create non matching filter . | train | false |
40,087 | def get_indexes(**kwargs):
return get_indexes_async(**kwargs).get_result()
| [
"def",
"get_indexes",
"(",
"**",
"kwargs",
")",
":",
"return",
"get_indexes_async",
"(",
"**",
"kwargs",
")",
".",
"get_result",
"(",
")"
] | get a data structure representing the configured indexes . | train | false |
40,088 | def _NamespaceKeyToString(key):
key_path = key.to_path()
if ((len(key_path) == 2) and (key_path[0] == '__namespace__')):
if (key_path[1] == datastore_types._EMPTY_NAMESPACE_ID):
return ''
if isinstance(key_path[1], basestring):
return key_path[1]
Check(False, 'invalid Key for __namespace__ table')
| [
"def",
"_NamespaceKeyToString",
"(",
"key",
")",
":",
"key_path",
"=",
"key",
".",
"to_path",
"(",
")",
"if",
"(",
"(",
"len",
"(",
"key_path",
")",
"==",
"2",
")",
"and",
"(",
"key_path",
"[",
"0",
"]",
"==",
"'__namespace__'",
")",
")",
":",
"if",
"(",
"key_path",
"[",
"1",
"]",
"==",
"datastore_types",
".",
"_EMPTY_NAMESPACE_ID",
")",
":",
"return",
"''",
"if",
"isinstance",
"(",
"key_path",
"[",
"1",
"]",
",",
"basestring",
")",
":",
"return",
"key_path",
"[",
"1",
"]",
"Check",
"(",
"False",
",",
"'invalid Key for __namespace__ table'",
")"
] | extract namespace name from __namespace__ key . | train | false |
40,091 | def _yield_clusters(max_days_ago=None, now=None, **runner_kwargs):
if (now is None):
now = datetime.utcnow()
emr_conn = EMRJobRunner(**runner_kwargs).make_emr_conn()
created_after = None
if (max_days_ago is not None):
created_after = (now - timedelta(days=max_days_ago))
for cluster_summary in _yield_all_clusters(emr_conn, created_after=created_after, _delay=_DELAY):
cluster_id = cluster_summary.id
sleep(_DELAY)
cluster = _patched_describe_cluster(emr_conn, cluster_id)
cluster.steps = _list_all_steps(emr_conn, cluster_id, _delay=_DELAY)
cluster.bootstrapactions = list(_yield_all_bootstrap_actions(emr_conn, cluster_id, _delay=_DELAY))
(yield cluster)
| [
"def",
"_yield_clusters",
"(",
"max_days_ago",
"=",
"None",
",",
"now",
"=",
"None",
",",
"**",
"runner_kwargs",
")",
":",
"if",
"(",
"now",
"is",
"None",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"emr_conn",
"=",
"EMRJobRunner",
"(",
"**",
"runner_kwargs",
")",
".",
"make_emr_conn",
"(",
")",
"created_after",
"=",
"None",
"if",
"(",
"max_days_ago",
"is",
"not",
"None",
")",
":",
"created_after",
"=",
"(",
"now",
"-",
"timedelta",
"(",
"days",
"=",
"max_days_ago",
")",
")",
"for",
"cluster_summary",
"in",
"_yield_all_clusters",
"(",
"emr_conn",
",",
"created_after",
"=",
"created_after",
",",
"_delay",
"=",
"_DELAY",
")",
":",
"cluster_id",
"=",
"cluster_summary",
".",
"id",
"sleep",
"(",
"_DELAY",
")",
"cluster",
"=",
"_patched_describe_cluster",
"(",
"emr_conn",
",",
"cluster_id",
")",
"cluster",
".",
"steps",
"=",
"_list_all_steps",
"(",
"emr_conn",
",",
"cluster_id",
",",
"_delay",
"=",
"_DELAY",
")",
"cluster",
".",
"bootstrapactions",
"=",
"list",
"(",
"_yield_all_bootstrap_actions",
"(",
"emr_conn",
",",
"cluster_id",
",",
"_delay",
"=",
"_DELAY",
")",
")",
"(",
"yield",
"cluster",
")"
] | get relevant cluster information from emr . | train | false |
40,092 | def ssh(host, cmd):
proc = sp.Popen(['ssh', host], stdin=sp.PIPE)
proc.stdin.write(cmd)
proc.wait()
| [
"def",
"ssh",
"(",
"host",
",",
"cmd",
")",
":",
"proc",
"=",
"sp",
".",
"Popen",
"(",
"[",
"'ssh'",
",",
"host",
"]",
",",
"stdin",
"=",
"sp",
".",
"PIPE",
")",
"proc",
".",
"stdin",
".",
"write",
"(",
"cmd",
")",
"proc",
".",
"wait",
"(",
")"
] | runs a command on a given machine . | train | false |
40,093 | def find_ca_bundle():
if (os.name == 'nt'):
return get_win_certfile()
else:
for cert_path in cert_paths:
if os.path.isfile(cert_path):
return cert_path
try:
return pkg_resources.resource_filename('certifi', 'cacert.pem')
except (ImportError, ResolutionError, ExtractionError):
return None
| [
"def",
"find_ca_bundle",
"(",
")",
":",
"if",
"(",
"os",
".",
"name",
"==",
"'nt'",
")",
":",
"return",
"get_win_certfile",
"(",
")",
"else",
":",
"for",
"cert_path",
"in",
"cert_paths",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"cert_path",
")",
":",
"return",
"cert_path",
"try",
":",
"return",
"pkg_resources",
".",
"resource_filename",
"(",
"'certifi'",
",",
"'cacert.pem'",
")",
"except",
"(",
"ImportError",
",",
"ResolutionError",
",",
"ExtractionError",
")",
":",
"return",
"None"
] | return an existing ca bundle path . | train | true |
40,096 | def show_form_errors(request, form):
for error in form.non_field_errors():
messages.error(request, error)
for field in form:
for error in field.errors:
messages.error(request, (_('Error in parameter %(field)s: %(error)s') % {'field': field.name, 'error': error}))
| [
"def",
"show_form_errors",
"(",
"request",
",",
"form",
")",
":",
"for",
"error",
"in",
"form",
".",
"non_field_errors",
"(",
")",
":",
"messages",
".",
"error",
"(",
"request",
",",
"error",
")",
"for",
"field",
"in",
"form",
":",
"for",
"error",
"in",
"field",
".",
"errors",
":",
"messages",
".",
"error",
"(",
"request",
",",
"(",
"_",
"(",
"'Error in parameter %(field)s: %(error)s'",
")",
"%",
"{",
"'field'",
":",
"field",
".",
"name",
",",
"'error'",
":",
"error",
"}",
")",
")"
] | shows all form errors as a message . | train | false |
40,098 | def is_xml(obj):
global types
try:
_bootstrap()
except ImportError:
return False
return isinstance(obj, types)
| [
"def",
"is_xml",
"(",
"obj",
")",
":",
"global",
"types",
"try",
":",
"_bootstrap",
"(",
")",
"except",
"ImportError",
":",
"return",
"False",
"return",
"isinstance",
"(",
"obj",
",",
"types",
")"
] | determines c{obj} is a valid xml type . | train | false |
40,099 | def versioned_fields(resource_def):
if (resource_def['versioning'] is not True):
return []
schema = resource_def['schema']
fields = [f for f in schema if ((schema[f].get('versioned', True) is True) and (f != resource_def['id_field']))]
fields.extend((app.config['LAST_UPDATED'], app.config['ETAG'], app.config['DELETED']))
return fields
| [
"def",
"versioned_fields",
"(",
"resource_def",
")",
":",
"if",
"(",
"resource_def",
"[",
"'versioning'",
"]",
"is",
"not",
"True",
")",
":",
"return",
"[",
"]",
"schema",
"=",
"resource_def",
"[",
"'schema'",
"]",
"fields",
"=",
"[",
"f",
"for",
"f",
"in",
"schema",
"if",
"(",
"(",
"schema",
"[",
"f",
"]",
".",
"get",
"(",
"'versioned'",
",",
"True",
")",
"is",
"True",
")",
"and",
"(",
"f",
"!=",
"resource_def",
"[",
"'id_field'",
"]",
")",
")",
"]",
"fields",
".",
"extend",
"(",
"(",
"app",
".",
"config",
"[",
"'LAST_UPDATED'",
"]",
",",
"app",
".",
"config",
"[",
"'ETAG'",
"]",
",",
"app",
".",
"config",
"[",
"'DELETED'",
"]",
")",
")",
"return",
"fields"
] | returns a list of versioned fields for a resource . | train | false |
40,100 | def get_customizationspec_ref(si, customization_spec_name):
customization_spec_name = si.content.customizationSpecManager.GetCustomizationSpec(name=customization_spec_name)
return customization_spec_name
| [
"def",
"get_customizationspec_ref",
"(",
"si",
",",
"customization_spec_name",
")",
":",
"customization_spec_name",
"=",
"si",
".",
"content",
".",
"customizationSpecManager",
".",
"GetCustomizationSpec",
"(",
"name",
"=",
"customization_spec_name",
")",
"return",
"customization_spec_name"
] | get a reference to a vmware customization spec for the purposes of customizing a clone si serviceinstance for the vsphere or esxi server customization_spec_name name of the customization spec . | train | true |
40,101 | def create_schema_for_required_keys(keys):
schema = {x: [not_missing] for x in keys}
return schema
| [
"def",
"create_schema_for_required_keys",
"(",
"keys",
")",
":",
"schema",
"=",
"{",
"x",
":",
"[",
"not_missing",
"]",
"for",
"x",
"in",
"keys",
"}",
"return",
"schema"
] | helper function that creates a schema definition where each key from keys is validated against not_missing . | train | false |
40,103 | def freeze_support():
if ((sys.platform == 'win32') and getattr(sys, 'frozen', False)):
from multiprocessing.forking import freeze_support
freeze_support()
| [
"def",
"freeze_support",
"(",
")",
":",
"if",
"(",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
"and",
"getattr",
"(",
"sys",
",",
"'frozen'",
",",
"False",
")",
")",
":",
"from",
"multiprocessing",
".",
"forking",
"import",
"freeze_support",
"freeze_support",
"(",
")"
] | run code for process object if this in not the main process . | train | false |
40,104 | def test_mro():
class A(object, ):
pass
AreEqual(A.__mro__, (A, object))
class B(object, ):
pass
AreEqual(B.__mro__, (B, object))
class C(B, ):
pass
AreEqual(C.__mro__, (C, B, object))
class N(C, B, A, ):
pass
AreEqual(N.__mro__, (N, C, B, A, object))
try:
class N(A, B, C, ):
pass
AssertUnreachable('impossible MRO created')
except TypeError:
pass
try:
class N(A, A, ):
pass
AssertUnreachable("can't dervie from the same base type twice")
except TypeError:
pass
| [
"def",
"test_mro",
"(",
")",
":",
"class",
"A",
"(",
"object",
",",
")",
":",
"pass",
"AreEqual",
"(",
"A",
".",
"__mro__",
",",
"(",
"A",
",",
"object",
")",
")",
"class",
"B",
"(",
"object",
",",
")",
":",
"pass",
"AreEqual",
"(",
"B",
".",
"__mro__",
",",
"(",
"B",
",",
"object",
")",
")",
"class",
"C",
"(",
"B",
",",
")",
":",
"pass",
"AreEqual",
"(",
"C",
".",
"__mro__",
",",
"(",
"C",
",",
"B",
",",
"object",
")",
")",
"class",
"N",
"(",
"C",
",",
"B",
",",
"A",
",",
")",
":",
"pass",
"AreEqual",
"(",
"N",
".",
"__mro__",
",",
"(",
"N",
",",
"C",
",",
"B",
",",
"A",
",",
"object",
")",
")",
"try",
":",
"class",
"N",
"(",
"A",
",",
"B",
",",
"C",
",",
")",
":",
"pass",
"AssertUnreachable",
"(",
"'impossible MRO created'",
")",
"except",
"TypeError",
":",
"pass",
"try",
":",
"class",
"N",
"(",
"A",
",",
"A",
",",
")",
":",
"pass",
"AssertUnreachable",
"(",
"\"can't dervie from the same base type twice\"",
")",
"except",
"TypeError",
":",
"pass"
] | mro support . | train | false |
40,105 | def prettify_class_name(name):
return sub('(?<=.)([A-Z])', ' \\1', name)
| [
"def",
"prettify_class_name",
"(",
"name",
")",
":",
"return",
"sub",
"(",
"'(?<=.)([A-Z])'",
",",
"' \\\\1'",
",",
"name",
")"
] | split words in pascalcase string into separate words . | train | false |
40,107 | def all_neighbors(graph, node):
if graph.is_directed():
values = chain(graph.predecessors(node), graph.successors(node))
else:
values = graph.neighbors(node)
return values
| [
"def",
"all_neighbors",
"(",
"graph",
",",
"node",
")",
":",
"if",
"graph",
".",
"is_directed",
"(",
")",
":",
"values",
"=",
"chain",
"(",
"graph",
".",
"predecessors",
"(",
"node",
")",
",",
"graph",
".",
"successors",
"(",
"node",
")",
")",
"else",
":",
"values",
"=",
"graph",
".",
"neighbors",
"(",
"node",
")",
"return",
"values"
] | returns all of the neighbors of a node in the graph . | train | true |
40,108 | def template_clone(call=None, kwargs=None):
if (call != 'function'):
raise SaltCloudSystemExit('The template_clone function must be called with -f or --function.')
if (kwargs is None):
kwargs = {}
name = kwargs.get('name', None)
template_id = kwargs.get('template_id', None)
template_name = kwargs.get('template_name', None)
if (name is None):
raise SaltCloudSystemExit('The template_clone function requires a name to be provided.')
if template_id:
if template_name:
log.warning("Both the 'template_id' and 'template_name' arguments were provided. 'template_id' will take precedence.")
elif template_name:
template_id = get_template_id(kwargs={'name': template_name})
else:
raise SaltCloudSystemExit("The template_clone function requires either a 'template_id' or a 'template_name' to be provided.")
(server, user, password) = _get_xml_rpc()
auth = ':'.join([user, password])
response = server.one.template.clone(auth, int(template_id), name)
data = {'action': 'template.clone', 'cloned': response[0], 'cloned_template_id': response[1], 'cloned_template_name': name, 'error_code': response[2]}
return data
| [
"def",
"template_clone",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'function'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The template_clone function must be called with -f or --function.'",
")",
"if",
"(",
"kwargs",
"is",
"None",
")",
":",
"kwargs",
"=",
"{",
"}",
"name",
"=",
"kwargs",
".",
"get",
"(",
"'name'",
",",
"None",
")",
"template_id",
"=",
"kwargs",
".",
"get",
"(",
"'template_id'",
",",
"None",
")",
"template_name",
"=",
"kwargs",
".",
"get",
"(",
"'template_name'",
",",
"None",
")",
"if",
"(",
"name",
"is",
"None",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The template_clone function requires a name to be provided.'",
")",
"if",
"template_id",
":",
"if",
"template_name",
":",
"log",
".",
"warning",
"(",
"\"Both the 'template_id' and 'template_name' arguments were provided. 'template_id' will take precedence.\"",
")",
"elif",
"template_name",
":",
"template_id",
"=",
"get_template_id",
"(",
"kwargs",
"=",
"{",
"'name'",
":",
"template_name",
"}",
")",
"else",
":",
"raise",
"SaltCloudSystemExit",
"(",
"\"The template_clone function requires either a 'template_id' or a 'template_name' to be provided.\"",
")",
"(",
"server",
",",
"user",
",",
"password",
")",
"=",
"_get_xml_rpc",
"(",
")",
"auth",
"=",
"':'",
".",
"join",
"(",
"[",
"user",
",",
"password",
"]",
")",
"response",
"=",
"server",
".",
"one",
".",
"template",
".",
"clone",
"(",
"auth",
",",
"int",
"(",
"template_id",
")",
",",
"name",
")",
"data",
"=",
"{",
"'action'",
":",
"'template.clone'",
",",
"'cloned'",
":",
"response",
"[",
"0",
"]",
",",
"'cloned_template_id'",
":",
"response",
"[",
"1",
"]",
",",
"'cloned_template_name'",
":",
"name",
",",
"'error_code'",
":",
"response",
"[",
"2",
"]",
"}",
"return",
"data"
] | clones an existing virtual machine template . | train | true |
40,109 | def autoDetectXMLEncoding(buffer):
encoding = 'utf_8'
if (len(buffer) >= 4):
bytes = (byte1, byte2, byte3, byte4) = tuple(map(ord, buffer[0:4]))
enc_info = autodetect_dict.get(bytes, None)
if (not enc_info):
bytes = (byte1, byte2, None, None)
enc_info = autodetect_dict.get(bytes)
else:
enc_info = None
if enc_info:
encoding = enc_info
secret_decoder_ring = codecs.lookup(encoding)[1]
(decoded, length) = secret_decoder_ring(buffer)
first_line = decoded.split('\n')[0]
if (first_line and first_line.startswith(u'<?xml')):
encoding_pos = first_line.find(u'encoding')
if (encoding_pos != (-1)):
quote_pos = first_line.find('"', encoding_pos)
if (quote_pos == (-1)):
quote_pos = first_line.find("'", encoding_pos)
if (quote_pos > (-1)):
(quote_char, rest) = (first_line[quote_pos], first_line[(quote_pos + 1):])
encoding = rest[:rest.find(quote_char)]
return encoding
| [
"def",
"autoDetectXMLEncoding",
"(",
"buffer",
")",
":",
"encoding",
"=",
"'utf_8'",
"if",
"(",
"len",
"(",
"buffer",
")",
">=",
"4",
")",
":",
"bytes",
"=",
"(",
"byte1",
",",
"byte2",
",",
"byte3",
",",
"byte4",
")",
"=",
"tuple",
"(",
"map",
"(",
"ord",
",",
"buffer",
"[",
"0",
":",
"4",
"]",
")",
")",
"enc_info",
"=",
"autodetect_dict",
".",
"get",
"(",
"bytes",
",",
"None",
")",
"if",
"(",
"not",
"enc_info",
")",
":",
"bytes",
"=",
"(",
"byte1",
",",
"byte2",
",",
"None",
",",
"None",
")",
"enc_info",
"=",
"autodetect_dict",
".",
"get",
"(",
"bytes",
")",
"else",
":",
"enc_info",
"=",
"None",
"if",
"enc_info",
":",
"encoding",
"=",
"enc_info",
"secret_decoder_ring",
"=",
"codecs",
".",
"lookup",
"(",
"encoding",
")",
"[",
"1",
"]",
"(",
"decoded",
",",
"length",
")",
"=",
"secret_decoder_ring",
"(",
"buffer",
")",
"first_line",
"=",
"decoded",
".",
"split",
"(",
"'\\n'",
")",
"[",
"0",
"]",
"if",
"(",
"first_line",
"and",
"first_line",
".",
"startswith",
"(",
"u'<?xml'",
")",
")",
":",
"encoding_pos",
"=",
"first_line",
".",
"find",
"(",
"u'encoding'",
")",
"if",
"(",
"encoding_pos",
"!=",
"(",
"-",
"1",
")",
")",
":",
"quote_pos",
"=",
"first_line",
".",
"find",
"(",
"'\"'",
",",
"encoding_pos",
")",
"if",
"(",
"quote_pos",
"==",
"(",
"-",
"1",
")",
")",
":",
"quote_pos",
"=",
"first_line",
".",
"find",
"(",
"\"'\"",
",",
"encoding_pos",
")",
"if",
"(",
"quote_pos",
">",
"(",
"-",
"1",
")",
")",
":",
"(",
"quote_char",
",",
"rest",
")",
"=",
"(",
"first_line",
"[",
"quote_pos",
"]",
",",
"first_line",
"[",
"(",
"quote_pos",
"+",
"1",
")",
":",
"]",
")",
"encoding",
"=",
"rest",
"[",
":",
"rest",
".",
"find",
"(",
"quote_char",
")",
"]",
"return",
"encoding"
] | buffer -> encoding_name the buffer should be at least 4 bytes long . | train | false |
40,113 | def set_url_prefix(prefix):
_local.prefix = prefix
| [
"def",
"set_url_prefix",
"(",
"prefix",
")",
":",
"_local",
".",
"prefix",
"=",
"prefix"
] | set prefix for the current thread . | train | false |
40,114 | def _coord_frame_name(cframe):
return _verbose_frames.get(int(cframe), 'unknown')
| [
"def",
"_coord_frame_name",
"(",
"cframe",
")",
":",
"return",
"_verbose_frames",
".",
"get",
"(",
"int",
"(",
"cframe",
")",
",",
"'unknown'",
")"
] | map integers to human-readable names . | train | false |
40,116 | def get_filename(path):
try:
return os.path.split(path)[1]
except:
return ''
| [
"def",
"get_filename",
"(",
"path",
")",
":",
"try",
":",
"return",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"[",
"1",
"]",
"except",
":",
"return",
"''"
] | return path without the file extension . | train | false |
40,117 | def GetResourcesSample():
client = CreateClient()
feed = client.GetResources()
PrintFeed(feed)
| [
"def",
"GetResourcesSample",
"(",
")",
":",
"client",
"=",
"CreateClient",
"(",
")",
"feed",
"=",
"client",
".",
"GetResources",
"(",
")",
"PrintFeed",
"(",
"feed",
")"
] | get and display first page of resources . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.