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 |
|---|---|---|---|---|---|
20,505 | def SpaceSeparatedTokenizer():
return RegexTokenizer('[^ \\t\\r\\n]+')
| [
"def",
"SpaceSeparatedTokenizer",
"(",
")",
":",
"return",
"RegexTokenizer",
"(",
"'[^ \\\\t\\\\r\\\\n]+'",
")"
] | returns a regextokenizer that splits tokens by whitespace . | train | false |
20,506 | def concat_xml(file_list):
checksum = hashlib.new('sha1')
if (not file_list):
return ('', checksum.hexdigest())
root = None
for fname in file_list:
with open(fname, 'rb') as fp:
contents = fp.read()
checksum.update(contents)
fp.seek(0)
xml = ElementTree.parse(fp).getroot()
if (root is None):
ro... | [
"def",
"concat_xml",
"(",
"file_list",
")",
":",
"checksum",
"=",
"hashlib",
".",
"new",
"(",
"'sha1'",
")",
"if",
"(",
"not",
"file_list",
")",
":",
"return",
"(",
"''",
",",
"checksum",
".",
"hexdigest",
"(",
")",
")",
"root",
"=",
"None",
"for",
... | concatenate xml files . | train | false |
20,508 | def find_executable_in_dir(dirname=None):
if (platform.system() == 'Windows'):
exe_name = 'caffe.exe'
else:
exe_name = 'caffe'
if (dirname is None):
dirnames = [path.strip('"\' ') for path in os.environ['PATH'].split(os.pathsep)]
else:
dirnames = [dirname]
for dirname in dirnames:
path = os.path.join(dir... | [
"def",
"find_executable_in_dir",
"(",
"dirname",
"=",
"None",
")",
":",
"if",
"(",
"platform",
".",
"system",
"(",
")",
"==",
"'Windows'",
")",
":",
"exe_name",
"=",
"'caffe.exe'",
"else",
":",
"exe_name",
"=",
"'caffe'",
"if",
"(",
"dirname",
"is",
"Non... | returns the path to the caffe executable at dirname if dirname is none . | train | false |
20,509 | def get_exploration_titles_and_categories(exp_ids):
explorations = [(get_exploration_from_model(e) if e else None) for e in exp_models.ExplorationModel.get_multi(exp_ids)]
result = {}
for exploration in explorations:
if (exploration is None):
logging.error('Could not find exploration corresponding to id')
els... | [
"def",
"get_exploration_titles_and_categories",
"(",
"exp_ids",
")",
":",
"explorations",
"=",
"[",
"(",
"get_exploration_from_model",
"(",
"e",
")",
"if",
"e",
"else",
"None",
")",
"for",
"e",
"in",
"exp_models",
".",
"ExplorationModel",
".",
"get_multi",
"(",
... | returns exploration titles and categories for the given ids . | train | false |
20,510 | def c12_mapping(char):
return (u' ' if stringprep.in_table_c12(char) else None)
| [
"def",
"c12_mapping",
"(",
"char",
")",
":",
"return",
"(",
"u' '",
"if",
"stringprep",
".",
"in_table_c12",
"(",
"char",
")",
"else",
"None",
")"
] | map non-ascii whitespace to spaces . | train | false |
20,512 | @LocalContext
def get_qemu_user():
arch = get_qemu_arch()
normal = ('qemu-' + arch)
static = (normal + '-static')
if misc.which(static):
return static
if misc.which(normal):
return normal
log.warn_once(('Neither %r nor %r are available' % (normal, static)))
| [
"@",
"LocalContext",
"def",
"get_qemu_user",
"(",
")",
":",
"arch",
"=",
"get_qemu_arch",
"(",
")",
"normal",
"=",
"(",
"'qemu-'",
"+",
"arch",
")",
"static",
"=",
"(",
"normal",
"+",
"'-static'",
")",
"if",
"misc",
".",
"which",
"(",
"static",
")",
... | returns the path to the qemu-user binary for the currently selected architecture . | train | false |
20,513 | def read_uint64(fid):
return _unpack_simple(fid, '>u8', np.uint64)
| [
"def",
"read_uint64",
"(",
"fid",
")",
":",
"return",
"_unpack_simple",
"(",
"fid",
",",
"'>u8'",
",",
"np",
".",
"uint64",
")"
] | read unsigned 64bit integer from bti file . | train | false |
20,514 | def get_path_parts(path):
if (not path):
return []
parent = os.path.split(path)[0]
parent_parts = parent.split(u'/')
if ((len(parent_parts) == 1) and (parent_parts[0] == u'')):
parts = []
else:
parts = [u'/'.join((parent_parts[:(parent_parts.index(part) + 1)] + [''])) for part in parent_parts]
if (path not ... | [
"def",
"get_path_parts",
"(",
"path",
")",
":",
"if",
"(",
"not",
"path",
")",
":",
"return",
"[",
"]",
"parent",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"[",
"0",
"]",
"parent_parts",
"=",
"parent",
".",
"split",
"(",
"u'/'",
")"... | returns a list of paths parent paths plus path . | train | false |
20,515 | def p_command_for_bad_final(p):
p[0] = 'BAD FINAL VALUE IN FOR STATEMENT'
| [
"def",
"p_command_for_bad_final",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"'BAD FINAL VALUE IN FOR STATEMENT'"
] | command : for id equals expr to error optstep . | train | false |
20,516 | def fields_to_dict(lines, delim=' DCTB ', strip_f=strip):
result = {}
for line in lines:
if strip_f:
fields = map(strip_f, line.split(delim))
else:
fields = line.split(delim)
if (not fields[0]):
continue
result[fields[0]] = fields[1:]
return result
| [
"def",
"fields_to_dict",
"(",
"lines",
",",
"delim",
"=",
"' DCTB '",
",",
"strip_f",
"=",
"strip",
")",
":",
"result",
"=",
"{",
"}",
"for",
"line",
"in",
"lines",
":",
"if",
"strip_f",
":",
"fields",
"=",
"map",
"(",
"strip_f",
",",
"line",
".",
... | makes a dict where first field is key . | train | false |
20,517 | def sprint(text, *colors):
return ('\x1b[{}m{content}\x1b[{}m'.format(';'.join([str(color) for color in colors]), RESET, content=text) if (IS_ANSI_TERMINAL and colors) else text)
| [
"def",
"sprint",
"(",
"text",
",",
"*",
"colors",
")",
":",
"return",
"(",
"'\\x1b[{}m{content}\\x1b[{}m'",
".",
"format",
"(",
"';'",
".",
"join",
"(",
"[",
"str",
"(",
"color",
")",
"for",
"color",
"in",
"colors",
"]",
")",
",",
"RESET",
",",
"cont... | format text with color or other effects into ansi escaped string . | train | true |
20,520 | def _create_hierarchies(metadata, levels, template):
levels = object_dict(levels)
hierarchies = []
for md in metadata:
if isinstance(md, compat.string_type):
if (not template):
raise ModelError('Can not specify just a hierarchy name ({}) if there is no template'.format(md))
hier = template.hierarchy(md)
... | [
"def",
"_create_hierarchies",
"(",
"metadata",
",",
"levels",
",",
"template",
")",
":",
"levels",
"=",
"object_dict",
"(",
"levels",
")",
"hierarchies",
"=",
"[",
"]",
"for",
"md",
"in",
"metadata",
":",
"if",
"isinstance",
"(",
"md",
",",
"compat",
"."... | create dimension hierarchies from metadata and possibly inherit from template dimension . | train | false |
20,521 | def to_naive_utc_dt(dt):
if (not isinstance(dt, datetime)):
raise TypeError('Arg must be type datetime')
if (dt.tzinfo is None):
return dt
return dt.astimezone(pytz.utc).replace(tzinfo=None)
| [
"def",
"to_naive_utc_dt",
"(",
"dt",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"dt",
",",
"datetime",
")",
")",
":",
"raise",
"TypeError",
"(",
"'Arg must be type datetime'",
")",
"if",
"(",
"dt",
".",
"tzinfo",
"is",
"None",
")",
":",
"return",
"... | converts a datetime to a naive datetime as follows: if inbound dt is already naive . | train | false |
20,523 | def test_ast_bad_with():
cant_compile(u'(with*)')
cant_compile(u'(with* [])')
cant_compile(u'(with* [] (pass))')
| [
"def",
"test_ast_bad_with",
"(",
")",
":",
"cant_compile",
"(",
"u'(with*)'",
")",
"cant_compile",
"(",
"u'(with* [])'",
")",
"cant_compile",
"(",
"u'(with* [] (pass))'",
")"
] | make sure ast cant compile invalid with . | train | false |
20,524 | def print_error(string):
sys.stderr.write((string + '\n'))
| [
"def",
"print_error",
"(",
"string",
")",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"(",
"string",
"+",
"'\\n'",
")",
")"
] | print error messages . | train | false |
20,525 | def _MakeStartNewThread(base_start_new_thread):
def StartNewThread(target, args, kw=None):
'A replacement for thread.start_new_thread.\n\n A replacement for thread.start_new_thread that inherits RequestEnvironment\n state from its creator and cleans up that state when it terminates.\n\n Args:\n See thr... | [
"def",
"_MakeStartNewThread",
"(",
"base_start_new_thread",
")",
":",
"def",
"StartNewThread",
"(",
"target",
",",
"args",
",",
"kw",
"=",
"None",
")",
":",
"if",
"(",
"kw",
"is",
"None",
")",
":",
"kw",
"=",
"{",
"}",
"cloner",
"=",
"request_environment... | returns a replacement for start_new_thread that inherits environment . | train | false |
20,526 | @pytest.mark.parametrize(u'mode', [u'partial', u'trim', u'strict'])
def test_extract_array_easy(mode):
large_test_array = np.zeros((11, 11))
small_test_array = np.ones((5, 5))
large_test_array[3:8, 3:8] = small_test_array
extracted_array = extract_array(large_test_array, (5, 5), (5, 5), mode=mode)
assert np.all((e... | [
"@",
"pytest",
".",
"mark",
".",
"parametrize",
"(",
"u'mode'",
",",
"[",
"u'partial'",
",",
"u'trim'",
",",
"u'strict'",
"]",
")",
"def",
"test_extract_array_easy",
"(",
"mode",
")",
":",
"large_test_array",
"=",
"np",
".",
"zeros",
"(",
"(",
"11",
",",... | test extract_array utility function . | train | false |
20,528 | def embedded_document(reference, data_relation, field_name):
if (('version' in data_relation) and (data_relation['version'] is True)):
embedded_doc = get_data_version_relation_document(data_relation, reference)
latest_embedded_doc = get_data_version_relation_document(data_relation, reference, latest=True)
if ((e... | [
"def",
"embedded_document",
"(",
"reference",
",",
"data_relation",
",",
"field_name",
")",
":",
"if",
"(",
"(",
"'version'",
"in",
"data_relation",
")",
"and",
"(",
"data_relation",
"[",
"'version'",
"]",
"is",
"True",
")",
")",
":",
"embedded_doc",
"=",
... | returns a document to be embedded by reference using data_relation taking into account document versions . | train | false |
20,529 | def getNewMouseTool():
return ViewpointRotate()
| [
"def",
"getNewMouseTool",
"(",
")",
":",
"return",
"ViewpointRotate",
"(",
")"
] | get a new mouse tool . | train | false |
20,530 | def binary_accuracy(y, t):
return BinaryAccuracy()(y, t)
| [
"def",
"binary_accuracy",
"(",
"y",
",",
"t",
")",
":",
"return",
"BinaryAccuracy",
"(",
")",
"(",
"y",
",",
"t",
")"
] | computes the binary accuracy between predictions and targets . | train | false |
20,532 | def str_to_bool(string):
if (string is not None):
if (string.lower() in ['true', 'yes', '1', 'on']):
return True
elif (string.lower() in ['false', 'no', '0', 'off']):
return False
return None
| [
"def",
"str_to_bool",
"(",
"string",
")",
":",
"if",
"(",
"string",
"is",
"not",
"None",
")",
":",
"if",
"(",
"string",
".",
"lower",
"(",
")",
"in",
"[",
"'true'",
",",
"'yes'",
",",
"'1'",
",",
"'on'",
"]",
")",
":",
"return",
"True",
"elif",
... | given a string . | train | false |
20,533 | def ManageBinaries(config=None, token=None):
print '\nStep 4: Installing template package and repackaging clients with new configuration.'
pack_templates = False
download_templates = False
if flags.FLAGS.noprompt:
if (not flags.FLAGS.no_templates_download):
download_templates = pack_templates = True
else:
i... | [
"def",
"ManageBinaries",
"(",
"config",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"print",
"'\\nStep 4: Installing template package and repackaging clients with new configuration.'",
"pack_templates",
"=",
"False",
"download_templates",
"=",
"False",
"if",
"flags",
... | repack templates into installers . | train | false |
20,534 | def copy_to(name, source, dest, overwrite=False, makedirs=False, path=None):
_ensure_running(name, no_start=True, path=path)
return __salt__['container_resource.copy_to'](name, source, dest, container_type=__virtualname__, path=path, exec_driver=EXEC_DRIVER, overwrite=overwrite, makedirs=makedirs)
| [
"def",
"copy_to",
"(",
"name",
",",
"source",
",",
"dest",
",",
"overwrite",
"=",
"False",
",",
"makedirs",
"=",
"False",
",",
"path",
"=",
"None",
")",
":",
"_ensure_running",
"(",
"name",
",",
"no_start",
"=",
"True",
",",
"path",
"=",
"path",
")",... | copy a file from the host into a container name container name source file to be copied to the container . | train | true |
20,535 | def encode_base64_dict(array):
return {'__ndarray__': base64.b64encode(array.data).decode('utf-8'), 'shape': array.shape, 'dtype': array.dtype.name}
| [
"def",
"encode_base64_dict",
"(",
"array",
")",
":",
"return",
"{",
"'__ndarray__'",
":",
"base64",
".",
"b64encode",
"(",
"array",
".",
"data",
")",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"'shape'",
":",
"array",
".",
"shape",
",",
"'dtype'",
":",
"... | encode a numpy array using base64: the encoded format is a dict with the following structure: . | train | true |
20,536 | def join_logical_line(logical_line):
indentation = _get_indentation(logical_line)
return ((indentation + untokenize_without_newlines(generate_tokens(logical_line.lstrip()))) + u'\n')
| [
"def",
"join_logical_line",
"(",
"logical_line",
")",
":",
"indentation",
"=",
"_get_indentation",
"(",
"logical_line",
")",
"return",
"(",
"(",
"indentation",
"+",
"untokenize_without_newlines",
"(",
"generate_tokens",
"(",
"logical_line",
".",
"lstrip",
"(",
")",
... | return single line based on logical line input . | train | true |
20,537 | @require_admin_context
def consistencygroup_get_all(context, filters=None, marker=None, limit=None, offset=None, sort_keys=None, sort_dirs=None):
return _consistencygroup_get_all(context, filters, marker, limit, offset, sort_keys, sort_dirs)
| [
"@",
"require_admin_context",
"def",
"consistencygroup_get_all",
"(",
"context",
",",
"filters",
"=",
"None",
",",
"marker",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"offset",
"=",
"None",
",",
"sort_keys",
"=",
"None",
",",
"sort_dirs",
"=",
"None",
"... | get all consistencygroups . | train | false |
20,538 | def get_amalgamation():
if os.path.exists(AMALGAMATION_ROOT):
return
os.mkdir(AMALGAMATION_ROOT)
print 'Downloading amalgation.'
download_page = urllib.urlopen('http://sqlite.org/download.html').read()
pattern = re.compile('(sqlite-amalgamation.*?\\.zip)')
download_file = pattern.findall(download_page)[0]
amal... | [
"def",
"get_amalgamation",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"AMALGAMATION_ROOT",
")",
":",
"return",
"os",
".",
"mkdir",
"(",
"AMALGAMATION_ROOT",
")",
"print",
"'Downloading amalgation.'",
"download_page",
"=",
"urllib",
".",
"urlop... | download the sqlite amalgamation if it isnt there . | train | false |
20,540 | def b16decode(s, casefold=False):
if casefold:
s = s.upper()
if re.search('[^0-9A-F]', s):
raise TypeError('Non-base16 digit found')
return binascii.unhexlify(s)
| [
"def",
"b16decode",
"(",
"s",
",",
"casefold",
"=",
"False",
")",
":",
"if",
"casefold",
":",
"s",
"=",
"s",
".",
"upper",
"(",
")",
"if",
"re",
".",
"search",
"(",
"'[^0-9A-F]'",
",",
"s",
")",
":",
"raise",
"TypeError",
"(",
"'Non-base16 digit foun... | decode a base16 encoded string . | train | true |
20,542 | def token_create_scoped(request, tenant, token):
if hasattr(request, '_keystone'):
del request._keystone
c = keystoneclient(request)
raw_token = c.tokens.authenticate(tenant_id=tenant, token=token, return_raw=True)
c.service_catalog = service_catalog.ServiceCatalog(raw_token)
if request.user.is_superuser:
c.ma... | [
"def",
"token_create_scoped",
"(",
"request",
",",
"tenant",
",",
"token",
")",
":",
"if",
"hasattr",
"(",
"request",
",",
"'_keystone'",
")",
":",
"del",
"request",
".",
"_keystone",
"c",
"=",
"keystoneclient",
"(",
"request",
")",
"raw_token",
"=",
"c",
... | creates a scoped token using the tenant id and unscoped token; retrieves the service catalog for the given tenant . | train | false |
20,543 | def apart_full_decomposition(P, Q):
return assemble_partfrac_list(apart_list((P / Q), P.gens[0]))
| [
"def",
"apart_full_decomposition",
"(",
"P",
",",
"Q",
")",
":",
"return",
"assemble_partfrac_list",
"(",
"apart_list",
"(",
"(",
"P",
"/",
"Q",
")",
",",
"P",
".",
"gens",
"[",
"0",
"]",
")",
")"
] | bronsteins full partial fraction decomposition algorithm . | train | false |
20,544 | def set_current_user(user):
_thread_locals.user = user
| [
"def",
"set_current_user",
"(",
"user",
")",
":",
"_thread_locals",
".",
"user",
"=",
"user"
] | assigns current user from request to thread_locals . | train | false |
20,547 | def http_now():
return dt_to_http(utcnow())
| [
"def",
"http_now",
"(",
")",
":",
"return",
"dt_to_http",
"(",
"utcnow",
"(",
")",
")"
] | returns the current utc time as an imf-fixdate . | train | false |
20,548 | def start_remote_debugger(rpcclt, pyshell):
global idb_adap_oid
idb_adap_oid = rpcclt.remotecall('exec', 'start_the_debugger', (gui_adap_oid,), {})
idb_proxy = IdbProxy(rpcclt, pyshell, idb_adap_oid)
gui = debugger.Debugger(pyshell, idb_proxy)
gui_adap = GUIAdapter(rpcclt, gui)
rpcclt.register(gui_adap_oid, gui_a... | [
"def",
"start_remote_debugger",
"(",
"rpcclt",
",",
"pyshell",
")",
":",
"global",
"idb_adap_oid",
"idb_adap_oid",
"=",
"rpcclt",
".",
"remotecall",
"(",
"'exec'",
",",
"'start_the_debugger'",
",",
"(",
"gui_adap_oid",
",",
")",
",",
"{",
"}",
")",
"idb_proxy"... | start the subprocess debugger . | train | false |
20,549 | def iter_all_children(obj, skipContainers=False):
if (hasattr(obj, 'get_children') and (len(obj.get_children()) > 0)):
for child in obj.get_children():
if (not skipContainers):
(yield child)
for grandchild in iter_all_children(child, skipContainers):
(yield grandchild)
else:
(yield obj)
| [
"def",
"iter_all_children",
"(",
"obj",
",",
"skipContainers",
"=",
"False",
")",
":",
"if",
"(",
"hasattr",
"(",
"obj",
",",
"'get_children'",
")",
"and",
"(",
"len",
"(",
"obj",
".",
"get_children",
"(",
")",
")",
">",
"0",
")",
")",
":",
"for",
... | returns an iterator over all children and nested children using objs get_children() method if skipcontainers is true . | train | true |
20,550 | def profiler(app):
def profile_internal(e, o):
(out, result) = profile(app)(e, o)
return (out + [(('<pre>' + result) + '</pre>')])
return profile_internal
| [
"def",
"profiler",
"(",
"app",
")",
":",
"def",
"profile_internal",
"(",
"e",
",",
"o",
")",
":",
"(",
"out",
",",
"result",
")",
"=",
"profile",
"(",
"app",
")",
"(",
"e",
",",
"o",
")",
"return",
"(",
"out",
"+",
"[",
"(",
"(",
"'<pre>'",
"... | to use the profiler start web2py with -f profiler . | train | false |
20,551 | def _gather_clone_loss(clone, num_clones, regularization_losses):
sum_loss = None
clone_loss = None
regularization_loss = None
with tf.device(clone.device):
all_losses = []
clone_losses = tf.get_collection(tf.GraphKeys.LOSSES, clone.scope)
if clone_losses:
clone_loss = tf.add_n(clone_losses, name='clone_lo... | [
"def",
"_gather_clone_loss",
"(",
"clone",
",",
"num_clones",
",",
"regularization_losses",
")",
":",
"sum_loss",
"=",
"None",
"clone_loss",
"=",
"None",
"regularization_loss",
"=",
"None",
"with",
"tf",
".",
"device",
"(",
"clone",
".",
"device",
")",
":",
... | gather the loss for a single clone . | train | false |
20,552 | def uuid_str_to_bin(uuid):
matches = re.match('([\\dA-Fa-f]{8})-([\\dA-Fa-f]{4})-([\\dA-Fa-f]{4})-([\\dA-Fa-f]{4})-([\\dA-Fa-f]{4})([\\dA-Fa-f]{8})', uuid)
(uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = map((lambda x: long(x, 16)), matches.groups())
uuid = struct.pack('<LHH', uuid1, uuid2, uuid3)
uuid += struct.pack(... | [
"def",
"uuid_str_to_bin",
"(",
"uuid",
")",
":",
"matches",
"=",
"re",
".",
"match",
"(",
"'([\\\\dA-Fa-f]{8})-([\\\\dA-Fa-f]{4})-([\\\\dA-Fa-f]{4})-([\\\\dA-Fa-f]{4})-([\\\\dA-Fa-f]{4})([\\\\dA-Fa-f]{8})'",
",",
"uuid",
")",
"(",
"uuid1",
",",
"uuid2",
",",
"uuid3",
",",... | ripped from core impacket . | train | false |
20,554 | def humanFilesize(size):
if (size < 10000):
return (ngettext('%u byte', '%u bytes', size) % size)
units = [_('KB'), _('MB'), _('GB'), _('TB')]
size = float(size)
divisor = 1024
for unit in units:
size = (size / divisor)
if (size < divisor):
return ('%.1f %s' % (size, unit))
return ('%u %s' % (size, unit)... | [
"def",
"humanFilesize",
"(",
"size",
")",
":",
"if",
"(",
"size",
"<",
"10000",
")",
":",
"return",
"(",
"ngettext",
"(",
"'%u byte'",
",",
"'%u bytes'",
",",
"size",
")",
"%",
"size",
")",
"units",
"=",
"[",
"_",
"(",
"'KB'",
")",
",",
"_",
"(",... | convert a file size in byte to human natural representation . | train | false |
20,555 | def afunc():
pass
| [
"def",
"afunc",
"(",
")",
":",
"pass"
] | this is a doctest . | train | false |
20,556 | @utils.arg('--reservation-id', dest='reservation_id', metavar='<reservation-id>', default=None, help=_('Only return servers that match reservation-id.'))
@utils.arg('--ip', dest='ip', metavar='<ip-regexp>', default=None, help=_('Search with regular expression match by IP address.'))
@utils.arg('--ip6', dest='ip6', meta... | [
"@",
"utils",
".",
"arg",
"(",
"'--reservation-id'",
",",
"dest",
"=",
"'reservation_id'",
",",
"metavar",
"=",
"'<reservation-id>'",
",",
"default",
"=",
"None",
",",
"help",
"=",
"_",
"(",
"'Only return servers that match reservation-id.'",
")",
")",
"@",
"uti... | convert the value into a list . | train | false |
20,557 | def set_session_data(storage, messages):
storage.request.session[storage.session_key] = storage.serialize_messages(messages)
if hasattr(storage, '_loaded_data'):
del storage._loaded_data
| [
"def",
"set_session_data",
"(",
"storage",
",",
"messages",
")",
":",
"storage",
".",
"request",
".",
"session",
"[",
"storage",
".",
"session_key",
"]",
"=",
"storage",
".",
"serialize_messages",
"(",
"messages",
")",
"if",
"hasattr",
"(",
"storage",
",",
... | store session data persistently so that it is propagated automatically to new logged in clients . | train | false |
20,558 | def get_certificate_template(course_key, mode):
(org_id, template) = (None, None)
course_organization = get_course_organizations(course_key)
if course_organization:
org_id = course_organization[0]['id']
if (org_id and mode):
template = CertificateTemplate.objects.filter(organization_id=org_id, course_key=course... | [
"def",
"get_certificate_template",
"(",
"course_key",
",",
"mode",
")",
":",
"(",
"org_id",
",",
"template",
")",
"=",
"(",
"None",
",",
"None",
")",
"course_organization",
"=",
"get_course_organizations",
"(",
"course_key",
")",
"if",
"course_organization",
":"... | retrieves the custom certificate template based on course_key and mode . | train | false |
20,559 | def _test_rational_new(cls):
assert (cls(0) is S.Zero)
assert (cls(1) is S.One)
assert (cls((-1)) is S.NegativeOne)
assert (cls('1') is S.One)
assert (cls(u'-1') is S.NegativeOne)
i = Integer(10)
assert _strictly_equal(i, cls('10'))
assert _strictly_equal(i, cls(u'10'))
assert _strictly_equal(i, cls(long(10)))... | [
"def",
"_test_rational_new",
"(",
"cls",
")",
":",
"assert",
"(",
"cls",
"(",
"0",
")",
"is",
"S",
".",
"Zero",
")",
"assert",
"(",
"cls",
"(",
"1",
")",
"is",
"S",
".",
"One",
")",
"assert",
"(",
"cls",
"(",
"(",
"-",
"1",
")",
")",
"is",
... | tests that are common between integer and rational . | train | false |
20,560 | def remove_args(url, keep_params=(), frags=False):
parsed = urlsplit(url)
filtered_query = '&'.join((qry_item for qry_item in parsed.query.split('&') if qry_item.startswith(keep_params)))
if frags:
frag = parsed[4:]
else:
frag = ('',)
return urlunsplit(((parsed[:3] + (filtered_query,)) + frag))
| [
"def",
"remove_args",
"(",
"url",
",",
"keep_params",
"=",
"(",
")",
",",
"frags",
"=",
"False",
")",
":",
"parsed",
"=",
"urlsplit",
"(",
"url",
")",
"filtered_query",
"=",
"'&'",
".",
"join",
"(",
"(",
"qry_item",
"for",
"qry_item",
"in",
"parsed",
... | remove all param arguments from a url . | train | false |
20,561 | def runRPC(port=4242):
print '[*] Starting Veil-Evasion RPC server...'
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('127.0.0.1', port))
s.listen(1)
server = VeilEvasionServer(s, name='VeilEvasionServer')
server.join()
| [
"def",
"runRPC",
"(",
"port",
"=",
"4242",
")",
":",
"print",
"'[*] Starting Veil-Evasion RPC server...'",
"import",
"socket",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"s",
".",
"setsockopt",
"... | invoke a veil-evasion rpc instance on the specified port . | train | false |
20,562 | def convergence(first_front, optimal_front):
distances = []
for ind in first_front:
distances.append(float('inf'))
for opt_ind in optimal_front:
dist = 0.0
for i in xrange(len(opt_ind)):
dist += ((ind.fitness.values[i] - opt_ind[i]) ** 2)
if (dist < distances[(-1)]):
distances[(-1)] = dist
dist... | [
"def",
"convergence",
"(",
"first_front",
",",
"optimal_front",
")",
":",
"distances",
"=",
"[",
"]",
"for",
"ind",
"in",
"first_front",
":",
"distances",
".",
"append",
"(",
"float",
"(",
"'inf'",
")",
")",
"for",
"opt_ind",
"in",
"optimal_front",
":",
... | given a pareto front first_front and the optimal pareto front . | train | false |
20,564 | def view_image():
try:
_id = request.args[0]
except:
return 'Need to provide the id of the Image'
table = s3db.doc_image
record = db((table.id == _id)).select(table.name, table.file, table.comments, limitby=(0, 1)).first()
desc = DIV(record.comments, _class='imageDesc')
filename = record.name
url = URL(c='de... | [
"def",
"view_image",
"(",
")",
":",
"try",
":",
"_id",
"=",
"request",
".",
"args",
"[",
"0",
"]",
"except",
":",
"return",
"'Need to provide the id of the Image'",
"table",
"=",
"s3db",
".",
"doc_image",
"record",
"=",
"db",
"(",
"(",
"table",
".",
"id"... | view a fullscreen version of an image - called from reports . | train | false |
20,565 | def compute_labels(pos, neg):
labels = np.zeros((len(pos) + len(neg)))
labels[:len(pos)] = 1.0
labels[len(pos):] = 0.0
return labels
| [
"def",
"compute_labels",
"(",
"pos",
",",
"neg",
")",
":",
"labels",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"pos",
")",
"+",
"len",
"(",
"neg",
")",
")",
")",
"labels",
"[",
":",
"len",
"(",
"pos",
")",
"]",
"=",
"1.0",
"labels",
"[",... | construct list of labels . | train | false |
20,566 | def read_user_yes_no(question, default_value):
return click.prompt(question, default=default_value, type=click.BOOL)
| [
"def",
"read_user_yes_no",
"(",
"question",
",",
"default_value",
")",
":",
"return",
"click",
".",
"prompt",
"(",
"question",
",",
"default",
"=",
"default_value",
",",
"type",
"=",
"click",
".",
"BOOL",
")"
] | prompt the user to reply with yes or no . | train | true |
20,567 | def jwt_get_username_from_payload_handler(payload):
return payload.get('username')
| [
"def",
"jwt_get_username_from_payload_handler",
"(",
"payload",
")",
":",
"return",
"payload",
".",
"get",
"(",
"'username'",
")"
] | override this function if username is formatted differently in payload . | train | false |
20,569 | def isdag(d, keys):
return (not getcycle(d, keys))
| [
"def",
"isdag",
"(",
"d",
",",
"keys",
")",
":",
"return",
"(",
"not",
"getcycle",
"(",
"d",
",",
"keys",
")",
")"
] | does dask form a directed acyclic graph when calculating keys? keys may be a single key or list of keys . | train | false |
20,570 | def finditer(pattern, string, flags=0):
return _compile(pattern, flags).finditer(string)
| [
"def",
"finditer",
"(",
"pattern",
",",
"string",
",",
"flags",
"=",
"0",
")",
":",
"return",
"_compile",
"(",
"pattern",
",",
"flags",
")",
".",
"finditer",
"(",
"string",
")"
] | return an iterator over all non-overlapping matches in the string . | train | false |
20,572 | def tstd_lls(y, params, df):
(mu, sigma2) = params.T
df = (df * 1.0)
lls = ((gammaln(((df + 1) / 2.0)) - gammaln((df / 2.0))) - (0.5 * np.log(((df - 2) * np.pi))))
lls -= ((((df + 1) / 2.0) * np.log((1.0 + ((((y - mu) ** 2) / (df - 2)) / sigma2)))) + (0.5 * np.log(sigma2)))
return lls
| [
"def",
"tstd_lls",
"(",
"y",
",",
"params",
",",
"df",
")",
":",
"(",
"mu",
",",
"sigma2",
")",
"=",
"params",
".",
"T",
"df",
"=",
"(",
"df",
"*",
"1.0",
")",
"lls",
"=",
"(",
"(",
"gammaln",
"(",
"(",
"(",
"df",
"+",
"1",
")",
"/",
"2.0... | t loglikelihood given observations and mean mu and variance sigma2 = 1 parameters y : array . | train | false |
20,573 | def compute_node_utilization_update(context, host, free_ram_mb_delta=0, free_disk_gb_delta=0, work_delta=0, vm_delta=0):
session = get_session()
compute_node = None
with session.begin(subtransactions=True):
compute_node = session.query(models.ComputeNode).options(joinedload('service')).filter((models.Service.host ... | [
"def",
"compute_node_utilization_update",
"(",
"context",
",",
"host",
",",
"free_ram_mb_delta",
"=",
"0",
",",
"free_disk_gb_delta",
"=",
"0",
",",
"work_delta",
"=",
"0",
",",
"vm_delta",
"=",
"0",
")",
":",
"session",
"=",
"get_session",
"(",
")",
"comput... | update a specific computenode entry by a series of deltas . | train | false |
20,574 | def grab_lock(l):
l.acquire()
print 'Got the lock again', l.filename
l.release()
| [
"def",
"grab_lock",
"(",
"l",
")",
":",
"l",
".",
"acquire",
"(",
")",
"print",
"'Got the lock again'",
",",
"l",
".",
"filename",
"l",
".",
"release",
"(",
")"
] | stub fn to grab lock inside a greenlet . | train | false |
20,575 | def flag_modified(instance, key):
(state, dict_) = (instance_state(instance), instance_dict(instance))
impl = state.manager[key].impl
state._modified_event(dict_, impl, NO_VALUE, force=True)
| [
"def",
"flag_modified",
"(",
"instance",
",",
"key",
")",
":",
"(",
"state",
",",
"dict_",
")",
"=",
"(",
"instance_state",
"(",
"instance",
")",
",",
"instance_dict",
"(",
"instance",
")",
")",
"impl",
"=",
"state",
".",
"manager",
"[",
"key",
"]",
... | mark an attribute on an instance as modified . | train | false |
20,576 | def enable_third_party_auth():
from third_party_auth import settings as auth_settings
auth_settings.apply_settings(settings)
| [
"def",
"enable_third_party_auth",
"(",
")",
":",
"from",
"third_party_auth",
"import",
"settings",
"as",
"auth_settings",
"auth_settings",
".",
"apply_settings",
"(",
"settings",
")"
] | enable the use of third_party_auth . | train | false |
20,577 | @app.cli.command('initdb')
def initdb_command():
init_db()
print 'Initialized the database.'
| [
"@",
"app",
".",
"cli",
".",
"command",
"(",
"'initdb'",
")",
"def",
"initdb_command",
"(",
")",
":",
"init_db",
"(",
")",
"print",
"'Initialized the database.'"
] | creates the database tables . | train | false |
20,578 | def set_metadata(xml):
try:
exml = etree.fromstring(xml)
except Exception as err:
raise GeoNodeException(('Uploaded XML document is not XML: %s' % str(err)))
tagname = get_tagname(exml)
if (tagname == 'GetRecordByIdResponse'):
LOGGER.info('stripping CSW root element')
exml = exml.getchildren()[0]
tagname ... | [
"def",
"set_metadata",
"(",
"xml",
")",
":",
"try",
":",
"exml",
"=",
"etree",
".",
"fromstring",
"(",
"xml",
")",
"except",
"Exception",
"as",
"err",
":",
"raise",
"GeoNodeException",
"(",
"(",
"'Uploaded XML document is not XML: %s'",
"%",
"str",
"(",
"err... | generate dict of model properties based on xml metadata . | train | false |
20,579 | @register.tag
def include_block(parser, token):
tokens = token.split_contents()
try:
tag_name = tokens.pop(0)
block_var_token = tokens.pop(0)
except IndexError:
raise template.TemplateSyntaxError((u'%r tag requires at least one argument' % tag_name))
block_var = parser.compile_filter(block_var_token)
if (tok... | [
"@",
"register",
".",
"tag",
"def",
"include_block",
"(",
"parser",
",",
"token",
")",
":",
"tokens",
"=",
"token",
".",
"split_contents",
"(",
")",
"try",
":",
"tag_name",
"=",
"tokens",
".",
"pop",
"(",
"0",
")",
"block_var_token",
"=",
"tokens",
"."... | render the passed item of streamfield content . | train | false |
20,580 | def printResult(records, domainname):
(answers, authority, additional) = records
if answers:
sys.stdout.write((((domainname + ' IN \n ') + '\n '.join((str(x.payload) for x in answers))) + '\n'))
else:
sys.stderr.write(('ERROR: No SRV records found for name %r\n' % (domainname,)))
| [
"def",
"printResult",
"(",
"records",
",",
"domainname",
")",
":",
"(",
"answers",
",",
"authority",
",",
"additional",
")",
"=",
"records",
"if",
"answers",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"(",
"(",
"(",
"domainname",
"+",
"' IN \\n '",
... | print a comma separated list of reverse domain names and associated pointer records . | train | false |
20,581 | def fixTimeout(second):
if isinstance(second, float):
second = int(ceil(second))
assert isinstance(second, (int, long))
return max(second, 1)
| [
"def",
"fixTimeout",
"(",
"second",
")",
":",
"if",
"isinstance",
"(",
"second",
",",
"float",
")",
":",
"second",
"=",
"int",
"(",
"ceil",
"(",
"second",
")",
")",
"assert",
"isinstance",
"(",
"second",
",",
"(",
"int",
",",
"long",
")",
")",
"ret... | fix timeout value: convert to integer with a minimum of 1 second . | train | false |
20,582 | def del_repo(alias):
repos = list_repos()
if repos:
deleted_from = dict()
for repo in repos:
source = repos[repo][0]
if (source['name'] == alias):
deleted_from[source['file']] = 0
_del_repo_from_file(alias, source['file'])
if deleted_from:
ret = ''
for repo in repos:
source = repos[repo]... | [
"def",
"del_repo",
"(",
"alias",
")",
":",
"repos",
"=",
"list_repos",
"(",
")",
"if",
"repos",
":",
"deleted_from",
"=",
"dict",
"(",
")",
"for",
"repo",
"in",
"repos",
":",
"source",
"=",
"repos",
"[",
"repo",
"]",
"[",
"0",
"]",
"if",
"(",
"so... | delete a repo . | train | false |
20,583 | def CONTAINSSTRING(expr, pattern):
return expr.like(('%%%s%%' % pattern))
| [
"def",
"CONTAINSSTRING",
"(",
"expr",
",",
"pattern",
")",
":",
"return",
"expr",
".",
"like",
"(",
"(",
"'%%%s%%'",
"%",
"pattern",
")",
")"
] | emulate sqlobjects containsstring . | train | false |
20,584 | def DeclareExtraKeyFlags(flag_values=FLAGS):
gflags.ADOPT_module_key_flags(module_bar, flag_values=flag_values)
| [
"def",
"DeclareExtraKeyFlags",
"(",
"flag_values",
"=",
"FLAGS",
")",
":",
"gflags",
".",
"ADOPT_module_key_flags",
"(",
"module_bar",
",",
"flag_values",
"=",
"flag_values",
")"
] | declares some extra key flags . | train | false |
20,587 | def get_sgemv_fix(info):
path = os.path.abspath(os.path.dirname(__file__))
if needs_sgemv_fix(info):
return [os.path.join(path, 'src', 'apple_sgemv_fix.c')]
else:
return []
| [
"def",
"get_sgemv_fix",
"(",
"info",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"if",
"needs_sgemv_fix",
"(",
"info",
")",
":",
"return",
"[",
"os",
".",
"path",
".",... | returns source file needed to correct sgemv . | train | false |
20,589 | def read_raw_eeglab(input_fname, montage=None, eog=(), event_id=None, event_id_func='strip_to_integer', preload=False, verbose=None, uint16_codec=None):
return RawEEGLAB(input_fname=input_fname, montage=montage, preload=preload, eog=eog, event_id=event_id, event_id_func=event_id_func, verbose=verbose, uint16_codec=uin... | [
"def",
"read_raw_eeglab",
"(",
"input_fname",
",",
"montage",
"=",
"None",
",",
"eog",
"=",
"(",
")",
",",
"event_id",
"=",
"None",
",",
"event_id_func",
"=",
"'strip_to_integer'",
",",
"preload",
"=",
"False",
",",
"verbose",
"=",
"None",
",",
"uint16_cod... | read an eeglab . | train | false |
20,591 | def l2_normalize(x, axis):
if (axis < 0):
axis = (axis % len(x.get_shape()))
return tf.nn.l2_normalize(x, dim=axis)
| [
"def",
"l2_normalize",
"(",
"x",
",",
"axis",
")",
":",
"if",
"(",
"axis",
"<",
"0",
")",
":",
"axis",
"=",
"(",
"axis",
"%",
"len",
"(",
"x",
".",
"get_shape",
"(",
")",
")",
")",
"return",
"tf",
".",
"nn",
".",
"l2_normalize",
"(",
"x",
","... | l2 normalization . | train | false |
20,592 | def _dump_arg_defaults(kwargs):
if current_app:
kwargs.setdefault('cls', current_app.json_encoder)
if (not current_app.config['JSON_AS_ASCII']):
kwargs.setdefault('ensure_ascii', False)
kwargs.setdefault('sort_keys', current_app.config['JSON_SORT_KEYS'])
else:
kwargs.setdefault('sort_keys', True)
kwargs.... | [
"def",
"_dump_arg_defaults",
"(",
"kwargs",
")",
":",
"if",
"current_app",
":",
"kwargs",
".",
"setdefault",
"(",
"'cls'",
",",
"current_app",
".",
"json_encoder",
")",
"if",
"(",
"not",
"current_app",
".",
"config",
"[",
"'JSON_AS_ASCII'",
"]",
")",
":",
... | inject default arguments for dump functions . | train | true |
20,593 | def kill_cursors(cursor_ids):
data = _ZERO_32
data += struct.pack('<i', len(cursor_ids))
for cursor_id in cursor_ids:
data += struct.pack('<q', cursor_id)
return __pack_message(2007, data)
| [
"def",
"kill_cursors",
"(",
"cursor_ids",
")",
":",
"data",
"=",
"_ZERO_32",
"data",
"+=",
"struct",
".",
"pack",
"(",
"'<i'",
",",
"len",
"(",
"cursor_ids",
")",
")",
"for",
"cursor_id",
"in",
"cursor_ids",
":",
"data",
"+=",
"struct",
".",
"pack",
"(... | get a **killcursors** message . | train | true |
20,595 | @when(u'we select from table')
def step_select_from_table(context):
context.cli.sendline(u'select * from a;')
| [
"@",
"when",
"(",
"u'we select from table'",
")",
"def",
"step_select_from_table",
"(",
"context",
")",
":",
"context",
".",
"cli",
".",
"sendline",
"(",
"u'select * from a;'",
")"
] | send select from table . | train | false |
20,596 | def read_char(fid, count=1):
return _unpack_simple(fid, ('>S%s' % count), 'S')
| [
"def",
"read_char",
"(",
"fid",
",",
"count",
"=",
"1",
")",
":",
"return",
"_unpack_simple",
"(",
"fid",
",",
"(",
"'>S%s'",
"%",
"count",
")",
",",
"'S'",
")"
] | read character from bti file . | train | false |
20,600 | def isPathInsideLoops(loops, path):
for loop in loops:
if isPathInsideLoop(loop, path):
return True
return False
| [
"def",
"isPathInsideLoops",
"(",
"loops",
",",
"path",
")",
":",
"for",
"loop",
"in",
"loops",
":",
"if",
"isPathInsideLoop",
"(",
"loop",
",",
"path",
")",
":",
"return",
"True",
"return",
"False"
] | determine if a path is inside another loop in a list . | train | false |
20,601 | def is_dn(s):
if (s == ''):
return 1
rm = dn_regex.match(s)
return ((rm != None) and (rm.group(0) == s))
| [
"def",
"is_dn",
"(",
"s",
")",
":",
"if",
"(",
"s",
"==",
"''",
")",
":",
"return",
"1",
"rm",
"=",
"dn_regex",
".",
"match",
"(",
"s",
")",
"return",
"(",
"(",
"rm",
"!=",
"None",
")",
"and",
"(",
"rm",
".",
"group",
"(",
"0",
")",
"==",
... | returns 1 if s is a ldap dn . | train | false |
20,602 | def mul(lin_op, val_dict, is_abs=False):
if (lin_op.type is lo.VARIABLE):
if (lin_op.data in val_dict):
if is_abs:
return np.abs(val_dict[lin_op.data])
else:
return val_dict[lin_op.data]
else:
return np.mat(np.zeros(lin_op.size))
elif (lin_op.type is lo.NO_OP):
return np.mat(np.zeros(lin_op.siz... | [
"def",
"mul",
"(",
"lin_op",
",",
"val_dict",
",",
"is_abs",
"=",
"False",
")",
":",
"if",
"(",
"lin_op",
".",
"type",
"is",
"lo",
".",
"VARIABLE",
")",
":",
"if",
"(",
"lin_op",
".",
"data",
"in",
"val_dict",
")",
":",
"if",
"is_abs",
":",
"retu... | element-wise multiplication . | train | false |
20,603 | def set_datatypes_registry(d_registry):
global _datatypes_registry
_datatypes_registry = d_registry
| [
"def",
"set_datatypes_registry",
"(",
"d_registry",
")",
":",
"global",
"_datatypes_registry",
"_datatypes_registry",
"=",
"d_registry"
] | set up datatypes_registry . | train | false |
20,604 | def filelineno():
if (not _state):
raise RuntimeError('no active input()')
return _state.filelineno()
| [
"def",
"filelineno",
"(",
")",
":",
"if",
"(",
"not",
"_state",
")",
":",
"raise",
"RuntimeError",
"(",
"'no active input()'",
")",
"return",
"_state",
".",
"filelineno",
"(",
")"
] | return the line number in the current file . | train | false |
20,605 | def p_multiplicative_expression_1(t):
pass
| [
"def",
"p_multiplicative_expression_1",
"(",
"t",
")",
":",
"pass"
] | multiplicative_expression : cast_expression . | train | false |
20,606 | def get_checkout_phases_for_service(checkout_process, service):
classes = get_provide_objects('front_service_checkout_phase_provider')
for provider_cls in classes:
provider = provider_cls()
assert isinstance(provider, ServiceCheckoutPhaseProvider)
phase = provider.get_checkout_phase(checkout_process, service)
... | [
"def",
"get_checkout_phases_for_service",
"(",
"checkout_process",
",",
"service",
")",
":",
"classes",
"=",
"get_provide_objects",
"(",
"'front_service_checkout_phase_provider'",
")",
"for",
"provider_cls",
"in",
"classes",
":",
"provider",
"=",
"provider_cls",
"(",
")... | get checkout phases for given service . | train | false |
20,608 | def readUntilRegex(stream, regex, ignore_eof=False):
name = b_('')
while True:
tok = stream.read(16)
if (not tok):
if (ignore_eof == True):
return name
else:
raise PdfStreamError('Stream has ended unexpectedly')
m = regex.search(tok)
if (m is not None):
name += tok[:m.start()]
stream.seek(... | [
"def",
"readUntilRegex",
"(",
"stream",
",",
"regex",
",",
"ignore_eof",
"=",
"False",
")",
":",
"name",
"=",
"b_",
"(",
"''",
")",
"while",
"True",
":",
"tok",
"=",
"stream",
".",
"read",
"(",
"16",
")",
"if",
"(",
"not",
"tok",
")",
":",
"if",
... | reads until the regular expression pattern matched raise pdfstreamerror on premature end-of-file . | train | false |
20,610 | def runcmd(cmdv, additional_env=None):
env = os.environ.copy()
if (additional_env is not None):
env.update(additional_env)
env['PATH'] = ((os.path.join(common.INSTALL_ROOT, 'build', 'env', 'bin') + os.path.pathsep) + env['PATH'])
shell_command = ' '.join(cmdv)
LOG.info(("Running '%s' with %r" % (shell_command, a... | [
"def",
"runcmd",
"(",
"cmdv",
",",
"additional_env",
"=",
"None",
")",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"if",
"(",
"additional_env",
"is",
"not",
"None",
")",
":",
"env",
".",
"update",
"(",
"additional_env",
")",
"env",
... | runcmd -> status code . | train | false |
20,611 | @click.command(u'new-language')
@pass_context
@click.argument(u'lang_code')
@click.argument(u'app')
def new_language(context, lang_code, app):
import frappe.translate
if (not context[u'sites']):
raise Exception(u'--site is required')
frappe.connect(site=context[u'sites'][0])
frappe.translate.write_translations_fi... | [
"@",
"click",
".",
"command",
"(",
"u'new-language'",
")",
"@",
"pass_context",
"@",
"click",
".",
"argument",
"(",
"u'lang_code'",
")",
"@",
"click",
".",
"argument",
"(",
"u'app'",
")",
"def",
"new_language",
"(",
"context",
",",
"lang_code",
",",
"app",... | create lang-code . | train | false |
20,612 | @core_helper
def dashboard_activity_stream(user_id, filter_type=None, filter_id=None, offset=0):
context = {'model': model, 'session': model.Session, 'user': c.user}
if filter_type:
action_functions = {'dataset': 'package_activity_list_html', 'user': 'user_activity_list_html', 'group': 'group_activity_list_html', '... | [
"@",
"core_helper",
"def",
"dashboard_activity_stream",
"(",
"user_id",
",",
"filter_type",
"=",
"None",
",",
"filter_id",
"=",
"None",
",",
"offset",
"=",
"0",
")",
":",
"context",
"=",
"{",
"'model'",
":",
"model",
",",
"'session'",
":",
"model",
".",
... | return the dashboard activity stream of the current user . | train | false |
20,613 | def sp_ones_like(x):
(data, indices, indptr, shape) = csm_properties(x)
return CSM(format=x.format)(tensor.ones_like(data), indices, indptr, shape)
| [
"def",
"sp_ones_like",
"(",
"x",
")",
":",
"(",
"data",
",",
"indices",
",",
"indptr",
",",
"shape",
")",
"=",
"csm_properties",
"(",
"x",
")",
"return",
"CSM",
"(",
"format",
"=",
"x",
".",
"format",
")",
"(",
"tensor",
".",
"ones_like",
"(",
"dat... | construct a sparse matrix of ones with the same sparsity pattern . | train | false |
20,615 | def check_export(op):
tpot_obj = TPOTClassifier(random_state=42)
prng = np.random.RandomState(42)
np.random.seed(42)
args = []
for type_ in op.parameter_types()[0][1:]:
args.append(prng.choice(tpot_obj._pset.terminals[type_]).value)
export_string = op.export(*args)
assert (export_string.startswith((op.__name__... | [
"def",
"check_export",
"(",
"op",
")",
":",
"tpot_obj",
"=",
"TPOTClassifier",
"(",
"random_state",
"=",
"42",
")",
"prng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"42",
")",
"np",
".",
"random",
".",
"seed",
"(",
"42",
")",
"args",
"=",
... | assert that a tpot operator exports as expected . | train | false |
20,616 | def resource_data_get_all(context, resource_id, data=None):
if (data is None):
data = context.session.query(models.ResourceData).filter_by(resource_id=resource_id).all()
if (not data):
raise exception.NotFound(_('no resource data found'))
ret = {}
for res in data:
if res.redact:
ret[res.key] = crypt.decryp... | [
"def",
"resource_data_get_all",
"(",
"context",
",",
"resource_id",
",",
"data",
"=",
"None",
")",
":",
"if",
"(",
"data",
"is",
"None",
")",
":",
"data",
"=",
"context",
".",
"session",
".",
"query",
"(",
"models",
".",
"ResourceData",
")",
".",
"filt... | looks up resource_data by resource . | train | false |
20,617 | def volume_down(hass):
hass.services.call(DOMAIN, SERVICE_VOLUME_DOWN)
| [
"def",
"volume_down",
"(",
"hass",
")",
":",
"hass",
".",
"services",
".",
"call",
"(",
"DOMAIN",
",",
"SERVICE_VOLUME_DOWN",
")"
] | press the keyboard button for volume down . | train | false |
20,618 | def FormatStats(data, percentiles=None, indent=0):
if (len(data) == 0):
return ''
leader = (' ' * indent)
out_str = (leader + ('mean=%.2f' % numpy.mean(data)))
out_str += (('\n' + leader) + ('median=%.2f' % numpy.median(data)))
out_str += (('\n' + leader) + ('stddev=%.2f' % numpy.std(data)))
if percentiles:
o... | [
"def",
"FormatStats",
"(",
"data",
",",
"percentiles",
"=",
"None",
",",
"indent",
"=",
"0",
")",
":",
"if",
"(",
"len",
"(",
"data",
")",
"==",
"0",
")",
":",
"return",
"''",
"leader",
"=",
"(",
"' '",
"*",
"indent",
")",
"out_str",
"=",
"(",
... | compute basic stats for an array and return a string containing average . | train | false |
20,619 | def get_host_ip(ip, shorten=True):
ip = netaddr.ip.IPAddress(ip)
cidr = netaddr.ip.IPNetwork(ip)
if (len(cidr) == 1):
return pretty_hex(ip)
else:
pretty = pretty_hex(cidr[0])
if ((not shorten) or (len(cidr) <= 8)):
return pretty
else:
cutoff = ((32 - cidr.prefixlen) / 4)
return pretty[0:(- cutoff)]... | [
"def",
"get_host_ip",
"(",
"ip",
",",
"shorten",
"=",
"True",
")",
":",
"ip",
"=",
"netaddr",
".",
"ip",
".",
"IPAddress",
"(",
"ip",
")",
"cidr",
"=",
"netaddr",
".",
"ip",
".",
"IPNetwork",
"(",
"ip",
")",
"if",
"(",
"len",
"(",
"cidr",
")",
... | return the ip encoding needed for the tftp boot tree . | train | false |
20,620 | def gen_resp_headers(info, is_deleted=False):
headers = {'X-Backend-Timestamp': Timestamp(info.get('created_at', 0)).internal, 'X-Backend-PUT-Timestamp': Timestamp(info.get('put_timestamp', 0)).internal, 'X-Backend-DELETE-Timestamp': Timestamp(info.get('delete_timestamp', 0)).internal, 'X-Backend-Status-Changed-At': T... | [
"def",
"gen_resp_headers",
"(",
"info",
",",
"is_deleted",
"=",
"False",
")",
":",
"headers",
"=",
"{",
"'X-Backend-Timestamp'",
":",
"Timestamp",
"(",
"info",
".",
"get",
"(",
"'created_at'",
",",
"0",
")",
")",
".",
"internal",
",",
"'X-Backend-PUT-Timesta... | convert container info dict to headers . | train | false |
20,623 | def _alter_sequence(cr, seq_name, number_increment=None, number_next=None):
if (number_increment == 0):
raise UserError(_('Step must not be zero.'))
cr.execute('SELECT relname FROM pg_class WHERE relkind=%s AND relname=%s', ('S', seq_name))
if (not cr.fetchone()):
return
statement = ('ALTER SEQUENCE %s' % (seq_... | [
"def",
"_alter_sequence",
"(",
"cr",
",",
"seq_name",
",",
"number_increment",
"=",
"None",
",",
"number_next",
"=",
"None",
")",
":",
"if",
"(",
"number_increment",
"==",
"0",
")",
":",
"raise",
"UserError",
"(",
"_",
"(",
"'Step must not be zero.'",
")",
... | alter a postresql sequence . | train | false |
20,624 | def table_from_file(file_in, start=0, stop=(-1)):
table = pyo.SndTable()
try:
table.setSound(file_in, start=start, stop=stop)
except TypeError:
msg = 'bad file `{0}`, or format not supported'.format(file_in)
raise PyoFormatException(msg)
rate = pyo.sndinfo(file_in)[2]
return (rate, table)
| [
"def",
"table_from_file",
"(",
"file_in",
",",
"start",
"=",
"0",
",",
"stop",
"=",
"(",
"-",
"1",
")",
")",
":",
"table",
"=",
"pyo",
".",
"SndTable",
"(",
")",
"try",
":",
"table",
".",
"setSound",
"(",
"file_in",
",",
"start",
"=",
"start",
",... | read data from files . | train | false |
20,625 | def register_live_index(model_cls):
uid = (str(model_cls) + 'live_indexing')
render_done.connect(render_done_handler, model_cls, dispatch_uid=uid)
pre_delete.connect(pre_delete_handler, model_cls, dispatch_uid=uid)
return model_cls
| [
"def",
"register_live_index",
"(",
"model_cls",
")",
":",
"uid",
"=",
"(",
"str",
"(",
"model_cls",
")",
"+",
"'live_indexing'",
")",
"render_done",
".",
"connect",
"(",
"render_done_handler",
",",
"model_cls",
",",
"dispatch_uid",
"=",
"uid",
")",
"pre_delete... | register a model and index for auto indexing . | train | false |
20,626 | @pytest.fixture
def tab_registry(win_registry):
registry = objreg.ObjectRegistry()
objreg.register('tab-registry', registry, scope='window', window=0)
(yield registry)
objreg.delete('tab-registry', scope='window', window=0)
| [
"@",
"pytest",
".",
"fixture",
"def",
"tab_registry",
"(",
"win_registry",
")",
":",
"registry",
"=",
"objreg",
".",
"ObjectRegistry",
"(",
")",
"objreg",
".",
"register",
"(",
"'tab-registry'",
",",
"registry",
",",
"scope",
"=",
"'window'",
",",
"window",
... | fixture providing a tab registry for win_id 0 . | train | false |
20,627 | def getLittleEndianFloatGivenFile(file):
return unpack('<f', file.read(4))[0]
| [
"def",
"getLittleEndianFloatGivenFile",
"(",
"file",
")",
":",
"return",
"unpack",
"(",
"'<f'",
",",
"file",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]"
] | get little endian float given a file . | train | false |
20,629 | def debug_on_error(type, value, tb):
traceback.print_exc(type, value, tb)
print
pdb.pm()
| [
"def",
"debug_on_error",
"(",
"type",
",",
"value",
",",
"tb",
")",
":",
"traceback",
".",
"print_exc",
"(",
"type",
",",
"value",
",",
"tb",
")",
"print",
"pdb",
".",
"pm",
"(",
")"
] | code due to thomas heller - published in python cookbook . | train | true |
20,630 | def basic_auth(realm, users, encrypt=None, debug=False):
if check_auth(users, encrypt):
if debug:
cherrypy.log('Auth successful', 'TOOLS.BASIC_AUTH')
return
cherrypy.serving.response.headers['www-authenticate'] = httpauth.basicAuth(realm)
raise cherrypy.HTTPError(401, 'You are not authorized to access that re... | [
"def",
"basic_auth",
"(",
"realm",
",",
"users",
",",
"encrypt",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"if",
"check_auth",
"(",
"users",
",",
"encrypt",
")",
":",
"if",
"debug",
":",
"cherrypy",
".",
"log",
"(",
"'Auth successful'",
",",
... | to use basic login with a different server from gluon . | train | false |
20,631 | def maxinconsts(Z, R):
Z = np.asarray(Z, order='c')
R = np.asarray(R, order='c')
is_valid_linkage(Z, throw=True, name='Z')
is_valid_im(R, throw=True, name='R')
n = (Z.shape[0] + 1)
if (Z.shape[0] != R.shape[0]):
raise ValueError('The inconsistency matrix and linkage matrix each have a different number of rows.'... | [
"def",
"maxinconsts",
"(",
"Z",
",",
"R",
")",
":",
"Z",
"=",
"np",
".",
"asarray",
"(",
"Z",
",",
"order",
"=",
"'c'",
")",
"R",
"=",
"np",
".",
"asarray",
"(",
"R",
",",
"order",
"=",
"'c'",
")",
"is_valid_linkage",
"(",
"Z",
",",
"throw",
... | returns the maximum inconsistency coefficient for each non-singleton cluster and its descendents . | train | false |
20,632 | def make_template(skeleton, getter, action):
def template():
skeleton(getter, action)
return template
| [
"def",
"make_template",
"(",
"skeleton",
",",
"getter",
",",
"action",
")",
":",
"def",
"template",
"(",
")",
":",
"skeleton",
"(",
"getter",
",",
"action",
")",
"return",
"template"
] | instantiate a template method with getter and action . | train | false |
20,635 | def encode_ascii(s):
return s
| [
"def",
"encode_ascii",
"(",
"s",
")",
":",
"return",
"s"
] | in python 2 this is a no-op . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.