id_within_dataset int64 1 55.5k | snippet stringlengths 19 14.2k | tokens listlengths 6 1.63k | nl stringlengths 6 352 | split_within_dataset stringclasses 1 value | is_duplicated bool 2 classes |
|---|---|---|---|---|---|
39,585 | @pytest.mark.skipif('not HAS_YAML')
def test_csv_ecsv_colnames_mismatch():
lines = copy.copy(SIMPLE_LINES)
header_index = lines.index('a b c')
lines[header_index] = 'a b d'
with pytest.raises(ValueError) as err:
ascii.read(lines, format='ecsv')
assert ("column names from ECSV header ['a', 'b', 'c']" in str(err))
| [
"@",
"pytest",
".",
"mark",
".",
"skipif",
"(",
"'not HAS_YAML'",
")",
"def",
"test_csv_ecsv_colnames_mismatch",
"(",
")",
":",
"lines",
"=",
"copy",
".",
"copy",
"(",
"SIMPLE_LINES",
")",
"header_index",
"=",
"lines",
".",
"index",
"(",
"'a b c'",
")",
"lines",
"[",
"header_index",
"]",
"=",
"'a b d'",
"with",
"pytest",
".",
"raises",
"(",
"ValueError",
")",
"as",
"err",
":",
"ascii",
".",
"read",
"(",
"lines",
",",
"format",
"=",
"'ecsv'",
")",
"assert",
"(",
"\"column names from ECSV header ['a', 'b', 'c']\"",
"in",
"str",
"(",
"err",
")",
")"
] | test that mismatch in column names from normal csv header vs . | train | false |
39,586 | def _copy_prefix(prefix, base_dict):
querydict = QueryDict(None, mutable=True)
for (key, val) in base_dict.iteritems():
if key.startswith(prefix):
querydict[key] = val
return querydict
| [
"def",
"_copy_prefix",
"(",
"prefix",
",",
"base_dict",
")",
":",
"querydict",
"=",
"QueryDict",
"(",
"None",
",",
"mutable",
"=",
"True",
")",
"for",
"(",
"key",
",",
"val",
")",
"in",
"base_dict",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
".",
"startswith",
"(",
"prefix",
")",
":",
"querydict",
"[",
"key",
"]",
"=",
"val",
"return",
"querydict"
] | copy keys starting with prefix . | train | false |
39,587 | def _fixup_ins_del_tags(doc):
for tag in ['ins', 'del']:
for el in doc.xpath(('descendant-or-self::%s' % tag)):
if (not _contains_block_level_tag(el)):
continue
_move_el_inside_block(el, tag=tag)
el.drop_tag()
| [
"def",
"_fixup_ins_del_tags",
"(",
"doc",
")",
":",
"for",
"tag",
"in",
"[",
"'ins'",
",",
"'del'",
"]",
":",
"for",
"el",
"in",
"doc",
".",
"xpath",
"(",
"(",
"'descendant-or-self::%s'",
"%",
"tag",
")",
")",
":",
"if",
"(",
"not",
"_contains_block_level_tag",
"(",
"el",
")",
")",
":",
"continue",
"_move_el_inside_block",
"(",
"el",
",",
"tag",
"=",
"tag",
")",
"el",
".",
"drop_tag",
"(",
")"
] | fixup_ins_del_tags that works on an lxml document in-place . | train | true |
39,588 | def is_empty_dir(path):
for (_, _, files) in os.walk(path):
if files:
return False
return True
| [
"def",
"is_empty_dir",
"(",
"path",
")",
":",
"for",
"(",
"_",
",",
"_",
",",
"files",
")",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"if",
"files",
":",
"return",
"False",
"return",
"True"
] | checks if any files are present within a directory and all sub-directories . | train | false |
39,590 | def set_file_utime(filename, desired_time):
try:
os.utime(filename, (desired_time, desired_time))
except OSError as e:
if (e.errno != errno.EPERM):
raise e
raise SetFileUtimeError('The file was downloaded, but attempting to modify the utime of the file failed. Is the file owned by another user?')
| [
"def",
"set_file_utime",
"(",
"filename",
",",
"desired_time",
")",
":",
"try",
":",
"os",
".",
"utime",
"(",
"filename",
",",
"(",
"desired_time",
",",
"desired_time",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"(",
"e",
".",
"errno",
"!=",
"errno",
".",
"EPERM",
")",
":",
"raise",
"e",
"raise",
"SetFileUtimeError",
"(",
"'The file was downloaded, but attempting to modify the utime of the file failed. Is the file owned by another user?'",
")"
] | set the utime of a file . | train | false |
39,591 | def Hexdump(data, width=16):
for offset in xrange(0, len(data), width):
row_data = data[offset:(offset + width)]
translated_data = [(x if ((ord(x) < 127) and (ord(x) > 32)) else '.') for x in row_data]
hexdata = ' '.join(['{0:02x}'.format(ord(x)) for x in row_data])
(yield (offset, hexdata, translated_data))
| [
"def",
"Hexdump",
"(",
"data",
",",
"width",
"=",
"16",
")",
":",
"for",
"offset",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"data",
")",
",",
"width",
")",
":",
"row_data",
"=",
"data",
"[",
"offset",
":",
"(",
"offset",
"+",
"width",
")",
"]",
"translated_data",
"=",
"[",
"(",
"x",
"if",
"(",
"(",
"ord",
"(",
"x",
")",
"<",
"127",
")",
"and",
"(",
"ord",
"(",
"x",
")",
">",
"32",
")",
")",
"else",
"'.'",
")",
"for",
"x",
"in",
"row_data",
"]",
"hexdata",
"=",
"' '",
".",
"join",
"(",
"[",
"'{0:02x}'",
".",
"format",
"(",
"ord",
"(",
"x",
")",
")",
"for",
"x",
"in",
"row_data",
"]",
")",
"(",
"yield",
"(",
"offset",
",",
"hexdata",
",",
"translated_data",
")",
")"
] | hexdump function shared by various plugins . | train | false |
39,593 | def _snapshot_attached_here_impl(session, instance, vm_ref, label, userdevice, post_snapshot_callback):
LOG.debug('Starting snapshot for VM', instance=instance)
(vm_vdi_ref, vm_vdi_rec) = get_vdi_for_vm_safely(session, vm_ref, userdevice)
chain = _walk_vdi_chain(session, vm_vdi_rec['uuid'])
vdi_uuid_chain = [vdi_rec['uuid'] for vdi_rec in chain]
sr_ref = vm_vdi_rec['SR']
_delete_snapshots_in_vdi_chain(session, instance, vdi_uuid_chain, sr_ref)
snapshot_ref = _vdi_snapshot(session, vm_vdi_ref)
if (post_snapshot_callback is not None):
post_snapshot_callback(task_state=task_states.IMAGE_PENDING_UPLOAD)
try:
_wait_for_vhd_coalesce(session, instance, sr_ref, vm_vdi_ref, vdi_uuid_chain)
snapshot_uuid = _vdi_get_uuid(session, snapshot_ref)
chain = _walk_vdi_chain(session, snapshot_uuid)
vdi_uuids = [vdi_rec['uuid'] for vdi_rec in chain]
(yield vdi_uuids)
finally:
safe_destroy_vdis(session, [snapshot_ref])
| [
"def",
"_snapshot_attached_here_impl",
"(",
"session",
",",
"instance",
",",
"vm_ref",
",",
"label",
",",
"userdevice",
",",
"post_snapshot_callback",
")",
":",
"LOG",
".",
"debug",
"(",
"'Starting snapshot for VM'",
",",
"instance",
"=",
"instance",
")",
"(",
"vm_vdi_ref",
",",
"vm_vdi_rec",
")",
"=",
"get_vdi_for_vm_safely",
"(",
"session",
",",
"vm_ref",
",",
"userdevice",
")",
"chain",
"=",
"_walk_vdi_chain",
"(",
"session",
",",
"vm_vdi_rec",
"[",
"'uuid'",
"]",
")",
"vdi_uuid_chain",
"=",
"[",
"vdi_rec",
"[",
"'uuid'",
"]",
"for",
"vdi_rec",
"in",
"chain",
"]",
"sr_ref",
"=",
"vm_vdi_rec",
"[",
"'SR'",
"]",
"_delete_snapshots_in_vdi_chain",
"(",
"session",
",",
"instance",
",",
"vdi_uuid_chain",
",",
"sr_ref",
")",
"snapshot_ref",
"=",
"_vdi_snapshot",
"(",
"session",
",",
"vm_vdi_ref",
")",
"if",
"(",
"post_snapshot_callback",
"is",
"not",
"None",
")",
":",
"post_snapshot_callback",
"(",
"task_state",
"=",
"task_states",
".",
"IMAGE_PENDING_UPLOAD",
")",
"try",
":",
"_wait_for_vhd_coalesce",
"(",
"session",
",",
"instance",
",",
"sr_ref",
",",
"vm_vdi_ref",
",",
"vdi_uuid_chain",
")",
"snapshot_uuid",
"=",
"_vdi_get_uuid",
"(",
"session",
",",
"snapshot_ref",
")",
"chain",
"=",
"_walk_vdi_chain",
"(",
"session",
",",
"snapshot_uuid",
")",
"vdi_uuids",
"=",
"[",
"vdi_rec",
"[",
"'uuid'",
"]",
"for",
"vdi_rec",
"in",
"chain",
"]",
"(",
"yield",
"vdi_uuids",
")",
"finally",
":",
"safe_destroy_vdis",
"(",
"session",
",",
"[",
"snapshot_ref",
"]",
")"
] | snapshot the root disk only . | train | false |
39,594 | def create_snapshot_query_with_metadata(metadata_query_string, api_microversion):
req = fakes.HTTPRequest.blank(('/v3/snapshots?metadata=' + metadata_query_string))
req.headers['OpenStack-API-Version'] = ('volume ' + api_microversion)
req.api_version_request = api_version.APIVersionRequest(api_microversion)
return req
| [
"def",
"create_snapshot_query_with_metadata",
"(",
"metadata_query_string",
",",
"api_microversion",
")",
":",
"req",
"=",
"fakes",
".",
"HTTPRequest",
".",
"blank",
"(",
"(",
"'/v3/snapshots?metadata='",
"+",
"metadata_query_string",
")",
")",
"req",
".",
"headers",
"[",
"'OpenStack-API-Version'",
"]",
"=",
"(",
"'volume '",
"+",
"api_microversion",
")",
"req",
".",
"api_version_request",
"=",
"api_version",
".",
"APIVersionRequest",
"(",
"api_microversion",
")",
"return",
"req"
] | helper to create metadata querystring with microversion . | train | false |
39,596 | def file_copy(name, dest=None):
ret = {'name': name, 'changes': {}, 'result': True, 'comment': ''}
ret['changes'] = __salt__['junos.file_copy'](name, dest)
return ret
| [
"def",
"file_copy",
"(",
"name",
",",
"dest",
"=",
"None",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
"}",
"ret",
"[",
"'changes'",
"]",
"=",
"__salt__",
"[",
"'junos.file_copy'",
"]",
"(",
"name",
",",
"dest",
")",
"return",
"ret"
] | copies the file from the local device to the junos device . | train | true |
39,597 | def local_add_mul_fusion(node):
if ((not isinstance(node.op, Elemwise)) or (not isinstance(node.op.scalar_op, (scalar.Add, scalar.Mul)))):
return False
s_op = node.op.scalar_op.__class__
new_inp = []
fused = False
for inp in node.inputs:
if (inp.owner and isinstance(inp.owner.op, Elemwise) and isinstance(inp.owner.op.scalar_op, s_op) and (len(inp.clients) == 1)):
new_inp.extend(inp.owner.inputs)
fused = True
else:
new_inp.append(inp)
if fused:
output = node.op(*new_inp)
copy_stack_trace(node.outputs[0], output)
if output.owner:
output2 = local_add_mul_fusion(output.owner)
if output2:
return output2
return [output]
| [
"def",
"local_add_mul_fusion",
"(",
"node",
")",
":",
"if",
"(",
"(",
"not",
"isinstance",
"(",
"node",
".",
"op",
",",
"Elemwise",
")",
")",
"or",
"(",
"not",
"isinstance",
"(",
"node",
".",
"op",
".",
"scalar_op",
",",
"(",
"scalar",
".",
"Add",
",",
"scalar",
".",
"Mul",
")",
")",
")",
")",
":",
"return",
"False",
"s_op",
"=",
"node",
".",
"op",
".",
"scalar_op",
".",
"__class__",
"new_inp",
"=",
"[",
"]",
"fused",
"=",
"False",
"for",
"inp",
"in",
"node",
".",
"inputs",
":",
"if",
"(",
"inp",
".",
"owner",
"and",
"isinstance",
"(",
"inp",
".",
"owner",
".",
"op",
",",
"Elemwise",
")",
"and",
"isinstance",
"(",
"inp",
".",
"owner",
".",
"op",
".",
"scalar_op",
",",
"s_op",
")",
"and",
"(",
"len",
"(",
"inp",
".",
"clients",
")",
"==",
"1",
")",
")",
":",
"new_inp",
".",
"extend",
"(",
"inp",
".",
"owner",
".",
"inputs",
")",
"fused",
"=",
"True",
"else",
":",
"new_inp",
".",
"append",
"(",
"inp",
")",
"if",
"fused",
":",
"output",
"=",
"node",
".",
"op",
"(",
"*",
"new_inp",
")",
"copy_stack_trace",
"(",
"node",
".",
"outputs",
"[",
"0",
"]",
",",
"output",
")",
"if",
"output",
".",
"owner",
":",
"output2",
"=",
"local_add_mul_fusion",
"(",
"output",
".",
"owner",
")",
"if",
"output2",
":",
"return",
"output2",
"return",
"[",
"output",
"]"
] | fuse consecutive add or mul in one such node with more inputs . | train | false |
39,598 | def authenticationResponse():
a = TpPd(pd=5)
b = MessageType(mesType=20)
c = AuthenticationParameterSRES()
packet = ((a / b) / c)
return packet
| [
"def",
"authenticationResponse",
"(",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"5",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"20",
")",
"c",
"=",
"AuthenticationParameterSRES",
"(",
")",
"packet",
"=",
"(",
"(",
"a",
"/",
"b",
")",
"/",
"c",
")",
"return",
"packet"
] | authentication response section 9 . | train | true |
39,599 | def SaveFormat(root, fmt='eps'):
filename = ('%s.%s' % (root, fmt))
print('Writing', filename)
pyplot.savefig(filename, format=fmt, dpi=300)
| [
"def",
"SaveFormat",
"(",
"root",
",",
"fmt",
"=",
"'eps'",
")",
":",
"filename",
"=",
"(",
"'%s.%s'",
"%",
"(",
"root",
",",
"fmt",
")",
")",
"print",
"(",
"'Writing'",
",",
"filename",
")",
"pyplot",
".",
"savefig",
"(",
"filename",
",",
"format",
"=",
"fmt",
",",
"dpi",
"=",
"300",
")"
] | writes the current figure to a file in the given format . | train | false |
39,600 | @xframe_allow_whitelisted
def mock_view(_request):
return HttpResponse()
| [
"@",
"xframe_allow_whitelisted",
"def",
"mock_view",
"(",
"_request",
")",
":",
"return",
"HttpResponse",
"(",
")"
] | a test view for testing purposes . | train | false |
39,603 | def create_test_input(batch_size, height, width, channels):
if (None in [batch_size, height, width, channels]):
return tf.placeholder(tf.float32, (batch_size, height, width, channels))
else:
return tf.to_float(np.tile(np.reshape((np.reshape(np.arange(height), [height, 1]) + np.reshape(np.arange(width), [1, width])), [1, height, width, 1]), [batch_size, 1, 1, channels]))
| [
"def",
"create_test_input",
"(",
"batch_size",
",",
"height",
",",
"width",
",",
"channels",
")",
":",
"if",
"(",
"None",
"in",
"[",
"batch_size",
",",
"height",
",",
"width",
",",
"channels",
"]",
")",
":",
"return",
"tf",
".",
"placeholder",
"(",
"tf",
".",
"float32",
",",
"(",
"batch_size",
",",
"height",
",",
"width",
",",
"channels",
")",
")",
"else",
":",
"return",
"tf",
".",
"to_float",
"(",
"np",
".",
"tile",
"(",
"np",
".",
"reshape",
"(",
"(",
"np",
".",
"reshape",
"(",
"np",
".",
"arange",
"(",
"height",
")",
",",
"[",
"height",
",",
"1",
"]",
")",
"+",
"np",
".",
"reshape",
"(",
"np",
".",
"arange",
"(",
"width",
")",
",",
"[",
"1",
",",
"width",
"]",
")",
")",
",",
"[",
"1",
",",
"height",
",",
"width",
",",
"1",
"]",
")",
",",
"[",
"batch_size",
",",
"1",
",",
"1",
",",
"channels",
"]",
")",
")"
] | create test input tensor . | train | false |
39,604 | def get(name, default=_UNSET, scope='global', window=None, tab=None):
reg = _get_registry(scope, window, tab)
try:
return reg[name]
except KeyError:
if (default is not _UNSET):
return default
else:
raise
| [
"def",
"get",
"(",
"name",
",",
"default",
"=",
"_UNSET",
",",
"scope",
"=",
"'global'",
",",
"window",
"=",
"None",
",",
"tab",
"=",
"None",
")",
":",
"reg",
"=",
"_get_registry",
"(",
"scope",
",",
"window",
",",
"tab",
")",
"try",
":",
"return",
"reg",
"[",
"name",
"]",
"except",
"KeyError",
":",
"if",
"(",
"default",
"is",
"not",
"_UNSET",
")",
":",
"return",
"default",
"else",
":",
"raise"
] | sends a get request . | train | false |
39,605 | def check_delayed_string_interpolation(logical_line, physical_line, filename):
if ('nova/tests' in filename):
return
if pep8.noqa(physical_line):
return
if log_string_interpolation.match(logical_line):
(yield (logical_line.index('%'), "N354: String interpolation should be delayed to be handled by the logging code, rather than being done at the point of the logging call. Use ',' instead of '%'."))
| [
"def",
"check_delayed_string_interpolation",
"(",
"logical_line",
",",
"physical_line",
",",
"filename",
")",
":",
"if",
"(",
"'nova/tests'",
"in",
"filename",
")",
":",
"return",
"if",
"pep8",
".",
"noqa",
"(",
"physical_line",
")",
":",
"return",
"if",
"log_string_interpolation",
".",
"match",
"(",
"logical_line",
")",
":",
"(",
"yield",
"(",
"logical_line",
".",
"index",
"(",
"'%'",
")",
",",
"\"N354: String interpolation should be delayed to be handled by the logging code, rather than being done at the point of the logging call. Use ',' instead of '%'.\"",
")",
")"
] | check whether string interpolation is delayed at logging calls not correct: log . | train | false |
39,606 | def caveman_graph(l, k):
G = nx.empty_graph((l * k))
G.name = ('caveman_graph(%s,%s)' % ((l * k), k))
if (k > 1):
for start in range(0, (l * k), k):
edges = itertools.combinations(range(start, (start + k)), 2)
G.add_edges_from(edges)
return G
| [
"def",
"caveman_graph",
"(",
"l",
",",
"k",
")",
":",
"G",
"=",
"nx",
".",
"empty_graph",
"(",
"(",
"l",
"*",
"k",
")",
")",
"G",
".",
"name",
"=",
"(",
"'caveman_graph(%s,%s)'",
"%",
"(",
"(",
"l",
"*",
"k",
")",
",",
"k",
")",
")",
"if",
"(",
"k",
">",
"1",
")",
":",
"for",
"start",
"in",
"range",
"(",
"0",
",",
"(",
"l",
"*",
"k",
")",
",",
"k",
")",
":",
"edges",
"=",
"itertools",
".",
"combinations",
"(",
"range",
"(",
"start",
",",
"(",
"start",
"+",
"k",
")",
")",
",",
"2",
")",
"G",
".",
"add_edges_from",
"(",
"edges",
")",
"return",
"G"
] | returns a caveman graph of l cliques of size k . | train | false |
39,607 | @must_be_contributor_or_public
def collect_file_trees(auth, node, **kwargs):
serialized = _view_project(node, auth, primary=True)
serialized.update(rubeus.collect_addon_assets(node))
return serialized
| [
"@",
"must_be_contributor_or_public",
"def",
"collect_file_trees",
"(",
"auth",
",",
"node",
",",
"**",
"kwargs",
")",
":",
"serialized",
"=",
"_view_project",
"(",
"node",
",",
"auth",
",",
"primary",
"=",
"True",
")",
"serialized",
".",
"update",
"(",
"rubeus",
".",
"collect_addon_assets",
"(",
"node",
")",
")",
"return",
"serialized"
] | collect file trees for all add-ons implementing hgrid views . | train | false |
39,608 | def drop_tables(names, session):
metadata = MetaData()
metadata.reflect(bind=session.bind)
for table in metadata.sorted_tables:
if (table.name in names):
table.drop()
| [
"def",
"drop_tables",
"(",
"names",
",",
"session",
")",
":",
"metadata",
"=",
"MetaData",
"(",
")",
"metadata",
".",
"reflect",
"(",
"bind",
"=",
"session",
".",
"bind",
")",
"for",
"table",
"in",
"metadata",
".",
"sorted_tables",
":",
"if",
"(",
"table",
".",
"name",
"in",
"names",
")",
":",
"table",
".",
"drop",
"(",
")"
] | takes a list of table names and drops them from the database if they exist . | train | false |
39,610 | def _import_fail_message(module, version):
_dict = {'which': which[0], 'module': module, 'specific': (version + module)}
print ('\nThe import of the %(which)s version of the %(module)s module,\n%(specific)s, failed. This is is either because %(which)s was\nunavailable when matplotlib was compiled, because a dependency of\n%(specific)s could not be satisfied, or because the build flag for\nthis module was turned off in setup.py. If it appears that\n%(specific)s was not built, make sure you have a working copy of\n%(which)s and then re-install matplotlib. Otherwise, the following\ntraceback gives more details:\n' % _dict)
| [
"def",
"_import_fail_message",
"(",
"module",
",",
"version",
")",
":",
"_dict",
"=",
"{",
"'which'",
":",
"which",
"[",
"0",
"]",
",",
"'module'",
":",
"module",
",",
"'specific'",
":",
"(",
"version",
"+",
"module",
")",
"}",
"print",
"(",
"'\\nThe import of the %(which)s version of the %(module)s module,\\n%(specific)s, failed. This is is either because %(which)s was\\nunavailable when matplotlib was compiled, because a dependency of\\n%(specific)s could not be satisfied, or because the build flag for\\nthis module was turned off in setup.py. If it appears that\\n%(specific)s was not built, make sure you have a working copy of\\n%(which)s and then re-install matplotlib. Otherwise, the following\\ntraceback gives more details:\\n'",
"%",
"_dict",
")"
] | prints a message when the array package specific version of an extension fails to import correctly . | train | false |
39,611 | def test_find_creds():
env = {'TWILIO_ACCOUNT_SID': 'AC123', 'foo': 'bar', 'TWILIO_AUTH_TOKEN': '456'}
assert_equal(find_credentials(env), ('AC123', '456'))
| [
"def",
"test_find_creds",
"(",
")",
":",
"env",
"=",
"{",
"'TWILIO_ACCOUNT_SID'",
":",
"'AC123'",
",",
"'foo'",
":",
"'bar'",
",",
"'TWILIO_AUTH_TOKEN'",
":",
"'456'",
"}",
"assert_equal",
"(",
"find_credentials",
"(",
"env",
")",
",",
"(",
"'AC123'",
",",
"'456'",
")",
")"
] | i should find the credentials if they are there . | train | false |
39,614 | def _sample_rois(roidb, fg_rois_per_image, rois_per_image, num_classes):
labels = roidb['max_classes']
overlaps = roidb['max_overlaps']
rois = roidb['boxes']
fg_inds = np.where((overlaps >= cfg.TRAIN.FG_THRESH))[0]
fg_rois_per_this_image = np.minimum(fg_rois_per_image, fg_inds.size)
if (fg_inds.size > 0):
fg_inds = npr.choice(fg_inds, size=fg_rois_per_this_image, replace=False)
bg_inds = np.where(((overlaps < cfg.TRAIN.BG_THRESH_HI) & (overlaps >= cfg.TRAIN.BG_THRESH_LO)))[0]
bg_rois_per_this_image = (rois_per_image - fg_rois_per_this_image)
bg_rois_per_this_image = np.minimum(bg_rois_per_this_image, bg_inds.size)
if (bg_inds.size > 0):
bg_inds = npr.choice(bg_inds, size=bg_rois_per_this_image, replace=False)
keep_inds = np.append(fg_inds, bg_inds)
labels = labels[keep_inds]
labels[fg_rois_per_this_image:] = 0
overlaps = overlaps[keep_inds]
rois = rois[keep_inds]
(bbox_targets, bbox_inside_weights) = _get_bbox_regression_labels(roidb['bbox_targets'][keep_inds, :], num_classes)
return (labels, overlaps, rois, bbox_targets, bbox_inside_weights)
| [
"def",
"_sample_rois",
"(",
"roidb",
",",
"fg_rois_per_image",
",",
"rois_per_image",
",",
"num_classes",
")",
":",
"labels",
"=",
"roidb",
"[",
"'max_classes'",
"]",
"overlaps",
"=",
"roidb",
"[",
"'max_overlaps'",
"]",
"rois",
"=",
"roidb",
"[",
"'boxes'",
"]",
"fg_inds",
"=",
"np",
".",
"where",
"(",
"(",
"overlaps",
">=",
"cfg",
".",
"TRAIN",
".",
"FG_THRESH",
")",
")",
"[",
"0",
"]",
"fg_rois_per_this_image",
"=",
"np",
".",
"minimum",
"(",
"fg_rois_per_image",
",",
"fg_inds",
".",
"size",
")",
"if",
"(",
"fg_inds",
".",
"size",
">",
"0",
")",
":",
"fg_inds",
"=",
"npr",
".",
"choice",
"(",
"fg_inds",
",",
"size",
"=",
"fg_rois_per_this_image",
",",
"replace",
"=",
"False",
")",
"bg_inds",
"=",
"np",
".",
"where",
"(",
"(",
"(",
"overlaps",
"<",
"cfg",
".",
"TRAIN",
".",
"BG_THRESH_HI",
")",
"&",
"(",
"overlaps",
">=",
"cfg",
".",
"TRAIN",
".",
"BG_THRESH_LO",
")",
")",
")",
"[",
"0",
"]",
"bg_rois_per_this_image",
"=",
"(",
"rois_per_image",
"-",
"fg_rois_per_this_image",
")",
"bg_rois_per_this_image",
"=",
"np",
".",
"minimum",
"(",
"bg_rois_per_this_image",
",",
"bg_inds",
".",
"size",
")",
"if",
"(",
"bg_inds",
".",
"size",
">",
"0",
")",
":",
"bg_inds",
"=",
"npr",
".",
"choice",
"(",
"bg_inds",
",",
"size",
"=",
"bg_rois_per_this_image",
",",
"replace",
"=",
"False",
")",
"keep_inds",
"=",
"np",
".",
"append",
"(",
"fg_inds",
",",
"bg_inds",
")",
"labels",
"=",
"labels",
"[",
"keep_inds",
"]",
"labels",
"[",
"fg_rois_per_this_image",
":",
"]",
"=",
"0",
"overlaps",
"=",
"overlaps",
"[",
"keep_inds",
"]",
"rois",
"=",
"rois",
"[",
"keep_inds",
"]",
"(",
"bbox_targets",
",",
"bbox_inside_weights",
")",
"=",
"_get_bbox_regression_labels",
"(",
"roidb",
"[",
"'bbox_targets'",
"]",
"[",
"keep_inds",
",",
":",
"]",
",",
"num_classes",
")",
"return",
"(",
"labels",
",",
"overlaps",
",",
"rois",
",",
"bbox_targets",
",",
"bbox_inside_weights",
")"
] | generate a random sample of rois comprising foreground and background examples . | train | false |
39,617 | def goto_position_target_local_ned(north, east, down):
msg = vehicle.message_factory.set_position_target_local_ned_encode(0, 0, 0, mavutil.mavlink.MAV_FRAME_LOCAL_NED, 4088, north, east, down, 0, 0, 0, 0, 0, 0, 0, 0)
vehicle.send_mavlink(msg)
| [
"def",
"goto_position_target_local_ned",
"(",
"north",
",",
"east",
",",
"down",
")",
":",
"msg",
"=",
"vehicle",
".",
"message_factory",
".",
"set_position_target_local_ned_encode",
"(",
"0",
",",
"0",
",",
"0",
",",
"mavutil",
".",
"mavlink",
".",
"MAV_FRAME_LOCAL_NED",
",",
"4088",
",",
"north",
",",
"east",
",",
"down",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
",",
"0",
")",
"vehicle",
".",
"send_mavlink",
"(",
"msg",
")"
] | send set_position_target_local_ned command to request the vehicle fly to a specified location in the north . | train | true |
39,619 | def do_install(app_loc_list, relative_paths=False):
reg = registry.AppRegistry()
for app_loc in app_loc_list:
if (not _do_install_one(reg, app_loc, relative_paths)):
return False
reg.save()
return (do_sync(reg) and do_collectstatic())
| [
"def",
"do_install",
"(",
"app_loc_list",
",",
"relative_paths",
"=",
"False",
")",
":",
"reg",
"=",
"registry",
".",
"AppRegistry",
"(",
")",
"for",
"app_loc",
"in",
"app_loc_list",
":",
"if",
"(",
"not",
"_do_install_one",
"(",
"reg",
",",
"app_loc",
",",
"relative_paths",
")",
")",
":",
"return",
"False",
"reg",
".",
"save",
"(",
")",
"return",
"(",
"do_sync",
"(",
"reg",
")",
"and",
"do_collectstatic",
"(",
")",
")"
] | install the apps . | train | false |
39,620 | def libvlc_media_get_codec_description(i_type, i_codec):
f = (_Cfunctions.get('libvlc_media_get_codec_description', None) or _Cfunction('libvlc_media_get_codec_description', ((1,), (1,)), None, ctypes.c_char_p, TrackType, ctypes.c_uint32))
return f(i_type, i_codec)
| [
"def",
"libvlc_media_get_codec_description",
"(",
"i_type",
",",
"i_codec",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_media_get_codec_description'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_media_get_codec_description'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
")",
",",
"None",
",",
"ctypes",
".",
"c_char_p",
",",
"TrackType",
",",
"ctypes",
".",
"c_uint32",
")",
")",
"return",
"f",
"(",
"i_type",
",",
"i_codec",
")"
] | get codec description from media elementary stream . | train | true |
39,621 | def init(mpstate):
return SerialModule(mpstate)
| [
"def",
"init",
"(",
"mpstate",
")",
":",
"return",
"SerialModule",
"(",
"mpstate",
")"
] | instantiates address manager and outsocket as globals . | train | false |
39,623 | def get_default_instance():
global _default_instance
if (_default_instance is None):
_default_instance = Instance()
return _default_instance
| [
"def",
"get_default_instance",
"(",
")",
":",
"global",
"_default_instance",
"if",
"(",
"_default_instance",
"is",
"None",
")",
":",
"_default_instance",
"=",
"Instance",
"(",
")",
"return",
"_default_instance"
] | return the default vlc . | train | false |
39,624 | def list_jails():
_check_config_exists()
cmd = 'poudriere jails -l'
res = __salt__['cmd.run'](cmd)
return res.splitlines()
| [
"def",
"list_jails",
"(",
")",
":",
"_check_config_exists",
"(",
")",
"cmd",
"=",
"'poudriere jails -l'",
"res",
"=",
"__salt__",
"[",
"'cmd.run'",
"]",
"(",
"cmd",
")",
"return",
"res",
".",
"splitlines",
"(",
")"
] | return a list of current jails managed by poudriere cli example: . | train | false |
39,625 | def activity_type():
return s3_rest_controller()
| [
"def",
"activity_type",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | restful crud controller . | train | false |
39,626 | @task
@timed
def reset_test_database():
sh('{}/scripts/reset-test-db.sh'.format(Env.REPO_ROOT))
| [
"@",
"task",
"@",
"timed",
"def",
"reset_test_database",
"(",
")",
":",
"sh",
"(",
"'{}/scripts/reset-test-db.sh'",
".",
"format",
"(",
"Env",
".",
"REPO_ROOT",
")",
")"
] | reset the database used by the bokchoy tests . | train | false |
39,627 | def signal_handler_block(obj, handler_id):
GObjectModule.signal_handler_block(obj, handler_id)
return _HandlerBlockManager(obj, handler_id)
| [
"def",
"signal_handler_block",
"(",
"obj",
",",
"handler_id",
")",
":",
"GObjectModule",
".",
"signal_handler_block",
"(",
"obj",
",",
"handler_id",
")",
"return",
"_HandlerBlockManager",
"(",
"obj",
",",
"handler_id",
")"
] | blocks the signal handler from being invoked until handler_unblock() is called . | train | true |
39,628 | def _handle_default(k, v=None):
this_mapping = deepcopy(DEFAULTS[k])
if (v is not None):
if isinstance(v, dict):
this_mapping.update(v)
else:
for key in this_mapping.keys():
this_mapping[key] = v
return this_mapping
| [
"def",
"_handle_default",
"(",
"k",
",",
"v",
"=",
"None",
")",
":",
"this_mapping",
"=",
"deepcopy",
"(",
"DEFAULTS",
"[",
"k",
"]",
")",
"if",
"(",
"v",
"is",
"not",
"None",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"dict",
")",
":",
"this_mapping",
".",
"update",
"(",
"v",
")",
"else",
":",
"for",
"key",
"in",
"this_mapping",
".",
"keys",
"(",
")",
":",
"this_mapping",
"[",
"key",
"]",
"=",
"v",
"return",
"this_mapping"
] | avoid dicts as default keyword arguments . | train | false |
39,629 | def clear_all_sessions(reason=None):
frappe.only_for(u'Administrator')
if (not reason):
reason = u'Deleted All Active Session'
for sid in frappe.db.sql_list(u'select sid from `tabSessions`'):
delete_session(sid, reason=reason)
| [
"def",
"clear_all_sessions",
"(",
"reason",
"=",
"None",
")",
":",
"frappe",
".",
"only_for",
"(",
"u'Administrator'",
")",
"if",
"(",
"not",
"reason",
")",
":",
"reason",
"=",
"u'Deleted All Active Session'",
"for",
"sid",
"in",
"frappe",
".",
"db",
".",
"sql_list",
"(",
"u'select sid from `tabSessions`'",
")",
":",
"delete_session",
"(",
"sid",
",",
"reason",
"=",
"reason",
")"
] | this effectively logs out all users . | train | false |
39,630 | def get_user_by_username(app, username):
sa_session = app.model.context.current
try:
user = sa_session.query(app.model.User).filter((app.model.User.table.c.username == username)).one()
return user
except Exception:
return None
| [
"def",
"get_user_by_username",
"(",
"app",
",",
"username",
")",
":",
"sa_session",
"=",
"app",
".",
"model",
".",
"context",
".",
"current",
"try",
":",
"user",
"=",
"sa_session",
".",
"query",
"(",
"app",
".",
"model",
".",
"User",
")",
".",
"filter",
"(",
"(",
"app",
".",
"model",
".",
"User",
".",
"table",
".",
"c",
".",
"username",
"==",
"username",
")",
")",
".",
"one",
"(",
")",
"return",
"user",
"except",
"Exception",
":",
"return",
"None"
] | get a user from the database by username . | train | false |
39,632 | def get_backend():
return os.environ.get('BACKEND_ID', None)
| [
"def",
"get_backend",
"(",
")",
":",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"'BACKEND_ID'",
",",
"None",
")"
] | returns the current backend . | train | false |
39,633 | def userInformation(MoreData_presence=0):
a = TpPd(pd=3)
b = MessageType(mesType=32)
c = UserUser()
packet = ((a / b) / c)
if (MoreData_presence is 1):
d = MoreDataHdr(ieiMD=160, eightBitMD=0)
packet = (packet / d)
return packet
| [
"def",
"userInformation",
"(",
"MoreData_presence",
"=",
"0",
")",
":",
"a",
"=",
"TpPd",
"(",
"pd",
"=",
"3",
")",
"b",
"=",
"MessageType",
"(",
"mesType",
"=",
"32",
")",
"c",
"=",
"UserUser",
"(",
")",
"packet",
"=",
"(",
"(",
"a",
"/",
"b",
")",
"/",
"c",
")",
"if",
"(",
"MoreData_presence",
"is",
"1",
")",
":",
"d",
"=",
"MoreDataHdr",
"(",
"ieiMD",
"=",
"160",
",",
"eightBitMD",
"=",
"0",
")",
"packet",
"=",
"(",
"packet",
"/",
"d",
")",
"return",
"packet"
] | user information section 9 . | train | true |
39,636 | def log_to_null(name=None):
logger = logging.getLogger(name)
logger.addHandler(NullHandler())
| [
"def",
"log_to_null",
"(",
"name",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"addHandler",
"(",
"NullHandler",
"(",
")",
")"
] | set up a null handler for the given stream . | train | false |
39,637 | def rands_array(nchars, size, dtype='O'):
retval = np.random.choice(RANDS_CHARS, size=(nchars * np.prod(size))).view((np.str_, nchars)).reshape(size)
if (dtype is None):
return retval
else:
return retval.astype(dtype)
| [
"def",
"rands_array",
"(",
"nchars",
",",
"size",
",",
"dtype",
"=",
"'O'",
")",
":",
"retval",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"RANDS_CHARS",
",",
"size",
"=",
"(",
"nchars",
"*",
"np",
".",
"prod",
"(",
"size",
")",
")",
")",
".",
"view",
"(",
"(",
"np",
".",
"str_",
",",
"nchars",
")",
")",
".",
"reshape",
"(",
"size",
")",
"if",
"(",
"dtype",
"is",
"None",
")",
":",
"return",
"retval",
"else",
":",
"return",
"retval",
".",
"astype",
"(",
"dtype",
")"
] | generate an array of byte strings . | train | false |
39,638 | @click.command('new-app')
@click.argument('app-name')
def new_app(app_name):
from bench.app import new_app
new_app(app_name)
| [
"@",
"click",
".",
"command",
"(",
"'new-app'",
")",
"@",
"click",
".",
"argument",
"(",
"'app-name'",
")",
"def",
"new_app",
"(",
"app_name",
")",
":",
"from",
"bench",
".",
"app",
"import",
"new_app",
"new_app",
"(",
"app_name",
")"
] | start a new app . | train | false |
39,639 | def local_site_reverse(viewname, request=None, local_site_name=None, local_site=None, args=None, kwargs=None, *func_args, **func_kwargs):
assert (not (local_site_name and local_site))
if (request or local_site_name or local_site):
if local_site:
local_site_name = local_site.name
elif (request and (not local_site_name)):
local_site_name = getattr(request, u'_local_site_name', None)
if local_site_name:
if args:
new_args = ([local_site_name] + list(args))
new_kwargs = kwargs
else:
new_args = args
new_kwargs = {u'local_site_name': local_site_name}
if kwargs:
new_kwargs.update(kwargs)
try:
return reverse(viewname, args=new_args, kwargs=new_kwargs, *func_args, **func_kwargs)
except NoReverseMatch:
pass
return reverse(viewname, args=args, kwargs=kwargs, *func_args, **func_kwargs)
| [
"def",
"local_site_reverse",
"(",
"viewname",
",",
"request",
"=",
"None",
",",
"local_site_name",
"=",
"None",
",",
"local_site",
"=",
"None",
",",
"args",
"=",
"None",
",",
"kwargs",
"=",
"None",
",",
"*",
"func_args",
",",
"**",
"func_kwargs",
")",
":",
"assert",
"(",
"not",
"(",
"local_site_name",
"and",
"local_site",
")",
")",
"if",
"(",
"request",
"or",
"local_site_name",
"or",
"local_site",
")",
":",
"if",
"local_site",
":",
"local_site_name",
"=",
"local_site",
".",
"name",
"elif",
"(",
"request",
"and",
"(",
"not",
"local_site_name",
")",
")",
":",
"local_site_name",
"=",
"getattr",
"(",
"request",
",",
"u'_local_site_name'",
",",
"None",
")",
"if",
"local_site_name",
":",
"if",
"args",
":",
"new_args",
"=",
"(",
"[",
"local_site_name",
"]",
"+",
"list",
"(",
"args",
")",
")",
"new_kwargs",
"=",
"kwargs",
"else",
":",
"new_args",
"=",
"args",
"new_kwargs",
"=",
"{",
"u'local_site_name'",
":",
"local_site_name",
"}",
"if",
"kwargs",
":",
"new_kwargs",
".",
"update",
"(",
"kwargs",
")",
"try",
":",
"return",
"reverse",
"(",
"viewname",
",",
"args",
"=",
"new_args",
",",
"kwargs",
"=",
"new_kwargs",
",",
"*",
"func_args",
",",
"**",
"func_kwargs",
")",
"except",
"NoReverseMatch",
":",
"pass",
"return",
"reverse",
"(",
"viewname",
",",
"args",
"=",
"args",
",",
"kwargs",
"=",
"kwargs",
",",
"*",
"func_args",
",",
"**",
"func_kwargs",
")"
] | reverse a url name and return a working url . | train | false |
39,640 | def _item_to_zone(iterator, resource):
return ManagedZone.from_api_repr(resource, iterator.client)
| [
"def",
"_item_to_zone",
"(",
"iterator",
",",
"resource",
")",
":",
"return",
"ManagedZone",
".",
"from_api_repr",
"(",
"resource",
",",
"iterator",
".",
"client",
")"
] | convert a json managed zone to the native object . | train | false |
39,641 | def _signature_str(function_name, arg_spec):
arg_spec_for_format = arg_spec[:(7 if PY3_OR_LATER else 4)]
arg_spec_str = inspect.formatargspec(*arg_spec_for_format)
return '{0}{1}'.format(function_name, arg_spec_str)
| [
"def",
"_signature_str",
"(",
"function_name",
",",
"arg_spec",
")",
":",
"arg_spec_for_format",
"=",
"arg_spec",
"[",
":",
"(",
"7",
"if",
"PY3_OR_LATER",
"else",
"4",
")",
"]",
"arg_spec_str",
"=",
"inspect",
".",
"formatargspec",
"(",
"*",
"arg_spec_for_format",
")",
"return",
"'{0}{1}'",
".",
"format",
"(",
"function_name",
",",
"arg_spec_str",
")"
] | helper function to output a function signature . | train | false |
39,643 | def iter_subclasses(cls, _seen=None, template_classes=[]):
if (not isinstance(cls, type)):
raise TypeError(('itersubclasses must be called with new-style classes, not %.100r' % cls))
if (_seen is None):
_seen = set()
try:
subs = cls.__subclasses__()
except TypeError:
subs = cls.__subclasses__(cls)
for sub in subs:
if ((sub not in _seen) and (sub.__name__ not in template_classes)):
_seen.add(sub)
(yield sub)
for sub in iter_subclasses(sub, _seen, template_classes):
(yield sub)
| [
"def",
"iter_subclasses",
"(",
"cls",
",",
"_seen",
"=",
"None",
",",
"template_classes",
"=",
"[",
"]",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"cls",
",",
"type",
")",
")",
":",
"raise",
"TypeError",
"(",
"(",
"'itersubclasses must be called with new-style classes, not %.100r'",
"%",
"cls",
")",
")",
"if",
"(",
"_seen",
"is",
"None",
")",
":",
"_seen",
"=",
"set",
"(",
")",
"try",
":",
"subs",
"=",
"cls",
".",
"__subclasses__",
"(",
")",
"except",
"TypeError",
":",
"subs",
"=",
"cls",
".",
"__subclasses__",
"(",
"cls",
")",
"for",
"sub",
"in",
"subs",
":",
"if",
"(",
"(",
"sub",
"not",
"in",
"_seen",
")",
"and",
"(",
"sub",
".",
"__name__",
"not",
"in",
"template_classes",
")",
")",
":",
"_seen",
".",
"add",
"(",
"sub",
")",
"(",
"yield",
"sub",
")",
"for",
"sub",
"in",
"iter_subclasses",
"(",
"sub",
",",
"_seen",
",",
"template_classes",
")",
":",
"(",
"yield",
"sub",
")"
] | generator to iterate over all the subclasses of model . | train | false |
39,644 | def rush(enable=True, realtime=False):
if importWindllFailed:
return False
pr_rights = (PROCESS_QUERY_INFORMATION | PROCESS_SET_INFORMATION)
pr = windll.OpenProcess(pr_rights, FALSE, os.getpid())
thr = windll.GetCurrentThread()
if (enable is True):
if (realtime is False):
windll.SetPriorityClass(pr, HIGH_PRIORITY_CLASS)
windll.SetThreadPriority(thr, THREAD_PRIORITY_HIGHEST)
else:
windll.SetPriorityClass(pr, REALTIME_PRIORITY_CLASS)
windll.SetThreadPriority(thr, THREAD_PRIORITY_TIME_CRITICAL)
else:
windll.SetPriorityClass(pr, NORMAL_PRIORITY_CLASS)
windll.SetThreadPriority(thr, THREAD_PRIORITY_NORMAL)
return True
| [
"def",
"rush",
"(",
"enable",
"=",
"True",
",",
"realtime",
"=",
"False",
")",
":",
"if",
"importWindllFailed",
":",
"return",
"False",
"pr_rights",
"=",
"(",
"PROCESS_QUERY_INFORMATION",
"|",
"PROCESS_SET_INFORMATION",
")",
"pr",
"=",
"windll",
".",
"OpenProcess",
"(",
"pr_rights",
",",
"FALSE",
",",
"os",
".",
"getpid",
"(",
")",
")",
"thr",
"=",
"windll",
".",
"GetCurrentThread",
"(",
")",
"if",
"(",
"enable",
"is",
"True",
")",
":",
"if",
"(",
"realtime",
"is",
"False",
")",
":",
"windll",
".",
"SetPriorityClass",
"(",
"pr",
",",
"HIGH_PRIORITY_CLASS",
")",
"windll",
".",
"SetThreadPriority",
"(",
"thr",
",",
"THREAD_PRIORITY_HIGHEST",
")",
"else",
":",
"windll",
".",
"SetPriorityClass",
"(",
"pr",
",",
"REALTIME_PRIORITY_CLASS",
")",
"windll",
".",
"SetThreadPriority",
"(",
"thr",
",",
"THREAD_PRIORITY_TIME_CRITICAL",
")",
"else",
":",
"windll",
".",
"SetPriorityClass",
"(",
"pr",
",",
"NORMAL_PRIORITY_CLASS",
")",
"windll",
".",
"SetThreadPriority",
"(",
"thr",
",",
"THREAD_PRIORITY_NORMAL",
")",
"return",
"True"
] | raise the priority of the current thread/process . | train | false |
39,647 | def virtualkey(hass, address, channel, param, proxy=None):
data = {ATTR_ADDRESS: address, ATTR_CHANNEL: channel, ATTR_PARAM: param, ATTR_PROXY: proxy}
hass.services.call(DOMAIN, SERVICE_VIRTUALKEY, data)
| [
"def",
"virtualkey",
"(",
"hass",
",",
"address",
",",
"channel",
",",
"param",
",",
"proxy",
"=",
"None",
")",
":",
"data",
"=",
"{",
"ATTR_ADDRESS",
":",
"address",
",",
"ATTR_CHANNEL",
":",
"channel",
",",
"ATTR_PARAM",
":",
"param",
",",
"ATTR_PROXY",
":",
"proxy",
"}",
"hass",
".",
"services",
".",
"call",
"(",
"DOMAIN",
",",
"SERVICE_VIRTUALKEY",
",",
"data",
")"
] | send virtual keypress to homematic controlller . | train | false |
39,649 | def p_const_map_item(p):
p[0] = [p[1], p[3]]
| [
"def",
"p_const_map_item",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
"]"
] | const_map_item : const_value : const_value . | train | false |
39,650 | def test_imap_folder_sync_enabled(db, default_account):
create_foldersyncstatuses(db, default_account)
assert all([fs.sync_enabled for fs in default_account.foldersyncstatuses])
default_account.disable_sync('testing')
db.session.commit()
assert all([(not fs.sync_enabled) for fs in default_account.foldersyncstatuses])
| [
"def",
"test_imap_folder_sync_enabled",
"(",
"db",
",",
"default_account",
")",
":",
"create_foldersyncstatuses",
"(",
"db",
",",
"default_account",
")",
"assert",
"all",
"(",
"[",
"fs",
".",
"sync_enabled",
"for",
"fs",
"in",
"default_account",
".",
"foldersyncstatuses",
"]",
")",
"default_account",
".",
"disable_sync",
"(",
"'testing'",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"assert",
"all",
"(",
"[",
"(",
"not",
"fs",
".",
"sync_enabled",
")",
"for",
"fs",
"in",
"default_account",
".",
"foldersyncstatuses",
"]",
")"
] | test that the imap folders sync_enabled property mirrors the account level sync_enabled property . | train | false |
39,651 | def reset():
_runtime.reset()
| [
"def",
"reset",
"(",
")",
":",
"_runtime",
".",
"reset",
"(",
")"
] | clears the securedrop development applications state . | train | false |
39,652 | def infer_bulk_complete_from_fs(datetimes, datetime_to_task, datetime_to_re):
filesystems_and_globs_by_location = _get_filesystems_and_globs(datetime_to_task, datetime_to_re)
paths_by_datetime = [[o.path for o in flatten_output(datetime_to_task(d))] for d in datetimes]
listing = set()
for ((f, g), p) in zip(filesystems_and_globs_by_location, zip(*paths_by_datetime)):
listing |= _list_existing(f, g, p)
missing_datetimes = []
for (d, p) in zip(datetimes, paths_by_datetime):
if (not (set(p) <= listing)):
missing_datetimes.append(d)
return missing_datetimes
| [
"def",
"infer_bulk_complete_from_fs",
"(",
"datetimes",
",",
"datetime_to_task",
",",
"datetime_to_re",
")",
":",
"filesystems_and_globs_by_location",
"=",
"_get_filesystems_and_globs",
"(",
"datetime_to_task",
",",
"datetime_to_re",
")",
"paths_by_datetime",
"=",
"[",
"[",
"o",
".",
"path",
"for",
"o",
"in",
"flatten_output",
"(",
"datetime_to_task",
"(",
"d",
")",
")",
"]",
"for",
"d",
"in",
"datetimes",
"]",
"listing",
"=",
"set",
"(",
")",
"for",
"(",
"(",
"f",
",",
"g",
")",
",",
"p",
")",
"in",
"zip",
"(",
"filesystems_and_globs_by_location",
",",
"zip",
"(",
"*",
"paths_by_datetime",
")",
")",
":",
"listing",
"|=",
"_list_existing",
"(",
"f",
",",
"g",
",",
"p",
")",
"missing_datetimes",
"=",
"[",
"]",
"for",
"(",
"d",
",",
"p",
")",
"in",
"zip",
"(",
"datetimes",
",",
"paths_by_datetime",
")",
":",
"if",
"(",
"not",
"(",
"set",
"(",
"p",
")",
"<=",
"listing",
")",
")",
":",
"missing_datetimes",
".",
"append",
"(",
"d",
")",
"return",
"missing_datetimes"
] | efficiently determines missing datetimes by filesystem listing . | train | true |
39,653 | def get_category(cookie, tokens, category, page=1):
timestamp = util.timestamp()
url = ''.join([const.PAN_API_URL, 'categorylist?channel=chunlei&clienttype=0&web=1', '&category=', str(category), '&pri=-1&num=100', '&t=', timestamp, '&page=', str(page), '&order=time&desc=1', '&_=', timestamp, '&bdstoken=', cookie.get('STOKEN').value])
req = net.urlopen(url, headers={'Cookie': cookie.header_output()})
if req:
content = req.data
return json.loads(content.decode())
else:
return None
| [
"def",
"get_category",
"(",
"cookie",
",",
"tokens",
",",
"category",
",",
"page",
"=",
"1",
")",
":",
"timestamp",
"=",
"util",
".",
"timestamp",
"(",
")",
"url",
"=",
"''",
".",
"join",
"(",
"[",
"const",
".",
"PAN_API_URL",
",",
"'categorylist?channel=chunlei&clienttype=0&web=1'",
",",
"'&category='",
",",
"str",
"(",
"category",
")",
",",
"'&pri=-1&num=100'",
",",
"'&t='",
",",
"timestamp",
",",
"'&page='",
",",
"str",
"(",
"page",
")",
",",
"'&order=time&desc=1'",
",",
"'&_='",
",",
"timestamp",
",",
"'&bdstoken='",
",",
"cookie",
".",
"get",
"(",
"'STOKEN'",
")",
".",
"value",
"]",
")",
"req",
"=",
"net",
".",
"urlopen",
"(",
"url",
",",
"headers",
"=",
"{",
"'Cookie'",
":",
"cookie",
".",
"header_output",
"(",
")",
"}",
")",
"if",
"req",
":",
"content",
"=",
"req",
".",
"data",
"return",
"json",
".",
"loads",
"(",
"content",
".",
"decode",
"(",
")",
")",
"else",
":",
"return",
"None"
] | get a category from the database . | train | true |
39,654 | def hashed_download(url, temp, digest):
def opener():
opener = build_opener(HTTPSHandler())
for handler in opener.handlers:
if isinstance(handler, HTTPHandler):
opener.handlers.remove(handler)
return opener
def read_chunks(response, chunk_size):
while True:
chunk = response.read(chunk_size)
if (not chunk):
break
(yield chunk)
response = opener().open(url)
path = join(temp, urlparse(url).path.split('/')[(-1)])
actual_hash = sha256()
with open(path, 'wb') as file:
for chunk in read_chunks(response, 4096):
file.write(chunk)
actual_hash.update(chunk)
actual_digest = actual_hash.hexdigest()
if (actual_digest != digest):
raise HashError(url, path, actual_digest, digest)
return path
| [
"def",
"hashed_download",
"(",
"url",
",",
"temp",
",",
"digest",
")",
":",
"def",
"opener",
"(",
")",
":",
"opener",
"=",
"build_opener",
"(",
"HTTPSHandler",
"(",
")",
")",
"for",
"handler",
"in",
"opener",
".",
"handlers",
":",
"if",
"isinstance",
"(",
"handler",
",",
"HTTPHandler",
")",
":",
"opener",
".",
"handlers",
".",
"remove",
"(",
"handler",
")",
"return",
"opener",
"def",
"read_chunks",
"(",
"response",
",",
"chunk_size",
")",
":",
"while",
"True",
":",
"chunk",
"=",
"response",
".",
"read",
"(",
"chunk_size",
")",
"if",
"(",
"not",
"chunk",
")",
":",
"break",
"(",
"yield",
"chunk",
")",
"response",
"=",
"opener",
"(",
")",
".",
"open",
"(",
"url",
")",
"path",
"=",
"join",
"(",
"temp",
",",
"urlparse",
"(",
"url",
")",
".",
"path",
".",
"split",
"(",
"'/'",
")",
"[",
"(",
"-",
"1",
")",
"]",
")",
"actual_hash",
"=",
"sha256",
"(",
")",
"with",
"open",
"(",
"path",
",",
"'wb'",
")",
"as",
"file",
":",
"for",
"chunk",
"in",
"read_chunks",
"(",
"response",
",",
"4096",
")",
":",
"file",
".",
"write",
"(",
"chunk",
")",
"actual_hash",
".",
"update",
"(",
"chunk",
")",
"actual_digest",
"=",
"actual_hash",
".",
"hexdigest",
"(",
")",
"if",
"(",
"actual_digest",
"!=",
"digest",
")",
":",
"raise",
"HashError",
"(",
"url",
",",
"path",
",",
"actual_digest",
",",
"digest",
")",
"return",
"path"
] | download url to temp . | train | true |
39,655 | def demographic_data():
return s3_rest_controller()
| [
"def",
"demographic_data",
"(",
")",
":",
"return",
"s3_rest_controller",
"(",
")"
] | rest controller . | train | false |
39,656 | def _min_dummies(dummies, sym, indices):
num_types = len(sym)
m = []
for dx in dummies:
if dx:
m.append(min(dx))
else:
m.append(None)
res = indices[:]
for i in range(num_types):
for (c, i) in enumerate(indices):
for j in range(num_types):
if (i in dummies[j]):
res[c] = m[j]
break
return res
| [
"def",
"_min_dummies",
"(",
"dummies",
",",
"sym",
",",
"indices",
")",
":",
"num_types",
"=",
"len",
"(",
"sym",
")",
"m",
"=",
"[",
"]",
"for",
"dx",
"in",
"dummies",
":",
"if",
"dx",
":",
"m",
".",
"append",
"(",
"min",
"(",
"dx",
")",
")",
"else",
":",
"m",
".",
"append",
"(",
"None",
")",
"res",
"=",
"indices",
"[",
":",
"]",
"for",
"i",
"in",
"range",
"(",
"num_types",
")",
":",
"for",
"(",
"c",
",",
"i",
")",
"in",
"enumerate",
"(",
"indices",
")",
":",
"for",
"j",
"in",
"range",
"(",
"num_types",
")",
":",
"if",
"(",
"i",
"in",
"dummies",
"[",
"j",
"]",
")",
":",
"res",
"[",
"c",
"]",
"=",
"m",
"[",
"j",
"]",
"break",
"return",
"res"
] | return list of minima of the orbits of indices in group of dummies see double_coset_can_rep for the description of dummies and sym indices is the initial list of dummy indices examples . | train | false |
39,658 | def _get_anchor(module_to_name, fullname):
if (not _anchor_re.match(fullname)):
raise ValueError(("'%s' is not a valid anchor" % fullname))
anchor = fullname
for module_name in module_to_name.values():
if fullname.startswith((module_name + '.')):
rest = fullname[(len(module_name) + 1):]
if (len(anchor) > len(rest)):
anchor = rest
return anchor
| [
"def",
"_get_anchor",
"(",
"module_to_name",
",",
"fullname",
")",
":",
"if",
"(",
"not",
"_anchor_re",
".",
"match",
"(",
"fullname",
")",
")",
":",
"raise",
"ValueError",
"(",
"(",
"\"'%s' is not a valid anchor\"",
"%",
"fullname",
")",
")",
"anchor",
"=",
"fullname",
"for",
"module_name",
"in",
"module_to_name",
".",
"values",
"(",
")",
":",
"if",
"fullname",
".",
"startswith",
"(",
"(",
"module_name",
"+",
"'.'",
")",
")",
":",
"rest",
"=",
"fullname",
"[",
"(",
"len",
"(",
"module_name",
")",
"+",
"1",
")",
":",
"]",
"if",
"(",
"len",
"(",
"anchor",
")",
">",
"len",
"(",
"rest",
")",
")",
":",
"anchor",
"=",
"rest",
"return",
"anchor"
] | turn a full member name into an anchor . | train | true |
39,659 | def regularized_lsq_operator(J, diag):
J = aslinearoperator(J)
(m, n) = J.shape
def matvec(x):
return np.hstack((J.matvec(x), (diag * x)))
def rmatvec(x):
x1 = x[:m]
x2 = x[m:]
return (J.rmatvec(x1) + (diag * x2))
return LinearOperator(((m + n), n), matvec=matvec, rmatvec=rmatvec)
| [
"def",
"regularized_lsq_operator",
"(",
"J",
",",
"diag",
")",
":",
"J",
"=",
"aslinearoperator",
"(",
"J",
")",
"(",
"m",
",",
"n",
")",
"=",
"J",
".",
"shape",
"def",
"matvec",
"(",
"x",
")",
":",
"return",
"np",
".",
"hstack",
"(",
"(",
"J",
".",
"matvec",
"(",
"x",
")",
",",
"(",
"diag",
"*",
"x",
")",
")",
")",
"def",
"rmatvec",
"(",
"x",
")",
":",
"x1",
"=",
"x",
"[",
":",
"m",
"]",
"x2",
"=",
"x",
"[",
"m",
":",
"]",
"return",
"(",
"J",
".",
"rmatvec",
"(",
"x1",
")",
"+",
"(",
"diag",
"*",
"x2",
")",
")",
"return",
"LinearOperator",
"(",
"(",
"(",
"m",
"+",
"n",
")",
",",
"n",
")",
",",
"matvec",
"=",
"matvec",
",",
"rmatvec",
"=",
"rmatvec",
")"
] | return a matrix arising in regularized least squares as linearoperator . | train | false |
39,660 | def roots_chebys(n, mu=False):
(x, w, m) = roots_chebyu(n, True)
x *= 2
w *= 2
m *= 2
if mu:
return (x, w, m)
else:
return (x, w)
| [
"def",
"roots_chebys",
"(",
"n",
",",
"mu",
"=",
"False",
")",
":",
"(",
"x",
",",
"w",
",",
"m",
")",
"=",
"roots_chebyu",
"(",
"n",
",",
"True",
")",
"x",
"*=",
"2",
"w",
"*=",
"2",
"m",
"*=",
"2",
"if",
"mu",
":",
"return",
"(",
"x",
",",
"w",
",",
"m",
")",
"else",
":",
"return",
"(",
"x",
",",
"w",
")"
] | gauss-chebyshev quadrature . | train | false |
39,661 | def arg_repr(*args, **kwargs):
return {'args': repr(args), 'kwargs': repr(kwargs)}
| [
"def",
"arg_repr",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"return",
"{",
"'args'",
":",
"repr",
"(",
"args",
")",
",",
"'kwargs'",
":",
"repr",
"(",
"kwargs",
")",
"}"
] | print out the data passed into the function *args and kwargs . | train | false |
39,664 | def DX(barDs, count, timeperiod=(- (2 ** 31))):
return call_talib_with_hlc(barDs, count, talib.DX, timeperiod)
| [
"def",
"DX",
"(",
"barDs",
",",
"count",
",",
"timeperiod",
"=",
"(",
"-",
"(",
"2",
"**",
"31",
")",
")",
")",
":",
"return",
"call_talib_with_hlc",
"(",
"barDs",
",",
"count",
",",
"talib",
".",
"DX",
",",
"timeperiod",
")"
] | directional movement index . | train | false |
39,665 | def _AddFilters(filters):
_cpplint_state.AddFilters(filters)
| [
"def",
"_AddFilters",
"(",
"filters",
")",
":",
"_cpplint_state",
".",
"AddFilters",
"(",
"filters",
")"
] | adds more filter overrides . | train | false |
39,667 | @error.context_aware
def vg_remove(vg_name):
error.context(("Removing volume '%s'" % vg_name), logging.info)
if (not vg_check(vg_name)):
raise error.TestError(("Volume group '%s' could not be found" % vg_name))
cmd = ('vgremove -f %s' % vg_name)
result = utils.run(cmd)
logging.info(result.stdout.rstrip())
| [
"@",
"error",
".",
"context_aware",
"def",
"vg_remove",
"(",
"vg_name",
")",
":",
"error",
".",
"context",
"(",
"(",
"\"Removing volume '%s'\"",
"%",
"vg_name",
")",
",",
"logging",
".",
"info",
")",
"if",
"(",
"not",
"vg_check",
"(",
"vg_name",
")",
")",
":",
"raise",
"error",
".",
"TestError",
"(",
"(",
"\"Volume group '%s' could not be found\"",
"%",
"vg_name",
")",
")",
"cmd",
"=",
"(",
"'vgremove -f %s'",
"%",
"vg_name",
")",
"result",
"=",
"utils",
".",
"run",
"(",
"cmd",
")",
"logging",
".",
"info",
"(",
"result",
".",
"stdout",
".",
"rstrip",
"(",
")",
")"
] | remove a volume group . | train | false |
39,668 | def safe(text):
return _safe(text)
| [
"def",
"safe",
"(",
"text",
")",
":",
"return",
"_safe",
"(",
"text",
")"
] | make a string safe to include in an sql statement . | train | false |
39,669 | def from_store_name(container_name):
return CallingInfo(container_name)
| [
"def",
"from_store_name",
"(",
"container_name",
")",
":",
"return",
"CallingInfo",
"(",
"container_name",
")"
] | construct a callinginfo value from a target container name . | train | false |
39,671 | def processChildrenByIndexValue(function, index, indexValue, value, xmlElement):
if (indexValue.indexName != ''):
function.localDictionary[indexValue.indexName] = index
if (indexValue.valueName != ''):
function.localDictionary[indexValue.valueName] = value
function.processChildren(xmlElement)
| [
"def",
"processChildrenByIndexValue",
"(",
"function",
",",
"index",
",",
"indexValue",
",",
"value",
",",
"xmlElement",
")",
":",
"if",
"(",
"indexValue",
".",
"indexName",
"!=",
"''",
")",
":",
"function",
".",
"localDictionary",
"[",
"indexValue",
".",
"indexName",
"]",
"=",
"index",
"if",
"(",
"indexValue",
".",
"valueName",
"!=",
"''",
")",
":",
"function",
".",
"localDictionary",
"[",
"indexValue",
".",
"valueName",
"]",
"=",
"value",
"function",
".",
"processChildren",
"(",
"xmlElement",
")"
] | process children by index value . | train | false |
39,672 | def block_user(block):
frappe.local.flags.in_patch = block
frappe.db.begin()
msg = u'Patches are being executed in the system. Please try again in a few moments.'
frappe.db.set_global(u'__session_status', ((block and u'stop') or None))
frappe.db.set_global(u'__session_status_message', ((block and msg) or None))
frappe.db.commit()
| [
"def",
"block_user",
"(",
"block",
")",
":",
"frappe",
".",
"local",
".",
"flags",
".",
"in_patch",
"=",
"block",
"frappe",
".",
"db",
".",
"begin",
"(",
")",
"msg",
"=",
"u'Patches are being executed in the system. Please try again in a few moments.'",
"frappe",
".",
"db",
".",
"set_global",
"(",
"u'__session_status'",
",",
"(",
"(",
"block",
"and",
"u'stop'",
")",
"or",
"None",
")",
")",
"frappe",
".",
"db",
".",
"set_global",
"(",
"u'__session_status_message'",
",",
"(",
"(",
"block",
"and",
"msg",
")",
"or",
"None",
")",
")",
"frappe",
".",
"db",
".",
"commit",
"(",
")"
] | stop/start execution till patch is run . | train | false |
39,673 | def calledby(callerdepth=1):
import inspect, os
stack = inspect.stack()
callerdepth = min(max(2, (callerdepth + 1)), (len(stack) - 1))
frame = inspect.stack()[callerdepth]
path = os.path.sep.join(frame[1].rsplit(os.path.sep, 2)[(-2):])
return ("[called by '%s': %s:%s %s]" % (frame[3], path, frame[2], frame[4]))
| [
"def",
"calledby",
"(",
"callerdepth",
"=",
"1",
")",
":",
"import",
"inspect",
",",
"os",
"stack",
"=",
"inspect",
".",
"stack",
"(",
")",
"callerdepth",
"=",
"min",
"(",
"max",
"(",
"2",
",",
"(",
"callerdepth",
"+",
"1",
")",
")",
",",
"(",
"len",
"(",
"stack",
")",
"-",
"1",
")",
")",
"frame",
"=",
"inspect",
".",
"stack",
"(",
")",
"[",
"callerdepth",
"]",
"path",
"=",
"os",
".",
"path",
".",
"sep",
".",
"join",
"(",
"frame",
"[",
"1",
"]",
".",
"rsplit",
"(",
"os",
".",
"path",
".",
"sep",
",",
"2",
")",
"[",
"(",
"-",
"2",
")",
":",
"]",
")",
"return",
"(",
"\"[called by '%s': %s:%s %s]\"",
"%",
"(",
"frame",
"[",
"3",
"]",
",",
"path",
",",
"frame",
"[",
"2",
"]",
",",
"frame",
"[",
"4",
"]",
")",
")"
] | only to be used for debug purposes . | train | false |
39,675 | def _yyyywwd2yyyymmdd(year, week, weekday):
d = datetime(year, month=1, day=4)
d = ((d - timedelta((d.isoweekday() - 1))) + timedelta(days=(weekday - 1), weeks=(week - 1)))
return (d.year, d.month, d.day)
| [
"def",
"_yyyywwd2yyyymmdd",
"(",
"year",
",",
"week",
",",
"weekday",
")",
":",
"d",
"=",
"datetime",
"(",
"year",
",",
"month",
"=",
"1",
",",
"day",
"=",
"4",
")",
"d",
"=",
"(",
"(",
"d",
"-",
"timedelta",
"(",
"(",
"d",
".",
"isoweekday",
"(",
")",
"-",
"1",
")",
")",
")",
"+",
"timedelta",
"(",
"days",
"=",
"(",
"weekday",
"-",
"1",
")",
",",
"weeks",
"=",
"(",
"week",
"-",
"1",
")",
")",
")",
"return",
"(",
"d",
".",
"year",
",",
"d",
".",
"month",
",",
"d",
".",
"day",
")"
] | returns for given . | train | false |
39,676 | def GetTokenSid(hToken):
dwSize = DWORD(0)
pStringSid = LPSTR()
TokenUser = 1
if (windll.advapi32.GetTokenInformation(hToken, TokenUser, byref(TOKEN_USER()), 0, byref(dwSize)) == 0):
address = windll.kernel32.LocalAlloc(64, dwSize)
if address:
windll.advapi32.GetTokenInformation(hToken, TokenUser, address, dwSize, byref(dwSize))
pToken_User = cast(address, POINTER(TOKEN_USER))
windll.advapi32.ConvertSidToStringSidA(pToken_User.contents.User.Sid, byref(pStringSid))
if pStringSid:
sid = pStringSid.value
windll.kernel32.LocalFree(address)
return sid
return False
| [
"def",
"GetTokenSid",
"(",
"hToken",
")",
":",
"dwSize",
"=",
"DWORD",
"(",
"0",
")",
"pStringSid",
"=",
"LPSTR",
"(",
")",
"TokenUser",
"=",
"1",
"if",
"(",
"windll",
".",
"advapi32",
".",
"GetTokenInformation",
"(",
"hToken",
",",
"TokenUser",
",",
"byref",
"(",
"TOKEN_USER",
"(",
")",
")",
",",
"0",
",",
"byref",
"(",
"dwSize",
")",
")",
"==",
"0",
")",
":",
"address",
"=",
"windll",
".",
"kernel32",
".",
"LocalAlloc",
"(",
"64",
",",
"dwSize",
")",
"if",
"address",
":",
"windll",
".",
"advapi32",
".",
"GetTokenInformation",
"(",
"hToken",
",",
"TokenUser",
",",
"address",
",",
"dwSize",
",",
"byref",
"(",
"dwSize",
")",
")",
"pToken_User",
"=",
"cast",
"(",
"address",
",",
"POINTER",
"(",
"TOKEN_USER",
")",
")",
"windll",
".",
"advapi32",
".",
"ConvertSidToStringSidA",
"(",
"pToken_User",
".",
"contents",
".",
"User",
".",
"Sid",
",",
"byref",
"(",
"pStringSid",
")",
")",
"if",
"pStringSid",
":",
"sid",
"=",
"pStringSid",
".",
"value",
"windll",
".",
"kernel32",
".",
"LocalFree",
"(",
"address",
")",
"return",
"sid",
"return",
"False"
] | retrieve sid from token . | train | false |
39,677 | def update_array_info(aryty, array):
context = array._context
builder = array._builder
nitems = context.get_constant(types.intp, 1)
unpacked_shape = cgutils.unpack_tuple(builder, array.shape, aryty.ndim)
for axlen in unpacked_shape:
nitems = builder.mul(nitems, axlen, flags=['nsw'])
array.nitems = nitems
array.itemsize = context.get_constant(types.intp, get_itemsize(context, aryty))
| [
"def",
"update_array_info",
"(",
"aryty",
",",
"array",
")",
":",
"context",
"=",
"array",
".",
"_context",
"builder",
"=",
"array",
".",
"_builder",
"nitems",
"=",
"context",
".",
"get_constant",
"(",
"types",
".",
"intp",
",",
"1",
")",
"unpacked_shape",
"=",
"cgutils",
".",
"unpack_tuple",
"(",
"builder",
",",
"array",
".",
"shape",
",",
"aryty",
".",
"ndim",
")",
"for",
"axlen",
"in",
"unpacked_shape",
":",
"nitems",
"=",
"builder",
".",
"mul",
"(",
"nitems",
",",
"axlen",
",",
"flags",
"=",
"[",
"'nsw'",
"]",
")",
"array",
".",
"nitems",
"=",
"nitems",
"array",
".",
"itemsize",
"=",
"context",
".",
"get_constant",
"(",
"types",
".",
"intp",
",",
"get_itemsize",
"(",
"context",
",",
"aryty",
")",
")"
] | update some auxiliary information in *array* after some of its fields were changed . | train | false |
39,678 | def pool_2d(input, **kwargs):
try:
return T.signal.pool.pool_2d(input, **kwargs)
except TypeError:
kwargs['ds'] = kwargs.pop('ws')
kwargs['st'] = kwargs.pop('stride')
kwargs['padding'] = kwargs.pop('pad')
return T.signal.pool.pool_2d(input, **kwargs)
| [
"def",
"pool_2d",
"(",
"input",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"T",
".",
"signal",
".",
"pool",
".",
"pool_2d",
"(",
"input",
",",
"**",
"kwargs",
")",
"except",
"TypeError",
":",
"kwargs",
"[",
"'ds'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'ws'",
")",
"kwargs",
"[",
"'st'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'stride'",
")",
"kwargs",
"[",
"'padding'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'pad'",
")",
"return",
"T",
".",
"signal",
".",
"pool",
".",
"pool_2d",
"(",
"input",
",",
"**",
"kwargs",
")"
] | wrapper function that calls :func:theano . | train | false |
39,679 | def getboth(dict1, dict2, key, default=None):
try:
return dict1[key]
except KeyError:
if (default is None):
return dict2[key]
else:
return dict2.get(key, default)
| [
"def",
"getboth",
"(",
"dict1",
",",
"dict2",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"dict1",
"[",
"key",
"]",
"except",
"KeyError",
":",
"if",
"(",
"default",
"is",
"None",
")",
":",
"return",
"dict2",
"[",
"key",
"]",
"else",
":",
"return",
"dict2",
".",
"get",
"(",
"key",
",",
"default",
")"
] | try to retrieve key from dict1 if exists . | train | false |
39,680 | def treq_with_authentication(reactor, ca_path, user_cert_path, user_key_path):
ca = Certificate.loadPEM(ca_path.getContent())
user_credential = UserCredential.from_files(user_cert_path, user_key_path)
policy = ControlServicePolicy(ca_certificate=ca, client_credential=user_credential.credential)
return HTTPClient(Agent(reactor, contextFactory=policy))
| [
"def",
"treq_with_authentication",
"(",
"reactor",
",",
"ca_path",
",",
"user_cert_path",
",",
"user_key_path",
")",
":",
"ca",
"=",
"Certificate",
".",
"loadPEM",
"(",
"ca_path",
".",
"getContent",
"(",
")",
")",
"user_credential",
"=",
"UserCredential",
".",
"from_files",
"(",
"user_cert_path",
",",
"user_key_path",
")",
"policy",
"=",
"ControlServicePolicy",
"(",
"ca_certificate",
"=",
"ca",
",",
"client_credential",
"=",
"user_credential",
".",
"credential",
")",
"return",
"HTTPClient",
"(",
"Agent",
"(",
"reactor",
",",
"contextFactory",
"=",
"policy",
")",
")"
] | create a treq-api object that implements the rest api tls authentication . | train | false |
39,682 | def threshold_mean(image):
return np.mean(image)
| [
"def",
"threshold_mean",
"(",
"image",
")",
":",
"return",
"np",
".",
"mean",
"(",
"image",
")"
] | return threshold value based on the mean of grayscale values . | train | false |
39,683 | def _smart_matrix_product(A, B, alpha=None, structure=None):
if (len(A.shape) != 2):
raise ValueError('expected A to be a rectangular matrix')
if (len(B.shape) != 2):
raise ValueError('expected B to be a rectangular matrix')
f = None
if (structure == UPPER_TRIANGULAR):
if ((not isspmatrix(A)) and (not isspmatrix(B))):
(f,) = scipy.linalg.get_blas_funcs(('trmm',), (A, B))
if (f is not None):
if (alpha is None):
alpha = 1.0
out = f(alpha, A, B)
elif (alpha is None):
out = A.dot(B)
else:
out = (alpha * A.dot(B))
return out
| [
"def",
"_smart_matrix_product",
"(",
"A",
",",
"B",
",",
"alpha",
"=",
"None",
",",
"structure",
"=",
"None",
")",
":",
"if",
"(",
"len",
"(",
"A",
".",
"shape",
")",
"!=",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'expected A to be a rectangular matrix'",
")",
"if",
"(",
"len",
"(",
"B",
".",
"shape",
")",
"!=",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'expected B to be a rectangular matrix'",
")",
"f",
"=",
"None",
"if",
"(",
"structure",
"==",
"UPPER_TRIANGULAR",
")",
":",
"if",
"(",
"(",
"not",
"isspmatrix",
"(",
"A",
")",
")",
"and",
"(",
"not",
"isspmatrix",
"(",
"B",
")",
")",
")",
":",
"(",
"f",
",",
")",
"=",
"scipy",
".",
"linalg",
".",
"get_blas_funcs",
"(",
"(",
"'trmm'",
",",
")",
",",
"(",
"A",
",",
"B",
")",
")",
"if",
"(",
"f",
"is",
"not",
"None",
")",
":",
"if",
"(",
"alpha",
"is",
"None",
")",
":",
"alpha",
"=",
"1.0",
"out",
"=",
"f",
"(",
"alpha",
",",
"A",
",",
"B",
")",
"elif",
"(",
"alpha",
"is",
"None",
")",
":",
"out",
"=",
"A",
".",
"dot",
"(",
"B",
")",
"else",
":",
"out",
"=",
"(",
"alpha",
"*",
"A",
".",
"dot",
"(",
"B",
")",
")",
"return",
"out"
] | a matrix product that knows about sparse and structured matrices . | train | false |
39,684 | def build_upload_html_form(project):
attrs = {'project': project}
active = project.versions.public()
if active.exists():
choices = []
choices += [(version.slug, version.verbose_name) for version in active]
attrs['version'] = forms.ChoiceField(label=_('Version of the project you are uploading HTML for'), choices=choices)
return type('UploadHTMLForm', (BaseUploadHTMLForm,), attrs)
| [
"def",
"build_upload_html_form",
"(",
"project",
")",
":",
"attrs",
"=",
"{",
"'project'",
":",
"project",
"}",
"active",
"=",
"project",
".",
"versions",
".",
"public",
"(",
")",
"if",
"active",
".",
"exists",
"(",
")",
":",
"choices",
"=",
"[",
"]",
"choices",
"+=",
"[",
"(",
"version",
".",
"slug",
",",
"version",
".",
"verbose_name",
")",
"for",
"version",
"in",
"active",
"]",
"attrs",
"[",
"'version'",
"]",
"=",
"forms",
".",
"ChoiceField",
"(",
"label",
"=",
"_",
"(",
"'Version of the project you are uploading HTML for'",
")",
",",
"choices",
"=",
"choices",
")",
"return",
"type",
"(",
"'UploadHTMLForm'",
",",
"(",
"BaseUploadHTMLForm",
",",
")",
",",
"attrs",
")"
] | upload html form with list of versions to upload html for . | train | false |
39,685 | def _permutation_test_score(estimator, X, y, cv, scorer):
avg_score = []
for (train, test) in cv:
(X_train, y_train) = _safe_split(estimator, X, y, train)
(X_test, y_test) = _safe_split(estimator, X, y, test, train)
estimator.fit(X_train, y_train)
avg_score.append(scorer(estimator, X_test, y_test))
return np.mean(avg_score)
| [
"def",
"_permutation_test_score",
"(",
"estimator",
",",
"X",
",",
"y",
",",
"cv",
",",
"scorer",
")",
":",
"avg_score",
"=",
"[",
"]",
"for",
"(",
"train",
",",
"test",
")",
"in",
"cv",
":",
"(",
"X_train",
",",
"y_train",
")",
"=",
"_safe_split",
"(",
"estimator",
",",
"X",
",",
"y",
",",
"train",
")",
"(",
"X_test",
",",
"y_test",
")",
"=",
"_safe_split",
"(",
"estimator",
",",
"X",
",",
"y",
",",
"test",
",",
"train",
")",
"estimator",
".",
"fit",
"(",
"X_train",
",",
"y_train",
")",
"avg_score",
".",
"append",
"(",
"scorer",
"(",
"estimator",
",",
"X_test",
",",
"y_test",
")",
")",
"return",
"np",
".",
"mean",
"(",
"avg_score",
")"
] | auxiliary function for permutation_test_score . | train | false |
39,686 | def json_api_exception_handler(exc, context):
from rest_framework.views import exception_handler
response = exception_handler(exc, context)
errors = []
if response:
message = response.data
if isinstance(exc, TwoFactorRequiredError):
response['X-OSF-OTP'] = 'required; app'
if isinstance(exc, JSONAPIException):
errors.extend([{'source': (exc.source or {}), 'detail': exc.detail, 'meta': (exc.meta or {})}])
elif isinstance(message, dict):
errors.extend(dict_error_formatting(message, None))
else:
if isinstance(message, basestring):
message = [message]
for (index, error) in enumerate(message):
if isinstance(error, dict):
errors.extend(dict_error_formatting(error, index))
else:
errors.append({'detail': error})
response.data = {'errors': errors}
return response
| [
"def",
"json_api_exception_handler",
"(",
"exc",
",",
"context",
")",
":",
"from",
"rest_framework",
".",
"views",
"import",
"exception_handler",
"response",
"=",
"exception_handler",
"(",
"exc",
",",
"context",
")",
"errors",
"=",
"[",
"]",
"if",
"response",
":",
"message",
"=",
"response",
".",
"data",
"if",
"isinstance",
"(",
"exc",
",",
"TwoFactorRequiredError",
")",
":",
"response",
"[",
"'X-OSF-OTP'",
"]",
"=",
"'required; app'",
"if",
"isinstance",
"(",
"exc",
",",
"JSONAPIException",
")",
":",
"errors",
".",
"extend",
"(",
"[",
"{",
"'source'",
":",
"(",
"exc",
".",
"source",
"or",
"{",
"}",
")",
",",
"'detail'",
":",
"exc",
".",
"detail",
",",
"'meta'",
":",
"(",
"exc",
".",
"meta",
"or",
"{",
"}",
")",
"}",
"]",
")",
"elif",
"isinstance",
"(",
"message",
",",
"dict",
")",
":",
"errors",
".",
"extend",
"(",
"dict_error_formatting",
"(",
"message",
",",
"None",
")",
")",
"else",
":",
"if",
"isinstance",
"(",
"message",
",",
"basestring",
")",
":",
"message",
"=",
"[",
"message",
"]",
"for",
"(",
"index",
",",
"error",
")",
"in",
"enumerate",
"(",
"message",
")",
":",
"if",
"isinstance",
"(",
"error",
",",
"dict",
")",
":",
"errors",
".",
"extend",
"(",
"dict_error_formatting",
"(",
"error",
",",
"index",
")",
")",
"else",
":",
"errors",
".",
"append",
"(",
"{",
"'detail'",
":",
"error",
"}",
")",
"response",
".",
"data",
"=",
"{",
"'errors'",
":",
"errors",
"}",
"return",
"response"
] | custom exception handler that returns errors object as an array . | train | false |
39,687 | def django_dottedstring_imports(django_root_dir):
pths = []
pths.append(misc.get_path_to_toplevel_modules(django_root_dir))
pths.append(django_root_dir)
package_name = (os.path.basename(django_root_dir) + '.settings')
env = {'DJANGO_SETTINGS_MODULE': package_name, 'PYTHONPATH': os.pathsep.join(pths)}
ret = eval_script('django_import_finder.py', env=env)
return ret
| [
"def",
"django_dottedstring_imports",
"(",
"django_root_dir",
")",
":",
"pths",
"=",
"[",
"]",
"pths",
".",
"append",
"(",
"misc",
".",
"get_path_to_toplevel_modules",
"(",
"django_root_dir",
")",
")",
"pths",
".",
"append",
"(",
"django_root_dir",
")",
"package_name",
"=",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"django_root_dir",
")",
"+",
"'.settings'",
")",
"env",
"=",
"{",
"'DJANGO_SETTINGS_MODULE'",
":",
"package_name",
",",
"'PYTHONPATH'",
":",
"os",
".",
"pathsep",
".",
"join",
"(",
"pths",
")",
"}",
"ret",
"=",
"eval_script",
"(",
"'django_import_finder.py'",
",",
"env",
"=",
"env",
")",
"return",
"ret"
] | get all the necessary django modules specified in settings . | train | false |
39,688 | def log_ceil(n, b):
p = 1
k = 0
while (p < n):
p *= b
k += 1
return k
| [
"def",
"log_ceil",
"(",
"n",
",",
"b",
")",
":",
"p",
"=",
"1",
"k",
"=",
"0",
"while",
"(",
"p",
"<",
"n",
")",
":",
"p",
"*=",
"b",
"k",
"+=",
"1",
"return",
"k"
] | the smallest integer k such that b^k >= n . | train | false |
39,691 | def p_union(p):
val = _fill_in_struct(p[1], p[3])
_add_thrift_meta('unions', val)
| [
"def",
"p_union",
"(",
"p",
")",
":",
"val",
"=",
"_fill_in_struct",
"(",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
")",
"_add_thrift_meta",
"(",
"'unions'",
",",
"val",
")"
] | union : seen_union { field_seq } . | train | false |
39,692 | def moments_hu(nu):
return _moments_cy.moments_hu(nu.astype(np.double))
| [
"def",
"moments_hu",
"(",
"nu",
")",
":",
"return",
"_moments_cy",
".",
"moments_hu",
"(",
"nu",
".",
"astype",
"(",
"np",
".",
"double",
")",
")"
] | calculate hus set of image moments . | train | false |
39,693 | def is_letter_or_number(char):
cat = category(char)
return (cat.startswith('L') or cat.startswith('N'))
| [
"def",
"is_letter_or_number",
"(",
"char",
")",
":",
"cat",
"=",
"category",
"(",
"char",
")",
"return",
"(",
"cat",
".",
"startswith",
"(",
"'L'",
")",
"or",
"cat",
".",
"startswith",
"(",
"'N'",
")",
")"
] | returns whether the specified unicode character is a letter or a number . | train | false |
39,695 | def _get_user_dirs(xdg_config_dir):
dirs_file = os.path.join(xdg_config_dir, 'user-dirs.dirs')
if (not os.path.exists(dirs_file)):
return {}
with open(dirs_file, u'rb') as fh:
data = fh.read().decode(u'utf-8')
data = (u'[XDG_USER_DIRS]\n' + data)
data = data.replace(u'$HOME', os.path.expanduser(u'~'))
data = data.replace(u'"', u'')
config = configparser.RawConfigParser()
config.readfp(io.StringIO(data))
return {k.upper(): os.path.abspath(v) for (k, v) in config.items(u'XDG_USER_DIRS') if (v is not None)}
| [
"def",
"_get_user_dirs",
"(",
"xdg_config_dir",
")",
":",
"dirs_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"xdg_config_dir",
",",
"'user-dirs.dirs'",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dirs_file",
")",
")",
":",
"return",
"{",
"}",
"with",
"open",
"(",
"dirs_file",
",",
"u'rb'",
")",
"as",
"fh",
":",
"data",
"=",
"fh",
".",
"read",
"(",
")",
".",
"decode",
"(",
"u'utf-8'",
")",
"data",
"=",
"(",
"u'[XDG_USER_DIRS]\\n'",
"+",
"data",
")",
"data",
"=",
"data",
".",
"replace",
"(",
"u'$HOME'",
",",
"os",
".",
"path",
".",
"expanduser",
"(",
"u'~'",
")",
")",
"data",
"=",
"data",
".",
"replace",
"(",
"u'\"'",
",",
"u''",
")",
"config",
"=",
"configparser",
".",
"RawConfigParser",
"(",
")",
"config",
".",
"readfp",
"(",
"io",
".",
"StringIO",
"(",
"data",
")",
")",
"return",
"{",
"k",
".",
"upper",
"(",
")",
":",
"os",
".",
"path",
".",
"abspath",
"(",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"config",
".",
"items",
"(",
"u'XDG_USER_DIRS'",
")",
"if",
"(",
"v",
"is",
"not",
"None",
")",
"}"
] | returns a dict of xdg dirs read from $xdg_config_home/user-dirs . | train | false |
39,696 | def disjuncts(expr):
return Or.make_args(expr)
| [
"def",
"disjuncts",
"(",
"expr",
")",
":",
"return",
"Or",
".",
"make_args",
"(",
"expr",
")"
] | return a list of the disjuncts in the sentence s . | train | false |
39,698 | def DisplayEstimate(message, min_estimate, max_estimate):
mean_avg_cpc = (_CalculateMean(min_estimate['averageCpc']['microAmount'], max_estimate['averageCpc']['microAmount']) if ('averageCpc' in min_estimate) else None)
mean_avg_pos = (_CalculateMean(min_estimate['averagePosition'], max_estimate['averagePosition']) if ('averagePosition' in min_estimate) else None)
mean_clicks = _CalculateMean(min_estimate['clicksPerDay'], max_estimate['clicksPerDay'])
mean_total_cost = _CalculateMean(min_estimate['totalCost']['microAmount'], max_estimate['totalCost']['microAmount'])
print message
print (' Estimated average CPC: %s' % _FormatMean(mean_avg_cpc))
print (' Estimated ad position: %s' % _FormatMean(mean_avg_pos))
print (' Estimated daily clicks: %s' % _FormatMean(mean_clicks))
print (' Estimated daily cost: %s' % _FormatMean(mean_total_cost))
| [
"def",
"DisplayEstimate",
"(",
"message",
",",
"min_estimate",
",",
"max_estimate",
")",
":",
"mean_avg_cpc",
"=",
"(",
"_CalculateMean",
"(",
"min_estimate",
"[",
"'averageCpc'",
"]",
"[",
"'microAmount'",
"]",
",",
"max_estimate",
"[",
"'averageCpc'",
"]",
"[",
"'microAmount'",
"]",
")",
"if",
"(",
"'averageCpc'",
"in",
"min_estimate",
")",
"else",
"None",
")",
"mean_avg_pos",
"=",
"(",
"_CalculateMean",
"(",
"min_estimate",
"[",
"'averagePosition'",
"]",
",",
"max_estimate",
"[",
"'averagePosition'",
"]",
")",
"if",
"(",
"'averagePosition'",
"in",
"min_estimate",
")",
"else",
"None",
")",
"mean_clicks",
"=",
"_CalculateMean",
"(",
"min_estimate",
"[",
"'clicksPerDay'",
"]",
",",
"max_estimate",
"[",
"'clicksPerDay'",
"]",
")",
"mean_total_cost",
"=",
"_CalculateMean",
"(",
"min_estimate",
"[",
"'totalCost'",
"]",
"[",
"'microAmount'",
"]",
",",
"max_estimate",
"[",
"'totalCost'",
"]",
"[",
"'microAmount'",
"]",
")",
"print",
"message",
"print",
"(",
"' Estimated average CPC: %s'",
"%",
"_FormatMean",
"(",
"mean_avg_cpc",
")",
")",
"print",
"(",
"' Estimated ad position: %s'",
"%",
"_FormatMean",
"(",
"mean_avg_pos",
")",
")",
"print",
"(",
"' Estimated daily clicks: %s'",
"%",
"_FormatMean",
"(",
"mean_clicks",
")",
")",
"print",
"(",
"' Estimated daily cost: %s'",
"%",
"_FormatMean",
"(",
"mean_total_cost",
")",
")"
] | displays mean average cpc . | train | true |
39,699 | def FileInputStream(filename, real_filename=None, **args):
assert isinstance(filename, unicode)
if (not real_filename):
real_filename = filename
try:
inputio = open(real_filename, 'rb')
except IOError as err:
charset = getTerminalCharset()
errmsg = unicode(str(err), charset)
raise InputStreamError((_('Unable to open file %s: %s') % (filename, errmsg)))
source = ('file:' + filename)
offset = args.pop('offset', 0)
size = args.pop('size', None)
if (offset or size):
if size:
size = (8 * size)
stream = InputIOStream(inputio, source=source, **args)
return InputSubStream(stream, (8 * offset), size, **args)
else:
args.setdefault('tags', []).append(('filename', filename))
return InputIOStream(inputio, source=source, **args)
| [
"def",
"FileInputStream",
"(",
"filename",
",",
"real_filename",
"=",
"None",
",",
"**",
"args",
")",
":",
"assert",
"isinstance",
"(",
"filename",
",",
"unicode",
")",
"if",
"(",
"not",
"real_filename",
")",
":",
"real_filename",
"=",
"filename",
"try",
":",
"inputio",
"=",
"open",
"(",
"real_filename",
",",
"'rb'",
")",
"except",
"IOError",
"as",
"err",
":",
"charset",
"=",
"getTerminalCharset",
"(",
")",
"errmsg",
"=",
"unicode",
"(",
"str",
"(",
"err",
")",
",",
"charset",
")",
"raise",
"InputStreamError",
"(",
"(",
"_",
"(",
"'Unable to open file %s: %s'",
")",
"%",
"(",
"filename",
",",
"errmsg",
")",
")",
")",
"source",
"=",
"(",
"'file:'",
"+",
"filename",
")",
"offset",
"=",
"args",
".",
"pop",
"(",
"'offset'",
",",
"0",
")",
"size",
"=",
"args",
".",
"pop",
"(",
"'size'",
",",
"None",
")",
"if",
"(",
"offset",
"or",
"size",
")",
":",
"if",
"size",
":",
"size",
"=",
"(",
"8",
"*",
"size",
")",
"stream",
"=",
"InputIOStream",
"(",
"inputio",
",",
"source",
"=",
"source",
",",
"**",
"args",
")",
"return",
"InputSubStream",
"(",
"stream",
",",
"(",
"8",
"*",
"offset",
")",
",",
"size",
",",
"**",
"args",
")",
"else",
":",
"args",
".",
"setdefault",
"(",
"'tags'",
",",
"[",
"]",
")",
".",
"append",
"(",
"(",
"'filename'",
",",
"filename",
")",
")",
"return",
"InputIOStream",
"(",
"inputio",
",",
"source",
"=",
"source",
",",
"**",
"args",
")"
] | create an input stream of a file . | train | false |
39,700 | def container():
rebulk = Rebulk().regex_defaults(flags=re.IGNORECASE).string_defaults(ignore_case=True)
rebulk.defaults(name='container', formatter=(lambda value: value[1:]), tags=['extension'], conflict_solver=(lambda match, other: (other if ((other.name in ['format', 'video_codec']) or ((other.name == 'container') and ('extension' not in other.tags))) else '__default__')))
subtitles = ['srt', 'idx', 'sub', 'ssa', 'ass']
info = ['nfo']
videos = ['3g2', '3gp', '3gp2', 'asf', 'avi', 'divx', 'flv', 'm4v', 'mk2', 'mka', 'mkv', 'mov', 'mp4', 'mp4a', 'mpeg', 'mpg', 'ogg', 'ogm', 'ogv', 'qt', 'ra', 'ram', 'rm', 'ts', 'wav', 'webm', 'wma', 'wmv', 'iso', 'vob']
torrent = ['torrent']
rebulk.regex((('\\.' + build_or_pattern(subtitles)) + '$'), exts=subtitles, tags=['extension', 'subtitle'])
rebulk.regex((('\\.' + build_or_pattern(info)) + '$'), exts=info, tags=['extension', 'info'])
rebulk.regex((('\\.' + build_or_pattern(videos)) + '$'), exts=videos, tags=['extension', 'video'])
rebulk.regex((('\\.' + build_or_pattern(torrent)) + '$'), exts=torrent, tags=['extension', 'torrent'])
rebulk.defaults(name='container', validator=seps_surround, formatter=(lambda s: s.upper()), conflict_solver=(lambda match, other: (match if ((other.name in ['format', 'video_codec']) or ((other.name == 'container') and ('extension' in other.tags))) else '__default__')))
rebulk.string(tags=['subtitle'], *[sub for sub in subtitles if (sub not in ['sub'])])
rebulk.string(tags=['video'], *videos)
rebulk.string(tags=['torrent'], *torrent)
return rebulk
| [
"def",
"container",
"(",
")",
":",
"rebulk",
"=",
"Rebulk",
"(",
")",
".",
"regex_defaults",
"(",
"flags",
"=",
"re",
".",
"IGNORECASE",
")",
".",
"string_defaults",
"(",
"ignore_case",
"=",
"True",
")",
"rebulk",
".",
"defaults",
"(",
"name",
"=",
"'container'",
",",
"formatter",
"=",
"(",
"lambda",
"value",
":",
"value",
"[",
"1",
":",
"]",
")",
",",
"tags",
"=",
"[",
"'extension'",
"]",
",",
"conflict_solver",
"=",
"(",
"lambda",
"match",
",",
"other",
":",
"(",
"other",
"if",
"(",
"(",
"other",
".",
"name",
"in",
"[",
"'format'",
",",
"'video_codec'",
"]",
")",
"or",
"(",
"(",
"other",
".",
"name",
"==",
"'container'",
")",
"and",
"(",
"'extension'",
"not",
"in",
"other",
".",
"tags",
")",
")",
")",
"else",
"'__default__'",
")",
")",
")",
"subtitles",
"=",
"[",
"'srt'",
",",
"'idx'",
",",
"'sub'",
",",
"'ssa'",
",",
"'ass'",
"]",
"info",
"=",
"[",
"'nfo'",
"]",
"videos",
"=",
"[",
"'3g2'",
",",
"'3gp'",
",",
"'3gp2'",
",",
"'asf'",
",",
"'avi'",
",",
"'divx'",
",",
"'flv'",
",",
"'m4v'",
",",
"'mk2'",
",",
"'mka'",
",",
"'mkv'",
",",
"'mov'",
",",
"'mp4'",
",",
"'mp4a'",
",",
"'mpeg'",
",",
"'mpg'",
",",
"'ogg'",
",",
"'ogm'",
",",
"'ogv'",
",",
"'qt'",
",",
"'ra'",
",",
"'ram'",
",",
"'rm'",
",",
"'ts'",
",",
"'wav'",
",",
"'webm'",
",",
"'wma'",
",",
"'wmv'",
",",
"'iso'",
",",
"'vob'",
"]",
"torrent",
"=",
"[",
"'torrent'",
"]",
"rebulk",
".",
"regex",
"(",
"(",
"(",
"'\\\\.'",
"+",
"build_or_pattern",
"(",
"subtitles",
")",
")",
"+",
"'$'",
")",
",",
"exts",
"=",
"subtitles",
",",
"tags",
"=",
"[",
"'extension'",
",",
"'subtitle'",
"]",
")",
"rebulk",
".",
"regex",
"(",
"(",
"(",
"'\\\\.'",
"+",
"build_or_pattern",
"(",
"info",
")",
")",
"+",
"'$'",
")",
",",
"exts",
"=",
"info",
",",
"tags",
"=",
"[",
"'extension'",
",",
"'info'",
"]",
")",
"rebulk",
".",
"regex",
"(",
"(",
"(",
"'\\\\.'",
"+",
"build_or_pattern",
"(",
"videos",
")",
")",
"+",
"'$'",
")",
",",
"exts",
"=",
"videos",
",",
"tags",
"=",
"[",
"'extension'",
",",
"'video'",
"]",
")",
"rebulk",
".",
"regex",
"(",
"(",
"(",
"'\\\\.'",
"+",
"build_or_pattern",
"(",
"torrent",
")",
")",
"+",
"'$'",
")",
",",
"exts",
"=",
"torrent",
",",
"tags",
"=",
"[",
"'extension'",
",",
"'torrent'",
"]",
")",
"rebulk",
".",
"defaults",
"(",
"name",
"=",
"'container'",
",",
"validator",
"=",
"seps_surround",
",",
"formatter",
"=",
"(",
"lambda",
"s",
":",
"s",
".",
"upper",
"(",
")",
")",
",",
"conflict_solver",
"=",
"(",
"lambda",
"match",
",",
"other",
":",
"(",
"match",
"if",
"(",
"(",
"other",
".",
"name",
"in",
"[",
"'format'",
",",
"'video_codec'",
"]",
")",
"or",
"(",
"(",
"other",
".",
"name",
"==",
"'container'",
")",
"and",
"(",
"'extension'",
"in",
"other",
".",
"tags",
")",
")",
")",
"else",
"'__default__'",
")",
")",
")",
"rebulk",
".",
"string",
"(",
"tags",
"=",
"[",
"'subtitle'",
"]",
",",
"*",
"[",
"sub",
"for",
"sub",
"in",
"subtitles",
"if",
"(",
"sub",
"not",
"in",
"[",
"'sub'",
"]",
")",
"]",
")",
"rebulk",
".",
"string",
"(",
"tags",
"=",
"[",
"'video'",
"]",
",",
"*",
"videos",
")",
"rebulk",
".",
"string",
"(",
"tags",
"=",
"[",
"'torrent'",
"]",
",",
"*",
"torrent",
")",
"return",
"rebulk"
] | require an openvz container . | train | false |
39,702 | def _dec2hex(decval):
return _pretty_hex('{0:X}'.format(decval))
| [
"def",
"_dec2hex",
"(",
"decval",
")",
":",
"return",
"_pretty_hex",
"(",
"'{0:X}'",
".",
"format",
"(",
"decval",
")",
")"
] | converts decimal values to nicely formatted hex strings . | train | false |
39,704 | def forced_replace(out, x, y):
if (out is None):
return None
visited = set()
def local_traverse(graph, x):
if (graph in visited):
return []
visited.add(graph)
if equal_computations([graph], [x]):
return [graph]
elif (not graph.owner):
return []
else:
rval = []
for inp in graph.owner.inputs:
rval += local_traverse(inp, x)
return rval
to_replace = local_traverse(out, x)
return clone(out, replace=OrderedDict(((v, y) for v in to_replace)))
| [
"def",
"forced_replace",
"(",
"out",
",",
"x",
",",
"y",
")",
":",
"if",
"(",
"out",
"is",
"None",
")",
":",
"return",
"None",
"visited",
"=",
"set",
"(",
")",
"def",
"local_traverse",
"(",
"graph",
",",
"x",
")",
":",
"if",
"(",
"graph",
"in",
"visited",
")",
":",
"return",
"[",
"]",
"visited",
".",
"add",
"(",
"graph",
")",
"if",
"equal_computations",
"(",
"[",
"graph",
"]",
",",
"[",
"x",
"]",
")",
":",
"return",
"[",
"graph",
"]",
"elif",
"(",
"not",
"graph",
".",
"owner",
")",
":",
"return",
"[",
"]",
"else",
":",
"rval",
"=",
"[",
"]",
"for",
"inp",
"in",
"graph",
".",
"owner",
".",
"inputs",
":",
"rval",
"+=",
"local_traverse",
"(",
"inp",
",",
"x",
")",
"return",
"rval",
"to_replace",
"=",
"local_traverse",
"(",
"out",
",",
"x",
")",
"return",
"clone",
"(",
"out",
",",
"replace",
"=",
"OrderedDict",
"(",
"(",
"(",
"v",
",",
"y",
")",
"for",
"v",
"in",
"to_replace",
")",
")",
")"
] | check all internal values of the graph that compute the variable out for occurrences of values identical with x . | train | false |
39,707 | def staticLimit(key, max_value):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
keep_inds = [copy.deepcopy(ind) for ind in args]
new_inds = list(func(*args, **kwargs))
for (i, ind) in enumerate(new_inds):
if (key(ind) > max_value):
new_inds[i] = random.choice(keep_inds)
return new_inds
return wrapper
return decorator
| [
"def",
"staticLimit",
"(",
"key",
",",
"max_value",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"keep_inds",
"=",
"[",
"copy",
".",
"deepcopy",
"(",
"ind",
")",
"for",
"ind",
"in",
"args",
"]",
"new_inds",
"=",
"list",
"(",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
")",
"for",
"(",
"i",
",",
"ind",
")",
"in",
"enumerate",
"(",
"new_inds",
")",
":",
"if",
"(",
"key",
"(",
"ind",
")",
">",
"max_value",
")",
":",
"new_inds",
"[",
"i",
"]",
"=",
"random",
".",
"choice",
"(",
"keep_inds",
")",
"return",
"new_inds",
"return",
"wrapper",
"return",
"decorator"
] | implement a static limit on some measurement on a gp tree . | train | true |
39,708 | def optimal_size(num_kmers, mem_cap=None, fp_rate=None):
if all(((num_kmers is not None), (mem_cap is not None), (fp_rate is None))):
return estimate_optimal_with_K_and_M(num_kmers, mem_cap)
elif all(((num_kmers is not None), (mem_cap is None), (fp_rate is not None))):
return estimate_optimal_with_K_and_f(num_kmers, fp_rate)
else:
raise TypeError(u'num_kmers and either mem_cap or fp_rate must be defined.')
| [
"def",
"optimal_size",
"(",
"num_kmers",
",",
"mem_cap",
"=",
"None",
",",
"fp_rate",
"=",
"None",
")",
":",
"if",
"all",
"(",
"(",
"(",
"num_kmers",
"is",
"not",
"None",
")",
",",
"(",
"mem_cap",
"is",
"not",
"None",
")",
",",
"(",
"fp_rate",
"is",
"None",
")",
")",
")",
":",
"return",
"estimate_optimal_with_K_and_M",
"(",
"num_kmers",
",",
"mem_cap",
")",
"elif",
"all",
"(",
"(",
"(",
"num_kmers",
"is",
"not",
"None",
")",
",",
"(",
"mem_cap",
"is",
"None",
")",
",",
"(",
"fp_rate",
"is",
"not",
"None",
")",
")",
")",
":",
"return",
"estimate_optimal_with_K_and_f",
"(",
"num_kmers",
",",
"fp_rate",
")",
"else",
":",
"raise",
"TypeError",
"(",
"u'num_kmers and either mem_cap or fp_rate must be defined.'",
")"
] | utility function for estimating optimal countgraph args . | train | false |
39,709 | def p_parameter_type_list_opt_2(t):
pass
| [
"def",
"p_parameter_type_list_opt_2",
"(",
"t",
")",
":",
"pass"
] | parameter_type_list_opt : parameter_type_list . | train | false |
39,711 | def doxygen(registry, xml_parent, data):
doxygen = XML.SubElement(xml_parent, 'hudson.plugins.doxygen.DoxygenBuilder')
mappings = [('doxyfile', 'doxyfilePath', None), ('install', 'installationName', None), ('ignore-failure', 'continueOnBuildFailure', False), ('unstable-warning', 'unstableIfWarnings', False)]
convert_mapping_to_xml(doxygen, data, mappings, fail_required=True)
| [
"def",
"doxygen",
"(",
"registry",
",",
"xml_parent",
",",
"data",
")",
":",
"doxygen",
"=",
"XML",
".",
"SubElement",
"(",
"xml_parent",
",",
"'hudson.plugins.doxygen.DoxygenBuilder'",
")",
"mappings",
"=",
"[",
"(",
"'doxyfile'",
",",
"'doxyfilePath'",
",",
"None",
")",
",",
"(",
"'install'",
",",
"'installationName'",
",",
"None",
")",
",",
"(",
"'ignore-failure'",
",",
"'continueOnBuildFailure'",
",",
"False",
")",
",",
"(",
"'unstable-warning'",
",",
"'unstableIfWarnings'",
",",
"False",
")",
"]",
"convert_mapping_to_xml",
"(",
"doxygen",
",",
"data",
",",
"mappings",
",",
"fail_required",
"=",
"True",
")"
] | yaml: doxygen builds doxygen html documentation . | train | false |
39,712 | @command(usage='parse links from kuai.xunlei.com')
def kuai(args):
import lixian_kuai
lixian_kuai.main(args)
| [
"@",
"command",
"(",
"usage",
"=",
"'parse links from kuai.xunlei.com'",
")",
"def",
"kuai",
"(",
"args",
")",
":",
"import",
"lixian_kuai",
"lixian_kuai",
".",
"main",
"(",
"args",
")"
] | usage: lx kuai URL note that you can simply use: lx add URL or: lx download URL . | train | false |
39,713 | def ber_zeros(nt):
if ((not isscalar(nt)) or (floor(nt) != nt) or (nt <= 0)):
raise ValueError('nt must be positive integer scalar.')
return specfun.klvnzo(nt, 1)
| [
"def",
"ber_zeros",
"(",
"nt",
")",
":",
"if",
"(",
"(",
"not",
"isscalar",
"(",
"nt",
")",
")",
"or",
"(",
"floor",
"(",
"nt",
")",
"!=",
"nt",
")",
"or",
"(",
"nt",
"<=",
"0",
")",
")",
":",
"raise",
"ValueError",
"(",
"'nt must be positive integer scalar.'",
")",
"return",
"specfun",
".",
"klvnzo",
"(",
"nt",
",",
"1",
")"
] | compute nt zeros of the kelvin function ber(x) . | train | false |
39,714 | def from_e164(text, origin=public_enum_domain):
parts = [d for d in text if d.isdigit()]
parts.reverse()
return dns.name.from_text('.'.join(parts), origin=origin)
| [
"def",
"from_e164",
"(",
"text",
",",
"origin",
"=",
"public_enum_domain",
")",
":",
"parts",
"=",
"[",
"d",
"for",
"d",
"in",
"text",
"if",
"d",
".",
"isdigit",
"(",
")",
"]",
"parts",
".",
"reverse",
"(",
")",
"return",
"dns",
".",
"name",
".",
"from_text",
"(",
"'.'",
".",
"join",
"(",
"parts",
")",
",",
"origin",
"=",
"origin",
")"
] | convert an e . | train | true |
39,716 | def path_length(X):
X = distances_along_curve(X)
return np.concatenate((np.zeros(1), np.cumsum(X)))
| [
"def",
"path_length",
"(",
"X",
")",
":",
"X",
"=",
"distances_along_curve",
"(",
"X",
")",
"return",
"np",
".",
"concatenate",
"(",
"(",
"np",
".",
"zeros",
"(",
"1",
")",
",",
"np",
".",
"cumsum",
"(",
"X",
")",
")",
")"
] | computes the distance travelled along a polygonal curve in *n* dimensions . | train | false |
39,717 | def attach_program_detail_url(programs):
for program in programs:
base = reverse('program_details_view', kwargs={'program_id': program['id']}).rstrip('/')
slug = slugify(program['name'])
program['detail_url'] = '{base}/{slug}'.format(base=base, slug=slug)
return programs
| [
"def",
"attach_program_detail_url",
"(",
"programs",
")",
":",
"for",
"program",
"in",
"programs",
":",
"base",
"=",
"reverse",
"(",
"'program_details_view'",
",",
"kwargs",
"=",
"{",
"'program_id'",
":",
"program",
"[",
"'id'",
"]",
"}",
")",
".",
"rstrip",
"(",
"'/'",
")",
"slug",
"=",
"slugify",
"(",
"program",
"[",
"'name'",
"]",
")",
"program",
"[",
"'detail_url'",
"]",
"=",
"'{base}/{slug}'",
".",
"format",
"(",
"base",
"=",
"base",
",",
"slug",
"=",
"slug",
")",
"return",
"programs"
] | extend program representations by attaching a url to be used when linking to program details . | train | false |
39,718 | def pkg_info(pkg_path):
(src, hsh) = pkg_commit_hash(pkg_path)
return dict(ipython_version=release.version, ipython_path=pkg_path, commit_source=src, commit_hash=hsh, sys_version=sys.version, sys_executable=sys.executable, sys_platform=sys.platform, platform=platform.platform(), os_name=os.name, default_encoding=encoding.DEFAULT_ENCODING)
| [
"def",
"pkg_info",
"(",
"pkg_path",
")",
":",
"(",
"src",
",",
"hsh",
")",
"=",
"pkg_commit_hash",
"(",
"pkg_path",
")",
"return",
"dict",
"(",
"ipython_version",
"=",
"release",
".",
"version",
",",
"ipython_path",
"=",
"pkg_path",
",",
"commit_source",
"=",
"src",
",",
"commit_hash",
"=",
"hsh",
",",
"sys_version",
"=",
"sys",
".",
"version",
",",
"sys_executable",
"=",
"sys",
".",
"executable",
",",
"sys_platform",
"=",
"sys",
".",
"platform",
",",
"platform",
"=",
"platform",
".",
"platform",
"(",
")",
",",
"os_name",
"=",
"os",
".",
"name",
",",
"default_encoding",
"=",
"encoding",
".",
"DEFAULT_ENCODING",
")"
] | return dict describing the context of this package parameters pkg_path : str path containing __init__ . | train | true |
39,721 | def has_user_permission_for_group_or_org(group_id, user_name, permission):
if (not group_id):
return False
group = model.Group.get(group_id)
if (not group):
return False
group_id = group.id
if is_sysadmin(user_name):
return True
user_id = get_user_id_for_username(user_name, allow_none=True)
if (not user_id):
return False
if _has_user_permission_for_groups(user_id, permission, [group_id]):
return True
for capacity in check_config_permission('roles_that_cascade_to_sub_groups'):
parent_groups = group.get_parent_group_hierarchy(type=group.type)
group_ids = [group_.id for group_ in parent_groups]
if _has_user_permission_for_groups(user_id, permission, group_ids, capacity=capacity):
return True
return False
| [
"def",
"has_user_permission_for_group_or_org",
"(",
"group_id",
",",
"user_name",
",",
"permission",
")",
":",
"if",
"(",
"not",
"group_id",
")",
":",
"return",
"False",
"group",
"=",
"model",
".",
"Group",
".",
"get",
"(",
"group_id",
")",
"if",
"(",
"not",
"group",
")",
":",
"return",
"False",
"group_id",
"=",
"group",
".",
"id",
"if",
"is_sysadmin",
"(",
"user_name",
")",
":",
"return",
"True",
"user_id",
"=",
"get_user_id_for_username",
"(",
"user_name",
",",
"allow_none",
"=",
"True",
")",
"if",
"(",
"not",
"user_id",
")",
":",
"return",
"False",
"if",
"_has_user_permission_for_groups",
"(",
"user_id",
",",
"permission",
",",
"[",
"group_id",
"]",
")",
":",
"return",
"True",
"for",
"capacity",
"in",
"check_config_permission",
"(",
"'roles_that_cascade_to_sub_groups'",
")",
":",
"parent_groups",
"=",
"group",
".",
"get_parent_group_hierarchy",
"(",
"type",
"=",
"group",
".",
"type",
")",
"group_ids",
"=",
"[",
"group_",
".",
"id",
"for",
"group_",
"in",
"parent_groups",
"]",
"if",
"_has_user_permission_for_groups",
"(",
"user_id",
",",
"permission",
",",
"group_ids",
",",
"capacity",
"=",
"capacity",
")",
":",
"return",
"True",
"return",
"False"
] | check if the user has the given permissions for the group . | train | false |
39,723 | def api_url(host, port, endpoint):
hostname_list = [host]
if (host.startswith('http://') or host.startswith('https://')):
hostname = ''.join(hostname_list)
else:
hostname_list.insert(0, 'http://')
hostname = ''.join(hostname_list)
joined = urljoin('{hostname}:{port}'.format(hostname=hostname, port=port), endpoint)
(scheme, netloc, path, query_string, fragment) = urlsplit(joined)
query_params = parse_qs(query_string)
query_params['format'] = ['json']
new_query_string = urlencode(query_params, doseq=True)
return urlunsplit((scheme, netloc, path, new_query_string, fragment))
| [
"def",
"api_url",
"(",
"host",
",",
"port",
",",
"endpoint",
")",
":",
"hostname_list",
"=",
"[",
"host",
"]",
"if",
"(",
"host",
".",
"startswith",
"(",
"'http://'",
")",
"or",
"host",
".",
"startswith",
"(",
"'https://'",
")",
")",
":",
"hostname",
"=",
"''",
".",
"join",
"(",
"hostname_list",
")",
"else",
":",
"hostname_list",
".",
"insert",
"(",
"0",
",",
"'http://'",
")",
"hostname",
"=",
"''",
".",
"join",
"(",
"hostname_list",
")",
"joined",
"=",
"urljoin",
"(",
"'{hostname}:{port}'",
".",
"format",
"(",
"hostname",
"=",
"hostname",
",",
"port",
"=",
"port",
")",
",",
"endpoint",
")",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"query_string",
",",
"fragment",
")",
"=",
"urlsplit",
"(",
"joined",
")",
"query_params",
"=",
"parse_qs",
"(",
"query_string",
")",
"query_params",
"[",
"'format'",
"]",
"=",
"[",
"'json'",
"]",
"new_query_string",
"=",
"urlencode",
"(",
"query_params",
",",
"doseq",
"=",
"True",
")",
"return",
"urlunsplit",
"(",
"(",
"scheme",
",",
"netloc",
",",
"path",
",",
"new_query_string",
",",
"fragment",
")",
")"
] | returns a joined url . | train | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.