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 |
|---|---|---|---|---|---|
13,246
|
def latex_to_html(s, alt='image'):
base64_data = latex_to_png(s, encode=True).decode('ascii')
if base64_data:
return (_data_uri_template_png % (base64_data, alt))
|
[
"def",
"latex_to_html",
"(",
"s",
",",
"alt",
"=",
"'image'",
")",
":",
"base64_data",
"=",
"latex_to_png",
"(",
"s",
",",
"encode",
"=",
"True",
")",
".",
"decode",
"(",
"'ascii'",
")",
"if",
"base64_data",
":",
"return",
"(",
"_data_uri_template_png",
"%",
"(",
"base64_data",
",",
"alt",
")",
")"
] |
render latex to html with embedded png data using data uris .
|
train
| true
|
13,247
|
@control_command(args=[(u'queue', text_t), (u'exchange', text_t), (u'exchange_type', text_t), (u'routing_key', text_t)], signature=u'<queue> [exchange [type [routing_key]]]')
def add_consumer(state, queue, exchange=None, exchange_type=None, routing_key=None, **options):
state.consumer.call_soon(state.consumer.add_task_queue, queue, exchange, (exchange_type or u'direct'), routing_key, **options)
return ok(u'add consumer {0}'.format(queue))
|
[
"@",
"control_command",
"(",
"args",
"=",
"[",
"(",
"u'queue'",
",",
"text_t",
")",
",",
"(",
"u'exchange'",
",",
"text_t",
")",
",",
"(",
"u'exchange_type'",
",",
"text_t",
")",
",",
"(",
"u'routing_key'",
",",
"text_t",
")",
"]",
",",
"signature",
"=",
"u'<queue> [exchange [type [routing_key]]]'",
")",
"def",
"add_consumer",
"(",
"state",
",",
"queue",
",",
"exchange",
"=",
"None",
",",
"exchange_type",
"=",
"None",
",",
"routing_key",
"=",
"None",
",",
"**",
"options",
")",
":",
"state",
".",
"consumer",
".",
"call_soon",
"(",
"state",
".",
"consumer",
".",
"add_task_queue",
",",
"queue",
",",
"exchange",
",",
"(",
"exchange_type",
"or",
"u'direct'",
")",
",",
"routing_key",
",",
"**",
"options",
")",
"return",
"ok",
"(",
"u'add consumer {0}'",
".",
"format",
"(",
"queue",
")",
")"
] |
tell worker(s) to consume from task queue by name .
|
train
| false
|
13,248
|
def extendArr(inArray, newSize):
if (type(inArray) in [tuple, list]):
inArray = numpy.asarray(inArray)
newArr = numpy.zeros(newSize, inArray.dtype)
indString = ''
for thisDim in inArray.shape:
indString += (('0:' + str(thisDim)) + ',')
indString = indString[0:(-1)]
exec (('newArr[' + indString) + '] = inArray')
return newArr
|
[
"def",
"extendArr",
"(",
"inArray",
",",
"newSize",
")",
":",
"if",
"(",
"type",
"(",
"inArray",
")",
"in",
"[",
"tuple",
",",
"list",
"]",
")",
":",
"inArray",
"=",
"numpy",
".",
"asarray",
"(",
"inArray",
")",
"newArr",
"=",
"numpy",
".",
"zeros",
"(",
"newSize",
",",
"inArray",
".",
"dtype",
")",
"indString",
"=",
"''",
"for",
"thisDim",
"in",
"inArray",
".",
"shape",
":",
"indString",
"+=",
"(",
"(",
"'0:'",
"+",
"str",
"(",
"thisDim",
")",
")",
"+",
"','",
")",
"indString",
"=",
"indString",
"[",
"0",
":",
"(",
"-",
"1",
")",
"]",
"exec",
"(",
"(",
"'newArr['",
"+",
"indString",
")",
"+",
"'] = inArray'",
")",
"return",
"newArr"
] |
takes a numpy array and returns it padded with zeros to the necessary size .
|
train
| false
|
13,251
|
def in6_isllsnmaddr(str):
temp = in6_and((('\xff' * 13) + ('\x00' * 3)), inet_pton(socket.AF_INET6, str))
temp2 = '\xff\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\xff\x00\x00\x00'
return (temp == temp2)
|
[
"def",
"in6_isllsnmaddr",
"(",
"str",
")",
":",
"temp",
"=",
"in6_and",
"(",
"(",
"(",
"'\\xff'",
"*",
"13",
")",
"+",
"(",
"'\\x00'",
"*",
"3",
")",
")",
",",
"inet_pton",
"(",
"socket",
".",
"AF_INET6",
",",
"str",
")",
")",
"temp2",
"=",
"'\\xff\\x02\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x01\\xff\\x00\\x00\\x00'",
"return",
"(",
"temp",
"==",
"temp2",
")"
] |
return true if provided address is a link-local solicited node multicast address .
|
train
| false
|
13,252
|
@manager.option('-a', '--accounts', dest='accounts', type=unicode, default=u'all')
@manager.option('-m', '--monitors', dest='monitors', type=unicode, default=u'all')
@manager.option('-o', '--outputfolder', dest='outputfolder', type=unicode, default=u'backups')
def backup_config_to_json(accounts, monitors, outputfolder):
monitor_names = _parse_tech_names(monitors)
account_names = _parse_accounts(accounts)
sm_backup_config_to_json(account_names, monitor_names, outputfolder)
|
[
"@",
"manager",
".",
"option",
"(",
"'-a'",
",",
"'--accounts'",
",",
"dest",
"=",
"'accounts'",
",",
"type",
"=",
"unicode",
",",
"default",
"=",
"u'all'",
")",
"@",
"manager",
".",
"option",
"(",
"'-m'",
",",
"'--monitors'",
",",
"dest",
"=",
"'monitors'",
",",
"type",
"=",
"unicode",
",",
"default",
"=",
"u'all'",
")",
"@",
"manager",
".",
"option",
"(",
"'-o'",
",",
"'--outputfolder'",
",",
"dest",
"=",
"'outputfolder'",
",",
"type",
"=",
"unicode",
",",
"default",
"=",
"u'backups'",
")",
"def",
"backup_config_to_json",
"(",
"accounts",
",",
"monitors",
",",
"outputfolder",
")",
":",
"monitor_names",
"=",
"_parse_tech_names",
"(",
"monitors",
")",
"account_names",
"=",
"_parse_accounts",
"(",
"accounts",
")",
"sm_backup_config_to_json",
"(",
"account_names",
",",
"monitor_names",
",",
"outputfolder",
")"
] |
saves the most current item revisions to a json file .
|
train
| false
|
13,253
|
def _resolve_clear_tags_in_list(items):
result = []
for item in items:
if isinstance(item, ClearedValue):
result = [item.value]
else:
result.append(item)
return result
|
[
"def",
"_resolve_clear_tags_in_list",
"(",
"items",
")",
":",
"result",
"=",
"[",
"]",
"for",
"item",
"in",
"items",
":",
"if",
"isinstance",
"(",
"item",
",",
"ClearedValue",
")",
":",
"result",
"=",
"[",
"item",
".",
"value",
"]",
"else",
":",
"result",
".",
"append",
"(",
"item",
")",
"return",
"result"
] |
create a list from *items* .
|
train
| false
|
13,254
|
def PortAllEntities(datastore_path):
previous_stub = apiproxy_stub_map.apiproxy.GetStub('datastore_v3')
try:
app_id = os.environ['APPLICATION_ID']
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
datastore_stub = datastore_file_stub.DatastoreFileStub(app_id, datastore_path, trusted=True)
apiproxy_stub_map.apiproxy.RegisterStub('datastore_v3', datastore_stub)
entities = FetchAllEntitites()
sqlite_datastore_stub = datastore_sqlite_stub.DatastoreSqliteStub(app_id, (datastore_path + '.sqlite'), trusted=True)
apiproxy_stub_map.apiproxy.ReplaceStub('datastore_v3', sqlite_datastore_stub)
PutAllEntities(entities)
sqlite_datastore_stub.Close()
finally:
apiproxy_stub_map.apiproxy.ReplaceStub('datastore_v3', previous_stub)
shutil.copy(datastore_path, (datastore_path + '.filestub'))
_RemoveFile(datastore_path)
shutil.move((datastore_path + '.sqlite'), datastore_path)
|
[
"def",
"PortAllEntities",
"(",
"datastore_path",
")",
":",
"previous_stub",
"=",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"GetStub",
"(",
"'datastore_v3'",
")",
"try",
":",
"app_id",
"=",
"os",
".",
"environ",
"[",
"'APPLICATION_ID'",
"]",
"apiproxy_stub_map",
".",
"apiproxy",
"=",
"apiproxy_stub_map",
".",
"APIProxyStubMap",
"(",
")",
"datastore_stub",
"=",
"datastore_file_stub",
".",
"DatastoreFileStub",
"(",
"app_id",
",",
"datastore_path",
",",
"trusted",
"=",
"True",
")",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"RegisterStub",
"(",
"'datastore_v3'",
",",
"datastore_stub",
")",
"entities",
"=",
"FetchAllEntitites",
"(",
")",
"sqlite_datastore_stub",
"=",
"datastore_sqlite_stub",
".",
"DatastoreSqliteStub",
"(",
"app_id",
",",
"(",
"datastore_path",
"+",
"'.sqlite'",
")",
",",
"trusted",
"=",
"True",
")",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"ReplaceStub",
"(",
"'datastore_v3'",
",",
"sqlite_datastore_stub",
")",
"PutAllEntities",
"(",
"entities",
")",
"sqlite_datastore_stub",
".",
"Close",
"(",
")",
"finally",
":",
"apiproxy_stub_map",
".",
"apiproxy",
".",
"ReplaceStub",
"(",
"'datastore_v3'",
",",
"previous_stub",
")",
"shutil",
".",
"copy",
"(",
"datastore_path",
",",
"(",
"datastore_path",
"+",
"'.filestub'",
")",
")",
"_RemoveFile",
"(",
"datastore_path",
")",
"shutil",
".",
"move",
"(",
"(",
"datastore_path",
"+",
"'.sqlite'",
")",
",",
"datastore_path",
")"
] |
copies entities from a datastorefilestub to an sqlite stub .
|
train
| false
|
13,255
|
def descendant_addresses_to_globs(address_mapper, descendant_addresses):
pattern = address_mapper.build_pattern
return PathGlobs.create_from_specs(descendant_addresses.directory, [pattern, join(u'**', pattern)])
|
[
"def",
"descendant_addresses_to_globs",
"(",
"address_mapper",
",",
"descendant_addresses",
")",
":",
"pattern",
"=",
"address_mapper",
".",
"build_pattern",
"return",
"PathGlobs",
".",
"create_from_specs",
"(",
"descendant_addresses",
".",
"directory",
",",
"[",
"pattern",
",",
"join",
"(",
"u'**'",
",",
"pattern",
")",
"]",
")"
] |
given a descendantaddresses object .
|
train
| false
|
13,256
|
def compare_links(actual, expected):
return compare_tree_to_dict(actual, expected, ('rel', 'href', 'type'))
|
[
"def",
"compare_links",
"(",
"actual",
",",
"expected",
")",
":",
"return",
"compare_tree_to_dict",
"(",
"actual",
",",
"expected",
",",
"(",
"'rel'",
",",
"'href'",
",",
"'type'",
")",
")"
] |
compare xml atom links .
|
train
| false
|
13,258
|
def get_cluster_version(cluster):
uri = '/ws.v1/control-cluster/node?_page_length=1&fields=uuid'
try:
res = do_single_request(HTTP_GET, uri, cluster=cluster)
res = json.loads(res)
except NvpApiClient.NvpApiException:
raise exception.QuantumException()
if (res['result_count'] == 0):
return None
node_uuid = res['results'][0]['uuid']
uri = ('/ws.v1/control-cluster/node/%s/status' % node_uuid)
try:
res = do_single_request(HTTP_GET, uri, cluster=cluster)
res = json.loads(res)
except NvpApiClient.NvpApiException:
raise exception.QuantumException()
version_parts = res['version'].split('.')
version = ('%s.%s' % tuple(version_parts[:2]))
LOG.info(_('NVP controller cluster version: %s'), version)
return version
|
[
"def",
"get_cluster_version",
"(",
"cluster",
")",
":",
"uri",
"=",
"'/ws.v1/control-cluster/node?_page_length=1&fields=uuid'",
"try",
":",
"res",
"=",
"do_single_request",
"(",
"HTTP_GET",
",",
"uri",
",",
"cluster",
"=",
"cluster",
")",
"res",
"=",
"json",
".",
"loads",
"(",
"res",
")",
"except",
"NvpApiClient",
".",
"NvpApiException",
":",
"raise",
"exception",
".",
"QuantumException",
"(",
")",
"if",
"(",
"res",
"[",
"'result_count'",
"]",
"==",
"0",
")",
":",
"return",
"None",
"node_uuid",
"=",
"res",
"[",
"'results'",
"]",
"[",
"0",
"]",
"[",
"'uuid'",
"]",
"uri",
"=",
"(",
"'/ws.v1/control-cluster/node/%s/status'",
"%",
"node_uuid",
")",
"try",
":",
"res",
"=",
"do_single_request",
"(",
"HTTP_GET",
",",
"uri",
",",
"cluster",
"=",
"cluster",
")",
"res",
"=",
"json",
".",
"loads",
"(",
"res",
")",
"except",
"NvpApiClient",
".",
"NvpApiException",
":",
"raise",
"exception",
".",
"QuantumException",
"(",
")",
"version_parts",
"=",
"res",
"[",
"'version'",
"]",
".",
"split",
"(",
"'.'",
")",
"version",
"=",
"(",
"'%s.%s'",
"%",
"tuple",
"(",
"version_parts",
"[",
":",
"2",
"]",
")",
")",
"LOG",
".",
"info",
"(",
"_",
"(",
"'NVP controller cluster version: %s'",
")",
",",
"version",
")",
"return",
"version"
] |
return major/minor version # .
|
train
| false
|
13,259
|
@mock_ec2
def test_eip_associate_invalid_args():
conn = boto.connect_ec2(u'the_key', u'the_secret')
reservation = conn.run_instances(u'ami-1234abcd')
instance = reservation.instances[0]
eip = conn.allocate_address()
with assert_raises(EC2ResponseError) as cm:
conn.associate_address(instance_id=instance.id)
cm.exception.code.should.equal(u'MissingParameter')
cm.exception.status.should.equal(400)
cm.exception.request_id.should_not.be.none
instance.terminate()
|
[
"@",
"mock_ec2",
"def",
"test_eip_associate_invalid_args",
"(",
")",
":",
"conn",
"=",
"boto",
".",
"connect_ec2",
"(",
"u'the_key'",
",",
"u'the_secret'",
")",
"reservation",
"=",
"conn",
".",
"run_instances",
"(",
"u'ami-1234abcd'",
")",
"instance",
"=",
"reservation",
".",
"instances",
"[",
"0",
"]",
"eip",
"=",
"conn",
".",
"allocate_address",
"(",
")",
"with",
"assert_raises",
"(",
"EC2ResponseError",
")",
"as",
"cm",
":",
"conn",
".",
"associate_address",
"(",
"instance_id",
"=",
"instance",
".",
"id",
")",
"cm",
".",
"exception",
".",
"code",
".",
"should",
".",
"equal",
"(",
"u'MissingParameter'",
")",
"cm",
".",
"exception",
".",
"status",
".",
"should",
".",
"equal",
"(",
"400",
")",
"cm",
".",
"exception",
".",
"request_id",
".",
"should_not",
".",
"be",
".",
"none",
"instance",
".",
"terminate",
"(",
")"
] |
associate eip .
|
train
| false
|
13,260
|
def gafbyproteiniterator(handle):
inline = handle.readline()
if (inline.strip() == '!gaf-version: 2.0'):
return _gaf20byproteiniterator(handle)
elif (inline.strip() == '!gaf-version: 1.0'):
return _gaf10byproteiniterator(handle)
elif (inline.strip() == '!gaf-version: 2.1'):
return _gaf20byproteiniterator(handle)
else:
raise ValueError('Unknown GAF version {0}\n'.format(inline))
|
[
"def",
"gafbyproteiniterator",
"(",
"handle",
")",
":",
"inline",
"=",
"handle",
".",
"readline",
"(",
")",
"if",
"(",
"inline",
".",
"strip",
"(",
")",
"==",
"'!gaf-version: 2.0'",
")",
":",
"return",
"_gaf20byproteiniterator",
"(",
"handle",
")",
"elif",
"(",
"inline",
".",
"strip",
"(",
")",
"==",
"'!gaf-version: 1.0'",
")",
":",
"return",
"_gaf10byproteiniterator",
"(",
"handle",
")",
"elif",
"(",
"inline",
".",
"strip",
"(",
")",
"==",
"'!gaf-version: 2.1'",
")",
":",
"return",
"_gaf20byproteiniterator",
"(",
"handle",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unknown GAF version {0}\\n'",
".",
"format",
"(",
"inline",
")",
")"
] |
iterates over records in a gene association file .
|
train
| false
|
13,261
|
def instantiateAddCallbacksBeforeResult(n):
d = defer.Deferred()
def f(result):
return result
for i in xrange(n):
d.addCallback(f)
d.addErrback(f)
d.addBoth(f)
d.addCallbacks(f)
d.callback(1)
|
[
"def",
"instantiateAddCallbacksBeforeResult",
"(",
"n",
")",
":",
"d",
"=",
"defer",
".",
"Deferred",
"(",
")",
"def",
"f",
"(",
"result",
")",
":",
"return",
"result",
"for",
"i",
"in",
"xrange",
"(",
"n",
")",
":",
"d",
".",
"addCallback",
"(",
"f",
")",
"d",
".",
"addErrback",
"(",
"f",
")",
"d",
".",
"addBoth",
"(",
"f",
")",
"d",
".",
"addCallbacks",
"(",
"f",
")",
"d",
".",
"callback",
"(",
"1",
")"
] |
create a deferred and adds a trivial callback/errback/both to it the given number of times .
|
train
| false
|
13,262
|
def enforce_action(context, action):
return enforce(context, action, {'project_id': context.project_id, 'user_id': context.user_id})
|
[
"def",
"enforce_action",
"(",
"context",
",",
"action",
")",
":",
"return",
"enforce",
"(",
"context",
",",
"action",
",",
"{",
"'project_id'",
":",
"context",
".",
"project_id",
",",
"'user_id'",
":",
"context",
".",
"user_id",
"}",
")"
] |
checks that the action can be done by the given context .
|
train
| false
|
13,264
|
def table_extend(tables, keep_headers=True):
from copy import deepcopy
for (ii, t) in enumerate(tables[:]):
t = deepcopy(t)
if (t[0].datatype == 'header'):
t[0][0].data = t.title
t[0][0]._datatype = None
t[0][0].row = t[0][1].row
if ((not keep_headers) and (ii > 0)):
for c in t[0][1:]:
c.data = ''
if (ii == 0):
table_all = t
else:
r1 = table_all[(-1)]
r1.add_format('txt', row_dec_below='-')
table_all.extend(t)
table_all.title = None
return table_all
|
[
"def",
"table_extend",
"(",
"tables",
",",
"keep_headers",
"=",
"True",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"for",
"(",
"ii",
",",
"t",
")",
"in",
"enumerate",
"(",
"tables",
"[",
":",
"]",
")",
":",
"t",
"=",
"deepcopy",
"(",
"t",
")",
"if",
"(",
"t",
"[",
"0",
"]",
".",
"datatype",
"==",
"'header'",
")",
":",
"t",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"data",
"=",
"t",
".",
"title",
"t",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"_datatype",
"=",
"None",
"t",
"[",
"0",
"]",
"[",
"0",
"]",
".",
"row",
"=",
"t",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"row",
"if",
"(",
"(",
"not",
"keep_headers",
")",
"and",
"(",
"ii",
">",
"0",
")",
")",
":",
"for",
"c",
"in",
"t",
"[",
"0",
"]",
"[",
"1",
":",
"]",
":",
"c",
".",
"data",
"=",
"''",
"if",
"(",
"ii",
"==",
"0",
")",
":",
"table_all",
"=",
"t",
"else",
":",
"r1",
"=",
"table_all",
"[",
"(",
"-",
"1",
")",
"]",
"r1",
".",
"add_format",
"(",
"'txt'",
",",
"row_dec_below",
"=",
"'-'",
")",
"table_all",
".",
"extend",
"(",
"t",
")",
"table_all",
".",
"title",
"=",
"None",
"return",
"table_all"
] |
extend a list of simpletables .
|
train
| false
|
13,265
|
def kill_app(proc):
try:
os.kill(proc.pid, SIGINT)
except Exception as j:
Error(('Error killing app: %s' % j))
return False
return True
|
[
"def",
"kill_app",
"(",
"proc",
")",
":",
"try",
":",
"os",
".",
"kill",
"(",
"proc",
".",
"pid",
",",
"SIGINT",
")",
"except",
"Exception",
"as",
"j",
":",
"Error",
"(",
"(",
"'Error killing app: %s'",
"%",
"j",
")",
")",
"return",
"False",
"return",
"True"
] |
kill a process .
|
train
| false
|
13,267
|
def _get_dev_port(backend, instance=None):
port = os.environ.get(_get_dev_port_var(backend, instance), None)
if port:
return int(port)
else:
return None
|
[
"def",
"_get_dev_port",
"(",
"backend",
",",
"instance",
"=",
"None",
")",
":",
"port",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"_get_dev_port_var",
"(",
"backend",
",",
"instance",
")",
",",
"None",
")",
"if",
"port",
":",
"return",
"int",
"(",
"port",
")",
"else",
":",
"return",
"None"
] |
returns the port for a backend [instance] in the dev_appserver .
|
train
| false
|
13,268
|
def SignedVarintReader(buf, pos=0):
result = 0
shift = 0
while 1:
b = buf[pos]
result |= (ORD_MAP_AND_0X7F[b] << shift)
pos += 1
if (not ORD_MAP_AND_0X80[b]):
if (result > 9223372036854775807):
result -= (1 << 64)
return (result, pos)
shift += 7
if (shift >= 64):
raise rdfvalue.DecodeError('Too many bytes when decoding varint.')
|
[
"def",
"SignedVarintReader",
"(",
"buf",
",",
"pos",
"=",
"0",
")",
":",
"result",
"=",
"0",
"shift",
"=",
"0",
"while",
"1",
":",
"b",
"=",
"buf",
"[",
"pos",
"]",
"result",
"|=",
"(",
"ORD_MAP_AND_0X7F",
"[",
"b",
"]",
"<<",
"shift",
")",
"pos",
"+=",
"1",
"if",
"(",
"not",
"ORD_MAP_AND_0X80",
"[",
"b",
"]",
")",
":",
"if",
"(",
"result",
">",
"9223372036854775807",
")",
":",
"result",
"-=",
"(",
"1",
"<<",
"64",
")",
"return",
"(",
"result",
",",
"pos",
")",
"shift",
"+=",
"7",
"if",
"(",
"shift",
">=",
"64",
")",
":",
"raise",
"rdfvalue",
".",
"DecodeError",
"(",
"'Too many bytes when decoding varint.'",
")"
] |
a signed 64 bit decoder from google .
|
train
| true
|
13,269
|
def alter(node, metadata):
if ((node is not None) and metadata and ('node' in metadata)):
node.attrib.update(dict(((k, str(v)) for (k, v) in metadata['node'].items())))
|
[
"def",
"alter",
"(",
"node",
",",
"metadata",
")",
":",
"if",
"(",
"(",
"node",
"is",
"not",
"None",
")",
"and",
"metadata",
"and",
"(",
"'node'",
"in",
"metadata",
")",
")",
":",
"node",
".",
"attrib",
".",
"update",
"(",
"dict",
"(",
"(",
"(",
"k",
",",
"str",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"metadata",
"[",
"'node'",
"]",
".",
"items",
"(",
")",
")",
")",
")"
] |
override nodes attributes from metadata node mapping .
|
train
| true
|
13,270
|
def findOPLocalIdentifier(service_element, type_uris):
local_id_tags = []
if ((OPENID_1_1_TYPE in type_uris) or (OPENID_1_0_TYPE in type_uris)):
local_id_tags.append(nsTag(OPENID_1_0_NS, 'Delegate'))
if (OPENID_2_0_TYPE in type_uris):
local_id_tags.append(nsTag(XRD_NS_2_0, 'LocalID'))
local_id = None
for local_id_tag in local_id_tags:
for local_id_element in service_element.findall(local_id_tag):
if (local_id is None):
local_id = local_id_element.text
elif (local_id != local_id_element.text):
format = 'More than one %r tag found in one service element'
message = (format % (local_id_tag,))
raise DiscoveryFailure(message, None)
return local_id
|
[
"def",
"findOPLocalIdentifier",
"(",
"service_element",
",",
"type_uris",
")",
":",
"local_id_tags",
"=",
"[",
"]",
"if",
"(",
"(",
"OPENID_1_1_TYPE",
"in",
"type_uris",
")",
"or",
"(",
"OPENID_1_0_TYPE",
"in",
"type_uris",
")",
")",
":",
"local_id_tags",
".",
"append",
"(",
"nsTag",
"(",
"OPENID_1_0_NS",
",",
"'Delegate'",
")",
")",
"if",
"(",
"OPENID_2_0_TYPE",
"in",
"type_uris",
")",
":",
"local_id_tags",
".",
"append",
"(",
"nsTag",
"(",
"XRD_NS_2_0",
",",
"'LocalID'",
")",
")",
"local_id",
"=",
"None",
"for",
"local_id_tag",
"in",
"local_id_tags",
":",
"for",
"local_id_element",
"in",
"service_element",
".",
"findall",
"(",
"local_id_tag",
")",
":",
"if",
"(",
"local_id",
"is",
"None",
")",
":",
"local_id",
"=",
"local_id_element",
".",
"text",
"elif",
"(",
"local_id",
"!=",
"local_id_element",
".",
"text",
")",
":",
"format",
"=",
"'More than one %r tag found in one service element'",
"message",
"=",
"(",
"format",
"%",
"(",
"local_id_tag",
",",
")",
")",
"raise",
"DiscoveryFailure",
"(",
"message",
",",
"None",
")",
"return",
"local_id"
] |
find the op-local identifier for this xrd:service element .
|
train
| true
|
13,271
|
def clues_too_many_ip(text):
text = text.lower()
for clue in ('simultaneous ip', 'multiple ip'):
if (clue in text):
return True
return False
|
[
"def",
"clues_too_many_ip",
"(",
"text",
")",
":",
"text",
"=",
"text",
".",
"lower",
"(",
")",
"for",
"clue",
"in",
"(",
"'simultaneous ip'",
",",
"'multiple ip'",
")",
":",
"if",
"(",
"clue",
"in",
"text",
")",
":",
"return",
"True",
"return",
"False"
] |
check for any "account sharing" clues in the response code .
|
train
| false
|
13,272
|
def sync_wheel(saltenv='base'):
return salt.utils.extmods.sync(__opts__, 'wheel', saltenv=saltenv)[0]
|
[
"def",
"sync_wheel",
"(",
"saltenv",
"=",
"'base'",
")",
":",
"return",
"salt",
".",
"utils",
".",
"extmods",
".",
"sync",
"(",
"__opts__",
",",
"'wheel'",
",",
"saltenv",
"=",
"saltenv",
")",
"[",
"0",
"]"
] |
sync wheel modules from salt://_wheel to the master saltenv : base the fileserver environment from which to sync .
|
train
| false
|
13,276
|
def show_test_item(item):
tw = item.config.get_terminal_writer()
tw.line()
tw.write((' ' * 8))
tw.write(item._nodeid)
used_fixtures = sorted(item._fixtureinfo.name2fixturedefs.keys())
if used_fixtures:
tw.write(' (fixtures used: {0})'.format(', '.join(used_fixtures)))
|
[
"def",
"show_test_item",
"(",
"item",
")",
":",
"tw",
"=",
"item",
".",
"config",
".",
"get_terminal_writer",
"(",
")",
"tw",
".",
"line",
"(",
")",
"tw",
".",
"write",
"(",
"(",
"' '",
"*",
"8",
")",
")",
"tw",
".",
"write",
"(",
"item",
".",
"_nodeid",
")",
"used_fixtures",
"=",
"sorted",
"(",
"item",
".",
"_fixtureinfo",
".",
"name2fixturedefs",
".",
"keys",
"(",
")",
")",
"if",
"used_fixtures",
":",
"tw",
".",
"write",
"(",
"' (fixtures used: {0})'",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"used_fixtures",
")",
")",
")"
] |
show test function .
|
train
| false
|
13,277
|
def _jitter_envelope(pos_data, xvals, violin, side):
if (side == 'both'):
(low, high) = ((-1.0), 1.0)
elif (side == 'right'):
(low, high) = (0, 1.0)
elif (side == 'left'):
(low, high) = ((-1.0), 0)
else:
raise ValueError(('`side` input incorrect: %s' % side))
jitter_envelope = np.interp(pos_data, xvals, violin)
jitter_coord = (jitter_envelope * np.random.uniform(low=low, high=high, size=pos_data.size))
return jitter_coord
|
[
"def",
"_jitter_envelope",
"(",
"pos_data",
",",
"xvals",
",",
"violin",
",",
"side",
")",
":",
"if",
"(",
"side",
"==",
"'both'",
")",
":",
"(",
"low",
",",
"high",
")",
"=",
"(",
"(",
"-",
"1.0",
")",
",",
"1.0",
")",
"elif",
"(",
"side",
"==",
"'right'",
")",
":",
"(",
"low",
",",
"high",
")",
"=",
"(",
"0",
",",
"1.0",
")",
"elif",
"(",
"side",
"==",
"'left'",
")",
":",
"(",
"low",
",",
"high",
")",
"=",
"(",
"(",
"-",
"1.0",
")",
",",
"0",
")",
"else",
":",
"raise",
"ValueError",
"(",
"(",
"'`side` input incorrect: %s'",
"%",
"side",
")",
")",
"jitter_envelope",
"=",
"np",
".",
"interp",
"(",
"pos_data",
",",
"xvals",
",",
"violin",
")",
"jitter_coord",
"=",
"(",
"jitter_envelope",
"*",
"np",
".",
"random",
".",
"uniform",
"(",
"low",
"=",
"low",
",",
"high",
"=",
"high",
",",
"size",
"=",
"pos_data",
".",
"size",
")",
")",
"return",
"jitter_coord"
] |
determine envelope for jitter markers .
|
train
| false
|
13,278
|
def _check_precisions(precisions, covariance_type, n_components, n_features):
precisions = check_array(precisions, dtype=[np.float64, np.float32], ensure_2d=False, allow_nd=(covariance_type == 'full'))
precisions_shape = {'full': (n_components, n_features, n_features), 'tied': (n_features, n_features), 'diag': (n_components, n_features), 'spherical': (n_components,)}
_check_shape(precisions, precisions_shape[covariance_type], ('%s precision' % covariance_type))
_check_precisions = {'full': _check_precisions_full, 'tied': _check_precision_matrix, 'diag': _check_precision_positivity, 'spherical': _check_precision_positivity}
_check_precisions[covariance_type](precisions, covariance_type)
return precisions
|
[
"def",
"_check_precisions",
"(",
"precisions",
",",
"covariance_type",
",",
"n_components",
",",
"n_features",
")",
":",
"precisions",
"=",
"check_array",
"(",
"precisions",
",",
"dtype",
"=",
"[",
"np",
".",
"float64",
",",
"np",
".",
"float32",
"]",
",",
"ensure_2d",
"=",
"False",
",",
"allow_nd",
"=",
"(",
"covariance_type",
"==",
"'full'",
")",
")",
"precisions_shape",
"=",
"{",
"'full'",
":",
"(",
"n_components",
",",
"n_features",
",",
"n_features",
")",
",",
"'tied'",
":",
"(",
"n_features",
",",
"n_features",
")",
",",
"'diag'",
":",
"(",
"n_components",
",",
"n_features",
")",
",",
"'spherical'",
":",
"(",
"n_components",
",",
")",
"}",
"_check_shape",
"(",
"precisions",
",",
"precisions_shape",
"[",
"covariance_type",
"]",
",",
"(",
"'%s precision'",
"%",
"covariance_type",
")",
")",
"_check_precisions",
"=",
"{",
"'full'",
":",
"_check_precisions_full",
",",
"'tied'",
":",
"_check_precision_matrix",
",",
"'diag'",
":",
"_check_precision_positivity",
",",
"'spherical'",
":",
"_check_precision_positivity",
"}",
"_check_precisions",
"[",
"covariance_type",
"]",
"(",
"precisions",
",",
"covariance_type",
")",
"return",
"precisions"
] |
validate user provided precisions .
|
train
| false
|
13,279
|
@reviewer_required(moderator=True)
def route_reviewer(request):
return http.HttpResponseRedirect(reverse('reviewers.home'))
|
[
"@",
"reviewer_required",
"(",
"moderator",
"=",
"True",
")",
"def",
"route_reviewer",
"(",
"request",
")",
":",
"return",
"http",
".",
"HttpResponseRedirect",
"(",
"reverse",
"(",
"'reviewers.home'",
")",
")"
] |
redirect to apps home page if app reviewer .
|
train
| false
|
13,280
|
def Point(*args, **kwargs):
model = modelcontext(kwargs.pop('model', None))
args = list(args)
try:
d = dict(*args, **kwargs)
except Exception as e:
raise TypeError("can't turn {} and {} into a dict. {}".format(args, kwargs, e))
return dict(((str(k), np.array(v)) for (k, v) in d.items() if (str(k) in map(str, model.vars))))
|
[
"def",
"Point",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"model",
"=",
"modelcontext",
"(",
"kwargs",
".",
"pop",
"(",
"'model'",
",",
"None",
")",
")",
"args",
"=",
"list",
"(",
"args",
")",
"try",
":",
"d",
"=",
"dict",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"TypeError",
"(",
"\"can't turn {} and {} into a dict. {}\"",
".",
"format",
"(",
"args",
",",
"kwargs",
",",
"e",
")",
")",
"return",
"dict",
"(",
"(",
"(",
"str",
"(",
"k",
")",
",",
"np",
".",
"array",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"d",
".",
"items",
"(",
")",
"if",
"(",
"str",
"(",
"k",
")",
"in",
"map",
"(",
"str",
",",
"model",
".",
"vars",
")",
")",
")",
")"
] |
build a point .
|
train
| false
|
13,281
|
def format_to_http_prompt(context, excluded_options=None):
cmds = _extract_httpie_options(context, quote=True, join_key_value=True, excluded_keys=excluded_options)
cmds.append(('cd ' + smart_quote(context.url)))
cmds += _extract_httpie_request_items(context, quote=True)
return ('\n'.join(cmds) + '\n')
|
[
"def",
"format_to_http_prompt",
"(",
"context",
",",
"excluded_options",
"=",
"None",
")",
":",
"cmds",
"=",
"_extract_httpie_options",
"(",
"context",
",",
"quote",
"=",
"True",
",",
"join_key_value",
"=",
"True",
",",
"excluded_keys",
"=",
"excluded_options",
")",
"cmds",
".",
"append",
"(",
"(",
"'cd '",
"+",
"smart_quote",
"(",
"context",
".",
"url",
")",
")",
")",
"cmds",
"+=",
"_extract_httpie_request_items",
"(",
"context",
",",
"quote",
"=",
"True",
")",
"return",
"(",
"'\\n'",
".",
"join",
"(",
"cmds",
")",
"+",
"'\\n'",
")"
] |
format a context object to http prompt commands .
|
train
| true
|
13,282
|
def create_metadata(name, ext_version=None, schema=None, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None):
installed_ext = get_installed_extension(name, user=user, host=host, port=port, maintenance_db=maintenance_db, password=password, runas=runas)
ret = [_EXTENSION_NOT_INSTALLED]
if installed_ext:
ret = [_EXTENSION_INSTALLED]
if ((ext_version is not None) and _pg_is_older_ext_ver(installed_ext.get('extversion', ext_version), ext_version)):
ret.append(_EXTENSION_TO_UPGRADE)
if ((schema is not None) and (installed_ext.get('extrelocatable', 'f') == 't') and (installed_ext.get('schema_name', schema) != schema)):
ret.append(_EXTENSION_TO_MOVE)
return ret
|
[
"def",
"create_metadata",
"(",
"name",
",",
"ext_version",
"=",
"None",
",",
"schema",
"=",
"None",
",",
"user",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"maintenance_db",
"=",
"None",
",",
"password",
"=",
"None",
",",
"runas",
"=",
"None",
")",
":",
"installed_ext",
"=",
"get_installed_extension",
"(",
"name",
",",
"user",
"=",
"user",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"maintenance_db",
"=",
"maintenance_db",
",",
"password",
"=",
"password",
",",
"runas",
"=",
"runas",
")",
"ret",
"=",
"[",
"_EXTENSION_NOT_INSTALLED",
"]",
"if",
"installed_ext",
":",
"ret",
"=",
"[",
"_EXTENSION_INSTALLED",
"]",
"if",
"(",
"(",
"ext_version",
"is",
"not",
"None",
")",
"and",
"_pg_is_older_ext_ver",
"(",
"installed_ext",
".",
"get",
"(",
"'extversion'",
",",
"ext_version",
")",
",",
"ext_version",
")",
")",
":",
"ret",
".",
"append",
"(",
"_EXTENSION_TO_UPGRADE",
")",
"if",
"(",
"(",
"schema",
"is",
"not",
"None",
")",
"and",
"(",
"installed_ext",
".",
"get",
"(",
"'extrelocatable'",
",",
"'f'",
")",
"==",
"'t'",
")",
"and",
"(",
"installed_ext",
".",
"get",
"(",
"'schema_name'",
",",
"schema",
")",
"!=",
"schema",
")",
")",
":",
"ret",
".",
"append",
"(",
"_EXTENSION_TO_MOVE",
")",
"return",
"ret"
] |
get lifecycle information about an extension cli example: .
|
train
| true
|
13,283
|
def invalid_url_error(url, action):
if url.isValid():
raise ValueError('Calling invalid_url_error with valid URL {}'.format(url.toDisplayString()))
errstring = get_errstring(url, 'Trying to {} with invalid URL'.format(action))
message.error(errstring)
|
[
"def",
"invalid_url_error",
"(",
"url",
",",
"action",
")",
":",
"if",
"url",
".",
"isValid",
"(",
")",
":",
"raise",
"ValueError",
"(",
"'Calling invalid_url_error with valid URL {}'",
".",
"format",
"(",
"url",
".",
"toDisplayString",
"(",
")",
")",
")",
"errstring",
"=",
"get_errstring",
"(",
"url",
",",
"'Trying to {} with invalid URL'",
".",
"format",
"(",
"action",
")",
")",
"message",
".",
"error",
"(",
"errstring",
")"
] |
display an error message for a url .
|
train
| false
|
13,284
|
def remove_credits(text):
textlines = text.split('\n')
credits = None
for i in (0, (-1)):
if (textlines and ('lyrics' in textlines[i].lower())):
credits = textlines.pop(i)
if credits:
text = '\n'.join(textlines)
return text
|
[
"def",
"remove_credits",
"(",
"text",
")",
":",
"textlines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"credits",
"=",
"None",
"for",
"i",
"in",
"(",
"0",
",",
"(",
"-",
"1",
")",
")",
":",
"if",
"(",
"textlines",
"and",
"(",
"'lyrics'",
"in",
"textlines",
"[",
"i",
"]",
".",
"lower",
"(",
")",
")",
")",
":",
"credits",
"=",
"textlines",
".",
"pop",
"(",
"i",
")",
"if",
"credits",
":",
"text",
"=",
"'\\n'",
".",
"join",
"(",
"textlines",
")",
"return",
"text"
] |
remove first/last line of text if it contains the word lyrics eg lyrics by songsdatabase .
|
train
| false
|
13,285
|
def screen():
_lib.RAND_screen()
|
[
"def",
"screen",
"(",
")",
":",
"_lib",
".",
"RAND_screen",
"(",
")"
] |
superimposes two inverted images on top of each other .
|
train
| false
|
13,286
|
def fetch_data(blob, start_index, end_index):
if isinstance(blob, BlobInfo):
blob = blob.key()
return blobstore.fetch_data(blob, start_index, end_index)
|
[
"def",
"fetch_data",
"(",
"blob",
",",
"start_index",
",",
"end_index",
")",
":",
"if",
"isinstance",
"(",
"blob",
",",
"BlobInfo",
")",
":",
"blob",
"=",
"blob",
".",
"key",
"(",
")",
"return",
"blobstore",
".",
"fetch_data",
"(",
"blob",
",",
"start_index",
",",
"end_index",
")"
] |
fetch data for blob .
|
train
| false
|
13,287
|
def find_object(name, blacklist=None, whitelist=None):
if blacklist:
for pre in blacklist:
if name.startswith(pre):
raise TypeError(("%r: can't instantiate names starting with %r" % (name, pre)))
if whitelist:
passes = False
for pre in whitelist:
if name.startswith(pre):
passes = True
break
if (not passes):
raise TypeError(("Can't instantiate %r" % name))
lastdot = name.rfind('.')
assert (lastdot > (-1)), ('Name %r must be fully qualified' % name)
modname = name[:lastdot]
clsname = name[(lastdot + 1):]
mod = __import__(modname, fromlist=[clsname])
cls = getattr(mod, clsname)
return cls
|
[
"def",
"find_object",
"(",
"name",
",",
"blacklist",
"=",
"None",
",",
"whitelist",
"=",
"None",
")",
":",
"if",
"blacklist",
":",
"for",
"pre",
"in",
"blacklist",
":",
"if",
"name",
".",
"startswith",
"(",
"pre",
")",
":",
"raise",
"TypeError",
"(",
"(",
"\"%r: can't instantiate names starting with %r\"",
"%",
"(",
"name",
",",
"pre",
")",
")",
")",
"if",
"whitelist",
":",
"passes",
"=",
"False",
"for",
"pre",
"in",
"whitelist",
":",
"if",
"name",
".",
"startswith",
"(",
"pre",
")",
":",
"passes",
"=",
"True",
"break",
"if",
"(",
"not",
"passes",
")",
":",
"raise",
"TypeError",
"(",
"(",
"\"Can't instantiate %r\"",
"%",
"name",
")",
")",
"lastdot",
"=",
"name",
".",
"rfind",
"(",
"'.'",
")",
"assert",
"(",
"lastdot",
">",
"(",
"-",
"1",
")",
")",
",",
"(",
"'Name %r must be fully qualified'",
"%",
"name",
")",
"modname",
"=",
"name",
"[",
":",
"lastdot",
"]",
"clsname",
"=",
"name",
"[",
"(",
"lastdot",
"+",
"1",
")",
":",
"]",
"mod",
"=",
"__import__",
"(",
"modname",
",",
"fromlist",
"=",
"[",
"clsname",
"]",
")",
"cls",
"=",
"getattr",
"(",
"mod",
",",
"clsname",
")",
"return",
"cls"
] |
imports and returns an object given a fully qualified name .
|
train
| false
|
13,288
|
def test_search_any_case():
result = list(search_packages_info(['PIP']))
assert (len(result) == 1)
assert ('pip' == result[0]['name'])
|
[
"def",
"test_search_any_case",
"(",
")",
":",
"result",
"=",
"list",
"(",
"search_packages_info",
"(",
"[",
"'PIP'",
"]",
")",
")",
"assert",
"(",
"len",
"(",
"result",
")",
"==",
"1",
")",
"assert",
"(",
"'pip'",
"==",
"result",
"[",
"0",
"]",
"[",
"'name'",
"]",
")"
] |
search for a package in any case .
|
train
| false
|
13,290
|
def _wait_for_new_device(base, expected_size, time_limit=60):
start_time = time.time()
elapsed_time = (time.time() - start_time)
while (elapsed_time < time_limit):
for device in list((set(FilePath('/sys/block').children()) - set(base))):
device_name = device.basename()
if (device_name.startswith(('sd', 'xvd')) and (_get_device_size(device_name) == expected_size)):
return FilePath('/dev').child(device_name)
time.sleep(0.1)
elapsed_time = (time.time() - start_time)
new_devices = list((device.basename() for device in (set(FilePath('/sys/block').children()) - set(base))))
new_devices_size = list((_get_device_size(device_name) for device_name in new_devices))
NO_NEW_DEVICE_IN_OS(new_devices=new_devices, new_devices_size=new_devices_size, expected_size=expected_size, time_limit=time_limit).write()
return None
|
[
"def",
"_wait_for_new_device",
"(",
"base",
",",
"expected_size",
",",
"time_limit",
"=",
"60",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"elapsed_time",
"=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"while",
"(",
"elapsed_time",
"<",
"time_limit",
")",
":",
"for",
"device",
"in",
"list",
"(",
"(",
"set",
"(",
"FilePath",
"(",
"'/sys/block'",
")",
".",
"children",
"(",
")",
")",
"-",
"set",
"(",
"base",
")",
")",
")",
":",
"device_name",
"=",
"device",
".",
"basename",
"(",
")",
"if",
"(",
"device_name",
".",
"startswith",
"(",
"(",
"'sd'",
",",
"'xvd'",
")",
")",
"and",
"(",
"_get_device_size",
"(",
"device_name",
")",
"==",
"expected_size",
")",
")",
":",
"return",
"FilePath",
"(",
"'/dev'",
")",
".",
"child",
"(",
"device_name",
")",
"time",
".",
"sleep",
"(",
"0.1",
")",
"elapsed_time",
"=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"start_time",
")",
"new_devices",
"=",
"list",
"(",
"(",
"device",
".",
"basename",
"(",
")",
"for",
"device",
"in",
"(",
"set",
"(",
"FilePath",
"(",
"'/sys/block'",
")",
".",
"children",
"(",
")",
")",
"-",
"set",
"(",
"base",
")",
")",
")",
")",
"new_devices_size",
"=",
"list",
"(",
"(",
"_get_device_size",
"(",
"device_name",
")",
"for",
"device_name",
"in",
"new_devices",
")",
")",
"NO_NEW_DEVICE_IN_OS",
"(",
"new_devices",
"=",
"new_devices",
",",
"new_devices_size",
"=",
"new_devices_size",
",",
"expected_size",
"=",
"expected_size",
",",
"time_limit",
"=",
"time_limit",
")",
".",
"write",
"(",
")",
"return",
"None"
] |
helper function to wait for up to 60s for new ebs block device to manifest in the os .
|
train
| false
|
13,291
|
@newrelic.agent.function_trace()
def filter_out_noinclude(src):
if (not src):
return ''
doc = pq(src)
doc.remove('*[class=noinclude]')
return doc.html()
|
[
"@",
"newrelic",
".",
"agent",
".",
"function_trace",
"(",
")",
"def",
"filter_out_noinclude",
"(",
"src",
")",
":",
"if",
"(",
"not",
"src",
")",
":",
"return",
"''",
"doc",
"=",
"pq",
"(",
"src",
")",
"doc",
".",
"remove",
"(",
"'*[class=noinclude]'",
")",
"return",
"doc",
".",
"html",
"(",
")"
] |
quick and dirty filter to remove <div class="noinclude"> blocks .
|
train
| false
|
13,292
|
def destroy_vbd(session, vbd_ref):
try:
session.call_xenapi('VBD.destroy', vbd_ref)
except session.XenAPI.Failure:
LOG.exception(_LE('Unable to destroy VBD'))
raise exception.StorageError(reason=(_('Unable to destroy VBD %s') % vbd_ref))
|
[
"def",
"destroy_vbd",
"(",
"session",
",",
"vbd_ref",
")",
":",
"try",
":",
"session",
".",
"call_xenapi",
"(",
"'VBD.destroy'",
",",
"vbd_ref",
")",
"except",
"session",
".",
"XenAPI",
".",
"Failure",
":",
"LOG",
".",
"exception",
"(",
"_LE",
"(",
"'Unable to destroy VBD'",
")",
")",
"raise",
"exception",
".",
"StorageError",
"(",
"reason",
"=",
"(",
"_",
"(",
"'Unable to destroy VBD %s'",
")",
"%",
"vbd_ref",
")",
")"
] |
destroy vbd from host database .
|
train
| false
|
13,293
|
def dup_irreducible_p(f, K):
return dmp_irreducible_p(f, 0, K)
|
[
"def",
"dup_irreducible_p",
"(",
"f",
",",
"K",
")",
":",
"return",
"dmp_irreducible_p",
"(",
"f",
",",
"0",
",",
"K",
")"
] |
returns true if f has no factors over its domain .
|
train
| false
|
13,295
|
def start_x_config_set(kodi_setting, all_settings):
return '1'
|
[
"def",
"start_x_config_set",
"(",
"kodi_setting",
",",
"all_settings",
")",
":",
"return",
"'1'"
] |
always return 1 .
|
train
| false
|
13,300
|
def connect_cognito_sync(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
from boto.cognito.sync.layer1 import CognitoSyncConnection
return CognitoSyncConnection(aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, **kwargs)
|
[
"def",
"connect_cognito_sync",
"(",
"aws_access_key_id",
"=",
"None",
",",
"aws_secret_access_key",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"from",
"boto",
".",
"cognito",
".",
"sync",
".",
"layer1",
"import",
"CognitoSyncConnection",
"return",
"CognitoSyncConnection",
"(",
"aws_access_key_id",
"=",
"aws_access_key_id",
",",
"aws_secret_access_key",
"=",
"aws_secret_access_key",
",",
"**",
"kwargs",
")"
] |
connect to amazon cognito sync :type aws_access_key_id: string .
|
train
| false
|
13,301
|
def javascript_url():
return (get_bootstrap_setting(u'javascript_url') or bootstrap_url(u'js/bootstrap.min.js'))
|
[
"def",
"javascript_url",
"(",
")",
":",
"return",
"(",
"get_bootstrap_setting",
"(",
"u'javascript_url'",
")",
"or",
"bootstrap_url",
"(",
"u'js/bootstrap.min.js'",
")",
")"
] |
return the full url to the bootstrap javascript file .
|
train
| false
|
13,302
|
def libvlc_vlm_get_media_instance_rate(p_instance, psz_name, i_instance):
f = (_Cfunctions.get('libvlc_vlm_get_media_instance_rate', None) or _Cfunction('libvlc_vlm_get_media_instance_rate', ((1,), (1,), (1,)), None, ctypes.c_int, Instance, ctypes.c_char_p, ctypes.c_int))
return f(p_instance, psz_name, i_instance)
|
[
"def",
"libvlc_vlm_get_media_instance_rate",
"(",
"p_instance",
",",
"psz_name",
",",
"i_instance",
")",
":",
"f",
"=",
"(",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_vlm_get_media_instance_rate'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_vlm_get_media_instance_rate'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
")",
",",
"None",
",",
"ctypes",
".",
"c_int",
",",
"Instance",
",",
"ctypes",
".",
"c_char_p",
",",
"ctypes",
".",
"c_int",
")",
")",
"return",
"f",
"(",
"p_instance",
",",
"psz_name",
",",
"i_instance",
")"
] |
get vlm_media instance playback rate by name or instance id .
|
train
| true
|
13,305
|
def _cached_path_needs_update(ca_path, cache_length):
exists = os.path.exists(ca_path)
if (not exists):
return True
stats = os.stat(ca_path)
if (stats.st_mtime < (time.time() - ((cache_length * 60) * 60))):
return True
if (stats.st_size == 0):
return True
return False
|
[
"def",
"_cached_path_needs_update",
"(",
"ca_path",
",",
"cache_length",
")",
":",
"exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"ca_path",
")",
"if",
"(",
"not",
"exists",
")",
":",
"return",
"True",
"stats",
"=",
"os",
".",
"stat",
"(",
"ca_path",
")",
"if",
"(",
"stats",
".",
"st_mtime",
"<",
"(",
"time",
".",
"time",
"(",
")",
"-",
"(",
"(",
"cache_length",
"*",
"60",
")",
"*",
"60",
")",
")",
")",
":",
"return",
"True",
"if",
"(",
"stats",
".",
"st_size",
"==",
"0",
")",
":",
"return",
"True",
"return",
"False"
] |
checks to see if a cache file needs to be refreshed .
|
train
| true
|
13,307
|
def make_server_description(server, hosts):
server_type = server['type']
if (server_type == 'Unknown'):
return ServerDescription(clean_node(server['address']), IsMaster({}))
ismaster_response = {'ok': True, 'hosts': hosts}
if ((server_type != 'Standalone') and (server_type != 'Mongos')):
ismaster_response['setName'] = 'rs'
if (server_type == 'RSPrimary'):
ismaster_response['ismaster'] = True
elif (server_type == 'RSSecondary'):
ismaster_response['secondary'] = True
elif (server_type == 'Mongos'):
ismaster_response['msg'] = 'isdbgrid'
ismaster_response['lastWrite'] = {'lastWriteDate': make_last_write_date(server)}
for field in ('maxWireVersion', 'tags', 'idleWritePeriodMillis'):
if (field in server):
ismaster_response[field] = server[field]
sd = ServerDescription(clean_node(server['address']), IsMaster(ismaster_response), round_trip_time=(server['avg_rtt_ms'] / 1000.0))
if ('lastUpdateTime' in server):
sd._last_update_time = (server['lastUpdateTime'] / 1000.0)
return sd
|
[
"def",
"make_server_description",
"(",
"server",
",",
"hosts",
")",
":",
"server_type",
"=",
"server",
"[",
"'type'",
"]",
"if",
"(",
"server_type",
"==",
"'Unknown'",
")",
":",
"return",
"ServerDescription",
"(",
"clean_node",
"(",
"server",
"[",
"'address'",
"]",
")",
",",
"IsMaster",
"(",
"{",
"}",
")",
")",
"ismaster_response",
"=",
"{",
"'ok'",
":",
"True",
",",
"'hosts'",
":",
"hosts",
"}",
"if",
"(",
"(",
"server_type",
"!=",
"'Standalone'",
")",
"and",
"(",
"server_type",
"!=",
"'Mongos'",
")",
")",
":",
"ismaster_response",
"[",
"'setName'",
"]",
"=",
"'rs'",
"if",
"(",
"server_type",
"==",
"'RSPrimary'",
")",
":",
"ismaster_response",
"[",
"'ismaster'",
"]",
"=",
"True",
"elif",
"(",
"server_type",
"==",
"'RSSecondary'",
")",
":",
"ismaster_response",
"[",
"'secondary'",
"]",
"=",
"True",
"elif",
"(",
"server_type",
"==",
"'Mongos'",
")",
":",
"ismaster_response",
"[",
"'msg'",
"]",
"=",
"'isdbgrid'",
"ismaster_response",
"[",
"'lastWrite'",
"]",
"=",
"{",
"'lastWriteDate'",
":",
"make_last_write_date",
"(",
"server",
")",
"}",
"for",
"field",
"in",
"(",
"'maxWireVersion'",
",",
"'tags'",
",",
"'idleWritePeriodMillis'",
")",
":",
"if",
"(",
"field",
"in",
"server",
")",
":",
"ismaster_response",
"[",
"field",
"]",
"=",
"server",
"[",
"field",
"]",
"sd",
"=",
"ServerDescription",
"(",
"clean_node",
"(",
"server",
"[",
"'address'",
"]",
")",
",",
"IsMaster",
"(",
"ismaster_response",
")",
",",
"round_trip_time",
"=",
"(",
"server",
"[",
"'avg_rtt_ms'",
"]",
"/",
"1000.0",
")",
")",
"if",
"(",
"'lastUpdateTime'",
"in",
"server",
")",
":",
"sd",
".",
"_last_update_time",
"=",
"(",
"server",
"[",
"'lastUpdateTime'",
"]",
"/",
"1000.0",
")",
"return",
"sd"
] |
make a serverdescription from server info in a json test .
|
train
| false
|
13,308
|
def encode_fs_path(path):
return smart_str(path, HDFS_ENCODING, errors='strict')
|
[
"def",
"encode_fs_path",
"(",
"path",
")",
":",
"return",
"smart_str",
"(",
"path",
",",
"HDFS_ENCODING",
",",
"errors",
"=",
"'strict'",
")"
] |
encode_fs_path -> byte string in utf8 .
|
train
| false
|
13,309
|
def init_state(inputs, state_shape, state_initializer=tf.zeros_initializer, dtype=tf.float32):
if (inputs is not None):
inferred_batch_size = inputs.get_shape().with_rank_at_least(1)[0]
batch_size = tf.shape(inputs)[0]
dtype = inputs.dtype
else:
inferred_batch_size = 0
batch_size = 0
initial_state = state_initializer(tf.pack(([batch_size] + state_shape)), dtype=dtype)
initial_state.set_shape(([inferred_batch_size] + state_shape))
return initial_state
|
[
"def",
"init_state",
"(",
"inputs",
",",
"state_shape",
",",
"state_initializer",
"=",
"tf",
".",
"zeros_initializer",
",",
"dtype",
"=",
"tf",
".",
"float32",
")",
":",
"if",
"(",
"inputs",
"is",
"not",
"None",
")",
":",
"inferred_batch_size",
"=",
"inputs",
".",
"get_shape",
"(",
")",
".",
"with_rank_at_least",
"(",
"1",
")",
"[",
"0",
"]",
"batch_size",
"=",
"tf",
".",
"shape",
"(",
"inputs",
")",
"[",
"0",
"]",
"dtype",
"=",
"inputs",
".",
"dtype",
"else",
":",
"inferred_batch_size",
"=",
"0",
"batch_size",
"=",
"0",
"initial_state",
"=",
"state_initializer",
"(",
"tf",
".",
"pack",
"(",
"(",
"[",
"batch_size",
"]",
"+",
"state_shape",
")",
")",
",",
"dtype",
"=",
"dtype",
")",
"initial_state",
".",
"set_shape",
"(",
"(",
"[",
"inferred_batch_size",
"]",
"+",
"state_shape",
")",
")",
"return",
"initial_state"
] |
helper function to create an initial state given inputs .
|
train
| false
|
13,310
|
@pytest.fixture(scope='session', autouse=True)
def allow_sudo_user(setup_package):
from fabtools.require import file as require_file
require_file('/etc/sudoers.d/fabtools', contents='vagrant ALL=(ALL) NOPASSWD:ALL\n', owner='root', mode='440', use_sudo=True)
|
[
"@",
"pytest",
".",
"fixture",
"(",
"scope",
"=",
"'session'",
",",
"autouse",
"=",
"True",
")",
"def",
"allow_sudo_user",
"(",
"setup_package",
")",
":",
"from",
"fabtools",
".",
"require",
"import",
"file",
"as",
"require_file",
"require_file",
"(",
"'/etc/sudoers.d/fabtools'",
",",
"contents",
"=",
"'vagrant ALL=(ALL) NOPASSWD:ALL\\n'",
",",
"owner",
"=",
"'root'",
",",
"mode",
"=",
"'440'",
",",
"use_sudo",
"=",
"True",
")"
] |
fix sudo config if needed some vagrant boxes come with a too restrictive sudoers config and only allow the vagrant user to run commands as root .
|
train
| false
|
13,311
|
def wsgifunc(func, *middleware):
middleware = list(middleware)
if (reloader in middleware):
relr = reloader(None)
relrcheck = relr.check
middleware.remove(reloader)
else:
relr = None
relrcheck = (lambda : None)
def wsgifunc(env, start_resp):
_load(env)
relrcheck()
try:
result = func()
except StopIteration:
result = None
is_generator = (result and hasattr(result, 'next'))
if is_generator:
try:
firstchunk = result.next()
except StopIteration:
firstchunk = ''
(status, headers, output) = (ctx.status, ctx.headers, ctx.output)
_unload()
start_resp(status, headers)
if is_generator:
return itertools.chain([firstchunk], result)
elif isinstance(output, str):
return [output]
elif hasattr(output, 'next'):
return output
else:
raise Exception, 'Invalid web.context.output'
for mw_func in middleware:
wsgifunc = mw_func(wsgifunc)
if relr:
relr.func = wsgifunc
return wsgifunc
return wsgifunc
|
[
"def",
"wsgifunc",
"(",
"func",
",",
"*",
"middleware",
")",
":",
"middleware",
"=",
"list",
"(",
"middleware",
")",
"if",
"(",
"reloader",
"in",
"middleware",
")",
":",
"relr",
"=",
"reloader",
"(",
"None",
")",
"relrcheck",
"=",
"relr",
".",
"check",
"middleware",
".",
"remove",
"(",
"reloader",
")",
"else",
":",
"relr",
"=",
"None",
"relrcheck",
"=",
"(",
"lambda",
":",
"None",
")",
"def",
"wsgifunc",
"(",
"env",
",",
"start_resp",
")",
":",
"_load",
"(",
"env",
")",
"relrcheck",
"(",
")",
"try",
":",
"result",
"=",
"func",
"(",
")",
"except",
"StopIteration",
":",
"result",
"=",
"None",
"is_generator",
"=",
"(",
"result",
"and",
"hasattr",
"(",
"result",
",",
"'next'",
")",
")",
"if",
"is_generator",
":",
"try",
":",
"firstchunk",
"=",
"result",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"firstchunk",
"=",
"''",
"(",
"status",
",",
"headers",
",",
"output",
")",
"=",
"(",
"ctx",
".",
"status",
",",
"ctx",
".",
"headers",
",",
"ctx",
".",
"output",
")",
"_unload",
"(",
")",
"start_resp",
"(",
"status",
",",
"headers",
")",
"if",
"is_generator",
":",
"return",
"itertools",
".",
"chain",
"(",
"[",
"firstchunk",
"]",
",",
"result",
")",
"elif",
"isinstance",
"(",
"output",
",",
"str",
")",
":",
"return",
"[",
"output",
"]",
"elif",
"hasattr",
"(",
"output",
",",
"'next'",
")",
":",
"return",
"output",
"else",
":",
"raise",
"Exception",
",",
"'Invalid web.context.output'",
"for",
"mw_func",
"in",
"middleware",
":",
"wsgifunc",
"=",
"mw_func",
"(",
"wsgifunc",
")",
"if",
"relr",
":",
"relr",
".",
"func",
"=",
"wsgifunc",
"return",
"wsgifunc",
"return",
"wsgifunc"
] |
returns a wsgi-compatible function from a webpy-function .
|
train
| false
|
13,313
|
def NDP_Attack_DAD_DoS_via_NA(iface=None, mac_src_filter=None, tgt_filter=None, reply_mac=None):
def na_reply_callback(req, reply_mac, iface):
'\n Callback that reply to a NS with a NA\n '
mac = req[Ether].src
dst = req[IPv6].dst
tgt = req[ICMPv6ND_NS].tgt
rep = (Ether(src=reply_mac) / IPv6(src=tgt, dst=dst))
rep /= ICMPv6ND_NA(tgt=tgt, S=0, R=0, O=1)
rep /= ICMPv6NDOptDstLLAddr(lladdr=reply_mac)
sendp(rep, iface=iface, verbose=0)
print ('Reply NA for target address %s (received from %s)' % (tgt, mac))
_NDP_Attack_DAD_DoS(na_reply_callback, iface, mac_src_filter, tgt_filter, reply_mac)
|
[
"def",
"NDP_Attack_DAD_DoS_via_NA",
"(",
"iface",
"=",
"None",
",",
"mac_src_filter",
"=",
"None",
",",
"tgt_filter",
"=",
"None",
",",
"reply_mac",
"=",
"None",
")",
":",
"def",
"na_reply_callback",
"(",
"req",
",",
"reply_mac",
",",
"iface",
")",
":",
"mac",
"=",
"req",
"[",
"Ether",
"]",
".",
"src",
"dst",
"=",
"req",
"[",
"IPv6",
"]",
".",
"dst",
"tgt",
"=",
"req",
"[",
"ICMPv6ND_NS",
"]",
".",
"tgt",
"rep",
"=",
"(",
"Ether",
"(",
"src",
"=",
"reply_mac",
")",
"/",
"IPv6",
"(",
"src",
"=",
"tgt",
",",
"dst",
"=",
"dst",
")",
")",
"rep",
"/=",
"ICMPv6ND_NA",
"(",
"tgt",
"=",
"tgt",
",",
"S",
"=",
"0",
",",
"R",
"=",
"0",
",",
"O",
"=",
"1",
")",
"rep",
"/=",
"ICMPv6NDOptDstLLAddr",
"(",
"lladdr",
"=",
"reply_mac",
")",
"sendp",
"(",
"rep",
",",
"iface",
"=",
"iface",
",",
"verbose",
"=",
"0",
")",
"print",
"(",
"'Reply NA for target address %s (received from %s)'",
"%",
"(",
"tgt",
",",
"mac",
")",
")",
"_NDP_Attack_DAD_DoS",
"(",
"na_reply_callback",
",",
"iface",
",",
"mac_src_filter",
",",
"tgt_filter",
",",
"reply_mac",
")"
] |
perform the dad dos attack using ns described in section 4 .
|
train
| true
|
13,314
|
def test_ros_fit():
ros = RandomOverSampler(random_state=RND_SEED)
ros.fit(X, Y)
assert_equal(ros.min_c_, 0)
assert_equal(ros.maj_c_, 1)
assert_equal(ros.stats_c_[0], 3)
assert_equal(ros.stats_c_[1], 7)
|
[
"def",
"test_ros_fit",
"(",
")",
":",
"ros",
"=",
"RandomOverSampler",
"(",
"random_state",
"=",
"RND_SEED",
")",
"ros",
".",
"fit",
"(",
"X",
",",
"Y",
")",
"assert_equal",
"(",
"ros",
".",
"min_c_",
",",
"0",
")",
"assert_equal",
"(",
"ros",
".",
"maj_c_",
",",
"1",
")",
"assert_equal",
"(",
"ros",
".",
"stats_c_",
"[",
"0",
"]",
",",
"3",
")",
"assert_equal",
"(",
"ros",
".",
"stats_c_",
"[",
"1",
"]",
",",
"7",
")"
] |
test the fitting method .
|
train
| false
|
13,316
|
def get_local_ip(target=None):
connect_target = ('4.4.4.2' if (target is None) else target)
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect((connect_target, 80))
local_address = sock.getsockname()[0]
except Exception:
return None
else:
return local_address
|
[
"def",
"get_local_ip",
"(",
"target",
"=",
"None",
")",
":",
"connect_target",
"=",
"(",
"'4.4.4.2'",
"if",
"(",
"target",
"is",
"None",
")",
"else",
"target",
")",
"try",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"sock",
".",
"connect",
"(",
"(",
"connect_target",
",",
"80",
")",
")",
"local_address",
"=",
"sock",
".",
"getsockname",
"(",
")",
"[",
"0",
"]",
"except",
"Exception",
":",
"return",
"None",
"else",
":",
"return",
"local_address"
] |
returns local ip address or none .
|
train
| false
|
13,317
|
def is_editor(request, addon):
return (check_addons_reviewer(request) or (check_personas_reviewer(request) and addon.is_persona()))
|
[
"def",
"is_editor",
"(",
"request",
",",
"addon",
")",
":",
"return",
"(",
"check_addons_reviewer",
"(",
"request",
")",
"or",
"(",
"check_personas_reviewer",
"(",
"request",
")",
"and",
"addon",
".",
"is_persona",
"(",
")",
")",
")"
] |
return true if the user is an addons reviewer .
|
train
| false
|
13,318
|
def longest_contiguous_ones(x):
x = np.ravel(x)
if (len(x) == 0):
return np.array([])
ind = (x == 0).nonzero()[0]
if (len(ind) == 0):
return np.arange(len(x))
if (len(ind) == len(x)):
return np.array([])
y = np.zeros(((len(x) + 2),), x.dtype)
y[1:(-1)] = x
dif = np.diff(y)
up = (dif == 1).nonzero()[0]
dn = (dif == (-1)).nonzero()[0]
i = ((dn - up) == max((dn - up))).nonzero()[0][0]
ind = np.arange(up[i], dn[i])
return ind
|
[
"def",
"longest_contiguous_ones",
"(",
"x",
")",
":",
"x",
"=",
"np",
".",
"ravel",
"(",
"x",
")",
"if",
"(",
"len",
"(",
"x",
")",
"==",
"0",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"ind",
"=",
"(",
"x",
"==",
"0",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"if",
"(",
"len",
"(",
"ind",
")",
"==",
"0",
")",
":",
"return",
"np",
".",
"arange",
"(",
"len",
"(",
"x",
")",
")",
"if",
"(",
"len",
"(",
"ind",
")",
"==",
"len",
"(",
"x",
")",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"]",
")",
"y",
"=",
"np",
".",
"zeros",
"(",
"(",
"(",
"len",
"(",
"x",
")",
"+",
"2",
")",
",",
")",
",",
"x",
".",
"dtype",
")",
"y",
"[",
"1",
":",
"(",
"-",
"1",
")",
"]",
"=",
"x",
"dif",
"=",
"np",
".",
"diff",
"(",
"y",
")",
"up",
"=",
"(",
"dif",
"==",
"1",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"dn",
"=",
"(",
"dif",
"==",
"(",
"-",
"1",
")",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"i",
"=",
"(",
"(",
"dn",
"-",
"up",
")",
"==",
"max",
"(",
"(",
"dn",
"-",
"up",
")",
")",
")",
".",
"nonzero",
"(",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"ind",
"=",
"np",
".",
"arange",
"(",
"up",
"[",
"i",
"]",
",",
"dn",
"[",
"i",
"]",
")",
"return",
"ind"
] |
return the indices of the longest stretch of contiguous ones in *x* .
|
train
| false
|
13,321
|
def edmonds_karp(G, s, t, capacity='capacity', residual=None, value_only=False, cutoff=None):
R = edmonds_karp_impl(G, s, t, capacity, residual, cutoff)
R.graph['algorithm'] = 'edmonds_karp'
return R
|
[
"def",
"edmonds_karp",
"(",
"G",
",",
"s",
",",
"t",
",",
"capacity",
"=",
"'capacity'",
",",
"residual",
"=",
"None",
",",
"value_only",
"=",
"False",
",",
"cutoff",
"=",
"None",
")",
":",
"R",
"=",
"edmonds_karp_impl",
"(",
"G",
",",
"s",
",",
"t",
",",
"capacity",
",",
"residual",
",",
"cutoff",
")",
"R",
".",
"graph",
"[",
"'algorithm'",
"]",
"=",
"'edmonds_karp'",
"return",
"R"
] |
find a maximum single-commodity flow using the edmonds-karp algorithm .
|
train
| false
|
13,322
|
def _approx_fprime_helper(xk, f, epsilon, args=(), f0=None):
if (f0 is None):
f0 = f(*((xk,) + args))
grad = numpy.zeros((len(xk),), float)
ei = numpy.zeros((len(xk),), float)
for k in range(len(xk)):
ei[k] = 1.0
d = (epsilon * ei)
grad[k] = ((f(*(((xk + d),) + args)) - f0) / d[k])
ei[k] = 0.0
return grad
|
[
"def",
"_approx_fprime_helper",
"(",
"xk",
",",
"f",
",",
"epsilon",
",",
"args",
"=",
"(",
")",
",",
"f0",
"=",
"None",
")",
":",
"if",
"(",
"f0",
"is",
"None",
")",
":",
"f0",
"=",
"f",
"(",
"*",
"(",
"(",
"xk",
",",
")",
"+",
"args",
")",
")",
"grad",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"len",
"(",
"xk",
")",
",",
")",
",",
"float",
")",
"ei",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"len",
"(",
"xk",
")",
",",
")",
",",
"float",
")",
"for",
"k",
"in",
"range",
"(",
"len",
"(",
"xk",
")",
")",
":",
"ei",
"[",
"k",
"]",
"=",
"1.0",
"d",
"=",
"(",
"epsilon",
"*",
"ei",
")",
"grad",
"[",
"k",
"]",
"=",
"(",
"(",
"f",
"(",
"*",
"(",
"(",
"(",
"xk",
"+",
"d",
")",
",",
")",
"+",
"args",
")",
")",
"-",
"f0",
")",
"/",
"d",
"[",
"k",
"]",
")",
"ei",
"[",
"k",
"]",
"=",
"0.0",
"return",
"grad"
] |
see approx_fprime .
|
train
| false
|
13,323
|
def filter_pathbase(val):
return os.path.basename((val or u''))
|
[
"def",
"filter_pathbase",
"(",
"val",
")",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"(",
"val",
"or",
"u''",
")",
")"
] |
base name of a path .
|
train
| false
|
13,325
|
def parseNextCommand():
global s3gFile
commandStr = s3gFile.read(1)
if (len(commandStr) == 0):
print 'EOF'
return False
sys.stdout.write((str(lineNumber) + ': '))
command = struct.unpack('B', commandStr)
(parse, disp) = commandTable[command[0]]
if (type(parse) == type('')):
packetLen = struct.calcsize(parse)
packetData = s3gFile.read(packetLen)
if (len(packetData) != packetLen):
raise 'Packet incomplete'
parsed = struct.unpack(parse, packetData)
else:
parsed = parse()
if (type(disp) == type('')):
print (disp % parsed)
else:
disp(parsed)
return True
|
[
"def",
"parseNextCommand",
"(",
")",
":",
"global",
"s3gFile",
"commandStr",
"=",
"s3gFile",
".",
"read",
"(",
"1",
")",
"if",
"(",
"len",
"(",
"commandStr",
")",
"==",
"0",
")",
":",
"print",
"'EOF'",
"return",
"False",
"sys",
".",
"stdout",
".",
"write",
"(",
"(",
"str",
"(",
"lineNumber",
")",
"+",
"': '",
")",
")",
"command",
"=",
"struct",
".",
"unpack",
"(",
"'B'",
",",
"commandStr",
")",
"(",
"parse",
",",
"disp",
")",
"=",
"commandTable",
"[",
"command",
"[",
"0",
"]",
"]",
"if",
"(",
"type",
"(",
"parse",
")",
"==",
"type",
"(",
"''",
")",
")",
":",
"packetLen",
"=",
"struct",
".",
"calcsize",
"(",
"parse",
")",
"packetData",
"=",
"s3gFile",
".",
"read",
"(",
"packetLen",
")",
"if",
"(",
"len",
"(",
"packetData",
")",
"!=",
"packetLen",
")",
":",
"raise",
"'Packet incomplete'",
"parsed",
"=",
"struct",
".",
"unpack",
"(",
"parse",
",",
"packetData",
")",
"else",
":",
"parsed",
"=",
"parse",
"(",
")",
"if",
"(",
"type",
"(",
"disp",
")",
"==",
"type",
"(",
"''",
")",
")",
":",
"print",
"(",
"disp",
"%",
"parsed",
")",
"else",
":",
"disp",
"(",
"parsed",
")",
"return",
"True"
] |
parse and handle the next command .
|
train
| false
|
13,326
|
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, httplib=False, subprocess=True, sys=False, aggressive=True, Event=False, builtins=True, signal=True):
(_warnings, first_time) = _check_repatching(**locals())
if ((not _warnings) and (not first_time)):
return
if os:
patch_os()
if time:
patch_time()
if thread:
patch_thread(Event=Event, _warnings=_warnings)
if sys:
patch_sys()
if socket:
patch_socket(dns=dns, aggressive=aggressive)
if select:
patch_select(aggressive=aggressive)
if ssl:
patch_ssl()
if httplib:
raise ValueError('gevent.httplib is no longer provided, httplib must be False')
if subprocess:
patch_subprocess()
if builtins:
patch_builtins()
if signal:
if (not os):
_queue_warning('Patching signal but not os will result in SIGCHLD handlers installed after this not being called and os.waitpid may not function correctly if gevent.subprocess is used. This may raise an error in the future.', _warnings)
patch_signal()
_process_warnings(_warnings)
|
[
"def",
"patch_all",
"(",
"socket",
"=",
"True",
",",
"dns",
"=",
"True",
",",
"time",
"=",
"True",
",",
"select",
"=",
"True",
",",
"thread",
"=",
"True",
",",
"os",
"=",
"True",
",",
"ssl",
"=",
"True",
",",
"httplib",
"=",
"False",
",",
"subprocess",
"=",
"True",
",",
"sys",
"=",
"False",
",",
"aggressive",
"=",
"True",
",",
"Event",
"=",
"False",
",",
"builtins",
"=",
"True",
",",
"signal",
"=",
"True",
")",
":",
"(",
"_warnings",
",",
"first_time",
")",
"=",
"_check_repatching",
"(",
"**",
"locals",
"(",
")",
")",
"if",
"(",
"(",
"not",
"_warnings",
")",
"and",
"(",
"not",
"first_time",
")",
")",
":",
"return",
"if",
"os",
":",
"patch_os",
"(",
")",
"if",
"time",
":",
"patch_time",
"(",
")",
"if",
"thread",
":",
"patch_thread",
"(",
"Event",
"=",
"Event",
",",
"_warnings",
"=",
"_warnings",
")",
"if",
"sys",
":",
"patch_sys",
"(",
")",
"if",
"socket",
":",
"patch_socket",
"(",
"dns",
"=",
"dns",
",",
"aggressive",
"=",
"aggressive",
")",
"if",
"select",
":",
"patch_select",
"(",
"aggressive",
"=",
"aggressive",
")",
"if",
"ssl",
":",
"patch_ssl",
"(",
")",
"if",
"httplib",
":",
"raise",
"ValueError",
"(",
"'gevent.httplib is no longer provided, httplib must be False'",
")",
"if",
"subprocess",
":",
"patch_subprocess",
"(",
")",
"if",
"builtins",
":",
"patch_builtins",
"(",
")",
"if",
"signal",
":",
"if",
"(",
"not",
"os",
")",
":",
"_queue_warning",
"(",
"'Patching signal but not os will result in SIGCHLD handlers installed after this not being called and os.waitpid may not function correctly if gevent.subprocess is used. This may raise an error in the future.'",
",",
"_warnings",
")",
"patch_signal",
"(",
")",
"_process_warnings",
"(",
"_warnings",
")"
] |
do all of the default monkey patching .
|
train
| false
|
13,327
|
def import_main_path(main_path):
_fixup_main_from_path(main_path)
|
[
"def",
"import_main_path",
"(",
"main_path",
")",
":",
"_fixup_main_from_path",
"(",
"main_path",
")"
] |
set sys .
|
train
| false
|
13,328
|
def get_checksum(content, encoding='utf8', block_size=8192):
md = hashlib.md5()
def safe_update(txt):
try:
md.update(txt)
except UnicodeEncodeError:
md.update(txt.encode(encoding))
try:
isfile = os.path.isfile(content)
except TypeError:
isfile = False
if isfile:
with open(content, 'rb') as ff:
txt = ff.read(block_size)
while txt:
safe_update(txt)
txt = ff.read(block_size)
elif hasattr(content, 'read'):
pos = content.tell()
content.seek(0)
txt = content.read(block_size)
while txt:
safe_update(txt)
txt = content.read(block_size)
content.seek(pos)
else:
safe_update(content)
return md.hexdigest()
|
[
"def",
"get_checksum",
"(",
"content",
",",
"encoding",
"=",
"'utf8'",
",",
"block_size",
"=",
"8192",
")",
":",
"md",
"=",
"hashlib",
".",
"md5",
"(",
")",
"def",
"safe_update",
"(",
"txt",
")",
":",
"try",
":",
"md",
".",
"update",
"(",
"txt",
")",
"except",
"UnicodeEncodeError",
":",
"md",
".",
"update",
"(",
"txt",
".",
"encode",
"(",
"encoding",
")",
")",
"try",
":",
"isfile",
"=",
"os",
".",
"path",
".",
"isfile",
"(",
"content",
")",
"except",
"TypeError",
":",
"isfile",
"=",
"False",
"if",
"isfile",
":",
"with",
"open",
"(",
"content",
",",
"'rb'",
")",
"as",
"ff",
":",
"txt",
"=",
"ff",
".",
"read",
"(",
"block_size",
")",
"while",
"txt",
":",
"safe_update",
"(",
"txt",
")",
"txt",
"=",
"ff",
".",
"read",
"(",
"block_size",
")",
"elif",
"hasattr",
"(",
"content",
",",
"'read'",
")",
":",
"pos",
"=",
"content",
".",
"tell",
"(",
")",
"content",
".",
"seek",
"(",
"0",
")",
"txt",
"=",
"content",
".",
"read",
"(",
"block_size",
")",
"while",
"txt",
":",
"safe_update",
"(",
"txt",
")",
"txt",
"=",
"content",
".",
"read",
"(",
"block_size",
")",
"content",
".",
"seek",
"(",
"pos",
")",
"else",
":",
"safe_update",
"(",
"content",
")",
"return",
"md",
".",
"hexdigest",
"(",
")"
] |
returns the md5 checksum in hex for the given content .
|
train
| true
|
13,329
|
def test_SAMPHubServer_run():
hub = SAMPHubServer(web_profile=False, mode='multiple', pool_size=1)
hub.start()
time.sleep(1)
hub.stop()
|
[
"def",
"test_SAMPHubServer_run",
"(",
")",
":",
"hub",
"=",
"SAMPHubServer",
"(",
"web_profile",
"=",
"False",
",",
"mode",
"=",
"'multiple'",
",",
"pool_size",
"=",
"1",
")",
"hub",
".",
"start",
"(",
")",
"time",
".",
"sleep",
"(",
"1",
")",
"hub",
".",
"stop",
"(",
")"
] |
test that samphub can be run .
|
train
| false
|
13,332
|
def get_relative_path_to_pack(pack_ref, file_path):
pack_base_path = get_pack_base_path(pack_name=pack_ref)
if (not os.path.isabs(file_path)):
return file_path
common_prefix = os.path.commonprefix([pack_base_path, file_path])
if (common_prefix != pack_base_path):
raise ValueError('file_path is not located inside the pack directory')
relative_path = os.path.relpath(file_path, common_prefix)
return relative_path
|
[
"def",
"get_relative_path_to_pack",
"(",
"pack_ref",
",",
"file_path",
")",
":",
"pack_base_path",
"=",
"get_pack_base_path",
"(",
"pack_name",
"=",
"pack_ref",
")",
"if",
"(",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"file_path",
")",
")",
":",
"return",
"file_path",
"common_prefix",
"=",
"os",
".",
"path",
".",
"commonprefix",
"(",
"[",
"pack_base_path",
",",
"file_path",
"]",
")",
"if",
"(",
"common_prefix",
"!=",
"pack_base_path",
")",
":",
"raise",
"ValueError",
"(",
"'file_path is not located inside the pack directory'",
")",
"relative_path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"file_path",
",",
"common_prefix",
")",
"return",
"relative_path"
] |
retrieve a file path which is relative to the provided pack directory .
|
train
| false
|
13,333
|
def inferno():
rc(u'image', cmap=u'inferno')
im = gci()
if (im is not None):
im.set_cmap(cm.inferno)
|
[
"def",
"inferno",
"(",
")",
":",
"rc",
"(",
"u'image'",
",",
"cmap",
"=",
"u'inferno'",
")",
"im",
"=",
"gci",
"(",
")",
"if",
"(",
"im",
"is",
"not",
"None",
")",
":",
"im",
".",
"set_cmap",
"(",
"cm",
".",
"inferno",
")"
] |
set the default colormap to inferno and apply to current image if any .
|
train
| false
|
13,335
|
def test_whiten_evoked():
evoked = read_evokeds(ave_fname, condition=0, baseline=(None, 0), proj=True)
cov = read_cov(cov_fname)
picks = pick_types(evoked.info, meg=True, eeg=True, ref_meg=False, exclude='bads')
noise_cov = regularize(cov, evoked.info, grad=0.1, mag=0.1, eeg=0.1, exclude='bads')
evoked_white = whiten_evoked(evoked, noise_cov, picks, diag=True)
whiten_baseline_data = evoked_white.data[picks][:, (evoked.times < 0)]
mean_baseline = np.mean(np.abs(whiten_baseline_data), axis=1)
assert_true(np.all((mean_baseline < 1.0)))
assert_true(np.all((mean_baseline > 0.2)))
cov_bad = pick_channels_cov(cov, include=evoked.ch_names[:10])
assert_raises(RuntimeError, whiten_evoked, evoked, cov_bad, picks)
|
[
"def",
"test_whiten_evoked",
"(",
")",
":",
"evoked",
"=",
"read_evokeds",
"(",
"ave_fname",
",",
"condition",
"=",
"0",
",",
"baseline",
"=",
"(",
"None",
",",
"0",
")",
",",
"proj",
"=",
"True",
")",
"cov",
"=",
"read_cov",
"(",
"cov_fname",
")",
"picks",
"=",
"pick_types",
"(",
"evoked",
".",
"info",
",",
"meg",
"=",
"True",
",",
"eeg",
"=",
"True",
",",
"ref_meg",
"=",
"False",
",",
"exclude",
"=",
"'bads'",
")",
"noise_cov",
"=",
"regularize",
"(",
"cov",
",",
"evoked",
".",
"info",
",",
"grad",
"=",
"0.1",
",",
"mag",
"=",
"0.1",
",",
"eeg",
"=",
"0.1",
",",
"exclude",
"=",
"'bads'",
")",
"evoked_white",
"=",
"whiten_evoked",
"(",
"evoked",
",",
"noise_cov",
",",
"picks",
",",
"diag",
"=",
"True",
")",
"whiten_baseline_data",
"=",
"evoked_white",
".",
"data",
"[",
"picks",
"]",
"[",
":",
",",
"(",
"evoked",
".",
"times",
"<",
"0",
")",
"]",
"mean_baseline",
"=",
"np",
".",
"mean",
"(",
"np",
".",
"abs",
"(",
"whiten_baseline_data",
")",
",",
"axis",
"=",
"1",
")",
"assert_true",
"(",
"np",
".",
"all",
"(",
"(",
"mean_baseline",
"<",
"1.0",
")",
")",
")",
"assert_true",
"(",
"np",
".",
"all",
"(",
"(",
"mean_baseline",
">",
"0.2",
")",
")",
")",
"cov_bad",
"=",
"pick_channels_cov",
"(",
"cov",
",",
"include",
"=",
"evoked",
".",
"ch_names",
"[",
":",
"10",
"]",
")",
"assert_raises",
"(",
"RuntimeError",
",",
"whiten_evoked",
",",
"evoked",
",",
"cov_bad",
",",
"picks",
")"
] |
test whitening of evoked data .
|
train
| false
|
13,336
|
def most_common(items):
counts = {}
for i in items:
counts.setdefault(i, 0)
counts[i] += 1
return max(six.iteritems(counts), key=operator.itemgetter(1))
|
[
"def",
"most_common",
"(",
"items",
")",
":",
"counts",
"=",
"{",
"}",
"for",
"i",
"in",
"items",
":",
"counts",
".",
"setdefault",
"(",
"i",
",",
"0",
")",
"counts",
"[",
"i",
"]",
"+=",
"1",
"return",
"max",
"(",
"six",
".",
"iteritems",
"(",
"counts",
")",
",",
"key",
"=",
"operator",
".",
"itemgetter",
"(",
"1",
")",
")"
] |
most common elements occurring more then n times .
|
train
| true
|
13,338
|
def ellip_harm(h2, k2, n, p, s, signm=1, signn=1):
return _ellip_harm(h2, k2, n, p, s, signm, signn)
|
[
"def",
"ellip_harm",
"(",
"h2",
",",
"k2",
",",
"n",
",",
"p",
",",
"s",
",",
"signm",
"=",
"1",
",",
"signn",
"=",
"1",
")",
":",
"return",
"_ellip_harm",
"(",
"h2",
",",
"k2",
",",
"n",
",",
"p",
",",
"s",
",",
"signm",
",",
"signn",
")"
] |
ellipsoidal harmonic functions e^p_n(l) these are also known as lame functions of the first kind .
|
train
| false
|
13,340
|
def finditem(func, seq):
return next((item for item in seq if func(item)))
|
[
"def",
"finditem",
"(",
"func",
",",
"seq",
")",
":",
"return",
"next",
"(",
"(",
"item",
"for",
"item",
"in",
"seq",
"if",
"func",
"(",
"item",
")",
")",
")"
] |
finds and returns first item in iterable for which func is true .
|
train
| false
|
13,342
|
def flatten_fieldsets(fieldsets):
field_names = []
for (name, opts) in fieldsets:
for field in opts[u'fields']:
if (type(field) == tuple):
field_names.extend(field)
else:
field_names.append(field)
return field_names
|
[
"def",
"flatten_fieldsets",
"(",
"fieldsets",
")",
":",
"field_names",
"=",
"[",
"]",
"for",
"(",
"name",
",",
"opts",
")",
"in",
"fieldsets",
":",
"for",
"field",
"in",
"opts",
"[",
"u'fields'",
"]",
":",
"if",
"(",
"type",
"(",
"field",
")",
"==",
"tuple",
")",
":",
"field_names",
".",
"extend",
"(",
"field",
")",
"else",
":",
"field_names",
".",
"append",
"(",
"field",
")",
"return",
"field_names"
] |
returns a list of field names from an admin fieldsets structure .
|
train
| false
|
13,344
|
def _is_deprecated(key):
key = key.lower()
return (key in _deprecated_options)
|
[
"def",
"_is_deprecated",
"(",
"key",
")",
":",
"key",
"=",
"key",
".",
"lower",
"(",
")",
"return",
"(",
"key",
"in",
"_deprecated_options",
")"
] |
returns true if the given option has been deprecated .
|
train
| false
|
13,346
|
def download_from_url(url, filename=None, progress_hook=None):
(temp_filename, headers) = urllib.urlretrieve(url, filename, progress_hook)
return temp_filename
|
[
"def",
"download_from_url",
"(",
"url",
",",
"filename",
"=",
"None",
",",
"progress_hook",
"=",
"None",
")",
":",
"(",
"temp_filename",
",",
"headers",
")",
"=",
"urllib",
".",
"urlretrieve",
"(",
"url",
",",
"filename",
",",
"progress_hook",
")",
"return",
"temp_filename"
] |
downloads a file from an url in the specificed filename .
|
train
| false
|
13,349
|
def put_recon_cache_entry(cache_entry, key, item):
if isinstance(item, dict):
if ((key not in cache_entry) or ((key in cache_entry) and (not isinstance(cache_entry[key], dict)))):
cache_entry[key] = {}
elif ((key in cache_entry) and (item == {})):
cache_entry.pop(key, None)
return
for (k, v) in item.items():
if (v == {}):
cache_entry[key].pop(k, None)
else:
cache_entry[key][k] = v
else:
cache_entry[key] = item
|
[
"def",
"put_recon_cache_entry",
"(",
"cache_entry",
",",
"key",
",",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
":",
"if",
"(",
"(",
"key",
"not",
"in",
"cache_entry",
")",
"or",
"(",
"(",
"key",
"in",
"cache_entry",
")",
"and",
"(",
"not",
"isinstance",
"(",
"cache_entry",
"[",
"key",
"]",
",",
"dict",
")",
")",
")",
")",
":",
"cache_entry",
"[",
"key",
"]",
"=",
"{",
"}",
"elif",
"(",
"(",
"key",
"in",
"cache_entry",
")",
"and",
"(",
"item",
"==",
"{",
"}",
")",
")",
":",
"cache_entry",
".",
"pop",
"(",
"key",
",",
"None",
")",
"return",
"for",
"(",
"k",
",",
"v",
")",
"in",
"item",
".",
"items",
"(",
")",
":",
"if",
"(",
"v",
"==",
"{",
"}",
")",
":",
"cache_entry",
"[",
"key",
"]",
".",
"pop",
"(",
"k",
",",
"None",
")",
"else",
":",
"cache_entry",
"[",
"key",
"]",
"[",
"k",
"]",
"=",
"v",
"else",
":",
"cache_entry",
"[",
"key",
"]",
"=",
"item"
] |
function that will check if item is a dict .
|
train
| false
|
13,350
|
def movmean(x, windowsize=3, lag='lagged'):
return movmoment(x, 1, windowsize=windowsize, lag=lag)
|
[
"def",
"movmean",
"(",
"x",
",",
"windowsize",
"=",
"3",
",",
"lag",
"=",
"'lagged'",
")",
":",
"return",
"movmoment",
"(",
"x",
",",
"1",
",",
"windowsize",
"=",
"windowsize",
",",
"lag",
"=",
"lag",
")"
] |
moving window mean parameters x : array time series data windsize : int window size lag : lagged .
|
train
| false
|
13,352
|
def aix_path_join(path_one, path_two):
if path_one.endswith('/'):
path_one = path_one.rstrip('/')
if path_two.startswith('/'):
path_two = path_two.lstrip('/')
final_path = ((path_one + '/') + path_two)
return final_path
|
[
"def",
"aix_path_join",
"(",
"path_one",
",",
"path_two",
")",
":",
"if",
"path_one",
".",
"endswith",
"(",
"'/'",
")",
":",
"path_one",
"=",
"path_one",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"path_two",
".",
"startswith",
"(",
"'/'",
")",
":",
"path_two",
"=",
"path_two",
".",
"lstrip",
"(",
"'/'",
")",
"final_path",
"=",
"(",
"(",
"path_one",
"+",
"'/'",
")",
"+",
"path_two",
")",
"return",
"final_path"
] |
ensures file path is built correctly for remote unix system .
|
train
| false
|
13,354
|
@task(default_retry_delay=settings.CREDIT_TASK_DEFAULT_RETRY_DELAY, max_retries=settings.CREDIT_TASK_MAX_RETRIES)
def update_credit_course_requirements(course_id):
try:
course_key = CourseKey.from_string(course_id)
is_credit_course = CreditCourse.is_credit_course(course_key)
if is_credit_course:
requirements = _get_course_credit_requirements(course_key)
set_credit_requirements(course_key, requirements)
except (InvalidKeyError, ItemNotFoundError, InvalidCreditRequirements) as exc:
LOGGER.error('Error on adding the requirements for course %s - %s', course_id, unicode(exc))
raise update_credit_course_requirements.retry(args=[course_id], exc=exc)
else:
LOGGER.info('Requirements added for course %s', course_id)
|
[
"@",
"task",
"(",
"default_retry_delay",
"=",
"settings",
".",
"CREDIT_TASK_DEFAULT_RETRY_DELAY",
",",
"max_retries",
"=",
"settings",
".",
"CREDIT_TASK_MAX_RETRIES",
")",
"def",
"update_credit_course_requirements",
"(",
"course_id",
")",
":",
"try",
":",
"course_key",
"=",
"CourseKey",
".",
"from_string",
"(",
"course_id",
")",
"is_credit_course",
"=",
"CreditCourse",
".",
"is_credit_course",
"(",
"course_key",
")",
"if",
"is_credit_course",
":",
"requirements",
"=",
"_get_course_credit_requirements",
"(",
"course_key",
")",
"set_credit_requirements",
"(",
"course_key",
",",
"requirements",
")",
"except",
"(",
"InvalidKeyError",
",",
"ItemNotFoundError",
",",
"InvalidCreditRequirements",
")",
"as",
"exc",
":",
"LOGGER",
".",
"error",
"(",
"'Error on adding the requirements for course %s - %s'",
",",
"course_id",
",",
"unicode",
"(",
"exc",
")",
")",
"raise",
"update_credit_course_requirements",
".",
"retry",
"(",
"args",
"=",
"[",
"course_id",
"]",
",",
"exc",
"=",
"exc",
")",
"else",
":",
"LOGGER",
".",
"info",
"(",
"'Requirements added for course %s'",
",",
"course_id",
")"
] |
updates course requirements table for a course .
|
train
| false
|
13,356
|
def vboxcmd():
return salt.utils.which('VBoxManage')
|
[
"def",
"vboxcmd",
"(",
")",
":",
"return",
"salt",
".",
"utils",
".",
"which",
"(",
"'VBoxManage'",
")"
] |
return the location of the vboxmanage command cli example: .
|
train
| false
|
13,357
|
def lang_altertrust(cursor, lang, trust):
query = 'UPDATE pg_language SET lanpltrusted = %s WHERE lanname=%s'
cursor.execute(query, (trust, lang))
return True
|
[
"def",
"lang_altertrust",
"(",
"cursor",
",",
"lang",
",",
"trust",
")",
":",
"query",
"=",
"'UPDATE pg_language SET lanpltrusted = %s WHERE lanname=%s'",
"cursor",
".",
"execute",
"(",
"query",
",",
"(",
"trust",
",",
"lang",
")",
")",
"return",
"True"
] |
changes if language is trusted for db .
|
train
| false
|
13,358
|
def HashEntity(entity):
return hashlib.sha1(entity.Encode()).digest()
|
[
"def",
"HashEntity",
"(",
"entity",
")",
":",
"return",
"hashlib",
".",
"sha1",
"(",
"entity",
".",
"Encode",
"(",
")",
")",
".",
"digest",
"(",
")"
] |
return a very-likely-unique hash of an entity .
|
train
| false
|
13,359
|
def iterCombinations(tup):
if (len(tup) == 1):
for i in range(tup[0]):
(yield (i,))
elif (len(tup) > 1):
for prefix in iterCombinations(tup[:(-1)]):
for i in range(tup[(-1)]):
(yield tuple((list(prefix) + [i])))
|
[
"def",
"iterCombinations",
"(",
"tup",
")",
":",
"if",
"(",
"len",
"(",
"tup",
")",
"==",
"1",
")",
":",
"for",
"i",
"in",
"range",
"(",
"tup",
"[",
"0",
"]",
")",
":",
"(",
"yield",
"(",
"i",
",",
")",
")",
"elif",
"(",
"len",
"(",
"tup",
")",
">",
"1",
")",
":",
"for",
"prefix",
"in",
"iterCombinations",
"(",
"tup",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
":",
"for",
"i",
"in",
"range",
"(",
"tup",
"[",
"(",
"-",
"1",
")",
"]",
")",
":",
"(",
"yield",
"tuple",
"(",
"(",
"list",
"(",
"prefix",
")",
"+",
"[",
"i",
"]",
")",
")",
")"
] |
all possible of integer tuples of the same dimension than tup .
|
train
| false
|
13,360
|
def getNewRepository():
return ExportRepository()
|
[
"def",
"getNewRepository",
"(",
")",
":",
"return",
"ExportRepository",
"(",
")"
] |
get the repository constructor .
|
train
| false
|
13,361
|
@shared_constructor
def generic_constructor(value, name=None, strict=False, allow_downcast=None):
return SharedVariable(type=generic, value=value, name=name, strict=strict, allow_downcast=allow_downcast)
|
[
"@",
"shared_constructor",
"def",
"generic_constructor",
"(",
"value",
",",
"name",
"=",
"None",
",",
"strict",
"=",
"False",
",",
"allow_downcast",
"=",
"None",
")",
":",
"return",
"SharedVariable",
"(",
"type",
"=",
"generic",
",",
"value",
"=",
"value",
",",
"name",
"=",
"name",
",",
"strict",
"=",
"strict",
",",
"allow_downcast",
"=",
"allow_downcast",
")"
] |
sharedvariable constructor .
|
train
| false
|
13,362
|
def check_fname(fname, filetype, endings, endings_err=()):
if ((len(endings_err) > 0) and (not fname.endswith(endings_err))):
print_endings = ' or '.join([', '.join(endings_err[:(-1)]), endings_err[(-1)]])
raise IOError(('The filename (%s) for file type %s must end with %s' % (fname, filetype, print_endings)))
print_endings = ' or '.join([', '.join(endings[:(-1)]), endings[(-1)]])
if (not fname.endswith(endings)):
warn(('This filename (%s) does not conform to MNE naming conventions. All %s files should end with %s' % (fname, filetype, print_endings)))
|
[
"def",
"check_fname",
"(",
"fname",
",",
"filetype",
",",
"endings",
",",
"endings_err",
"=",
"(",
")",
")",
":",
"if",
"(",
"(",
"len",
"(",
"endings_err",
")",
">",
"0",
")",
"and",
"(",
"not",
"fname",
".",
"endswith",
"(",
"endings_err",
")",
")",
")",
":",
"print_endings",
"=",
"' or '",
".",
"join",
"(",
"[",
"', '",
".",
"join",
"(",
"endings_err",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
",",
"endings_err",
"[",
"(",
"-",
"1",
")",
"]",
"]",
")",
"raise",
"IOError",
"(",
"(",
"'The filename (%s) for file type %s must end with %s'",
"%",
"(",
"fname",
",",
"filetype",
",",
"print_endings",
")",
")",
")",
"print_endings",
"=",
"' or '",
".",
"join",
"(",
"[",
"', '",
".",
"join",
"(",
"endings",
"[",
":",
"(",
"-",
"1",
")",
"]",
")",
",",
"endings",
"[",
"(",
"-",
"1",
")",
"]",
"]",
")",
"if",
"(",
"not",
"fname",
".",
"endswith",
"(",
"endings",
")",
")",
":",
"warn",
"(",
"(",
"'This filename (%s) does not conform to MNE naming conventions. All %s files should end with %s'",
"%",
"(",
"fname",
",",
"filetype",
",",
"print_endings",
")",
")",
")"
] |
enforce mne filename conventions .
|
train
| false
|
13,364
|
def service_get_by_host_and_topic(context, host, topic):
return IMPL.service_get_by_host_and_topic(context, host, topic)
|
[
"def",
"service_get_by_host_and_topic",
"(",
"context",
",",
"host",
",",
"topic",
")",
":",
"return",
"IMPL",
".",
"service_get_by_host_and_topic",
"(",
"context",
",",
"host",
",",
"topic",
")"
] |
get a service by hostname and topic it listens to .
|
train
| false
|
13,365
|
def loadJsonValueFromFile(inputFilePath):
with open(inputFilePath) as fileObj:
value = json.load(fileObj)
return value
|
[
"def",
"loadJsonValueFromFile",
"(",
"inputFilePath",
")",
":",
"with",
"open",
"(",
"inputFilePath",
")",
"as",
"fileObj",
":",
"value",
"=",
"json",
".",
"load",
"(",
"fileObj",
")",
"return",
"value"
] |
loads a json value from a file and converts it to the corresponding python object .
|
train
| true
|
13,366
|
def patient_rheader(r, tabs=[]):
if (r.representation == 'html'):
if (r.record is None):
return None
table = db.patient_patient
rheader_tabs = s3_rheader_tabs(r, tabs)
patient = r.record
if patient.person_id:
name = s3_fullname(patient.person_id)
else:
name = None
if patient.country:
country = table.country.represent(patient.country)
else:
country = None
if patient.hospital_id:
hospital = table.hospital_id.represent(patient.hospital_id)
else:
hospital = None
rheader = DIV(TABLE(TR(TH(('%s: ' % T('Patient'))), name, TH(('%s: ' % COUNTRY)), country), TR(TH(), TH(), TH(('%s: ' % T('Hospital'))), hospital)), rheader_tabs)
return rheader
return None
|
[
"def",
"patient_rheader",
"(",
"r",
",",
"tabs",
"=",
"[",
"]",
")",
":",
"if",
"(",
"r",
".",
"representation",
"==",
"'html'",
")",
":",
"if",
"(",
"r",
".",
"record",
"is",
"None",
")",
":",
"return",
"None",
"table",
"=",
"db",
".",
"patient_patient",
"rheader_tabs",
"=",
"s3_rheader_tabs",
"(",
"r",
",",
"tabs",
")",
"patient",
"=",
"r",
".",
"record",
"if",
"patient",
".",
"person_id",
":",
"name",
"=",
"s3_fullname",
"(",
"patient",
".",
"person_id",
")",
"else",
":",
"name",
"=",
"None",
"if",
"patient",
".",
"country",
":",
"country",
"=",
"table",
".",
"country",
".",
"represent",
"(",
"patient",
".",
"country",
")",
"else",
":",
"country",
"=",
"None",
"if",
"patient",
".",
"hospital_id",
":",
"hospital",
"=",
"table",
".",
"hospital_id",
".",
"represent",
"(",
"patient",
".",
"hospital_id",
")",
"else",
":",
"hospital",
"=",
"None",
"rheader",
"=",
"DIV",
"(",
"TABLE",
"(",
"TR",
"(",
"TH",
"(",
"(",
"'%s: '",
"%",
"T",
"(",
"'Patient'",
")",
")",
")",
",",
"name",
",",
"TH",
"(",
"(",
"'%s: '",
"%",
"COUNTRY",
")",
")",
",",
"country",
")",
",",
"TR",
"(",
"TH",
"(",
")",
",",
"TH",
"(",
")",
",",
"TH",
"(",
"(",
"'%s: '",
"%",
"T",
"(",
"'Hospital'",
")",
")",
")",
",",
"hospital",
")",
")",
",",
"rheader_tabs",
")",
"return",
"rheader",
"return",
"None"
] |
resource page header .
|
train
| false
|
13,368
|
@core_helper
def roles_translated():
return authz.roles_trans()
|
[
"@",
"core_helper",
"def",
"roles_translated",
"(",
")",
":",
"return",
"authz",
".",
"roles_trans",
"(",
")"
] |
return a dict of available roles with their translations .
|
train
| false
|
13,369
|
def carmichael_of_ppower(pp):
(p, a) = pp
if ((p == 2) and (a > 2)):
return (2 ** (a - 2))
else:
return ((p - 1) * (p ** (a - 1)))
|
[
"def",
"carmichael_of_ppower",
"(",
"pp",
")",
":",
"(",
"p",
",",
"a",
")",
"=",
"pp",
"if",
"(",
"(",
"p",
"==",
"2",
")",
"and",
"(",
"a",
">",
"2",
")",
")",
":",
"return",
"(",
"2",
"**",
"(",
"a",
"-",
"2",
")",
")",
"else",
":",
"return",
"(",
"(",
"p",
"-",
"1",
")",
"*",
"(",
"p",
"**",
"(",
"a",
"-",
"1",
")",
")",
")"
] |
carmichael function of the given power of the given prime .
|
train
| true
|
13,370
|
def config_value(option):
return option_list[option]
|
[
"def",
"config_value",
"(",
"option",
")",
":",
"return",
"option_list",
"[",
"option",
"]"
] |
get a flask-security configuration value .
|
train
| false
|
13,371
|
def modularity_spectrum(G):
from scipy.linalg import eigvals
if G.is_directed():
return eigvals(nx.directed_modularity_matrix(G))
else:
return eigvals(nx.modularity_matrix(G))
|
[
"def",
"modularity_spectrum",
"(",
"G",
")",
":",
"from",
"scipy",
".",
"linalg",
"import",
"eigvals",
"if",
"G",
".",
"is_directed",
"(",
")",
":",
"return",
"eigvals",
"(",
"nx",
".",
"directed_modularity_matrix",
"(",
"G",
")",
")",
"else",
":",
"return",
"eigvals",
"(",
"nx",
".",
"modularity_matrix",
"(",
"G",
")",
")"
] |
return eigenvalues of the modularity matrix of g .
|
train
| false
|
13,372
|
def parse_labels_string(header, labels_str):
if (header in SPACE_SEPARATED_LABEL_HEADERS):
sep = ' '
else:
sep = ','
labels = labels_str.strip().split(sep)
return set([l.strip() for l in labels if l.strip()])
|
[
"def",
"parse_labels_string",
"(",
"header",
",",
"labels_str",
")",
":",
"if",
"(",
"header",
"in",
"SPACE_SEPARATED_LABEL_HEADERS",
")",
":",
"sep",
"=",
"' '",
"else",
":",
"sep",
"=",
"','",
"labels",
"=",
"labels_str",
".",
"strip",
"(",
")",
".",
"split",
"(",
"sep",
")",
"return",
"set",
"(",
"[",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"labels",
"if",
"l",
".",
"strip",
"(",
")",
"]",
")"
] |
parses a string into a set of labels .
|
train
| false
|
13,373
|
def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw):
fig = figure(**fig_kw)
axs = fig.subplots(nrows=nrows, ncols=ncols, sharex=sharex, sharey=sharey, squeeze=squeeze, subplot_kw=subplot_kw, gridspec_kw=gridspec_kw)
return (fig, axs)
|
[
"def",
"subplots",
"(",
"nrows",
"=",
"1",
",",
"ncols",
"=",
"1",
",",
"sharex",
"=",
"False",
",",
"sharey",
"=",
"False",
",",
"squeeze",
"=",
"True",
",",
"subplot_kw",
"=",
"None",
",",
"gridspec_kw",
"=",
"None",
",",
"**",
"fig_kw",
")",
":",
"fig",
"=",
"figure",
"(",
"**",
"fig_kw",
")",
"axs",
"=",
"fig",
".",
"subplots",
"(",
"nrows",
"=",
"nrows",
",",
"ncols",
"=",
"ncols",
",",
"sharex",
"=",
"sharex",
",",
"sharey",
"=",
"sharey",
",",
"squeeze",
"=",
"squeeze",
",",
"subplot_kw",
"=",
"subplot_kw",
",",
"gridspec_kw",
"=",
"gridspec_kw",
")",
"return",
"(",
"fig",
",",
"axs",
")"
] |
create a figure and a set of subplots this utility wrapper makes it convenient to create common layouts of subplots .
|
train
| false
|
13,374
|
def aslist(value, flatten=True):
values = aslist_cronly(value)
if (not flatten):
return values
result = []
for value in values:
subvalues = value.split()
result.extend(subvalues)
return result
|
[
"def",
"aslist",
"(",
"value",
",",
"flatten",
"=",
"True",
")",
":",
"values",
"=",
"aslist_cronly",
"(",
"value",
")",
"if",
"(",
"not",
"flatten",
")",
":",
"return",
"values",
"result",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
":",
"subvalues",
"=",
"value",
".",
"split",
"(",
")",
"result",
".",
"extend",
"(",
"subvalues",
")",
"return",
"result"
] |
return a list of strings .
|
train
| false
|
13,376
|
def assert_none(obj, msg=None, values=True):
_msg = ('%r is not None' % obj)
if (obj is not None):
if (msg is None):
msg = _msg
elif (values is True):
msg = ('%s: %s' % (msg, _msg))
_report_failure(msg)
|
[
"def",
"assert_none",
"(",
"obj",
",",
"msg",
"=",
"None",
",",
"values",
"=",
"True",
")",
":",
"_msg",
"=",
"(",
"'%r is not None'",
"%",
"obj",
")",
"if",
"(",
"obj",
"is",
"not",
"None",
")",
":",
"if",
"(",
"msg",
"is",
"None",
")",
":",
"msg",
"=",
"_msg",
"elif",
"(",
"values",
"is",
"True",
")",
":",
"msg",
"=",
"(",
"'%s: %s'",
"%",
"(",
"msg",
",",
"_msg",
")",
")",
"_report_failure",
"(",
"msg",
")"
] |
verify that item is none .
|
train
| false
|
13,377
|
def get_minus_sign_symbol(locale=LC_NUMERIC):
return Locale.parse(locale).number_symbols.get('minusSign', u'-')
|
[
"def",
"get_minus_sign_symbol",
"(",
"locale",
"=",
"LC_NUMERIC",
")",
":",
"return",
"Locale",
".",
"parse",
"(",
"locale",
")",
".",
"number_symbols",
".",
"get",
"(",
"'minusSign'",
",",
"u'-'",
")"
] |
return the plus sign symbol used by the current locale .
|
train
| false
|
13,378
|
def vobj(symb, height):
return '\n'.join(xobj(symb, height))
|
[
"def",
"vobj",
"(",
"symb",
",",
"height",
")",
":",
"return",
"'\\n'",
".",
"join",
"(",
"xobj",
"(",
"symb",
",",
"height",
")",
")"
] |
construct vertical object of a given height see: xobj .
|
train
| false
|
13,379
|
@blueprint.route('/projects/<project>/resources')
def list_resources_by_project(project):
check_authorized_project(project)
return _list_resources(project=project)
|
[
"@",
"blueprint",
".",
"route",
"(",
"'/projects/<project>/resources'",
")",
"def",
"list_resources_by_project",
"(",
"project",
")",
":",
"check_authorized_project",
"(",
"project",
")",
"return",
"_list_resources",
"(",
"project",
"=",
"project",
")"
] |
return a list of resources owned by the project .
|
train
| false
|
13,380
|
def p_exception(p):
val = _make_struct(p[2], p[4], base_cls=TException)
setattr(thrift_stack[(-1)], p[2], val)
_add_thrift_meta('exceptions', val)
|
[
"def",
"p_exception",
"(",
"p",
")",
":",
"val",
"=",
"_make_struct",
"(",
"p",
"[",
"2",
"]",
",",
"p",
"[",
"4",
"]",
",",
"base_cls",
"=",
"TException",
")",
"setattr",
"(",
"thrift_stack",
"[",
"(",
"-",
"1",
")",
"]",
",",
"p",
"[",
"2",
"]",
",",
"val",
")",
"_add_thrift_meta",
"(",
"'exceptions'",
",",
"val",
")"
] |
exception : exception identifier { field_seq } .
|
train
| false
|
13,381
|
def mutualinfo(px, py, pxpy, logbase=2):
if ((not _isproperdist(px)) or (not _isproperdist(py))):
raise ValueError('px or py is not a proper probability distribution')
if ((pxpy != None) and (not _isproperdist(pxpy))):
raise ValueError('pxpy is not a proper joint distribtion')
if (pxpy == None):
pxpy = np.outer(py, px)
return (shannonentropy(px, logbase=logbase) - condentropy(px, py, pxpy, logbase=logbase))
|
[
"def",
"mutualinfo",
"(",
"px",
",",
"py",
",",
"pxpy",
",",
"logbase",
"=",
"2",
")",
":",
"if",
"(",
"(",
"not",
"_isproperdist",
"(",
"px",
")",
")",
"or",
"(",
"not",
"_isproperdist",
"(",
"py",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"'px or py is not a proper probability distribution'",
")",
"if",
"(",
"(",
"pxpy",
"!=",
"None",
")",
"and",
"(",
"not",
"_isproperdist",
"(",
"pxpy",
")",
")",
")",
":",
"raise",
"ValueError",
"(",
"'pxpy is not a proper joint distribtion'",
")",
"if",
"(",
"pxpy",
"==",
"None",
")",
":",
"pxpy",
"=",
"np",
".",
"outer",
"(",
"py",
",",
"px",
")",
"return",
"(",
"shannonentropy",
"(",
"px",
",",
"logbase",
"=",
"logbase",
")",
"-",
"condentropy",
"(",
"px",
",",
"py",
",",
"pxpy",
",",
"logbase",
"=",
"logbase",
")",
")"
] |
returns the mutual information between x and y .
|
train
| false
|
13,382
|
def _dehook(klass, name):
if (not hasattr(klass, ORIG(klass, name))):
raise HookError('Cannot unhook!')
setattr(klass, name, getattr(klass, ORIG(klass, name)))
delattr(klass, PRE(klass, name))
delattr(klass, POST(klass, name))
delattr(klass, ORIG(klass, name))
|
[
"def",
"_dehook",
"(",
"klass",
",",
"name",
")",
":",
"if",
"(",
"not",
"hasattr",
"(",
"klass",
",",
"ORIG",
"(",
"klass",
",",
"name",
")",
")",
")",
":",
"raise",
"HookError",
"(",
"'Cannot unhook!'",
")",
"setattr",
"(",
"klass",
",",
"name",
",",
"getattr",
"(",
"klass",
",",
"ORIG",
"(",
"klass",
",",
"name",
")",
")",
")",
"delattr",
"(",
"klass",
",",
"PRE",
"(",
"klass",
",",
"name",
")",
")",
"delattr",
"(",
"klass",
",",
"POST",
"(",
"klass",
",",
"name",
")",
")",
"delattr",
"(",
"klass",
",",
"ORIG",
"(",
"klass",
",",
"name",
")",
")"
] |
causes a certain method name no longer to be hooked on a class .
|
train
| false
|
13,383
|
@deprecated
def get_urllib_object(uri, timeout, headers=None, verify_ssl=True, data=None):
if (headers is None):
headers = default_headers
else:
tmp = default_headers.copy()
headers = tmp.update(headers)
if (data is not None):
response = requests.post(uri, timeout=timeout, verify=verify_ssl, data=data, headers=headers)
else:
response = requests.get(uri, timeout=timeout, verify=verify_ssl, headers=headers)
return MockHttpResponse(response)
|
[
"@",
"deprecated",
"def",
"get_urllib_object",
"(",
"uri",
",",
"timeout",
",",
"headers",
"=",
"None",
",",
"verify_ssl",
"=",
"True",
",",
"data",
"=",
"None",
")",
":",
"if",
"(",
"headers",
"is",
"None",
")",
":",
"headers",
"=",
"default_headers",
"else",
":",
"tmp",
"=",
"default_headers",
".",
"copy",
"(",
")",
"headers",
"=",
"tmp",
".",
"update",
"(",
"headers",
")",
"if",
"(",
"data",
"is",
"not",
"None",
")",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"uri",
",",
"timeout",
"=",
"timeout",
",",
"verify",
"=",
"verify_ssl",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"else",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"uri",
",",
"timeout",
"=",
"timeout",
",",
"verify",
"=",
"verify_ssl",
",",
"headers",
"=",
"headers",
")",
"return",
"MockHttpResponse",
"(",
"response",
")"
] |
return an httpresponse object for uri and timeout and headers .
|
train
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.