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 |
|---|---|---|---|---|---|
38,033 | def run_in_transaction(fn, *args, **kwargs):
return ndb.transaction((lambda : fn(*args, **kwargs)), xg=True, propagation=ndb.TransactionOptions.ALLOWED)
| [
"def",
"run_in_transaction",
"(",
"fn",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"ndb",
".",
"transaction",
"(",
"(",
"lambda",
":",
"fn",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
")",
",",
"xg",
"=",
"True",
",",
"propagation",
"=",
"ndb",
".",
"TransactionOptions",
".",
"ALLOWED",
")"
] | runs a function in a transaction . | train | false |
38,034 | @bdd.when(bdd.parsers.re('I wait for (?P<is_regex>regex )?"(?P<pattern>[^"]+)" in the log(?P<do_skip> or skip the test)?'))
def wait_in_log(quteproc, is_regex, pattern, do_skip):
if is_regex:
pattern = re.compile(pattern)
line = quteproc.wait_for(message=pattern, do_skip=bool(do_skip))
line.expected = True
| [
"@",
"bdd",
".",
"when",
"(",
"bdd",
".",
"parsers",
".",
"re",
"(",
"'I wait for (?P<is_regex>regex )?\"(?P<pattern>[^\"]+)\" in the log(?P<do_skip> or skip the test)?'",
")",
")",
"def",
"wait_in_log",
"(",
"quteproc",
",",
"is_regex",
",",
"pattern",
",",
"do_skip",
")",
":",
"if",
"is_regex",
":",
"pattern",
"=",
"re",
".",
"compile",
"(",
"pattern",
")",
"line",
"=",
"quteproc",
".",
"wait_for",
"(",
"message",
"=",
"pattern",
",",
"do_skip",
"=",
"bool",
"(",
"do_skip",
")",
")",
"line",
".",
"expected",
"=",
"True"
] | wait for a given pattern in the qutebrowser log . | train | false |
38,035 | def make_resource_object(resource_type, credentials_path):
try:
(api_name, resource) = resource_type.split('.', 1)
except ValueError:
raise ValueError('resource_type "{0}" is not in form <api>.<resource>'.format(resource_type))
version = determine_version(api_name)
service = make_service(api_name, version, credentials_path)
path = resource.split('.')
node = service
for elem in path:
try:
node = getattr(node, elem)()
except AttributeError:
path_str = '.'.join(path[0:path.index(elem)])
raise AttributeError('"{0}{1}" has no attribute "{2}"'.format(api_name, (('.' + path_str) if path_str else ''), elem))
return node
| [
"def",
"make_resource_object",
"(",
"resource_type",
",",
"credentials_path",
")",
":",
"try",
":",
"(",
"api_name",
",",
"resource",
")",
"=",
"resource_type",
".",
"split",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'resource_type \"{0}\" is not in form <api>.<resource>'",
".",
"format",
"(",
"resource_type",
")",
")",
"version",
"=",
"determine_version",
"(",
"api_name",
")",
"service",
"=",
"make_service",
"(",
"api_name",
",",
"version",
",",
"credentials_path",
")",
"path",
"=",
"resource",
".",
"split",
"(",
"'.'",
")",
"node",
"=",
"service",
"for",
"elem",
"in",
"path",
":",
"try",
":",
"node",
"=",
"getattr",
"(",
"node",
",",
"elem",
")",
"(",
")",
"except",
"AttributeError",
":",
"path_str",
"=",
"'.'",
".",
"join",
"(",
"path",
"[",
"0",
":",
"path",
".",
"index",
"(",
"elem",
")",
"]",
")",
"raise",
"AttributeError",
"(",
"'\"{0}{1}\" has no attribute \"{2}\"'",
".",
"format",
"(",
"api_name",
",",
"(",
"(",
"'.'",
"+",
"path_str",
")",
"if",
"path_str",
"else",
"''",
")",
",",
"elem",
")",
")",
"return",
"node"
] | creates and configures the service object for operating on resources . | train | false |
38,037 | def untokenize(iterable):
ut = Untokenizer()
return ut.untokenize(iterable)
| [
"def",
"untokenize",
"(",
"iterable",
")",
":",
"ut",
"=",
"Untokenizer",
"(",
")",
"return",
"ut",
".",
"untokenize",
"(",
"iterable",
")"
] | transform tokens back into python source code . | train | false |
38,038 | def dmp_sqf_part(f, u, K):
if (not u):
return dup_sqf_part(f, K)
if K.is_FiniteField:
return dmp_gf_sqf_part(f, u, K)
if dmp_zero_p(f, u):
return f
if K.is_negative(dmp_ground_LC(f, u, K)):
f = dmp_neg(f, u, K)
gcd = dmp_gcd(f, dmp_diff(f, 1, u, K), u, K)
sqf = dmp_quo(f, gcd, u, K)
if K.has_Field:
return dmp_ground_monic(sqf, u, K)
else:
return dmp_ground_primitive(sqf, u, K)[1]
| [
"def",
"dmp_sqf_part",
"(",
"f",
",",
"u",
",",
"K",
")",
":",
"if",
"(",
"not",
"u",
")",
":",
"return",
"dup_sqf_part",
"(",
"f",
",",
"K",
")",
"if",
"K",
".",
"is_FiniteField",
":",
"return",
"dmp_gf_sqf_part",
"(",
"f",
",",
"u",
",",
"K",
")",
"if",
"dmp_zero_p",
"(",
"f",
",",
"u",
")",
":",
"return",
"f",
"if",
"K",
".",
"is_negative",
"(",
"dmp_ground_LC",
"(",
"f",
",",
"u",
",",
"K",
")",
")",
":",
"f",
"=",
"dmp_neg",
"(",
"f",
",",
"u",
",",
"K",
")",
"gcd",
"=",
"dmp_gcd",
"(",
"f",
",",
"dmp_diff",
"(",
"f",
",",
"1",
",",
"u",
",",
"K",
")",
",",
"u",
",",
"K",
")",
"sqf",
"=",
"dmp_quo",
"(",
"f",
",",
"gcd",
",",
"u",
",",
"K",
")",
"if",
"K",
".",
"has_Field",
":",
"return",
"dmp_ground_monic",
"(",
"sqf",
",",
"u",
",",
"K",
")",
"else",
":",
"return",
"dmp_ground_primitive",
"(",
"sqf",
",",
"u",
",",
"K",
")",
"[",
"1",
"]"
] | returns square-free part of a polynomial in k[x] . | train | false |
38,039 | def sysctl(cmdline):
result = sh(('sysctl ' + cmdline))
if FREEBSD:
result = result[(result.find(': ') + 2):]
elif (OPENBSD or NETBSD):
result = result[(result.find('=') + 1):]
try:
return int(result)
except ValueError:
return result
| [
"def",
"sysctl",
"(",
"cmdline",
")",
":",
"result",
"=",
"sh",
"(",
"(",
"'sysctl '",
"+",
"cmdline",
")",
")",
"if",
"FREEBSD",
":",
"result",
"=",
"result",
"[",
"(",
"result",
".",
"find",
"(",
"': '",
")",
"+",
"2",
")",
":",
"]",
"elif",
"(",
"OPENBSD",
"or",
"NETBSD",
")",
":",
"result",
"=",
"result",
"[",
"(",
"result",
".",
"find",
"(",
"'='",
")",
"+",
"1",
")",
":",
"]",
"try",
":",
"return",
"int",
"(",
"result",
")",
"except",
"ValueError",
":",
"return",
"result"
] | require a kernel parameter to have a specific value . | train | false |
38,040 | def volume_metadata_update(context, volume_id, metadata, delete):
IMPL.volume_metadata_update(context, volume_id, metadata, delete)
| [
"def",
"volume_metadata_update",
"(",
"context",
",",
"volume_id",
",",
"metadata",
",",
"delete",
")",
":",
"IMPL",
".",
"volume_metadata_update",
"(",
"context",
",",
"volume_id",
",",
"metadata",
",",
"delete",
")"
] | update metadata if it exists . | train | false |
38,042 | def unify_string_literals(js_string):
n = 0
res = ''
limit = len(js_string)
while (n < limit):
char = js_string[n]
if (char == '\\'):
(new, n) = do_escape(js_string, n)
res += new
else:
res += char
n += 1
return res
| [
"def",
"unify_string_literals",
"(",
"js_string",
")",
":",
"n",
"=",
"0",
"res",
"=",
"''",
"limit",
"=",
"len",
"(",
"js_string",
")",
"while",
"(",
"n",
"<",
"limit",
")",
":",
"char",
"=",
"js_string",
"[",
"n",
"]",
"if",
"(",
"char",
"==",
"'\\\\'",
")",
":",
"(",
"new",
",",
"n",
")",
"=",
"do_escape",
"(",
"js_string",
",",
"n",
")",
"res",
"+=",
"new",
"else",
":",
"res",
"+=",
"char",
"n",
"+=",
"1",
"return",
"res"
] | this function parses the string just like javascript for example literal d in javascript would be interpreted as d - backslash would be ignored and in pyhon this would be interpreted as d this function fixes this problem . | train | true |
38,043 | def fileserver_update(fileserver):
try:
if (not fileserver.servers):
log.error('No fileservers loaded, the master will not be able to serve files to minions')
raise SaltMasterError('No fileserver backends available')
fileserver.update()
except Exception as exc:
log.error('Exception {0} occurred in file server update'.format(exc), exc_info_on_loglevel=logging.DEBUG)
| [
"def",
"fileserver_update",
"(",
"fileserver",
")",
":",
"try",
":",
"if",
"(",
"not",
"fileserver",
".",
"servers",
")",
":",
"log",
".",
"error",
"(",
"'No fileservers loaded, the master will not be able to serve files to minions'",
")",
"raise",
"SaltMasterError",
"(",
"'No fileserver backends available'",
")",
"fileserver",
".",
"update",
"(",
")",
"except",
"Exception",
"as",
"exc",
":",
"log",
".",
"error",
"(",
"'Exception {0} occurred in file server update'",
".",
"format",
"(",
"exc",
")",
",",
"exc_info_on_loglevel",
"=",
"logging",
".",
"DEBUG",
")"
] | update the fileserver backends . | train | true |
38,045 | def error_message(msg, parent=None, title=None):
dialog = gtk.MessageDialog(parent=None, type=gtk.MESSAGE_ERROR, buttons=gtk.BUTTONS_OK, message_format=msg)
if (parent is not None):
dialog.set_transient_for(parent)
if (title is not None):
dialog.set_title(title)
else:
dialog.set_title(u'Error!')
dialog.show()
dialog.run()
dialog.destroy()
return None
| [
"def",
"error_message",
"(",
"msg",
",",
"parent",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"dialog",
"=",
"gtk",
".",
"MessageDialog",
"(",
"parent",
"=",
"None",
",",
"type",
"=",
"gtk",
".",
"MESSAGE_ERROR",
",",
"buttons",
"=",
"gtk",
".",
"BUTTONS_OK",
",",
"message_format",
"=",
"msg",
")",
"if",
"(",
"parent",
"is",
"not",
"None",
")",
":",
"dialog",
".",
"set_transient_for",
"(",
"parent",
")",
"if",
"(",
"title",
"is",
"not",
"None",
")",
":",
"dialog",
".",
"set_title",
"(",
"title",
")",
"else",
":",
"dialog",
".",
"set_title",
"(",
"u'Error!'",
")",
"dialog",
".",
"show",
"(",
")",
"dialog",
".",
"run",
"(",
")",
"dialog",
".",
"destroy",
"(",
")",
"return",
"None"
] | create an error message dialog with string msg . | train | false |
38,046 | def _get_build_env(env):
env_override = ''
if (env is None):
return env_override
if (not isinstance(env, dict)):
raise SaltInvocationError("'env' must be a Python dictionary")
for (key, value) in env.items():
env_override += '{0}={1}\n'.format(key, value)
env_override += 'export {0}\n'.format(key)
return env_override
| [
"def",
"_get_build_env",
"(",
"env",
")",
":",
"env_override",
"=",
"''",
"if",
"(",
"env",
"is",
"None",
")",
":",
"return",
"env_override",
"if",
"(",
"not",
"isinstance",
"(",
"env",
",",
"dict",
")",
")",
":",
"raise",
"SaltInvocationError",
"(",
"\"'env' must be a Python dictionary\"",
")",
"for",
"(",
"key",
",",
"value",
")",
"in",
"env",
".",
"items",
"(",
")",
":",
"env_override",
"+=",
"'{0}={1}\\n'",
".",
"format",
"(",
"key",
",",
"value",
")",
"env_override",
"+=",
"'export {0}\\n'",
".",
"format",
"(",
"key",
")",
"return",
"env_override"
] | get build environment overrides dictionary to use in build process . | train | true |
38,048 | def get_examples_from_docstring(doc_str):
examples = _DOCSTRING_TEST_PARSER.get_examples(doc_str)
example_str = ''
for example in examples:
example_str += ('%s' % (example.source,))
example_str += ('%s' % (example.want,))
return cgi.escape(example_str)
| [
"def",
"get_examples_from_docstring",
"(",
"doc_str",
")",
":",
"examples",
"=",
"_DOCSTRING_TEST_PARSER",
".",
"get_examples",
"(",
"doc_str",
")",
"example_str",
"=",
"''",
"for",
"example",
"in",
"examples",
":",
"example_str",
"+=",
"(",
"'%s'",
"%",
"(",
"example",
".",
"source",
",",
")",
")",
"example_str",
"+=",
"(",
"'%s'",
"%",
"(",
"example",
".",
"want",
",",
")",
")",
"return",
"cgi",
".",
"escape",
"(",
"example_str",
")"
] | parse doctest style code examples from a docstring . | train | false |
38,049 | def check_new_version_available(this_version):
pypi_url = 'https://pypi.python.org/pypi/Zappa/json'
resp = requests.get(pypi_url, timeout=1.5)
top_version = resp.json()['info']['version']
if (this_version != top_version):
return True
else:
return False
| [
"def",
"check_new_version_available",
"(",
"this_version",
")",
":",
"pypi_url",
"=",
"'https://pypi.python.org/pypi/Zappa/json'",
"resp",
"=",
"requests",
".",
"get",
"(",
"pypi_url",
",",
"timeout",
"=",
"1.5",
")",
"top_version",
"=",
"resp",
".",
"json",
"(",
")",
"[",
"'info'",
"]",
"[",
"'version'",
"]",
"if",
"(",
"this_version",
"!=",
"top_version",
")",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | checks if a newer version of zappa is available . | train | true |
38,051 | def set_lights_xy(hass, lights, x_val, y_val, brightness):
for light in lights:
if is_on(hass, light):
turn_on(hass, light, xy_color=[x_val, y_val], brightness=brightness, transition=30)
| [
"def",
"set_lights_xy",
"(",
"hass",
",",
"lights",
",",
"x_val",
",",
"y_val",
",",
"brightness",
")",
":",
"for",
"light",
"in",
"lights",
":",
"if",
"is_on",
"(",
"hass",
",",
"light",
")",
":",
"turn_on",
"(",
"hass",
",",
"light",
",",
"xy_color",
"=",
"[",
"x_val",
",",
"y_val",
"]",
",",
"brightness",
"=",
"brightness",
",",
"transition",
"=",
"30",
")"
] | set color of array of lights . | train | false |
38,052 | def _check_hosts(service_instance, host, host_names):
if (not host_names):
host_name = _get_host_ref(service_instance, host)
if host_name:
host_names = [host]
else:
raise CommandExecutionError("No host reference found. If connecting to a vCenter Server, a list of 'host_names' must be provided.")
elif (not isinstance(host_names, list)):
raise CommandExecutionError("'host_names' must be a list.")
return host_names
| [
"def",
"_check_hosts",
"(",
"service_instance",
",",
"host",
",",
"host_names",
")",
":",
"if",
"(",
"not",
"host_names",
")",
":",
"host_name",
"=",
"_get_host_ref",
"(",
"service_instance",
",",
"host",
")",
"if",
"host_name",
":",
"host_names",
"=",
"[",
"host",
"]",
"else",
":",
"raise",
"CommandExecutionError",
"(",
"\"No host reference found. If connecting to a vCenter Server, a list of 'host_names' must be provided.\"",
")",
"elif",
"(",
"not",
"isinstance",
"(",
"host_names",
",",
"list",
")",
")",
":",
"raise",
"CommandExecutionError",
"(",
"\"'host_names' must be a list.\"",
")",
"return",
"host_names"
] | helper function that checks to see if the host provided is a vcenter server or an esxi host . | train | true |
38,053 | def update_samples(autotest_dir, add_noncompliant, add_experimental):
sample_path = os.path.join(autotest_dir, 'server/samples')
if os.path.exists(sample_path):
logging.info('Scanning %s', sample_path)
tests = get_tests_from_fs(sample_path, '.*srv$', add_noncompliant=add_noncompliant)
update_tests_in_db(tests, add_experimental=add_experimental, add_noncompliant=add_noncompliant, autotest_dir=autotest_dir)
| [
"def",
"update_samples",
"(",
"autotest_dir",
",",
"add_noncompliant",
",",
"add_experimental",
")",
":",
"sample_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"autotest_dir",
",",
"'server/samples'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"sample_path",
")",
":",
"logging",
".",
"info",
"(",
"'Scanning %s'",
",",
"sample_path",
")",
"tests",
"=",
"get_tests_from_fs",
"(",
"sample_path",
",",
"'.*srv$'",
",",
"add_noncompliant",
"=",
"add_noncompliant",
")",
"update_tests_in_db",
"(",
"tests",
",",
"add_experimental",
"=",
"add_experimental",
",",
"add_noncompliant",
"=",
"add_noncompliant",
",",
"autotest_dir",
"=",
"autotest_dir",
")"
] | add only sample tests to the database from the filesystem . | train | false |
38,055 | def _api_set_config(name, output, kwargs):
if (kwargs.get('section') == 'servers'):
kwargs['keyword'] = handle_server_api(output, kwargs)
elif (kwargs.get('section') == 'rss'):
kwargs['keyword'] = handle_rss_api(output, kwargs)
elif (kwargs.get('section') == 'categories'):
kwargs['keyword'] = handle_cat_api(output, kwargs)
else:
res = config.set_config(kwargs)
if (not res):
return report(output, _MSG_NO_SUCH_CONFIG)
config.save_config()
(res, data) = config.get_dconfig(kwargs.get('section'), kwargs.get('keyword'))
return report(output, keyword='config', data=data)
| [
"def",
"_api_set_config",
"(",
"name",
",",
"output",
",",
"kwargs",
")",
":",
"if",
"(",
"kwargs",
".",
"get",
"(",
"'section'",
")",
"==",
"'servers'",
")",
":",
"kwargs",
"[",
"'keyword'",
"]",
"=",
"handle_server_api",
"(",
"output",
",",
"kwargs",
")",
"elif",
"(",
"kwargs",
".",
"get",
"(",
"'section'",
")",
"==",
"'rss'",
")",
":",
"kwargs",
"[",
"'keyword'",
"]",
"=",
"handle_rss_api",
"(",
"output",
",",
"kwargs",
")",
"elif",
"(",
"kwargs",
".",
"get",
"(",
"'section'",
")",
"==",
"'categories'",
")",
":",
"kwargs",
"[",
"'keyword'",
"]",
"=",
"handle_cat_api",
"(",
"output",
",",
"kwargs",
")",
"else",
":",
"res",
"=",
"config",
".",
"set_config",
"(",
"kwargs",
")",
"if",
"(",
"not",
"res",
")",
":",
"return",
"report",
"(",
"output",
",",
"_MSG_NO_SUCH_CONFIG",
")",
"config",
".",
"save_config",
"(",
")",
"(",
"res",
",",
"data",
")",
"=",
"config",
".",
"get_dconfig",
"(",
"kwargs",
".",
"get",
"(",
"'section'",
")",
",",
"kwargs",
".",
"get",
"(",
"'keyword'",
")",
")",
"return",
"report",
"(",
"output",
",",
"keyword",
"=",
"'config'",
",",
"data",
"=",
"data",
")"
] | api: accepts output . | train | false |
38,057 | def update_installed_list(op, package):
if (op == 'i'):
installed_packages_list[package.name] = package
elif (op == 'r'):
del installed_packages_list[package.name]
else:
raise RuntimeError(("[cf] fatal: invalid configuration op '%s'." % op))
write_installed_packages_list()
| [
"def",
"update_installed_list",
"(",
"op",
",",
"package",
")",
":",
"if",
"(",
"op",
"==",
"'i'",
")",
":",
"installed_packages_list",
"[",
"package",
".",
"name",
"]",
"=",
"package",
"elif",
"(",
"op",
"==",
"'r'",
")",
":",
"del",
"installed_packages_list",
"[",
"package",
".",
"name",
"]",
"else",
":",
"raise",
"RuntimeError",
"(",
"(",
"\"[cf] fatal: invalid configuration op '%s'.\"",
"%",
"op",
")",
")",
"write_installed_packages_list",
"(",
")"
] | updates the internal list of installed packages . | train | false |
38,060 | def MakeSuiteFromList(t, label=None):
hist = MakeHistFromList(t, label=label)
d = hist.GetDict()
return MakeSuiteFromDict(d)
| [
"def",
"MakeSuiteFromList",
"(",
"t",
",",
"label",
"=",
"None",
")",
":",
"hist",
"=",
"MakeHistFromList",
"(",
"t",
",",
"label",
"=",
"label",
")",
"d",
"=",
"hist",
".",
"GetDict",
"(",
")",
"return",
"MakeSuiteFromDict",
"(",
"d",
")"
] | makes a suite from an unsorted sequence of values . | train | false |
38,061 | def write_to_file(filename, data, report=False):
f = open(filename, 'w')
try:
f.write(data)
finally:
f.close()
if report:
gdb_report(filename)
return filename
| [
"def",
"write_to_file",
"(",
"filename",
",",
"data",
",",
"report",
"=",
"False",
")",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"'w'",
")",
"try",
":",
"f",
".",
"write",
"(",
"data",
")",
"finally",
":",
"f",
".",
"close",
"(",
")",
"if",
"report",
":",
"gdb_report",
"(",
"filename",
")",
"return",
"filename"
] | write contents to a given file path specified . | train | false |
38,062 | def setup_output(port):
import RPi.GPIO as GPIO
GPIO.setup(port, GPIO.OUT)
| [
"def",
"setup_output",
"(",
"port",
")",
":",
"import",
"RPi",
".",
"GPIO",
"as",
"GPIO",
"GPIO",
".",
"setup",
"(",
"port",
",",
"GPIO",
".",
"OUT",
")"
] | setup a gpio as output . | train | false |
38,063 | def load_compute_driver(virtapi, compute_driver=None):
if (not compute_driver):
compute_driver = CONF.compute_driver
if (not compute_driver):
LOG.error(_LE('Compute driver option required, but not specified'))
sys.exit(1)
LOG.info(_LI("Loading compute driver '%s'"), compute_driver)
try:
driver = importutils.import_object(('nova.virt.%s' % compute_driver), virtapi)
return utils.check_isinstance(driver, ComputeDriver)
except ImportError:
LOG.exception(_LE('Unable to load the virtualization driver'))
sys.exit(1)
| [
"def",
"load_compute_driver",
"(",
"virtapi",
",",
"compute_driver",
"=",
"None",
")",
":",
"if",
"(",
"not",
"compute_driver",
")",
":",
"compute_driver",
"=",
"CONF",
".",
"compute_driver",
"if",
"(",
"not",
"compute_driver",
")",
":",
"LOG",
".",
"error",
"(",
"_LE",
"(",
"'Compute driver option required, but not specified'",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"LOG",
".",
"info",
"(",
"_LI",
"(",
"\"Loading compute driver '%s'\"",
")",
",",
"compute_driver",
")",
"try",
":",
"driver",
"=",
"importutils",
".",
"import_object",
"(",
"(",
"'nova.virt.%s'",
"%",
"compute_driver",
")",
",",
"virtapi",
")",
"return",
"utils",
".",
"check_isinstance",
"(",
"driver",
",",
"ComputeDriver",
")",
"except",
"ImportError",
":",
"LOG",
".",
"exception",
"(",
"_LE",
"(",
"'Unable to load the virtualization driver'",
")",
")",
"sys",
".",
"exit",
"(",
"1",
")"
] | load a compute driver module . | train | false |
38,064 | def test_load_started(progress_widget):
progress_widget.on_load_started()
assert (progress_widget.value() == 0)
assert progress_widget.isVisible()
| [
"def",
"test_load_started",
"(",
"progress_widget",
")",
":",
"progress_widget",
".",
"on_load_started",
"(",
")",
"assert",
"(",
"progress_widget",
".",
"value",
"(",
")",
"==",
"0",
")",
"assert",
"progress_widget",
".",
"isVisible",
"(",
")"
] | ensure the progress widget reacts properly when the page starts loading . | train | false |
38,065 | def flavor_extra_specs_delete(context, flavor_id, key):
IMPL.flavor_extra_specs_delete(context, flavor_id, key)
| [
"def",
"flavor_extra_specs_delete",
"(",
"context",
",",
"flavor_id",
",",
"key",
")",
":",
"IMPL",
".",
"flavor_extra_specs_delete",
"(",
"context",
",",
"flavor_id",
",",
"key",
")"
] | delete the given extra specs item . | train | false |
38,068 | def median(values):
values = sorted(values)
length = len(values)
mid = (length // 2)
if (length % 2):
return values[mid]
else:
return ((values[(mid - 1)] + values[mid]) / 2)
| [
"def",
"median",
"(",
"values",
")",
":",
"values",
"=",
"sorted",
"(",
"values",
")",
"length",
"=",
"len",
"(",
"values",
")",
"mid",
"=",
"(",
"length",
"//",
"2",
")",
"if",
"(",
"length",
"%",
"2",
")",
":",
"return",
"values",
"[",
"mid",
"]",
"else",
":",
"return",
"(",
"(",
"values",
"[",
"(",
"mid",
"-",
"1",
")",
"]",
"+",
"values",
"[",
"mid",
"]",
")",
"/",
"2",
")"
] | performs median/wpgmc linkage . | train | false |
38,069 | def remove_extension(template):
return template[:(- len('.template'))]
| [
"def",
"remove_extension",
"(",
"template",
")",
":",
"return",
"template",
"[",
":",
"(",
"-",
"len",
"(",
"'.template'",
")",
")",
"]"
] | remove download or media extension from name . | train | false |
38,071 | def sendEmail(SUBJECT, BODY, TO, FROM, SENDER, PASSWORD, SMTP_SERVER):
for body_charset in ('US-ASCII', 'ISO-8859-1', 'UTF-8'):
try:
BODY.encode(body_charset)
except UnicodeError:
pass
else:
break
msg = MIMEText(BODY.encode(body_charset), 'html', body_charset)
msg['From'] = SENDER
msg['To'] = TO
msg['Subject'] = SUBJECT
SMTP_PORT = 587
session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
session.starttls()
session.login(FROM, PASSWORD)
session.sendmail(SENDER, TO, msg.as_string())
session.quit()
| [
"def",
"sendEmail",
"(",
"SUBJECT",
",",
"BODY",
",",
"TO",
",",
"FROM",
",",
"SENDER",
",",
"PASSWORD",
",",
"SMTP_SERVER",
")",
":",
"for",
"body_charset",
"in",
"(",
"'US-ASCII'",
",",
"'ISO-8859-1'",
",",
"'UTF-8'",
")",
":",
"try",
":",
"BODY",
".",
"encode",
"(",
"body_charset",
")",
"except",
"UnicodeError",
":",
"pass",
"else",
":",
"break",
"msg",
"=",
"MIMEText",
"(",
"BODY",
".",
"encode",
"(",
"body_charset",
")",
",",
"'html'",
",",
"body_charset",
")",
"msg",
"[",
"'From'",
"]",
"=",
"SENDER",
"msg",
"[",
"'To'",
"]",
"=",
"TO",
"msg",
"[",
"'Subject'",
"]",
"=",
"SUBJECT",
"SMTP_PORT",
"=",
"587",
"session",
"=",
"smtplib",
".",
"SMTP",
"(",
"SMTP_SERVER",
",",
"SMTP_PORT",
")",
"session",
".",
"starttls",
"(",
")",
"session",
".",
"login",
"(",
"FROM",
",",
"PASSWORD",
")",
"session",
".",
"sendmail",
"(",
"SENDER",
",",
"TO",
",",
"msg",
".",
"as_string",
"(",
")",
")",
"session",
".",
"quit",
"(",
")"
] | sends an html email . | train | false |
38,074 | def absent(name):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
grp_info = __salt__['group.info'](name)
if grp_info:
if __opts__['test']:
ret['result'] = None
ret['comment'] = 'Group {0} is set for removal'.format(name)
return ret
ret['result'] = __salt__['group.delete'](name)
if ret['result']:
ret['changes'] = {name: ''}
ret['comment'] = 'Removed group {0}'.format(name)
return ret
else:
ret['comment'] = 'Failed to remove group {0}'.format(name)
return ret
else:
ret['comment'] = 'Group not present'
return ret
| [
"def",
"absent",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"grp_info",
"=",
"__salt__",
"[",
"'group.info'",
"]",
"(",
"name",
")",
"if",
"grp_info",
":",
"if",
"__opts__",
"[",
"'test'",
"]",
":",
"ret",
"[",
"'result'",
"]",
"=",
"None",
"ret",
"[",
"'comment'",
"]",
"=",
"'Group {0} is set for removal'",
".",
"format",
"(",
"name",
")",
"return",
"ret",
"ret",
"[",
"'result'",
"]",
"=",
"__salt__",
"[",
"'group.delete'",
"]",
"(",
"name",
")",
"if",
"ret",
"[",
"'result'",
"]",
":",
"ret",
"[",
"'changes'",
"]",
"=",
"{",
"name",
":",
"''",
"}",
"ret",
"[",
"'comment'",
"]",
"=",
"'Removed group {0}'",
".",
"format",
"(",
"name",
")",
"return",
"ret",
"else",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Failed to remove group {0}'",
".",
"format",
"(",
"name",
")",
"return",
"ret",
"else",
":",
"ret",
"[",
"'comment'",
"]",
"=",
"'Group not present'",
"return",
"ret"
] | ensure that a org is present . | train | false |
38,075 | def run_dummyrunner(number_of_dummies):
number_of_dummies = (str(int(number_of_dummies)) if number_of_dummies else 1)
cmdstr = [sys.executable, EVENNIA_DUMMYRUNNER, '-N', number_of_dummies]
config_file = os.path.join(SETTINGS_PATH, 'dummyrunner_settings.py')
if os.path.exists(config_file):
cmdstr.extend(['--config', config_file])
try:
call(cmdstr, env=getenv())
except KeyboardInterrupt:
pass
| [
"def",
"run_dummyrunner",
"(",
"number_of_dummies",
")",
":",
"number_of_dummies",
"=",
"(",
"str",
"(",
"int",
"(",
"number_of_dummies",
")",
")",
"if",
"number_of_dummies",
"else",
"1",
")",
"cmdstr",
"=",
"[",
"sys",
".",
"executable",
",",
"EVENNIA_DUMMYRUNNER",
",",
"'-N'",
",",
"number_of_dummies",
"]",
"config_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"SETTINGS_PATH",
",",
"'dummyrunner_settings.py'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"cmdstr",
".",
"extend",
"(",
"[",
"'--config'",
",",
"config_file",
"]",
")",
"try",
":",
"call",
"(",
"cmdstr",
",",
"env",
"=",
"getenv",
"(",
")",
")",
"except",
"KeyboardInterrupt",
":",
"pass"
] | start an instance of the dummyrunner args: number_of_dummies : the number of dummy players to start . | train | false |
38,078 | def _is_valid_field_name(name):
return (name and (name == name.strip()) and (not name.startswith('_')) and ('"' not in name))
| [
"def",
"_is_valid_field_name",
"(",
"name",
")",
":",
"return",
"(",
"name",
"and",
"(",
"name",
"==",
"name",
".",
"strip",
"(",
")",
")",
"and",
"(",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
")",
"and",
"(",
"'\"'",
"not",
"in",
"name",
")",
")"
] | check that field name is valid: * cant start or end with whitespace characters * cant start with underscore * cant contain double quote (") * cant be empty . | train | false |
38,079 | def sent_tokenize(text, language='english'):
tokenizer = load('tokenizers/punkt/{0}.pickle'.format(language))
return tokenizer.tokenize(text)
| [
"def",
"sent_tokenize",
"(",
"text",
",",
"language",
"=",
"'english'",
")",
":",
"tokenizer",
"=",
"load",
"(",
"'tokenizers/punkt/{0}.pickle'",
".",
"format",
"(",
"language",
")",
")",
"return",
"tokenizer",
".",
"tokenize",
"(",
"text",
")"
] | return a sentence-tokenized copy of *text* . | train | false |
38,080 | def gs_distill(tmpfile, eps=False, ptype=u'letter', bbox=None, rotated=False):
if eps:
paper_option = u'-dEPSCrop'
else:
paper_option = (u'-sPAPERSIZE=%s' % ptype)
psfile = (tmpfile + u'.ps')
outfile = (tmpfile + u'.output')
dpi = rcParams[u'ps.distiller.res']
gs_exe = ps_backend_helper.gs_exe
if ps_backend_helper.supports_ps2write:
device_name = u'ps2write'
else:
device_name = u'pswrite'
command = (u'%s -dBATCH -dNOPAUSE -r%d -sDEVICE=%s %s -sOutputFile="%s" "%s" > "%s"' % (gs_exe, dpi, device_name, paper_option, psfile, tmpfile, outfile))
verbose.report(command, u'debug')
exit_status = os.system(command)
with io.open(outfile, u'rb') as fh:
if exit_status:
output = fh.read()
m = u'\n'.join([u'ghostscript was not able to process your image.', u'Here is the full report generated by ghostscript:', u'', u'%s'])
raise RuntimeError((m % output))
else:
verbose.report(fh.read(), u'debug')
os.remove(outfile)
os.remove(tmpfile)
shutil.move(psfile, tmpfile)
if eps:
if ps_backend_helper.supports_ps2write:
pstoeps(tmpfile, bbox, rotated=rotated)
else:
pstoeps(tmpfile)
| [
"def",
"gs_distill",
"(",
"tmpfile",
",",
"eps",
"=",
"False",
",",
"ptype",
"=",
"u'letter'",
",",
"bbox",
"=",
"None",
",",
"rotated",
"=",
"False",
")",
":",
"if",
"eps",
":",
"paper_option",
"=",
"u'-dEPSCrop'",
"else",
":",
"paper_option",
"=",
"(",
"u'-sPAPERSIZE=%s'",
"%",
"ptype",
")",
"psfile",
"=",
"(",
"tmpfile",
"+",
"u'.ps'",
")",
"outfile",
"=",
"(",
"tmpfile",
"+",
"u'.output'",
")",
"dpi",
"=",
"rcParams",
"[",
"u'ps.distiller.res'",
"]",
"gs_exe",
"=",
"ps_backend_helper",
".",
"gs_exe",
"if",
"ps_backend_helper",
".",
"supports_ps2write",
":",
"device_name",
"=",
"u'ps2write'",
"else",
":",
"device_name",
"=",
"u'pswrite'",
"command",
"=",
"(",
"u'%s -dBATCH -dNOPAUSE -r%d -sDEVICE=%s %s -sOutputFile=\"%s\" \"%s\" > \"%s\"'",
"%",
"(",
"gs_exe",
",",
"dpi",
",",
"device_name",
",",
"paper_option",
",",
"psfile",
",",
"tmpfile",
",",
"outfile",
")",
")",
"verbose",
".",
"report",
"(",
"command",
",",
"u'debug'",
")",
"exit_status",
"=",
"os",
".",
"system",
"(",
"command",
")",
"with",
"io",
".",
"open",
"(",
"outfile",
",",
"u'rb'",
")",
"as",
"fh",
":",
"if",
"exit_status",
":",
"output",
"=",
"fh",
".",
"read",
"(",
")",
"m",
"=",
"u'\\n'",
".",
"join",
"(",
"[",
"u'ghostscript was not able to process your image.'",
",",
"u'Here is the full report generated by ghostscript:'",
",",
"u''",
",",
"u'%s'",
"]",
")",
"raise",
"RuntimeError",
"(",
"(",
"m",
"%",
"output",
")",
")",
"else",
":",
"verbose",
".",
"report",
"(",
"fh",
".",
"read",
"(",
")",
",",
"u'debug'",
")",
"os",
".",
"remove",
"(",
"outfile",
")",
"os",
".",
"remove",
"(",
"tmpfile",
")",
"shutil",
".",
"move",
"(",
"psfile",
",",
"tmpfile",
")",
"if",
"eps",
":",
"if",
"ps_backend_helper",
".",
"supports_ps2write",
":",
"pstoeps",
"(",
"tmpfile",
",",
"bbox",
",",
"rotated",
"=",
"rotated",
")",
"else",
":",
"pstoeps",
"(",
"tmpfile",
")"
] | use ghostscripts pswrite or epswrite device to distill a file . | train | false |
38,081 | def _list_taps():
cmd = 'brew tap'
return _call_brew(cmd)['stdout'].splitlines()
| [
"def",
"_list_taps",
"(",
")",
":",
"cmd",
"=",
"'brew tap'",
"return",
"_call_brew",
"(",
"cmd",
")",
"[",
"'stdout'",
"]",
".",
"splitlines",
"(",
")"
] | list currently installed brew taps . | train | false |
38,083 | def example1_build_mountains(x, y, **kwargs):
room = create_object(rooms.Room, key=(('mountains' + str(x)) + str(y)))
room_desc = ['Mountains as far as the eye can see', 'Your path is surrounded by sheer cliffs', "Haven't you seen that rock before?"]
room.db.desc = random.choice(room_desc)
for i in xrange(randint(0, 3)):
rock = create_object(key='Rock', location=room)
rock.db.desc = 'An ordinary rock.'
kwargs['caller'].msg(((room.key + ' ') + room.dbref))
return room
| [
"def",
"example1_build_mountains",
"(",
"x",
",",
"y",
",",
"**",
"kwargs",
")",
":",
"room",
"=",
"create_object",
"(",
"rooms",
".",
"Room",
",",
"key",
"=",
"(",
"(",
"'mountains'",
"+",
"str",
"(",
"x",
")",
")",
"+",
"str",
"(",
"y",
")",
")",
")",
"room_desc",
"=",
"[",
"'Mountains as far as the eye can see'",
",",
"'Your path is surrounded by sheer cliffs'",
",",
"\"Haven't you seen that rock before?\"",
"]",
"room",
".",
"db",
".",
"desc",
"=",
"random",
".",
"choice",
"(",
"room_desc",
")",
"for",
"i",
"in",
"xrange",
"(",
"randint",
"(",
"0",
",",
"3",
")",
")",
":",
"rock",
"=",
"create_object",
"(",
"key",
"=",
"'Rock'",
",",
"location",
"=",
"room",
")",
"rock",
".",
"db",
".",
"desc",
"=",
"'An ordinary rock.'",
"kwargs",
"[",
"'caller'",
"]",
".",
"msg",
"(",
"(",
"(",
"room",
".",
"key",
"+",
"' '",
")",
"+",
"room",
".",
"dbref",
")",
")",
"return",
"room"
] | a room that is a little more advanced . | train | false |
38,084 | def servicegroup_server_exists(sg_name, s_name, s_port=None, **connection_args):
return (_servicegroup_get_server(sg_name, s_name, s_port, **connection_args) is not None)
| [
"def",
"servicegroup_server_exists",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
"=",
"None",
",",
"**",
"connection_args",
")",
":",
"return",
"(",
"_servicegroup_get_server",
"(",
"sg_name",
",",
"s_name",
",",
"s_port",
",",
"**",
"connection_args",
")",
"is",
"not",
"None",
")"
] | check if a server:port combination is a member of a servicegroup cli example: . | train | true |
38,085 | @_built_in_directive
def documentation(default=None, api_version=None, api=None, **kwargs):
api_version = (default or api_version)
if api:
return api.http.documentation(base_url='', api_version=api_version)
| [
"@",
"_built_in_directive",
"def",
"documentation",
"(",
"default",
"=",
"None",
",",
"api_version",
"=",
"None",
",",
"api",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"api_version",
"=",
"(",
"default",
"or",
"api_version",
")",
"if",
"api",
":",
"return",
"api",
".",
"http",
".",
"documentation",
"(",
"base_url",
"=",
"''",
",",
"api_version",
"=",
"api_version",
")"
] | returns link to weblate documentation . | train | true |
38,088 | def _arrays_to_mgr(arrays, arr_names, index, columns, dtype=None):
if (index is None):
index = extract_index(arrays)
else:
index = _ensure_index(index)
arrays = _homogenize(arrays, index, dtype)
axes = [_ensure_index(columns), _ensure_index(index)]
return create_block_manager_from_arrays(arrays, arr_names, axes)
| [
"def",
"_arrays_to_mgr",
"(",
"arrays",
",",
"arr_names",
",",
"index",
",",
"columns",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"(",
"index",
"is",
"None",
")",
":",
"index",
"=",
"extract_index",
"(",
"arrays",
")",
"else",
":",
"index",
"=",
"_ensure_index",
"(",
"index",
")",
"arrays",
"=",
"_homogenize",
"(",
"arrays",
",",
"index",
",",
"dtype",
")",
"axes",
"=",
"[",
"_ensure_index",
"(",
"columns",
")",
",",
"_ensure_index",
"(",
"index",
")",
"]",
"return",
"create_block_manager_from_arrays",
"(",
"arrays",
",",
"arr_names",
",",
"axes",
")"
] | segregate series based on type and coerce into matrices . | train | false |
38,089 | def format_directive(module, package=None):
directive = ('.. automodule:: %s\n' % makename(package, module))
for option in OPTIONS:
directive += (' :%s:\n' % option)
return directive
| [
"def",
"format_directive",
"(",
"module",
",",
"package",
"=",
"None",
")",
":",
"directive",
"=",
"(",
"'.. automodule:: %s\\n'",
"%",
"makename",
"(",
"package",
",",
"module",
")",
")",
"for",
"option",
"in",
"OPTIONS",
":",
"directive",
"+=",
"(",
"' :%s:\\n'",
"%",
"option",
")",
"return",
"directive"
] | create the automodule directive and add the options . | train | true |
38,090 | def migration_update(context, id, values):
return IMPL.migration_update(context, id, values)
| [
"def",
"migration_update",
"(",
"context",
",",
"id",
",",
"values",
")",
":",
"return",
"IMPL",
".",
"migration_update",
"(",
"context",
",",
"id",
",",
"values",
")"
] | update a migration instance . | train | false |
38,091 | def plot_mesh(x, y, tri):
for t in tri:
t_ext = [t[0], t[1], t[2], t[0]]
plot(x[t_ext], y[t_ext], 'r')
| [
"def",
"plot_mesh",
"(",
"x",
",",
"y",
",",
"tri",
")",
":",
"for",
"t",
"in",
"tri",
":",
"t_ext",
"=",
"[",
"t",
"[",
"0",
"]",
",",
"t",
"[",
"1",
"]",
",",
"t",
"[",
"2",
"]",
",",
"t",
"[",
"0",
"]",
"]",
"plot",
"(",
"x",
"[",
"t_ext",
"]",
",",
"y",
"[",
"t_ext",
"]",
",",
"'r'",
")"
] | plot triangles . | train | false |
38,092 | def _printAvailableCheckpoints(experimentDir):
checkpointParentDir = getCheckpointParentDir(experimentDir)
if (not os.path.exists(checkpointParentDir)):
print 'No available checkpoints.'
return
checkpointDirs = [x for x in os.listdir(checkpointParentDir) if _isCheckpointDir(os.path.join(checkpointParentDir, x))]
if (not checkpointDirs):
print 'No available checkpoints.'
return
print 'Available checkpoints:'
checkpointList = [_checkpointLabelFromCheckpointDir(x) for x in checkpointDirs]
for checkpoint in sorted(checkpointList):
print ' DCTB ', checkpoint
print
print 'To start from a checkpoint:'
print ' python run_opf_experiment.py experiment --load <CHECKPOINT>'
print 'For example, to start from the checkpoint "MyCheckpoint":'
print ' python run_opf_experiment.py experiment --load MyCheckpoint'
| [
"def",
"_printAvailableCheckpoints",
"(",
"experimentDir",
")",
":",
"checkpointParentDir",
"=",
"getCheckpointParentDir",
"(",
"experimentDir",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"checkpointParentDir",
")",
")",
":",
"print",
"'No available checkpoints.'",
"return",
"checkpointDirs",
"=",
"[",
"x",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"checkpointParentDir",
")",
"if",
"_isCheckpointDir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"checkpointParentDir",
",",
"x",
")",
")",
"]",
"if",
"(",
"not",
"checkpointDirs",
")",
":",
"print",
"'No available checkpoints.'",
"return",
"print",
"'Available checkpoints:'",
"checkpointList",
"=",
"[",
"_checkpointLabelFromCheckpointDir",
"(",
"x",
")",
"for",
"x",
"in",
"checkpointDirs",
"]",
"for",
"checkpoint",
"in",
"sorted",
"(",
"checkpointList",
")",
":",
"print",
"' DCTB '",
",",
"checkpoint",
"print",
"print",
"'To start from a checkpoint:'",
"print",
"' python run_opf_experiment.py experiment --load <CHECKPOINT>'",
"print",
"'For example, to start from the checkpoint \"MyCheckpoint\":'",
"print",
"' python run_opf_experiment.py experiment --load MyCheckpoint'"
] | list available checkpoints for the specified experiment . | train | true |
38,093 | def extract_wininst_cfg(dist_filename):
f = open(dist_filename, 'rb')
try:
endrec = zipfile._EndRecData(f)
if (endrec is None):
return None
prepended = ((endrec[9] - endrec[5]) - endrec[6])
if (prepended < 12):
return None
f.seek((prepended - 12))
import struct, StringIO, ConfigParser
(tag, cfglen, bmlen) = struct.unpack('<iii', f.read(12))
if (tag not in (305419898, 305419899)):
return None
f.seek((prepended - (12 + cfglen)))
cfg = ConfigParser.RawConfigParser({'version': '', 'target_version': ''})
try:
cfg.readfp(StringIO.StringIO(f.read(cfglen).split(chr(0), 1)[0]))
except ConfigParser.Error:
return None
if ((not cfg.has_section('metadata')) or (not cfg.has_section('Setup'))):
return None
return cfg
finally:
f.close()
| [
"def",
"extract_wininst_cfg",
"(",
"dist_filename",
")",
":",
"f",
"=",
"open",
"(",
"dist_filename",
",",
"'rb'",
")",
"try",
":",
"endrec",
"=",
"zipfile",
".",
"_EndRecData",
"(",
"f",
")",
"if",
"(",
"endrec",
"is",
"None",
")",
":",
"return",
"None",
"prepended",
"=",
"(",
"(",
"endrec",
"[",
"9",
"]",
"-",
"endrec",
"[",
"5",
"]",
")",
"-",
"endrec",
"[",
"6",
"]",
")",
"if",
"(",
"prepended",
"<",
"12",
")",
":",
"return",
"None",
"f",
".",
"seek",
"(",
"(",
"prepended",
"-",
"12",
")",
")",
"import",
"struct",
",",
"StringIO",
",",
"ConfigParser",
"(",
"tag",
",",
"cfglen",
",",
"bmlen",
")",
"=",
"struct",
".",
"unpack",
"(",
"'<iii'",
",",
"f",
".",
"read",
"(",
"12",
")",
")",
"if",
"(",
"tag",
"not",
"in",
"(",
"305419898",
",",
"305419899",
")",
")",
":",
"return",
"None",
"f",
".",
"seek",
"(",
"(",
"prepended",
"-",
"(",
"12",
"+",
"cfglen",
")",
")",
")",
"cfg",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
"{",
"'version'",
":",
"''",
",",
"'target_version'",
":",
"''",
"}",
")",
"try",
":",
"cfg",
".",
"readfp",
"(",
"StringIO",
".",
"StringIO",
"(",
"f",
".",
"read",
"(",
"cfglen",
")",
".",
"split",
"(",
"chr",
"(",
"0",
")",
",",
"1",
")",
"[",
"0",
"]",
")",
")",
"except",
"ConfigParser",
".",
"Error",
":",
"return",
"None",
"if",
"(",
"(",
"not",
"cfg",
".",
"has_section",
"(",
"'metadata'",
")",
")",
"or",
"(",
"not",
"cfg",
".",
"has_section",
"(",
"'Setup'",
")",
")",
")",
":",
"return",
"None",
"return",
"cfg",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | extract configuration data from a bdist_wininst . | train | false |
38,094 | def in6_getRandomizedIfaceId(ifaceid, previous=None):
s = ''
if (previous is None):
d = ''.join(map(chr, range(256)))
for i in range(8):
s += random.choice(d)
previous = s
s = (inet_pton(socket.AF_INET6, ('::' + ifaceid))[8:] + previous)
import md5
s = md5.new(s).digest()
(s1, s2) = (s[:8], s[8:])
s1 = (chr((ord(s1[0]) | 4)) + s1[1:])
s1 = inet_ntop(socket.AF_INET6, (('\xff' * 8) + s1))[20:]
s2 = inet_ntop(socket.AF_INET6, (('\xff' * 8) + s2))[20:]
return (s1, s2)
| [
"def",
"in6_getRandomizedIfaceId",
"(",
"ifaceid",
",",
"previous",
"=",
"None",
")",
":",
"s",
"=",
"''",
"if",
"(",
"previous",
"is",
"None",
")",
":",
"d",
"=",
"''",
".",
"join",
"(",
"map",
"(",
"chr",
",",
"range",
"(",
"256",
")",
")",
")",
"for",
"i",
"in",
"range",
"(",
"8",
")",
":",
"s",
"+=",
"random",
".",
"choice",
"(",
"d",
")",
"previous",
"=",
"s",
"s",
"=",
"(",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"(",
"'::'",
"+",
"ifaceid",
")",
")",
"[",
"8",
":",
"]",
"+",
"previous",
")",
"import",
"md5",
"s",
"=",
"md5",
".",
"new",
"(",
"s",
")",
".",
"digest",
"(",
")",
"(",
"s1",
",",
"s2",
")",
"=",
"(",
"s",
"[",
":",
"8",
"]",
",",
"s",
"[",
"8",
":",
"]",
")",
"s1",
"=",
"(",
"chr",
"(",
"(",
"ord",
"(",
"s1",
"[",
"0",
"]",
")",
"|",
"4",
")",
")",
"+",
"s1",
"[",
"1",
":",
"]",
")",
"s1",
"=",
"inet_ntop",
"(",
"socket",
".",
"AF_INET6",
",",
"(",
"(",
"'\\xff'",
"*",
"8",
")",
"+",
"s1",
")",
")",
"[",
"20",
":",
"]",
"s2",
"=",
"inet_ntop",
"(",
"socket",
".",
"AF_INET6",
",",
"(",
"(",
"'\\xff'",
"*",
"8",
")",
"+",
"s2",
")",
")",
"[",
"20",
":",
"]",
"return",
"(",
"s1",
",",
"s2",
")"
] | implements the interface id generation algorithm described in rfc 3041 . | train | false |
38,095 | def slave_lag(**connection_args):
dbc = _connect(**connection_args)
if (dbc is None):
return (-3)
cur = dbc.cursor(MySQLdb.cursors.DictCursor)
qry = 'show slave status'
try:
_execute(cur, qry)
except MySQLdb.OperationalError as exc:
err = 'MySQL Error {0}: {1}'.format(*exc)
__context__['mysql.error'] = err
log.error(err)
return (-3)
results = cur.fetchone()
if (cur.rowcount == 0):
return (-1)
elif (results['Slave_IO_Running'] == 'Yes'):
return results['Seconds_Behind_Master']
else:
return (-2)
| [
"def",
"slave_lag",
"(",
"**",
"connection_args",
")",
":",
"dbc",
"=",
"_connect",
"(",
"**",
"connection_args",
")",
"if",
"(",
"dbc",
"is",
"None",
")",
":",
"return",
"(",
"-",
"3",
")",
"cur",
"=",
"dbc",
".",
"cursor",
"(",
"MySQLdb",
".",
"cursors",
".",
"DictCursor",
")",
"qry",
"=",
"'show slave status'",
"try",
":",
"_execute",
"(",
"cur",
",",
"qry",
")",
"except",
"MySQLdb",
".",
"OperationalError",
"as",
"exc",
":",
"err",
"=",
"'MySQL Error {0}: {1}'",
".",
"format",
"(",
"*",
"exc",
")",
"__context__",
"[",
"'mysql.error'",
"]",
"=",
"err",
"log",
".",
"error",
"(",
"err",
")",
"return",
"(",
"-",
"3",
")",
"results",
"=",
"cur",
".",
"fetchone",
"(",
")",
"if",
"(",
"cur",
".",
"rowcount",
"==",
"0",
")",
":",
"return",
"(",
"-",
"1",
")",
"elif",
"(",
"results",
"[",
"'Slave_IO_Running'",
"]",
"==",
"'Yes'",
")",
":",
"return",
"results",
"[",
"'Seconds_Behind_Master'",
"]",
"else",
":",
"return",
"(",
"-",
"2",
")"
] | return the number of seconds that a slave sql server is lagging behind the master . | train | true |
38,096 | def unsubscribe_to_messages(observer_function):
all_output_plugins = om.manager.get_output_plugin_inst()
for plugin_inst in all_output_plugins:
if isinstance(plugin_inst, GtkOutput):
plugin_inst.unsubscribe(observer_function)
break
| [
"def",
"unsubscribe_to_messages",
"(",
"observer_function",
")",
":",
"all_output_plugins",
"=",
"om",
".",
"manager",
".",
"get_output_plugin_inst",
"(",
")",
"for",
"plugin_inst",
"in",
"all_output_plugins",
":",
"if",
"isinstance",
"(",
"plugin_inst",
",",
"GtkOutput",
")",
":",
"plugin_inst",
".",
"unsubscribe",
"(",
"observer_function",
")",
"break"
] | unsubscribe observer_function to the gtkoutput messages . | train | false |
38,097 | def _split_commits_and_tags(obj_store, lst, ignore_unknown=False, pool=None):
commits = set()
tags = set()
def find_commit_type(sha):
try:
o = obj_store[sha]
except KeyError:
if (not ignore_unknown):
raise
else:
if isinstance(o, Commit):
commits.add(sha)
elif isinstance(o, Tag):
tags.add(sha)
commits.add(o.object[1])
else:
raise KeyError(('Not a commit or a tag: %s' % sha))
jobs = [pool.spawn(find_commit_type, s) for s in lst]
gevent.joinall(jobs)
return (commits, tags)
| [
"def",
"_split_commits_and_tags",
"(",
"obj_store",
",",
"lst",
",",
"ignore_unknown",
"=",
"False",
",",
"pool",
"=",
"None",
")",
":",
"commits",
"=",
"set",
"(",
")",
"tags",
"=",
"set",
"(",
")",
"def",
"find_commit_type",
"(",
"sha",
")",
":",
"try",
":",
"o",
"=",
"obj_store",
"[",
"sha",
"]",
"except",
"KeyError",
":",
"if",
"(",
"not",
"ignore_unknown",
")",
":",
"raise",
"else",
":",
"if",
"isinstance",
"(",
"o",
",",
"Commit",
")",
":",
"commits",
".",
"add",
"(",
"sha",
")",
"elif",
"isinstance",
"(",
"o",
",",
"Tag",
")",
":",
"tags",
".",
"add",
"(",
"sha",
")",
"commits",
".",
"add",
"(",
"o",
".",
"object",
"[",
"1",
"]",
")",
"else",
":",
"raise",
"KeyError",
"(",
"(",
"'Not a commit or a tag: %s'",
"%",
"sha",
")",
")",
"jobs",
"=",
"[",
"pool",
".",
"spawn",
"(",
"find_commit_type",
",",
"s",
")",
"for",
"s",
"in",
"lst",
"]",
"gevent",
".",
"joinall",
"(",
"jobs",
")",
"return",
"(",
"commits",
",",
"tags",
")"
] | split object id list into two list with commit sha1s and tag sha1s . | train | false |
38,098 | def stop_session(module, number):
global HOUSE
if ((module == 'all') and (number == (-1))):
for key in HOUSE.keys():
for entry in HOUSE[key]:
HOUSE[key][entry].shutdown()
else:
(mod, mod_inst) = get_mod_num(module, number)
if ((not (mod is None)) and (not (mod_inst is None))):
HOUSE[mod][mod_inst].shutdown()
del HOUSE[mod][mod_inst]
if (len(HOUSE[mod].keys()) is 0):
del HOUSE[mod]
else:
return
gc.collect()
| [
"def",
"stop_session",
"(",
"module",
",",
"number",
")",
":",
"global",
"HOUSE",
"if",
"(",
"(",
"module",
"==",
"'all'",
")",
"and",
"(",
"number",
"==",
"(",
"-",
"1",
")",
")",
")",
":",
"for",
"key",
"in",
"HOUSE",
".",
"keys",
"(",
")",
":",
"for",
"entry",
"in",
"HOUSE",
"[",
"key",
"]",
":",
"HOUSE",
"[",
"key",
"]",
"[",
"entry",
"]",
".",
"shutdown",
"(",
")",
"else",
":",
"(",
"mod",
",",
"mod_inst",
")",
"=",
"get_mod_num",
"(",
"module",
",",
"number",
")",
"if",
"(",
"(",
"not",
"(",
"mod",
"is",
"None",
")",
")",
"and",
"(",
"not",
"(",
"mod_inst",
"is",
"None",
")",
")",
")",
":",
"HOUSE",
"[",
"mod",
"]",
"[",
"mod_inst",
"]",
".",
"shutdown",
"(",
")",
"del",
"HOUSE",
"[",
"mod",
"]",
"[",
"mod_inst",
"]",
"if",
"(",
"len",
"(",
"HOUSE",
"[",
"mod",
"]",
".",
"keys",
"(",
")",
")",
"is",
"0",
")",
":",
"del",
"HOUSE",
"[",
"mod",
"]",
"else",
":",
"return",
"gc",
".",
"collect",
"(",
")"
] | stop a specific session; calls the respective modules shutdown() method . | train | false |
38,099 | def _get_bytes_buffer(ptr, nbytes):
if isinstance(ptr, ctypes.c_void_p):
ptr = ptr.value
arrty = (ctypes.c_byte * nbytes)
return arrty.from_address(ptr)
| [
"def",
"_get_bytes_buffer",
"(",
"ptr",
",",
"nbytes",
")",
":",
"if",
"isinstance",
"(",
"ptr",
",",
"ctypes",
".",
"c_void_p",
")",
":",
"ptr",
"=",
"ptr",
".",
"value",
"arrty",
"=",
"(",
"ctypes",
".",
"c_byte",
"*",
"nbytes",
")",
"return",
"arrty",
".",
"from_address",
"(",
"ptr",
")"
] | get a ctypes array of *nbytes* starting at *ptr* . | train | false |
38,100 | def load_data(fname, icept=True):
cur_dir = os.path.dirname(os.path.abspath(__file__))
Z = np.genfromtxt(os.path.join(cur_dir, 'results', fname), delimiter=',')
group = Z[:, 0]
endog = Z[:, 1]
exog = Z[:, 2:]
if icept:
exog = np.concatenate((np.ones((exog.shape[0], 1)), exog), axis=1)
return (endog, exog, group)
| [
"def",
"load_data",
"(",
"fname",
",",
"icept",
"=",
"True",
")",
":",
"cur_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"Z",
"=",
"np",
".",
"genfromtxt",
"(",
"os",
".",
"path",
".",
"join",
"(",
"cur_dir",
",",
"'results'",
",",
"fname",
")",
",",
"delimiter",
"=",
"','",
")",
"group",
"=",
"Z",
"[",
":",
",",
"0",
"]",
"endog",
"=",
"Z",
"[",
":",
",",
"1",
"]",
"exog",
"=",
"Z",
"[",
":",
",",
"2",
":",
"]",
"if",
"icept",
":",
"exog",
"=",
"np",
".",
"concatenate",
"(",
"(",
"np",
".",
"ones",
"(",
"(",
"exog",
".",
"shape",
"[",
"0",
"]",
",",
"1",
")",
")",
",",
"exog",
")",
",",
"axis",
"=",
"1",
")",
"return",
"(",
"endog",
",",
"exog",
",",
"group",
")"
] | return the mnist data as a tuple containing the training data . | train | false |
38,101 | def _parse_progress_from_resource_manager(html_bytes):
for line in html_bytes.splitlines():
m = _RESOURCE_MANAGER_JS_RE.match(line)
if m:
return float(m.group('percent'))
return None
| [
"def",
"_parse_progress_from_resource_manager",
"(",
"html_bytes",
")",
":",
"for",
"line",
"in",
"html_bytes",
".",
"splitlines",
"(",
")",
":",
"m",
"=",
"_RESOURCE_MANAGER_JS_RE",
".",
"match",
"(",
"line",
")",
"if",
"m",
":",
"return",
"float",
"(",
"m",
".",
"group",
"(",
"'percent'",
")",
")",
"return",
"None"
] | pull progress_precent for running job from job tracker html . | train | false |
38,102 | def _VarUInt64ByteSizeNoTag(uint64):
if (uint64 <= 127):
return 1
if (uint64 <= 16383):
return 2
if (uint64 <= 2097151):
return 3
if (uint64 <= 268435455):
return 4
if (uint64 <= 34359738367):
return 5
if (uint64 <= 4398046511103):
return 6
if (uint64 <= 562949953421311):
return 7
if (uint64 <= 72057594037927935):
return 8
if (uint64 <= 9223372036854775807):
return 9
if (uint64 > UINT64_MAX):
raise message.EncodeError(('Value out of range: %d' % uint64))
return 10
| [
"def",
"_VarUInt64ByteSizeNoTag",
"(",
"uint64",
")",
":",
"if",
"(",
"uint64",
"<=",
"127",
")",
":",
"return",
"1",
"if",
"(",
"uint64",
"<=",
"16383",
")",
":",
"return",
"2",
"if",
"(",
"uint64",
"<=",
"2097151",
")",
":",
"return",
"3",
"if",
"(",
"uint64",
"<=",
"268435455",
")",
":",
"return",
"4",
"if",
"(",
"uint64",
"<=",
"34359738367",
")",
":",
"return",
"5",
"if",
"(",
"uint64",
"<=",
"4398046511103",
")",
":",
"return",
"6",
"if",
"(",
"uint64",
"<=",
"562949953421311",
")",
":",
"return",
"7",
"if",
"(",
"uint64",
"<=",
"72057594037927935",
")",
":",
"return",
"8",
"if",
"(",
"uint64",
"<=",
"9223372036854775807",
")",
":",
"return",
"9",
"if",
"(",
"uint64",
">",
"UINT64_MAX",
")",
":",
"raise",
"message",
".",
"EncodeError",
"(",
"(",
"'Value out of range: %d'",
"%",
"uint64",
")",
")",
"return",
"10"
] | returns the number of bytes required to serialize a single varint using boundary value comparisons . | train | true |
38,103 | def _response_cell_name_from_path(routing_path, neighbor_only=False):
path = _reverse_path(routing_path)
if ((not neighbor_only) or (len(path) == 1)):
return path
return _PATH_CELL_SEP.join(path.split(_PATH_CELL_SEP)[:2])
| [
"def",
"_response_cell_name_from_path",
"(",
"routing_path",
",",
"neighbor_only",
"=",
"False",
")",
":",
"path",
"=",
"_reverse_path",
"(",
"routing_path",
")",
"if",
"(",
"(",
"not",
"neighbor_only",
")",
"or",
"(",
"len",
"(",
"path",
")",
"==",
"1",
")",
")",
":",
"return",
"path",
"return",
"_PATH_CELL_SEP",
".",
"join",
"(",
"path",
".",
"split",
"(",
"_PATH_CELL_SEP",
")",
"[",
":",
"2",
"]",
")"
] | reverse the routing_path . | train | false |
38,104 | def p_expression_number(p):
p[0] = p[1]
| [
"def",
"p_expression_number",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | expression : number . | train | false |
38,105 | def swap_memory():
if (psutil.version_info < (0, 6, 0)):
msg = 'swap_memory is only available in psutil 0.6.0 or greater'
raise CommandExecutionError(msg)
return dict(psutil.swap_memory()._asdict())
| [
"def",
"swap_memory",
"(",
")",
":",
"if",
"(",
"psutil",
".",
"version_info",
"<",
"(",
"0",
",",
"6",
",",
"0",
")",
")",
":",
"msg",
"=",
"'swap_memory is only available in psutil 0.6.0 or greater'",
"raise",
"CommandExecutionError",
"(",
"msg",
")",
"return",
"dict",
"(",
"psutil",
".",
"swap_memory",
"(",
")",
".",
"_asdict",
"(",
")",
")"
] | return system swap memory statistics as a namedtuple including the following fields: - total: total swap memory in bytes - used: used swap memory in bytes - free: free swap memory in bytes - percent: the percentage usage - sin: no . | train | true |
38,106 | def _reverse_lookup(dictionary, value):
value_index = (-1)
for (idx, dict_value) in enumerate(dictionary.values()):
if (type(dict_value) == list):
if (value in dict_value):
value_index = idx
break
elif (value == dict_value):
value_index = idx
break
return dictionary.keys()[value_index]
| [
"def",
"_reverse_lookup",
"(",
"dictionary",
",",
"value",
")",
":",
"value_index",
"=",
"(",
"-",
"1",
")",
"for",
"(",
"idx",
",",
"dict_value",
")",
"in",
"enumerate",
"(",
"dictionary",
".",
"values",
"(",
")",
")",
":",
"if",
"(",
"type",
"(",
"dict_value",
")",
"==",
"list",
")",
":",
"if",
"(",
"value",
"in",
"dict_value",
")",
":",
"value_index",
"=",
"idx",
"break",
"elif",
"(",
"value",
"==",
"dict_value",
")",
":",
"value_index",
"=",
"idx",
"break",
"return",
"dictionary",
".",
"keys",
"(",
")",
"[",
"value_index",
"]"
] | lookup the key in a dictionary by its value . | train | true |
38,107 | def getProfilesDirectoryInAboveDirectory(subName=''):
aboveProfilesDirectory = archive.getSkeinforgePath('profiles')
if (subName == ''):
return aboveProfilesDirectory
return os.path.join(aboveProfilesDirectory, subName)
| [
"def",
"getProfilesDirectoryInAboveDirectory",
"(",
"subName",
"=",
"''",
")",
":",
"aboveProfilesDirectory",
"=",
"archive",
".",
"getSkeinforgePath",
"(",
"'profiles'",
")",
"if",
"(",
"subName",
"==",
"''",
")",
":",
"return",
"aboveProfilesDirectory",
"return",
"os",
".",
"path",
".",
"join",
"(",
"aboveProfilesDirectory",
",",
"subName",
")"
] | get the profiles directory path in the above directory . | train | false |
38,108 | def label_from_index_dict(chart_index, include_cols=False):
if isinstance(chart_index, str):
return chart_index
elif (chart_index is None):
return 'None'
elif isinstance(chart_index, dict):
if include_cols:
label = ', '.join([('%s=%s' % (col, val)) for (col, val) in iteritems(chart_index)])
else:
label = tuple(chart_index.values())
if (len(label) == 1):
label = label[0]
return label
else:
raise ValueError(('chart_index type is not recognized, received %s' % type(chart_index)))
| [
"def",
"label_from_index_dict",
"(",
"chart_index",
",",
"include_cols",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"chart_index",
",",
"str",
")",
":",
"return",
"chart_index",
"elif",
"(",
"chart_index",
"is",
"None",
")",
":",
"return",
"'None'",
"elif",
"isinstance",
"(",
"chart_index",
",",
"dict",
")",
":",
"if",
"include_cols",
":",
"label",
"=",
"', '",
".",
"join",
"(",
"[",
"(",
"'%s=%s'",
"%",
"(",
"col",
",",
"val",
")",
")",
"for",
"(",
"col",
",",
"val",
")",
"in",
"iteritems",
"(",
"chart_index",
")",
"]",
")",
"else",
":",
"label",
"=",
"tuple",
"(",
"chart_index",
".",
"values",
"(",
")",
")",
"if",
"(",
"len",
"(",
"label",
")",
"==",
"1",
")",
":",
"label",
"=",
"label",
"[",
"0",
"]",
"return",
"label",
"else",
":",
"raise",
"ValueError",
"(",
"(",
"'chart_index type is not recognized, received %s'",
"%",
"type",
"(",
"chart_index",
")",
")",
")"
] | args: chart_index (dict or str or none): identifier for the data group . | train | false |
38,109 | def get_desktop_module(name):
global DESKTOP_MODULES
for app in DESKTOP_MODULES:
if (app.name == name):
return app
return None
| [
"def",
"get_desktop_module",
"(",
"name",
")",
":",
"global",
"DESKTOP_MODULES",
"for",
"app",
"in",
"DESKTOP_MODULES",
":",
"if",
"(",
"app",
".",
"name",
"==",
"name",
")",
":",
"return",
"app",
"return",
"None"
] | harmless linear search . | train | false |
38,110 | def test_no_data_sparktext():
chart2 = Line()
chart2.add('_', [])
assert (chart2.render_sparktext() == u(''))
chart3 = Line()
assert (chart3.render_sparktext() == u(''))
| [
"def",
"test_no_data_sparktext",
"(",
")",
":",
"chart2",
"=",
"Line",
"(",
")",
"chart2",
".",
"add",
"(",
"'_'",
",",
"[",
"]",
")",
"assert",
"(",
"chart2",
".",
"render_sparktext",
"(",
")",
"==",
"u",
"(",
"''",
")",
")",
"chart3",
"=",
"Line",
"(",
")",
"assert",
"(",
"chart3",
".",
"render_sparktext",
"(",
")",
"==",
"u",
"(",
"''",
")",
")"
] | test no data sparktext . | train | false |
38,111 | def producer(obj, func, results):
try:
result = func(obj)
results.put((obj, result, None))
except Exception as e:
results.put((obj, None, e))
| [
"def",
"producer",
"(",
"obj",
",",
"func",
",",
"results",
")",
":",
"try",
":",
"result",
"=",
"func",
"(",
"obj",
")",
"results",
".",
"put",
"(",
"(",
"obj",
",",
"result",
",",
"None",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"results",
".",
"put",
"(",
"(",
"obj",
",",
"None",
",",
"e",
")",
")"
] | the entry point for a producer thread which runs func on a single object . | train | false |
38,112 | @requires_sklearn
def test_plot_ica_overlay():
import matplotlib.pyplot as plt
raw = _get_raw(preload=True)
picks = _get_picks(raw)
ica = ICA(noise_cov=read_cov(cov_fname), n_components=2, max_pca_components=3, n_pca_components=3)
with warnings.catch_warnings(record=True):
ica.fit(raw, picks=picks)
with warnings.catch_warnings(record=True):
ecg_epochs = create_ecg_epochs(raw, picks=picks)
ica.plot_overlay(ecg_epochs.average())
with warnings.catch_warnings(record=True):
eog_epochs = create_eog_epochs(raw, picks=picks)
ica.plot_overlay(eog_epochs.average())
assert_raises(ValueError, ica.plot_overlay, raw[:2, :3][0])
ica.plot_overlay(raw)
plt.close('all')
| [
"@",
"requires_sklearn",
"def",
"test_plot_ica_overlay",
"(",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"raw",
"=",
"_get_raw",
"(",
"preload",
"=",
"True",
")",
"picks",
"=",
"_get_picks",
"(",
"raw",
")",
"ica",
"=",
"ICA",
"(",
"noise_cov",
"=",
"read_cov",
"(",
"cov_fname",
")",
",",
"n_components",
"=",
"2",
",",
"max_pca_components",
"=",
"3",
",",
"n_pca_components",
"=",
"3",
")",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
":",
"ica",
".",
"fit",
"(",
"raw",
",",
"picks",
"=",
"picks",
")",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
":",
"ecg_epochs",
"=",
"create_ecg_epochs",
"(",
"raw",
",",
"picks",
"=",
"picks",
")",
"ica",
".",
"plot_overlay",
"(",
"ecg_epochs",
".",
"average",
"(",
")",
")",
"with",
"warnings",
".",
"catch_warnings",
"(",
"record",
"=",
"True",
")",
":",
"eog_epochs",
"=",
"create_eog_epochs",
"(",
"raw",
",",
"picks",
"=",
"picks",
")",
"ica",
".",
"plot_overlay",
"(",
"eog_epochs",
".",
"average",
"(",
")",
")",
"assert_raises",
"(",
"ValueError",
",",
"ica",
".",
"plot_overlay",
",",
"raw",
"[",
":",
"2",
",",
":",
"3",
"]",
"[",
"0",
"]",
")",
"ica",
".",
"plot_overlay",
"(",
"raw",
")",
"plt",
".",
"close",
"(",
"'all'",
")"
] | test plotting of ica cleaning . | train | false |
38,113 | @rule(u'.*/([a-z]+\\.wikipedia.org)/wiki/([^ ]+).*')
def mw_info(bot, trigger, found_match=None):
match = (found_match or trigger)
say_snippet(bot, match.group(1), unquote(match.group(2)), show_url=False)
| [
"@",
"rule",
"(",
"u'.*/([a-z]+\\\\.wikipedia.org)/wiki/([^ ]+).*'",
")",
"def",
"mw_info",
"(",
"bot",
",",
"trigger",
",",
"found_match",
"=",
"None",
")",
":",
"match",
"=",
"(",
"found_match",
"or",
"trigger",
")",
"say_snippet",
"(",
"bot",
",",
"match",
".",
"group",
"(",
"1",
")",
",",
"unquote",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
",",
"show_url",
"=",
"False",
")"
] | retrives a snippet of the specified length from the given page on the given server . | train | false |
38,114 | def vt_get_volume_type(context, vt_id):
if (vt_id == fake_vt['id']):
return fake_vt
raise exception.VolumeTypeNotFound(volume_type_id=vt_id)
| [
"def",
"vt_get_volume_type",
"(",
"context",
",",
"vt_id",
")",
":",
"if",
"(",
"vt_id",
"==",
"fake_vt",
"[",
"'id'",
"]",
")",
":",
"return",
"fake_vt",
"raise",
"exception",
".",
"VolumeTypeNotFound",
"(",
"volume_type_id",
"=",
"vt_id",
")"
] | replacement for cinder . | train | false |
38,115 | def inherit_docstring_from(cls):
def _doc(func):
cls_docstring = getattr(cls, func.__name__).__doc__
func_docstring = func.__doc__
if (func_docstring is None):
func.__doc__ = cls_docstring
else:
new_docstring = (func_docstring % dict(super=cls_docstring))
func.__doc__ = new_docstring
return func
return _doc
| [
"def",
"inherit_docstring_from",
"(",
"cls",
")",
":",
"def",
"_doc",
"(",
"func",
")",
":",
"cls_docstring",
"=",
"getattr",
"(",
"cls",
",",
"func",
".",
"__name__",
")",
".",
"__doc__",
"func_docstring",
"=",
"func",
".",
"__doc__",
"if",
"(",
"func_docstring",
"is",
"None",
")",
":",
"func",
".",
"__doc__",
"=",
"cls_docstring",
"else",
":",
"new_docstring",
"=",
"(",
"func_docstring",
"%",
"dict",
"(",
"super",
"=",
"cls_docstring",
")",
")",
"func",
".",
"__doc__",
"=",
"new_docstring",
"return",
"func",
"return",
"_doc"
] | this decorator modifies the decorated functions docstring by replacing occurrences of %s with the docstring of the method of the same name from the class cls . | train | true |
38,118 | def print_subtitle(text):
print_col('------ {} ------'.format(text), 'cyan')
| [
"def",
"print_subtitle",
"(",
"text",
")",
":",
"print_col",
"(",
"'------ {} ------'",
".",
"format",
"(",
"text",
")",
",",
"'cyan'",
")"
] | print a subtitle . | train | false |
38,119 | def _parse_range_value(range_value):
end = None
if range_value.startswith('-'):
start = int(range_value)
if (start == 0):
raise ValueError('-0 is not a valid range.')
else:
split_range = range_value.split('-', 1)
start = int(split_range[0])
if ((len(split_range) > 1) and split_range[1].strip()):
end = int(split_range[1])
if (start > end):
raise ValueError('start must be <= end.')
return (start, end)
| [
"def",
"_parse_range_value",
"(",
"range_value",
")",
":",
"end",
"=",
"None",
"if",
"range_value",
".",
"startswith",
"(",
"'-'",
")",
":",
"start",
"=",
"int",
"(",
"range_value",
")",
"if",
"(",
"start",
"==",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'-0 is not a valid range.'",
")",
"else",
":",
"split_range",
"=",
"range_value",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"start",
"=",
"int",
"(",
"split_range",
"[",
"0",
"]",
")",
"if",
"(",
"(",
"len",
"(",
"split_range",
")",
">",
"1",
")",
"and",
"split_range",
"[",
"1",
"]",
".",
"strip",
"(",
")",
")",
":",
"end",
"=",
"int",
"(",
"split_range",
"[",
"1",
"]",
")",
"if",
"(",
"start",
">",
"end",
")",
":",
"raise",
"ValueError",
"(",
"'start must be <= end.'",
")",
"return",
"(",
"start",
",",
"end",
")"
] | parses a single range value from a range header . | train | false |
38,121 | def ValidateDomain(url):
domain_name = url.split('/')
if (('http:' in domain_name) or ('https:' in domain_name)):
domain_name = domain_name[2]
else:
domain_name = domain_name[0]
www_domain_name = domain_name.split('.')
final_domain = ''
if (www_domain_name[0] == 'www'):
final_domain = '.'.join(www_domain_name[1:])
else:
final_domain = domain_name
return (final_domain, domain_name)
| [
"def",
"ValidateDomain",
"(",
"url",
")",
":",
"domain_name",
"=",
"url",
".",
"split",
"(",
"'/'",
")",
"if",
"(",
"(",
"'http:'",
"in",
"domain_name",
")",
"or",
"(",
"'https:'",
"in",
"domain_name",
")",
")",
":",
"domain_name",
"=",
"domain_name",
"[",
"2",
"]",
"else",
":",
"domain_name",
"=",
"domain_name",
"[",
"0",
"]",
"www_domain_name",
"=",
"domain_name",
".",
"split",
"(",
"'.'",
")",
"final_domain",
"=",
"''",
"if",
"(",
"www_domain_name",
"[",
"0",
"]",
"==",
"'www'",
")",
":",
"final_domain",
"=",
"'.'",
".",
"join",
"(",
"www_domain_name",
"[",
"1",
":",
"]",
")",
"else",
":",
"final_domain",
"=",
"domain_name",
"return",
"(",
"final_domain",
",",
"domain_name",
")"
] | this function returns domain name removing http:// and https:// returns domain name only with or without www as user provided . | train | false |
38,123 | def get_clean_env(extra=None):
environ = {u'LANG': u'en_US.UTF-8', u'HOME': data_dir(u'home')}
if (extra is not None):
environ.update(extra)
variables = (u'PATH', u'LD_LIBRARY_PATH')
for var in variables:
if (var in os.environ):
environ[var] = os.environ[var]
if (six.PY2 and (sys.platform == u'win32')):
return {str(key): str(val) for (key, val) in environ.items()}
return environ
| [
"def",
"get_clean_env",
"(",
"extra",
"=",
"None",
")",
":",
"environ",
"=",
"{",
"u'LANG'",
":",
"u'en_US.UTF-8'",
",",
"u'HOME'",
":",
"data_dir",
"(",
"u'home'",
")",
"}",
"if",
"(",
"extra",
"is",
"not",
"None",
")",
":",
"environ",
".",
"update",
"(",
"extra",
")",
"variables",
"=",
"(",
"u'PATH'",
",",
"u'LD_LIBRARY_PATH'",
")",
"for",
"var",
"in",
"variables",
":",
"if",
"(",
"var",
"in",
"os",
".",
"environ",
")",
":",
"environ",
"[",
"var",
"]",
"=",
"os",
".",
"environ",
"[",
"var",
"]",
"if",
"(",
"six",
".",
"PY2",
"and",
"(",
"sys",
".",
"platform",
"==",
"u'win32'",
")",
")",
":",
"return",
"{",
"str",
"(",
"key",
")",
":",
"str",
"(",
"val",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"environ",
".",
"items",
"(",
")",
"}",
"return",
"environ"
] | returns cleaned up environment for subprocess execution . | train | false |
38,124 | def _AddPropertiesForRepeatedField(field, cls):
proto_field_name = field.name
property_name = _PropertyName(proto_field_name)
def getter(self):
field_value = self._fields.get(field)
if (field_value is None):
field_value = field._default_constructor(self)
field_value = self._fields.setdefault(field, field_value)
return field_value
getter.__module__ = None
getter.__doc__ = ('Getter for %s.' % proto_field_name)
def setter(self, new_value):
raise AttributeError(('Assignment not allowed to repeated field "%s" in protocol message object.' % proto_field_name))
doc = ('Magic attribute generated for "%s" proto field.' % proto_field_name)
setattr(cls, property_name, property(getter, setter, doc=doc))
| [
"def",
"_AddPropertiesForRepeatedField",
"(",
"field",
",",
"cls",
")",
":",
"proto_field_name",
"=",
"field",
".",
"name",
"property_name",
"=",
"_PropertyName",
"(",
"proto_field_name",
")",
"def",
"getter",
"(",
"self",
")",
":",
"field_value",
"=",
"self",
".",
"_fields",
".",
"get",
"(",
"field",
")",
"if",
"(",
"field_value",
"is",
"None",
")",
":",
"field_value",
"=",
"field",
".",
"_default_constructor",
"(",
"self",
")",
"field_value",
"=",
"self",
".",
"_fields",
".",
"setdefault",
"(",
"field",
",",
"field_value",
")",
"return",
"field_value",
"getter",
".",
"__module__",
"=",
"None",
"getter",
".",
"__doc__",
"=",
"(",
"'Getter for %s.'",
"%",
"proto_field_name",
")",
"def",
"setter",
"(",
"self",
",",
"new_value",
")",
":",
"raise",
"AttributeError",
"(",
"(",
"'Assignment not allowed to repeated field \"%s\" in protocol message object.'",
"%",
"proto_field_name",
")",
")",
"doc",
"=",
"(",
"'Magic attribute generated for \"%s\" proto field.'",
"%",
"proto_field_name",
")",
"setattr",
"(",
"cls",
",",
"property_name",
",",
"property",
"(",
"getter",
",",
"setter",
",",
"doc",
"=",
"doc",
")",
")"
] | adds a public property for a "repeated" protocol message field . | train | true |
38,125 | def _remove_file(file_path):
if (file_path.find('.vmdk') != (-1)):
if (file_path not in _db_content.get('files')):
raise vexc.FileNotFoundException(file_path)
_db_content.get('files').remove(file_path)
else:
to_delete = set()
for file in _db_content.get('files'):
if (file.find(file_path) != (-1)):
to_delete.add(file)
for file in to_delete:
_db_content.get('files').remove(file)
| [
"def",
"_remove_file",
"(",
"file_path",
")",
":",
"if",
"(",
"file_path",
".",
"find",
"(",
"'.vmdk'",
")",
"!=",
"(",
"-",
"1",
")",
")",
":",
"if",
"(",
"file_path",
"not",
"in",
"_db_content",
".",
"get",
"(",
"'files'",
")",
")",
":",
"raise",
"vexc",
".",
"FileNotFoundException",
"(",
"file_path",
")",
"_db_content",
".",
"get",
"(",
"'files'",
")",
".",
"remove",
"(",
"file_path",
")",
"else",
":",
"to_delete",
"=",
"set",
"(",
")",
"for",
"file",
"in",
"_db_content",
".",
"get",
"(",
"'files'",
")",
":",
"if",
"(",
"file",
".",
"find",
"(",
"file_path",
")",
"!=",
"(",
"-",
"1",
")",
")",
":",
"to_delete",
".",
"add",
"(",
"file",
")",
"for",
"file",
"in",
"to_delete",
":",
"_db_content",
".",
"get",
"(",
"'files'",
")",
".",
"remove",
"(",
"file",
")"
] | removes a file reference from the db . | train | false |
38,126 | def timedelta_total_seconds(td):
try:
return td.total_seconds()
except AttributeError:
return ((((td.days * 24) * 3600) + td.seconds) + (td.microseconds / 1000000))
| [
"def",
"timedelta_total_seconds",
"(",
"td",
")",
":",
"try",
":",
"return",
"td",
".",
"total_seconds",
"(",
")",
"except",
"AttributeError",
":",
"return",
"(",
"(",
"(",
"(",
"td",
".",
"days",
"*",
"24",
")",
"*",
"3600",
")",
"+",
"td",
".",
"seconds",
")",
"+",
"(",
"td",
".",
"microseconds",
"/",
"1000000",
")",
")"
] | replaces python 2 . | train | false |
38,127 | def make_permanent():
return __firewall_cmd('--runtime-to-permanent')
| [
"def",
"make_permanent",
"(",
")",
":",
"return",
"__firewall_cmd",
"(",
"'--runtime-to-permanent'",
")"
] | make current runtime configuration permanent . | train | false |
38,128 | def join_path_native(a, *p):
return to_native_path(join_path(a, *p))
| [
"def",
"join_path_native",
"(",
"a",
",",
"*",
"p",
")",
":",
"return",
"to_native_path",
"(",
"join_path",
"(",
"a",
",",
"*",
"p",
")",
")"
] | as join path . | train | false |
38,129 | def _get_upload_content(field_storage):
message = email.message.Message()
message.add_header('content-transfer-encoding', field_storage.headers.getheader('Content-Transfer-Encoding', ''))
message.set_payload(field_storage.file.read())
payload = message.get_payload(decode=True)
return email.message_from_string(payload)
| [
"def",
"_get_upload_content",
"(",
"field_storage",
")",
":",
"message",
"=",
"email",
".",
"message",
".",
"Message",
"(",
")",
"message",
".",
"add_header",
"(",
"'content-transfer-encoding'",
",",
"field_storage",
".",
"headers",
".",
"getheader",
"(",
"'Content-Transfer-Encoding'",
",",
"''",
")",
")",
"message",
".",
"set_payload",
"(",
"field_storage",
".",
"file",
".",
"read",
"(",
")",
")",
"payload",
"=",
"message",
".",
"get_payload",
"(",
"decode",
"=",
"True",
")",
"return",
"email",
".",
"message_from_string",
"(",
"payload",
")"
] | returns an email . | train | false |
38,132 | @pytest.mark.parametrize('i, item', enumerate(ITEMS))
def test_titles(objects, i, item):
assert (objects.history.itemAt(i).title() == item.title)
| [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"'i, item'",
",",
"enumerate",
"(",
"ITEMS",
")",
")",
"def",
"test_titles",
"(",
"objects",
",",
"i",
",",
"item",
")",
":",
"assert",
"(",
"objects",
".",
"history",
".",
"itemAt",
"(",
"i",
")",
".",
"title",
"(",
")",
"==",
"item",
".",
"title",
")"
] | check if the titles were loaded correctly . | train | false |
38,133 | def _connect(uri):
uri_l = uri.rsplit(' as ', 1)
if (len(uri_l) == 2):
(credentials, mode) = uri_l
mode = MODE[mode]
else:
credentials = uri_l[0]
mode = 0
(userpass, hostportsid) = credentials.split('@')
(user, password) = userpass.split('/')
(hostport, sid) = hostportsid.split('/')
hostport_l = hostport.split(':')
if (len(hostport_l) == 2):
(host, port) = hostport_l
else:
host = hostport_l[0]
port = 1521
log.debug('connect: {0}'.format((user, password, host, port, sid, mode)))
os.environ['NLS_LANG'] = '.AL32UTF8'
conn = cx_Oracle.connect(user, password, cx_Oracle.makedsn(host, port, sid), mode)
conn.outputtypehandler = _unicode_output
return conn
| [
"def",
"_connect",
"(",
"uri",
")",
":",
"uri_l",
"=",
"uri",
".",
"rsplit",
"(",
"' as '",
",",
"1",
")",
"if",
"(",
"len",
"(",
"uri_l",
")",
"==",
"2",
")",
":",
"(",
"credentials",
",",
"mode",
")",
"=",
"uri_l",
"mode",
"=",
"MODE",
"[",
"mode",
"]",
"else",
":",
"credentials",
"=",
"uri_l",
"[",
"0",
"]",
"mode",
"=",
"0",
"(",
"userpass",
",",
"hostportsid",
")",
"=",
"credentials",
".",
"split",
"(",
"'@'",
")",
"(",
"user",
",",
"password",
")",
"=",
"userpass",
".",
"split",
"(",
"'/'",
")",
"(",
"hostport",
",",
"sid",
")",
"=",
"hostportsid",
".",
"split",
"(",
"'/'",
")",
"hostport_l",
"=",
"hostport",
".",
"split",
"(",
"':'",
")",
"if",
"(",
"len",
"(",
"hostport_l",
")",
"==",
"2",
")",
":",
"(",
"host",
",",
"port",
")",
"=",
"hostport_l",
"else",
":",
"host",
"=",
"hostport_l",
"[",
"0",
"]",
"port",
"=",
"1521",
"log",
".",
"debug",
"(",
"'connect: {0}'",
".",
"format",
"(",
"(",
"user",
",",
"password",
",",
"host",
",",
"port",
",",
"sid",
",",
"mode",
")",
")",
")",
"os",
".",
"environ",
"[",
"'NLS_LANG'",
"]",
"=",
"'.AL32UTF8'",
"conn",
"=",
"cx_Oracle",
".",
"connect",
"(",
"user",
",",
"password",
",",
"cx_Oracle",
".",
"makedsn",
"(",
"host",
",",
"port",
",",
"sid",
")",
",",
"mode",
")",
"conn",
".",
"outputtypehandler",
"=",
"_unicode_output",
"return",
"conn"
] | return server object used to interact with jenkins . | train | false |
38,134 | def delete_lead_addresses(company_name):
for lead in frappe.get_all(u'Lead', filters={u'company': company_name}):
frappe.db.sql(u"delete from `tabAddress`\n DCTB DCTB DCTB where lead=%s and (customer='' or customer is null) and (supplier='' or supplier is null)", lead.name)
frappe.db.sql(u'update `tabAddress` set lead=null, lead_name=null where lead=%s', lead.name)
| [
"def",
"delete_lead_addresses",
"(",
"company_name",
")",
":",
"for",
"lead",
"in",
"frappe",
".",
"get_all",
"(",
"u'Lead'",
",",
"filters",
"=",
"{",
"u'company'",
":",
"company_name",
"}",
")",
":",
"frappe",
".",
"db",
".",
"sql",
"(",
"u\"delete from `tabAddress`\\n DCTB DCTB DCTB where lead=%s and (customer='' or customer is null) and (supplier='' or supplier is null)\"",
",",
"lead",
".",
"name",
")",
"frappe",
".",
"db",
".",
"sql",
"(",
"u'update `tabAddress` set lead=null, lead_name=null where lead=%s'",
",",
"lead",
".",
"name",
")"
] | delete addresses to which leads are linked . | train | false |
38,135 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
38,137 | def unzip(file_obj):
files = []
zip = ZipFile(file_obj)
bad_file = zip.testzip()
if bad_file:
raise Exception(('"%s" in the .zip archive is corrupt.' % bad_file))
infolist = zip.infolist()
for zipinfo in infolist:
if zipinfo.filename.startswith('__'):
continue
file_obj = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo))
files.append((file_obj, zipinfo.filename))
zip.close()
return files
| [
"def",
"unzip",
"(",
"file_obj",
")",
":",
"files",
"=",
"[",
"]",
"zip",
"=",
"ZipFile",
"(",
"file_obj",
")",
"bad_file",
"=",
"zip",
".",
"testzip",
"(",
")",
"if",
"bad_file",
":",
"raise",
"Exception",
"(",
"(",
"'\"%s\" in the .zip archive is corrupt.'",
"%",
"bad_file",
")",
")",
"infolist",
"=",
"zip",
".",
"infolist",
"(",
")",
"for",
"zipinfo",
"in",
"infolist",
":",
"if",
"zipinfo",
".",
"filename",
".",
"startswith",
"(",
"'__'",
")",
":",
"continue",
"file_obj",
"=",
"SimpleUploadedFile",
"(",
"name",
"=",
"zipinfo",
".",
"filename",
",",
"content",
"=",
"zip",
".",
"read",
"(",
"zipinfo",
")",
")",
"files",
".",
"append",
"(",
"(",
"file_obj",
",",
"zipinfo",
".",
"filename",
")",
")",
"zip",
".",
"close",
"(",
")",
"return",
"files"
] | extract the contents of the zip file filename into the directory root . | train | true |
38,139 | def delete_sent_email(crispin_client, account_id, message_id, args):
message_id_header = args.get('message_id_header')
assert message_id_header, 'Need the message_id_header'
remote_delete_sent(crispin_client, account_id, message_id_header)
| [
"def",
"delete_sent_email",
"(",
"crispin_client",
",",
"account_id",
",",
"message_id",
",",
"args",
")",
":",
"message_id_header",
"=",
"args",
".",
"get",
"(",
"'message_id_header'",
")",
"assert",
"message_id_header",
",",
"'Need the message_id_header'",
"remote_delete_sent",
"(",
"crispin_client",
",",
"account_id",
",",
"message_id_header",
")"
] | delete an email on the remote backend . | train | false |
38,140 | def partition_dict(dict_, keys):
intersection = {}
difference = {}
for (key, value) in dict_.iteritems():
if (key in keys):
intersection[key] = value
else:
difference[key] = value
return (intersection, difference)
| [
"def",
"partition_dict",
"(",
"dict_",
",",
"keys",
")",
":",
"intersection",
"=",
"{",
"}",
"difference",
"=",
"{",
"}",
"for",
"(",
"key",
",",
"value",
")",
"in",
"dict_",
".",
"iteritems",
"(",
")",
":",
"if",
"(",
"key",
"in",
"keys",
")",
":",
"intersection",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"difference",
"[",
"key",
"]",
"=",
"value",
"return",
"(",
"intersection",
",",
"difference",
")"
] | return two dicts . | train | false |
38,141 | @db_api.retry_if_session_inactive()
def provisioning_complete(context, object_id, object_type, entity):
log_dict = {'oid': object_id, 'entity': entity, 'otype': object_type}
if context.session.is_active:
raise RuntimeError(_LE('Must not be called in a transaction'))
standard_attr_id = _get_standard_attr_id(context, object_id, object_type)
if (not standard_attr_id):
return
if remove_provisioning_component(context, object_id, object_type, entity, standard_attr_id):
LOG.debug('Provisioning for %(otype)s %(oid)s completed by entity %(entity)s.', log_dict)
records = context.session.query(pb_model.ProvisioningBlock).filter_by(standard_attr_id=standard_attr_id).count()
if (not records):
LOG.debug('Provisioning complete for %(otype)s %(oid)s triggered by entity %(entity)s.', log_dict)
registry.notify(object_type, PROVISIONING_COMPLETE, 'neutron.db.provisioning_blocks', context=context, object_id=object_id)
| [
"@",
"db_api",
".",
"retry_if_session_inactive",
"(",
")",
"def",
"provisioning_complete",
"(",
"context",
",",
"object_id",
",",
"object_type",
",",
"entity",
")",
":",
"log_dict",
"=",
"{",
"'oid'",
":",
"object_id",
",",
"'entity'",
":",
"entity",
",",
"'otype'",
":",
"object_type",
"}",
"if",
"context",
".",
"session",
".",
"is_active",
":",
"raise",
"RuntimeError",
"(",
"_LE",
"(",
"'Must not be called in a transaction'",
")",
")",
"standard_attr_id",
"=",
"_get_standard_attr_id",
"(",
"context",
",",
"object_id",
",",
"object_type",
")",
"if",
"(",
"not",
"standard_attr_id",
")",
":",
"return",
"if",
"remove_provisioning_component",
"(",
"context",
",",
"object_id",
",",
"object_type",
",",
"entity",
",",
"standard_attr_id",
")",
":",
"LOG",
".",
"debug",
"(",
"'Provisioning for %(otype)s %(oid)s completed by entity %(entity)s.'",
",",
"log_dict",
")",
"records",
"=",
"context",
".",
"session",
".",
"query",
"(",
"pb_model",
".",
"ProvisioningBlock",
")",
".",
"filter_by",
"(",
"standard_attr_id",
"=",
"standard_attr_id",
")",
".",
"count",
"(",
")",
"if",
"(",
"not",
"records",
")",
":",
"LOG",
".",
"debug",
"(",
"'Provisioning complete for %(otype)s %(oid)s triggered by entity %(entity)s.'",
",",
"log_dict",
")",
"registry",
".",
"notify",
"(",
"object_type",
",",
"PROVISIONING_COMPLETE",
",",
"'neutron.db.provisioning_blocks'",
",",
"context",
"=",
"context",
",",
"object_id",
"=",
"object_id",
")"
] | mark that the provisioning for object_id has been completed by entity . | train | false |
38,142 | def saveSupportedExtensions():
return ['.amf', '.stl']
| [
"def",
"saveSupportedExtensions",
"(",
")",
":",
"return",
"[",
"'.amf'",
",",
"'.stl'",
"]"
] | return a list of supported file extensions for saving . | train | false |
38,143 | def test_forum_update_last_post(topic, user):
post = Post(content='Test Content 2')
post.save(topic=topic, user=user)
assert (topic.forum.last_post == post)
post.delete()
topic.forum.update_last_post()
assert (topic.forum.last_post == topic.first_post)
| [
"def",
"test_forum_update_last_post",
"(",
"topic",
",",
"user",
")",
":",
"post",
"=",
"Post",
"(",
"content",
"=",
"'Test Content 2'",
")",
"post",
".",
"save",
"(",
"topic",
"=",
"topic",
",",
"user",
"=",
"user",
")",
"assert",
"(",
"topic",
".",
"forum",
".",
"last_post",
"==",
"post",
")",
"post",
".",
"delete",
"(",
")",
"topic",
".",
"forum",
".",
"update_last_post",
"(",
")",
"assert",
"(",
"topic",
".",
"forum",
".",
"last_post",
"==",
"topic",
".",
"first_post",
")"
] | test the update last post method . | train | false |
38,145 | def dfs_successors(G, source=None):
d = defaultdict(list)
for (s, t) in dfs_edges(G, source=source):
d[s].append(t)
return dict(d)
| [
"def",
"dfs_successors",
"(",
"G",
",",
"source",
"=",
"None",
")",
":",
"d",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"(",
"s",
",",
"t",
")",
"in",
"dfs_edges",
"(",
"G",
",",
"source",
"=",
"source",
")",
":",
"d",
"[",
"s",
"]",
".",
"append",
"(",
"t",
")",
"return",
"dict",
"(",
"d",
")"
] | return dictionary of successors in depth-first-search from source . | train | false |
38,147 | def hyper_re(DE, r, k):
RE = S.Zero
g = DE.atoms(Function).pop()
x = g.atoms(Symbol).pop()
mini = None
for t in Add.make_args(DE.expand()):
(coeff, d) = t.as_independent(g)
(c, v) = coeff.as_independent(x)
l = v.as_coeff_exponent(x)[1]
if isinstance(d, Derivative):
j = len(d.args[1:])
else:
j = 0
RE += ((c * rf(((k + 1) - l), j)) * r(((k + j) - l)))
if ((mini is None) or ((j - l) < mini)):
mini = (j - l)
RE = RE.subs(k, (k - mini))
m = Wild('m')
return RE.collect(r((k + m)))
| [
"def",
"hyper_re",
"(",
"DE",
",",
"r",
",",
"k",
")",
":",
"RE",
"=",
"S",
".",
"Zero",
"g",
"=",
"DE",
".",
"atoms",
"(",
"Function",
")",
".",
"pop",
"(",
")",
"x",
"=",
"g",
".",
"atoms",
"(",
"Symbol",
")",
".",
"pop",
"(",
")",
"mini",
"=",
"None",
"for",
"t",
"in",
"Add",
".",
"make_args",
"(",
"DE",
".",
"expand",
"(",
")",
")",
":",
"(",
"coeff",
",",
"d",
")",
"=",
"t",
".",
"as_independent",
"(",
"g",
")",
"(",
"c",
",",
"v",
")",
"=",
"coeff",
".",
"as_independent",
"(",
"x",
")",
"l",
"=",
"v",
".",
"as_coeff_exponent",
"(",
"x",
")",
"[",
"1",
"]",
"if",
"isinstance",
"(",
"d",
",",
"Derivative",
")",
":",
"j",
"=",
"len",
"(",
"d",
".",
"args",
"[",
"1",
":",
"]",
")",
"else",
":",
"j",
"=",
"0",
"RE",
"+=",
"(",
"(",
"c",
"*",
"rf",
"(",
"(",
"(",
"k",
"+",
"1",
")",
"-",
"l",
")",
",",
"j",
")",
")",
"*",
"r",
"(",
"(",
"(",
"k",
"+",
"j",
")",
"-",
"l",
")",
")",
")",
"if",
"(",
"(",
"mini",
"is",
"None",
")",
"or",
"(",
"(",
"j",
"-",
"l",
")",
"<",
"mini",
")",
")",
":",
"mini",
"=",
"(",
"j",
"-",
"l",
")",
"RE",
"=",
"RE",
".",
"subs",
"(",
"k",
",",
"(",
"k",
"-",
"mini",
")",
")",
"m",
"=",
"Wild",
"(",
"'m'",
")",
"return",
"RE",
".",
"collect",
"(",
"r",
"(",
"(",
"k",
"+",
"m",
")",
")",
")"
] | converts a de into a re . | train | false |
38,149 | def correct_font(source_name, unhinted_name, target_font_name, family_name):
font = ttLib.TTFont(source_name)
unhinted = ttLib.TTFont(unhinted_name)
apply_web_cros_common_fixes(font, unhinted, family_name)
temporary_touchups.apply_temporary_fixes(font, is_for_cros=True)
temporary_touchups.update_version_and_revision(font)
drop_non_windows_name_records(font)
font.save(target_font_name)
| [
"def",
"correct_font",
"(",
"source_name",
",",
"unhinted_name",
",",
"target_font_name",
",",
"family_name",
")",
":",
"font",
"=",
"ttLib",
".",
"TTFont",
"(",
"source_name",
")",
"unhinted",
"=",
"ttLib",
".",
"TTFont",
"(",
"unhinted_name",
")",
"apply_web_cros_common_fixes",
"(",
"font",
",",
"unhinted",
",",
"family_name",
")",
"temporary_touchups",
".",
"apply_temporary_fixes",
"(",
"font",
",",
"is_for_cros",
"=",
"True",
")",
"temporary_touchups",
".",
"update_version_and_revision",
"(",
"font",
")",
"drop_non_windows_name_records",
"(",
"font",
")",
"font",
".",
"save",
"(",
"target_font_name",
")"
] | corrects metrics and other meta information . | train | false |
38,150 | def list_datacenters(conn=None, call=None):
if (call != 'function'):
raise SaltCloudSystemExit('The list_datacenters function must be called with -f or --function.')
datacenters = []
if (not conn):
conn = get_conn()
for item in conn.list_datacenters()['items']:
datacenter = {'id': item['id']}
datacenter.update(item['properties'])
datacenters.append({item['properties']['name']: datacenter})
return {'Datacenters': datacenters}
| [
"def",
"list_datacenters",
"(",
"conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"(",
"call",
"!=",
"'function'",
")",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_datacenters function must be called with -f or --function.'",
")",
"datacenters",
"=",
"[",
"]",
"if",
"(",
"not",
"conn",
")",
":",
"conn",
"=",
"get_conn",
"(",
")",
"for",
"item",
"in",
"conn",
".",
"list_datacenters",
"(",
")",
"[",
"'items'",
"]",
":",
"datacenter",
"=",
"{",
"'id'",
":",
"item",
"[",
"'id'",
"]",
"}",
"datacenter",
".",
"update",
"(",
"item",
"[",
"'properties'",
"]",
")",
"datacenters",
".",
"append",
"(",
"{",
"item",
"[",
"'properties'",
"]",
"[",
"'name'",
"]",
":",
"datacenter",
"}",
")",
"return",
"{",
"'Datacenters'",
":",
"datacenters",
"}"
] | returns a list of datacenters for the the specified host . | train | true |
38,151 | def getNewRepository():
return ExportRepository()
| [
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] | get new repository . | train | false |
38,155 | def MatchesRoutingRules(rules):
return AfterPreprocessing(RoutingRules.to_xml, Equals(RoutingRules(rules).to_xml()))
| [
"def",
"MatchesRoutingRules",
"(",
"rules",
")",
":",
"return",
"AfterPreprocessing",
"(",
"RoutingRules",
".",
"to_xml",
",",
"Equals",
"(",
"RoutingRules",
"(",
"rules",
")",
".",
"to_xml",
"(",
")",
")",
")"
] | matches against routing rules . | train | false |
38,156 | def p_argument(p):
p[0] = p[1]
| [
"def",
"p_argument",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]"
] | argument : test . | train | false |
38,157 | def ParseTotalStorageLimit(limit):
limit = limit.strip()
if (not limit):
raise MalformedQueueConfiguration('Total Storage Limit must not be empty.')
try:
if (limit[(-1)] in BYTE_SUFFIXES):
number = float(limit[0:(-1)])
for c in BYTE_SUFFIXES:
if (limit[(-1)] != c):
number = (number * 1024)
else:
return int(number)
else:
return int(limit)
except ValueError:
raise MalformedQueueConfiguration(('Total Storage Limit "%s" is invalid.' % limit))
| [
"def",
"ParseTotalStorageLimit",
"(",
"limit",
")",
":",
"limit",
"=",
"limit",
".",
"strip",
"(",
")",
"if",
"(",
"not",
"limit",
")",
":",
"raise",
"MalformedQueueConfiguration",
"(",
"'Total Storage Limit must not be empty.'",
")",
"try",
":",
"if",
"(",
"limit",
"[",
"(",
"-",
"1",
")",
"]",
"in",
"BYTE_SUFFIXES",
")",
":",
"number",
"=",
"float",
"(",
"limit",
"[",
"0",
":",
"(",
"-",
"1",
")",
"]",
")",
"for",
"c",
"in",
"BYTE_SUFFIXES",
":",
"if",
"(",
"limit",
"[",
"(",
"-",
"1",
")",
"]",
"!=",
"c",
")",
":",
"number",
"=",
"(",
"number",
"*",
"1024",
")",
"else",
":",
"return",
"int",
"(",
"number",
")",
"else",
":",
"return",
"int",
"(",
"limit",
")",
"except",
"ValueError",
":",
"raise",
"MalformedQueueConfiguration",
"(",
"(",
"'Total Storage Limit \"%s\" is invalid.'",
"%",
"limit",
")",
")"
] | parses a string representing the storage bytes limit . | train | false |
38,158 | def _print_dot(_self, expr):
return ('{((%s) \\cdot (%s))}' % (expr.args[0], expr.args[1]))
| [
"def",
"_print_dot",
"(",
"_self",
",",
"expr",
")",
":",
"return",
"(",
"'{((%s) \\\\cdot (%s))}'",
"%",
"(",
"expr",
".",
"args",
"[",
"0",
"]",
",",
"expr",
".",
"args",
"[",
"1",
"]",
")",
")"
] | print statement used for latexprinter . | train | false |
38,160 | def process_css(css_source, tabid, base_uri):
def _absolutize_css_import(match):
return '@import "{}"'.format(wrap_url(match.group(1), tabid, base_uri).replace('"', '%22'))
def _absolutize_css_url(match):
url = match.group(1).strip('"\'')
return 'url("{}")'.format(wrap_url(url, tabid, base_uri).replace('"', '%22'))
css_source = CSS_IMPORT.sub(_absolutize_css_import, css_source)
css_source = CSS_URL.sub(_absolutize_css_url, css_source)
css_source = BAD_CSS.sub('portia-blocked', css_source)
return css_source
| [
"def",
"process_css",
"(",
"css_source",
",",
"tabid",
",",
"base_uri",
")",
":",
"def",
"_absolutize_css_import",
"(",
"match",
")",
":",
"return",
"'@import \"{}\"'",
".",
"format",
"(",
"wrap_url",
"(",
"match",
".",
"group",
"(",
"1",
")",
",",
"tabid",
",",
"base_uri",
")",
".",
"replace",
"(",
"'\"'",
",",
"'%22'",
")",
")",
"def",
"_absolutize_css_url",
"(",
"match",
")",
":",
"url",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
"'\"\\''",
")",
"return",
"'url(\"{}\")'",
".",
"format",
"(",
"wrap_url",
"(",
"url",
",",
"tabid",
",",
"base_uri",
")",
".",
"replace",
"(",
"'\"'",
",",
"'%22'",
")",
")",
"css_source",
"=",
"CSS_IMPORT",
".",
"sub",
"(",
"_absolutize_css_import",
",",
"css_source",
")",
"css_source",
"=",
"CSS_URL",
".",
"sub",
"(",
"_absolutize_css_url",
",",
"css_source",
")",
"css_source",
"=",
"BAD_CSS",
".",
"sub",
"(",
"'portia-blocked'",
",",
"css_source",
")",
"return",
"css_source"
] | wraps urls in css source . | train | false |
38,161 | def ssh_interface(vm_):
return config.get_cloud_config_value('ssh_interface', vm_, __opts__, default='public_ips', search_global=False)
| [
"def",
"ssh_interface",
"(",
"vm_",
")",
":",
"return",
"config",
".",
"get_cloud_config_value",
"(",
"'ssh_interface'",
",",
"vm_",
",",
"__opts__",
",",
"default",
"=",
"'public_ips'",
",",
"search_global",
"=",
"False",
")"
] | return the ssh_interface type to connect to . | train | false |
38,162 | def alt_sg_coeffs(window_length, polyorder, pos):
if (pos is None):
pos = (window_length // 2)
t = np.arange(window_length)
unit = (t == pos).astype(int)
h = np.polyval(np.polyfit(t, unit, polyorder), t)
return h
| [
"def",
"alt_sg_coeffs",
"(",
"window_length",
",",
"polyorder",
",",
"pos",
")",
":",
"if",
"(",
"pos",
"is",
"None",
")",
":",
"pos",
"=",
"(",
"window_length",
"//",
"2",
")",
"t",
"=",
"np",
".",
"arange",
"(",
"window_length",
")",
"unit",
"=",
"(",
"t",
"==",
"pos",
")",
".",
"astype",
"(",
"int",
")",
"h",
"=",
"np",
".",
"polyval",
"(",
"np",
".",
"polyfit",
"(",
"t",
",",
"unit",
",",
"polyorder",
")",
",",
"t",
")",
"return",
"h"
] | this is an alternative implementation of the sg coefficients . | train | false |
38,163 | def make_non_empty_sample_lists(fields, headers, mdata):
fsi = make_field_set_iterable(headers, fields, mdata)
samples = mdata[:, 0]
f_inds = [headers.index(i) for i in fields]
metadata = mdata[:, f_inds]
sample_groups = []
value_groups = []
for value_set in fsi:
(rows,) = (metadata == value_set).all(1).nonzero()
if (rows.size > 0):
sample_groups.append(samples[rows])
value_groups.append(value_set)
else:
pass
return (sample_groups, value_groups)
| [
"def",
"make_non_empty_sample_lists",
"(",
"fields",
",",
"headers",
",",
"mdata",
")",
":",
"fsi",
"=",
"make_field_set_iterable",
"(",
"headers",
",",
"fields",
",",
"mdata",
")",
"samples",
"=",
"mdata",
"[",
":",
",",
"0",
"]",
"f_inds",
"=",
"[",
"headers",
".",
"index",
"(",
"i",
")",
"for",
"i",
"in",
"fields",
"]",
"metadata",
"=",
"mdata",
"[",
":",
",",
"f_inds",
"]",
"sample_groups",
"=",
"[",
"]",
"value_groups",
"=",
"[",
"]",
"for",
"value_set",
"in",
"fsi",
":",
"(",
"rows",
",",
")",
"=",
"(",
"metadata",
"==",
"value_set",
")",
".",
"all",
"(",
"1",
")",
".",
"nonzero",
"(",
")",
"if",
"(",
"rows",
".",
"size",
">",
"0",
")",
":",
"sample_groups",
".",
"append",
"(",
"samples",
"[",
"rows",
"]",
")",
"value_groups",
".",
"append",
"(",
"value_set",
")",
"else",
":",
"pass",
"return",
"(",
"sample_groups",
",",
"value_groups",
")"
] | return non-empty sample lists for corresponding field value sets . | train | false |
38,164 | def wiki_template(template_slug, sr=None):
if (not sr):
try:
sr = Subreddit._by_name(g.default_sr)
except NotFound:
return None
try:
wiki = WikiPage.get(sr, ('templates/%s' % template_slug))
except tdb_cassandra.NotFound:
return None
return wiki._get('content')
| [
"def",
"wiki_template",
"(",
"template_slug",
",",
"sr",
"=",
"None",
")",
":",
"if",
"(",
"not",
"sr",
")",
":",
"try",
":",
"sr",
"=",
"Subreddit",
".",
"_by_name",
"(",
"g",
".",
"default_sr",
")",
"except",
"NotFound",
":",
"return",
"None",
"try",
":",
"wiki",
"=",
"WikiPage",
".",
"get",
"(",
"sr",
",",
"(",
"'templates/%s'",
"%",
"template_slug",
")",
")",
"except",
"tdb_cassandra",
".",
"NotFound",
":",
"return",
"None",
"return",
"wiki",
".",
"_get",
"(",
"'content'",
")"
] | pull content from a subreddits wiki page for internal use . | train | false |
38,165 | def process(cmd):
return dict(zip(cmdset, funcset)).get(cmd, reset)
| [
"def",
"process",
"(",
"cmd",
")",
":",
"return",
"dict",
"(",
"zip",
"(",
"cmdset",
",",
"funcset",
")",
")",
".",
"get",
"(",
"cmd",
",",
"reset",
")"
] | payment handler for the stripe api . | train | false |
38,166 | def _api_config_get_speedlimit(output, kwargs):
return report(output, keyword='speedlimit', data=Downloader.do.get_limit())
| [
"def",
"_api_config_get_speedlimit",
"(",
"output",
",",
"kwargs",
")",
":",
"return",
"report",
"(",
"output",
",",
"keyword",
"=",
"'speedlimit'",
",",
"data",
"=",
"Downloader",
".",
"do",
".",
"get_limit",
"(",
")",
")"
] | api: accepts output . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.