code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def partition_items(count, bin_size):
"""
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But if... | def function[partition_items, parameter[count, bin_size]]:
constant[
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_i... | keyword[def] identifier[partition_items] ( identifier[count] , identifier[bin_size] ):
literal[string]
identifier[num_bins] = identifier[int] ( identifier[math] . identifier[ceil] ( identifier[count] / identifier[float] ( identifier[bin_size] )))
identifier[bins] =[ literal[int] ]* identifier[num_bins]
keyw... | def partition_items(count, bin_size):
"""
Given the total number of items, determine the number of items that
can be added to each bin with a limit on the bin size.
So if you want to partition 11 items into groups of 3, you'll want
three of three and one of two.
>>> partition_items(11, 3)
[3, 3, 3, 2]
But... |
def pickupSearch(self):
"""Pick up the latest search from a saved jobID and monitor it to completion
Parameters:
----------------------------------------------------------------------
retval: nothing
"""
self.__searchJob = self.loadSavedHyperSearchJob(
permWorkDir=self._options["pe... | def function[pickupSearch, parameter[self]]:
constant[Pick up the latest search from a saved jobID and monitor it to completion
Parameters:
----------------------------------------------------------------------
retval: nothing
]
name[self].__searchJob assign[=] call[name[self].lo... | keyword[def] identifier[pickupSearch] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__searchJob] = identifier[self] . identifier[loadSavedHyperSearchJob] (
identifier[permWorkDir] = identifier[self] . identifier[_options] [ literal[string] ],
identifier[outputLabel] = identi... | def pickupSearch(self):
"""Pick up the latest search from a saved jobID and monitor it to completion
Parameters:
----------------------------------------------------------------------
retval: nothing
"""
self.__searchJob = self.loadSavedHyperSearchJob(permWorkDir=self._options['permWorkD... |
def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = (
(self.random_state.rand(no_item_features, no_components) - 0.5)
/ no_compone... | def function[_initialize, parameter[self, no_components, no_item_features, no_user_features]]:
constant[
Initialise internal latent representations.
]
name[self].item_embeddings assign[=] call[binary_operation[binary_operation[call[name[self].random_state.rand, parameter[name[no_item_fea... | keyword[def] identifier[_initialize] ( identifier[self] , identifier[no_components] , identifier[no_item_features] , identifier[no_user_features] ):
literal[string]
identifier[self] . identifier[item_embeddings] =(
( identifier[self] . identifier[random_state] . identifier[rand] (... | def _initialize(self, no_components, no_item_features, no_user_features):
"""
Initialise internal latent representations.
"""
# Initialise item features.
self.item_embeddings = ((self.random_state.rand(no_item_features, no_components) - 0.5) / no_components).astype(np.float32)
self.item_... |
def srv_rec(rdatas):
'''
Validate and parse DNS record data for SRV record(s)
:param rdata: DNS record data
:return: dict w/fields
'''
rschema = OrderedDict((
('prio', int),
('weight', int),
('port', _to_port),
('name', str),
))
return _data2rec_group(rsch... | def function[srv_rec, parameter[rdatas]]:
constant[
Validate and parse DNS record data for SRV record(s)
:param rdata: DNS record data
:return: dict w/fields
]
variable[rschema] assign[=] call[name[OrderedDict], parameter[tuple[[<ast.Tuple object at 0x7da1b1fa2950>, <ast.Tuple object at ... | keyword[def] identifier[srv_rec] ( identifier[rdatas] ):
literal[string]
identifier[rschema] = identifier[OrderedDict] ((
( literal[string] , identifier[int] ),
( literal[string] , identifier[int] ),
( literal[string] , identifier[_to_port] ),
( literal[string] , identifier[str] ),
))
... | def srv_rec(rdatas):
"""
Validate and parse DNS record data for SRV record(s)
:param rdata: DNS record data
:return: dict w/fields
"""
rschema = OrderedDict((('prio', int), ('weight', int), ('port', _to_port), ('name', str)))
return _data2rec_group(rschema, rdatas, 'prio') |
def cluster_setup(nodes, pcsclustername='pcscluster', extra_args=None):
'''
Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option for the \'pcs c... | def function[cluster_setup, parameter[nodes, pcsclustername, extra_args]]:
constant[
Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option fo... | keyword[def] identifier[cluster_setup] ( identifier[nodes] , identifier[pcsclustername] = literal[string] , identifier[extra_args] = keyword[None] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] ]
identifier[cmd] +=[ literal[string] , identifier[pcsclusternam... | def cluster_setup(nodes, pcsclustername='pcscluster', extra_args=None):
"""
Setup pacemaker cluster via pcs command
nodes
a list of nodes which should be set up
pcsclustername
Name of the Pacemaker cluster (default: pcscluster)
extra_args
list of extra option for the 'pcs cl... |
def parse_status_file(status_file,nas_addr):
''' parse openvpn status log
'''
session_users = {}
flag1 = False
flag2 = False
with open(status_file) as stlines:
for line in stlines:
if line.startswith("Common Name"):
flag1 = True
continue
... | def function[parse_status_file, parameter[status_file, nas_addr]]:
constant[ parse openvpn status log
]
variable[session_users] assign[=] dictionary[[], []]
variable[flag1] assign[=] constant[False]
variable[flag2] assign[=] constant[False]
with call[name[open], parameter[nam... | keyword[def] identifier[parse_status_file] ( identifier[status_file] , identifier[nas_addr] ):
literal[string]
identifier[session_users] ={}
identifier[flag1] = keyword[False]
identifier[flag2] = keyword[False]
keyword[with] identifier[open] ( identifier[status_file] ) keyword[as] identi... | def parse_status_file(status_file, nas_addr):
""" parse openvpn status log
"""
session_users = {}
flag1 = False
flag2 = False
with open(status_file) as stlines:
for line in stlines:
if line.startswith('Common Name'):
flag1 = True
continue # de... |
def tune_pair(self, pair):
"""Tune a pair of images."""
self._save_bm_state()
self.pair = pair
self.update_disparity_map() | def function[tune_pair, parameter[self, pair]]:
constant[Tune a pair of images.]
call[name[self]._save_bm_state, parameter[]]
name[self].pair assign[=] name[pair]
call[name[self].update_disparity_map, parameter[]] | keyword[def] identifier[tune_pair] ( identifier[self] , identifier[pair] ):
literal[string]
identifier[self] . identifier[_save_bm_state] ()
identifier[self] . identifier[pair] = identifier[pair]
identifier[self] . identifier[update_disparity_map] () | def tune_pair(self, pair):
"""Tune a pair of images."""
self._save_bm_state()
self.pair = pair
self.update_disparity_map() |
def Verify(self, completely=False):
"""
Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise.
"""
res = super(Block, self).Verify()
if not res:
retur... | def function[Verify, parameter[self, completely]]:
constant[
Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise.
]
variable[res] assign[=] call[call[name[super], param... | keyword[def] identifier[Verify] ( identifier[self] , identifier[completely] = keyword[False] ):
literal[string]
identifier[res] = identifier[super] ( identifier[Block] , identifier[self] ). identifier[Verify] ()
keyword[if] keyword[not] identifier[res] :
keyword[return] key... | def Verify(self, completely=False):
"""
Verify the integrity of the block.
Args:
completely: (Not functional at this time).
Returns:
bool: True if valid. False otherwise.
"""
res = super(Block, self).Verify()
if not res:
return False # depen... |
def open_data(self, url, data=None):
"""Use "data" URL."""
if not isinstance(url, str):
raise URLError('data error: proxy support for data protocol currently not implemented')
# ignore POSTed data
#
# syntax of data URLs:
# dataurl := "data:" [ mediatype ] [... | def function[open_data, parameter[self, url, data]]:
constant[Use "data" URL.]
if <ast.UnaryOp object at 0x7da20c6abe50> begin[:]
<ast.Raise object at 0x7da20c6aa3e0>
<ast.Try object at 0x7da20c6a9f60>
if <ast.UnaryOp object at 0x7da20c6a9ff0> begin[:]
variable[type] ... | keyword[def] identifier[open_data] ( identifier[self] , identifier[url] , identifier[data] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[url] , identifier[str] ):
keyword[raise] identifier[URLError] ( literal[string] )
... | def open_data(self, url, data=None):
"""Use "data" URL."""
if not isinstance(url, str):
raise URLError('data error: proxy support for data protocol currently not implemented') # depends on [control=['if'], data=[]]
# ignore POSTed data
#
# syntax of data URLs:
# dataurl := "data:" [ m... |
def rpcexec(self, payload):
""" Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
"""
log.debug(json.dumps(payload)... | def function[rpcexec, parameter[self, payload]]:
constant[ Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
]
call... | keyword[def] identifier[rpcexec] ( identifier[self] , identifier[payload] ):
literal[string]
identifier[log] . identifier[debug] ( identifier[json] . identifier[dumps] ( identifier[payload] ))
identifier[self] . identifier[ws] . identifier[send] ( identifier[json] . identifier[dumps] ( ide... | def rpcexec(self, payload):
""" Execute a call by sending the payload
:param dict payload: Payload data
:raises ValueError: if the server does not respond in proper JSON format
:raises RPCError: if the server returns an error
"""
log.debug(json.dumps(payload))
se... |
def _parse_bbox_list(bbox_list):
""" Helper method for parsing a list of bounding boxes
"""
if isinstance(bbox_list, BBoxCollection):
return bbox_list.bbox_list, bbox_list.crs
if not isinstance(bbox_list, list) or not bbox_list:
raise ValueError('Expected non-emp... | def function[_parse_bbox_list, parameter[bbox_list]]:
constant[ Helper method for parsing a list of bounding boxes
]
if call[name[isinstance], parameter[name[bbox_list], name[BBoxCollection]]] begin[:]
return[tuple[[<ast.Attribute object at 0x7da1b180d1e0>, <ast.Attribute object at 0x7da... | keyword[def] identifier[_parse_bbox_list] ( identifier[bbox_list] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[bbox_list] , identifier[BBoxCollection] ):
keyword[return] identifier[bbox_list] . identifier[bbox_list] , identifier[bbox_list] . identifier[crs]
... | def _parse_bbox_list(bbox_list):
""" Helper method for parsing a list of bounding boxes
"""
if isinstance(bbox_list, BBoxCollection):
return (bbox_list.bbox_list, bbox_list.crs) # depends on [control=['if'], data=[]]
if not isinstance(bbox_list, list) or not bbox_list:
raise ValueEr... |
def quit(self):
"""
Send LMTP QUIT command, read the server response and disconnect.
"""
self._send('QUIT\r\n')
resp = self._read()
if not resp.startswith('221'):
logger.warning('Unexpected server response at QUIT: ' + resp)
self._socket.close()
... | def function[quit, parameter[self]]:
constant[
Send LMTP QUIT command, read the server response and disconnect.
]
call[name[self]._send, parameter[constant[QUIT
]]]
variable[resp] assign[=] call[name[self]._read, parameter[]]
if <ast.UnaryOp object at 0x7da1b0adbf40> be... | keyword[def] identifier[quit] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_send] ( literal[string] )
identifier[resp] = identifier[self] . identifier[_read] ()
keyword[if] keyword[not] identifier[resp] . identifier[startswith] ( literal[string] ):
... | def quit(self):
"""
Send LMTP QUIT command, read the server response and disconnect.
"""
self._send('QUIT\r\n')
resp = self._read()
if not resp.startswith('221'):
logger.warning('Unexpected server response at QUIT: ' + resp) # depends on [control=['if'], data=[]]
self._sock... |
def installed(name, password, keychain="/Library/Keychains/System.keychain", **kwargs):
'''
Install a p12 certificate file into the macOS keychain
name
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openss... | def function[installed, parameter[name, password, keychain]]:
constant[
Install a p12 certificate file into the macOS keychain
name
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openssl command in the... | keyword[def] identifier[installed] ( identifier[name] , identifier[password] , identifier[keychain] = literal[string] ,** identifier[kwargs] ):
literal[string]
identifier[ret] ={ literal[string] : identifier[name] ,
literal[string] : keyword[True] ,
literal[string] : literal[string] ,
litera... | def installed(name, password, keychain='/Library/Keychains/System.keychain', **kwargs):
"""
Install a p12 certificate file into the macOS keychain
name
The certificate to install
password
The password for the certificate being installed formatted in the way
described for openss... |
def _parse_timestamp(timestamp):
"""
Parse a given timestamp value, raising ValueError if None or Flasey
"""
if timestamp:
try:
return aniso8601.parse_datetime(timestamp)
except AttributeError:
# raised by aniso8601 if raw_timestamp... | def function[_parse_timestamp, parameter[timestamp]]:
constant[
Parse a given timestamp value, raising ValueError if None or Flasey
]
if name[timestamp] begin[:]
<ast.Try object at 0x7da18c4cd090>
<ast.Raise object at 0x7da18c4cf1f0> | keyword[def] identifier[_parse_timestamp] ( identifier[timestamp] ):
literal[string]
keyword[if] identifier[timestamp] :
keyword[try] :
keyword[return] identifier[aniso8601] . identifier[parse_datetime] ( identifier[timestamp] )
keyword[except] identifi... | def _parse_timestamp(timestamp):
"""
Parse a given timestamp value, raising ValueError if None or Flasey
"""
if timestamp:
try:
return aniso8601.parse_datetime(timestamp) # depends on [control=['try'], data=[]]
except AttributeError:
# raised by aniso8601... |
def sed_or_dryrun(*args, **kwargs):
"""
Wrapper around Fabric's contrib.files.sed() to give it a dryrun option.
http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed
"""
dryrun = get_dryrun(kwargs.get('dryrun'))
if 'dryrun' in kwargs:
del kwargs['dryrun']
... | def function[sed_or_dryrun, parameter[]]:
constant[
Wrapper around Fabric's contrib.files.sed() to give it a dryrun option.
http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed
]
variable[dryrun] assign[=] call[name[get_dryrun], parameter[call[name[kwargs].get, p... | keyword[def] identifier[sed_or_dryrun] (* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[dryrun] = identifier[get_dryrun] ( identifier[kwargs] . identifier[get] ( literal[string] ))
keyword[if] literal[string] keyword[in] identifier[kwargs] :
keyword[del] identifier... | def sed_or_dryrun(*args, **kwargs):
"""
Wrapper around Fabric's contrib.files.sed() to give it a dryrun option.
http://docs.fabfile.org/en/0.9.1/api/contrib/files.html#fabric.contrib.files.sed
"""
dryrun = get_dryrun(kwargs.get('dryrun'))
if 'dryrun' in kwargs:
del kwargs['dryrun'] # d... |
def blob(self, nodeid, tag, start=0, end=0xFFFFFFFF):
"""
Blobs are stored in sequential nodes
with increasing index values.
most blobs, like scripts start at index
0, long names start at a specified
offset.
"""
startkey = self.makekey(nodeid, ... | def function[blob, parameter[self, nodeid, tag, start, end]]:
constant[
Blobs are stored in sequential nodes
with increasing index values.
most blobs, like scripts start at index
0, long names start at a specified
offset.
]
variable[startkey] assign[=] c... | keyword[def] identifier[blob] ( identifier[self] , identifier[nodeid] , identifier[tag] , identifier[start] = literal[int] , identifier[end] = literal[int] ):
literal[string]
identifier[startkey] = identifier[self] . identifier[makekey] ( identifier[nodeid] , identifier[tag] , identifier[start] )... | def blob(self, nodeid, tag, start=0, end=4294967295):
"""
Blobs are stored in sequential nodes
with increasing index values.
most blobs, like scripts start at index
0, long names start at a specified
offset.
"""
startkey = self.makekey(nodeid, tag, start)
en... |
def _get_identical_contigs(self, hits_dict):
'''Input is a dict:
key=contig name. Value = set of contigs that contain the key.
Returns a list of sets of contigs that are equivalent'''
equivalent_contigs = []
for qry_name, containing in hits_dict.items():
equi... | def function[_get_identical_contigs, parameter[self, hits_dict]]:
constant[Input is a dict:
key=contig name. Value = set of contigs that contain the key.
Returns a list of sets of contigs that are equivalent]
variable[equivalent_contigs] assign[=] list[[]]
for taget[tuple... | keyword[def] identifier[_get_identical_contigs] ( identifier[self] , identifier[hits_dict] ):
literal[string]
identifier[equivalent_contigs] =[]
keyword[for] identifier[qry_name] , identifier[containing] keyword[in] identifier[hits_dict] . identifier[items] ():
identifier[... | def _get_identical_contigs(self, hits_dict):
"""Input is a dict:
key=contig name. Value = set of contigs that contain the key.
Returns a list of sets of contigs that are equivalent"""
equivalent_contigs = []
for (qry_name, containing) in hits_dict.items():
equivalent = set()
... |
def ux_actions(parser, args):
"""Handle some human triggers actions"""
# cryptorito uses native logging (as aomi should tbh)
normal_fmt = '%(message)s'
if hasattr(args, 'verbose') and args.verbose and args.verbose >= 2:
logging.basicConfig(level=logging.DEBUG)
elif hasattr(args, 'verbose') a... | def function[ux_actions, parameter[parser, args]]:
constant[Handle some human triggers actions]
variable[normal_fmt] assign[=] constant[%(message)s]
if <ast.BoolOp object at 0x7da1b1bee830> begin[:]
call[name[logging].basicConfig, parameter[]]
if compare[name[args].operat... | keyword[def] identifier[ux_actions] ( identifier[parser] , identifier[args] ):
literal[string]
identifier[normal_fmt] = literal[string]
keyword[if] identifier[hasattr] ( identifier[args] , literal[string] ) keyword[and] identifier[args] . identifier[verbose] keyword[and] identifier[args] . i... | def ux_actions(parser, args):
"""Handle some human triggers actions"""
# cryptorito uses native logging (as aomi should tbh)
normal_fmt = '%(message)s'
if hasattr(args, 'verbose') and args.verbose and (args.verbose >= 2):
logging.basicConfig(level=logging.DEBUG) # depends on [control=['if'], da... |
def run(self):
"Run each middleware function on files"
# load files from source directory
files = self.get_files()
# loop through each middleware
for func in self.middleware:
# call each one, ignoring return value
func(files, self)
# store and r... | def function[run, parameter[self]]:
constant[Run each middleware function on files]
variable[files] assign[=] call[name[self].get_files, parameter[]]
for taget[name[func]] in starred[name[self].middleware] begin[:]
call[name[func], parameter[name[files], name[self]]]
call... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[files] = identifier[self] . identifier[get_files] ()
keyword[for] identifier[func] keyword[in] identifier[self] . identifier[middleware] :
identifier[func] ( identifie... | def run(self):
"""Run each middleware function on files"""
# load files from source directory
files = self.get_files()
# loop through each middleware
for func in self.middleware:
# call each one, ignoring return value
func(files, self) # depends on [control=['for'], data=['func']]
... |
def get_usrgos_g_hdrgos(self, hdrgos):
"""Return usrgos under provided hdrgos."""
usrgos_all = set()
if isinstance(hdrgos, str):
hdrgos = [hdrgos]
for hdrgo in hdrgos:
usrgos_cur = self.hdrgo2usrgos.get(hdrgo, None)
if usrgos_cur is not None:
... | def function[get_usrgos_g_hdrgos, parameter[self, hdrgos]]:
constant[Return usrgos under provided hdrgos.]
variable[usrgos_all] assign[=] call[name[set], parameter[]]
if call[name[isinstance], parameter[name[hdrgos], name[str]]] begin[:]
variable[hdrgos] assign[=] list[[<ast.Name... | keyword[def] identifier[get_usrgos_g_hdrgos] ( identifier[self] , identifier[hdrgos] ):
literal[string]
identifier[usrgos_all] = identifier[set] ()
keyword[if] identifier[isinstance] ( identifier[hdrgos] , identifier[str] ):
identifier[hdrgos] =[ identifier[hdrgos] ]
... | def get_usrgos_g_hdrgos(self, hdrgos):
"""Return usrgos under provided hdrgos."""
usrgos_all = set()
if isinstance(hdrgos, str):
hdrgos = [hdrgos] # depends on [control=['if'], data=[]]
for hdrgo in hdrgos:
usrgos_cur = self.hdrgo2usrgos.get(hdrgo, None)
if usrgos_cur is not Non... |
def call_senders(self, routing, clients_list, *args, **kwargs):
"""
Calls senders callbacks
"""
for func, routings, routings_re in self.senders:
call_callback = False
# Message is published globally
if routing is None or (routings is None and routings... | def function[call_senders, parameter[self, routing, clients_list]]:
constant[
Calls senders callbacks
]
for taget[tuple[[<ast.Name object at 0x7da2041daef0>, <ast.Name object at 0x7da2041d8b50>, <ast.Name object at 0x7da2041da560>]]] in starred[name[self].senders] begin[:]
... | keyword[def] identifier[call_senders] ( identifier[self] , identifier[routing] , identifier[clients_list] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[for] identifier[func] , identifier[routings] , identifier[routings_re] keyword[in] identifier[self] . identifier[senders... | def call_senders(self, routing, clients_list, *args, **kwargs):
"""
Calls senders callbacks
"""
for (func, routings, routings_re) in self.senders:
call_callback = False
# Message is published globally
if routing is None or (routings is None and routings_re is None):
... |
def _get_all_ns_packages(self):
"""Return sorted list of all package namespaces"""
nsp = set()
for pkg in self.distribution.namespace_packages or []:
pkg = pkg.split('.')
while pkg:
nsp.add('.'.join(pkg))
pkg.pop()
return sorted(nsp... | def function[_get_all_ns_packages, parameter[self]]:
constant[Return sorted list of all package namespaces]
variable[nsp] assign[=] call[name[set], parameter[]]
for taget[name[pkg]] in starred[<ast.BoolOp object at 0x7da18f811ba0>] begin[:]
variable[pkg] assign[=] call[name[pkg].... | keyword[def] identifier[_get_all_ns_packages] ( identifier[self] ):
literal[string]
identifier[nsp] = identifier[set] ()
keyword[for] identifier[pkg] keyword[in] identifier[self] . identifier[distribution] . identifier[namespace_packages] keyword[or] []:
identifier[pkg] = ... | def _get_all_ns_packages(self):
"""Return sorted list of all package namespaces"""
nsp = set()
for pkg in self.distribution.namespace_packages or []:
pkg = pkg.split('.')
while pkg:
nsp.add('.'.join(pkg))
pkg.pop() # depends on [control=['while'], data=[]] # depends... |
def part(self, *args, **kwargs):
# type: (*Any, **Any) -> Part
"""Retrieve single KE-chain part.
Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`
instance.
If additional `keyword=value` arguments are provided, these ar... | def function[part, parameter[self]]:
constant[Retrieve single KE-chain part.
Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`
instance.
If additional `keyword=value` arguments are provided, these are added to the request param... | keyword[def] identifier[part] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[_parts] = identifier[self] . identifier[parts] (* identifier[args] ,** identifier[kwargs] )
keyword[if] identifier[len] ( identifier[_parts] )== literal[int] :
... | def part(self, *args, **kwargs):
# type: (*Any, **Any) -> Part
'Retrieve single KE-chain part.\n\n Uses the same interface as the :func:`parts` method but returns only a single pykechain :class:`models.Part`\n instance.\n\n If additional `keyword=value` arguments are provided, these are add... |
def is_number(obj):
"""
Helper function to determine numbers
across Python 2.x and 3.x
"""
try:
from numbers import Number
except ImportError:
from operator import isNumberType
return isNumberType(obj)
else:
return isinstance(obj, Number) | def function[is_number, parameter[obj]]:
constant[
Helper function to determine numbers
across Python 2.x and 3.x
]
<ast.Try object at 0x7da18bc71630> | keyword[def] identifier[is_number] ( identifier[obj] ):
literal[string]
keyword[try] :
keyword[from] identifier[numbers] keyword[import] identifier[Number]
keyword[except] identifier[ImportError] :
keyword[from] identifier[operator] keyword[import] identifier[isNumberType]
... | def is_number(obj):
"""
Helper function to determine numbers
across Python 2.x and 3.x
"""
try:
from numbers import Number # depends on [control=['try'], data=[]]
except ImportError:
from operator import isNumberType
return isNumberType(obj) # depends on [control=['exce... |
def encode(self, value):
"""
Return a bytestring representation of the value
"""
if isinstance(value, Token):
return b(value.value)
if isinstance(value, bytes):
return value
elif isinstance(value, (int, long)):
value = b(str(val... | def function[encode, parameter[self, value]]:
constant[
Return a bytestring representation of the value
]
if call[name[isinstance], parameter[name[value], name[Token]]] begin[:]
return[call[name[b], parameter[name[value].value]]]
if call[name[isinstance], parameter[name[v... | keyword[def] identifier[encode] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[value] , identifier[Token] ):
keyword[return] identifier[b] ( identifier[value] . identifier[value] )
keyword[if] identifier[isinstance]... | def encode(self, value):
"""
Return a bytestring representation of the value
"""
if isinstance(value, Token):
return b(value.value) # depends on [control=['if'], data=[]]
if isinstance(value, bytes):
return value # depends on [control=['if'], data=[]]
elif isinstance(va... |
def validateDtdFinal(self, ctxt):
"""Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible values matches
one ... | def function[validateDtdFinal, parameter[self, ctxt]]:
constant[Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible va... | keyword[def] identifier[validateDtdFinal] ( identifier[self] , identifier[ctxt] ):
literal[string]
keyword[if] identifier[ctxt] keyword[is] keyword[None] : identifier[ctxt__o] = keyword[None]
keyword[else] : identifier[ctxt__o] = identifier[ctxt] . identifier[_o]
identifier[r... | def validateDtdFinal(self, ctxt):
"""Does the final step for the dtds validation once all the
subsets have been parsed basically it does the following
checks described by the XML Rec - check that ENTITY and
ENTITIES type attributes default or possible values matches
one of t... |
def call_closers(self, client, clients_list):
"""
Calls closers callbacks
"""
for func in self.closers:
func(client, clients_list) | def function[call_closers, parameter[self, client, clients_list]]:
constant[
Calls closers callbacks
]
for taget[name[func]] in starred[name[self].closers] begin[:]
call[name[func], parameter[name[client], name[clients_list]]] | keyword[def] identifier[call_closers] ( identifier[self] , identifier[client] , identifier[clients_list] ):
literal[string]
keyword[for] identifier[func] keyword[in] identifier[self] . identifier[closers] :
identifier[func] ( identifier[client] , identifier[clients_list] ) | def call_closers(self, client, clients_list):
"""
Calls closers callbacks
"""
for func in self.closers:
func(client, clients_list) # depends on [control=['for'], data=['func']] |
def paraminfo(param="", short=False):
""" Returns detailed information for the numbered parameter.
Further information is available in the tutorial.
Unlike params() this function doesn't deal well with *
It only takes one parameter at a time and returns the desc
"""
## If the short... | def function[paraminfo, parameter[param, short]]:
constant[ Returns detailed information for the numbered parameter.
Further information is available in the tutorial.
Unlike params() this function doesn't deal well with *
It only takes one parameter at a time and returns the desc
]
... | keyword[def] identifier[paraminfo] ( identifier[param] = literal[string] , identifier[short] = keyword[False] ):
literal[string]
keyword[if] identifier[short] :
identifier[desc] = literal[int]
keyword[else] :
identifier[desc] = literal[int]
keyword[try] :
... | def paraminfo(param='', short=False):
""" Returns detailed information for the numbered parameter.
Further information is available in the tutorial.
Unlike params() this function doesn't deal well with *
It only takes one parameter at a time and returns the desc
"""
## If the short ... |
def show(self):
"""
Prints the content of this method to stdout.
This will print the method signature and the decompiled code.
"""
args, ret = self.method.get_descriptor()[1:].split(")")
if self.code:
# We patch the descriptor here and add the registers, if c... | def function[show, parameter[self]]:
constant[
Prints the content of this method to stdout.
This will print the method signature and the decompiled code.
]
<ast.Tuple object at 0x7da2041da3b0> assign[=] call[call[call[name[self].method.get_descriptor, parameter[]]][<ast.Slice ob... | keyword[def] identifier[show] ( identifier[self] ):
literal[string]
identifier[args] , identifier[ret] = identifier[self] . identifier[method] . identifier[get_descriptor] ()[ literal[int] :]. identifier[split] ( literal[string] )
keyword[if] identifier[self] . identifier[code] :
... | def show(self):
"""
Prints the content of this method to stdout.
This will print the method signature and the decompiled code.
"""
(args, ret) = self.method.get_descriptor()[1:].split(')')
if self.code:
# We patch the descriptor here and add the registers, if code is availab... |
def check_folders(name):
"""Only checks and asks questions. Nothing is written to disk."""
if os.getcwd().endswith('analyses'):
correct = input('You are in an analyses folder. This will create '
'another analyses folder inside this one. Do '
'you want to ... | def function[check_folders, parameter[name]]:
constant[Only checks and asks questions. Nothing is written to disk.]
if call[call[name[os].getcwd, parameter[]].endswith, parameter[constant[analyses]]] begin[:]
variable[correct] assign[=] call[name[input], parameter[constant[You are in an ... | keyword[def] identifier[check_folders] ( identifier[name] ):
literal[string]
keyword[if] identifier[os] . identifier[getcwd] (). identifier[endswith] ( literal[string] ):
identifier[correct] = identifier[input] ( literal[string]
literal[string]
literal[string] )
keyw... | def check_folders(name):
"""Only checks and asks questions. Nothing is written to disk."""
if os.getcwd().endswith('analyses'):
correct = input('You are in an analyses folder. This will create another analyses folder inside this one. Do you want to continue? (y/N)')
if correct != 'y':
... |
def datasets_download(self, owner_slug, dataset_slug, **kwargs): # noqa: E501
"""Download dataset file # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_download(owner_slug, ... | def function[datasets_download, parameter[self, owner_slug, dataset_slug]]:
constant[Download dataset file # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.datasets_download(owner_slu... | keyword[def] identifier[datasets_download] ( identifier[self] , identifier[owner_slug] , identifier[dataset_slug] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def datasets_download(self, owner_slug, dataset_slug, **kwargs): # noqa: E501
'Download dataset file # noqa: E501\n\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread = api.datasets_download(owner_slug, da... |
def _split_source_page(self, path):
"""Split the source file texts by triple-dashed lines.
shit code
"""
with codecs.open(path, "rb", "utf-8") as fd:
textlist = fd.readlines()
metadata_notation = "---\n"
if textlist[0] != metadata_notation:
loggi... | def function[_split_source_page, parameter[self, path]]:
constant[Split the source file texts by triple-dashed lines.
shit code
]
with call[name[codecs].open, parameter[name[path], constant[rb], constant[utf-8]]] begin[:]
variable[textlist] assign[=] call[name[fd].readli... | keyword[def] identifier[_split_source_page] ( identifier[self] , identifier[path] ):
literal[string]
keyword[with] identifier[codecs] . identifier[open] ( identifier[path] , literal[string] , literal[string] ) keyword[as] identifier[fd] :
identifier[textlist] = identifier[fd] . ident... | def _split_source_page(self, path):
"""Split the source file texts by triple-dashed lines.
shit code
"""
with codecs.open(path, 'rb', 'utf-8') as fd:
textlist = fd.readlines() # depends on [control=['with'], data=['fd']]
metadata_notation = '---\n'
if textlist[0] != metadata_no... |
def read_file(path, encoding='utf-8', *args, **kwargs):
''' Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
'''
if 'mode' in kwargs and kwargs['mode'] == 'r... | def function[read_file, parameter[path, encoding]]:
constant[ Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
]
if <ast.BoolOp object at 0x7da1b1132... | keyword[def] identifier[read_file] ( identifier[path] , identifier[encoding] = literal[string] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[kwargs] keyword[and] identifier[kwargs] [ literal[string] ]== literal[string] :
keywo... | def read_file(path, encoding='utf-8', *args, **kwargs):
""" Read text file content. If the file name ends with .gz, read it as gzip file.
If mode argument is provided as 'rb', content will be read as byte stream.
By default, content is read as string.
"""
if 'mode' in kwargs and kwargs['mode'] == 'r... |
def _get_energy(self, x):
"""
Computes reaction energy in eV/atom at mixing ratio x : (1-x) for
self.comp1 : self.comp2.
Args:
x (float): Mixing ratio x of reactants, a float between 0 and 1.
Returns:
Reaction energy.
"""
return self.pd.g... | def function[_get_energy, parameter[self, x]]:
constant[
Computes reaction energy in eV/atom at mixing ratio x : (1-x) for
self.comp1 : self.comp2.
Args:
x (float): Mixing ratio x of reactants, a float between 0 and 1.
Returns:
Reaction energy.
]... | keyword[def] identifier[_get_energy] ( identifier[self] , identifier[x] ):
literal[string]
keyword[return] identifier[self] . identifier[pd] . identifier[get_hull_energy] ( identifier[self] . identifier[comp1] * identifier[x] + identifier[self] . identifier[comp2] *( literal[int] - identifier[x] )... | def _get_energy(self, x):
"""
Computes reaction energy in eV/atom at mixing ratio x : (1-x) for
self.comp1 : self.comp2.
Args:
x (float): Mixing ratio x of reactants, a float between 0 and 1.
Returns:
Reaction energy.
"""
return self.pd.get_hull_... |
def set_state(name, backend, state, socket=DEFAULT_SOCKET_URL):
'''
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the... | def function[set_state, parameter[name, backend, state, socket]]:
constant[
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalen... | keyword[def] identifier[set_state] ( identifier[name] , identifier[backend] , identifier[state] , identifier[socket] = identifier[DEFAULT_SOCKET_URL] ):
literal[string]
keyword[class] identifier[setServerState] ( identifier[haproxy] . identifier[cmds] . identifier[Cmd] ):
literal[string... | def set_state(name, backend, state, socket=DEFAULT_SOCKET_URL):
"""
Force a server's administrative state to a new state. This can be useful to
disable load balancing and/or any traffic to a server. Setting the state to
"ready" puts the server in normal mode, and the command is the equivalent of
the... |
def _cast_message(self, message=None):
'''Convert message data to :class:`Message` if needed, and
merge with the default message.
:param message: Message to merge with the default message.
:rtype: :class:`Message`
'''
if message is None:
message = {}
... | def function[_cast_message, parameter[self, message]]:
constant[Convert message data to :class:`Message` if needed, and
merge with the default message.
:param message: Message to merge with the default message.
:rtype: :class:`Message`
]
if compare[name[message] is const... | keyword[def] identifier[_cast_message] ( identifier[self] , identifier[message] = keyword[None] ):
literal[string]
keyword[if] identifier[message] keyword[is] keyword[None] :
identifier[message] ={}
keyword[if] identifier[isinstance] ( identifier[message] , identifier[Mapp... | def _cast_message(self, message=None):
"""Convert message data to :class:`Message` if needed, and
merge with the default message.
:param message: Message to merge with the default message.
:rtype: :class:`Message`
"""
if message is None:
message = {} # depends on [contr... |
async def jsk_shell(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Executes statements in the system shell.
This uses the bash shell. Execution can be cancelled by closing the paginator.
"""
async with ReplResponseReactor(ctx.message):
with self.... | <ast.AsyncFunctionDef object at 0x7da1b1e65f30> | keyword[async] keyword[def] identifier[jsk_shell] ( identifier[self] , identifier[ctx] : identifier[commands] . identifier[Context] ,*, identifier[argument] : identifier[CodeblockConverter] ):
literal[string]
keyword[async] keyword[with] identifier[ReplResponseReactor] ( identifier[ctx] . ident... | async def jsk_shell(self, ctx: commands.Context, *, argument: CodeblockConverter):
"""
Executes statements in the system shell.
This uses the bash shell. Execution can be cancelled by closing the paginator.
"""
async with ReplResponseReactor(ctx.message):
with self.submit(ctx):
... |
def _to_string(inp: str) -> str:
""" Convert a URL or file name to a string """
if '://' in inp:
req = requests.get(inp)
if not req.ok:
raise ValueError(f"Unable to read {inp}")
return req.text
else:
with open(inp) as infile:
... | def function[_to_string, parameter[inp]]:
constant[ Convert a URL or file name to a string ]
if compare[constant[://] in name[inp]] begin[:]
variable[req] assign[=] call[name[requests].get, parameter[name[inp]]]
if <ast.UnaryOp object at 0x7da1b2491900> begin[:]
... | keyword[def] identifier[_to_string] ( identifier[inp] : identifier[str] )-> identifier[str] :
literal[string]
keyword[if] literal[string] keyword[in] identifier[inp] :
identifier[req] = identifier[requests] . identifier[get] ( identifier[inp] )
keyword[if] keyword[not]... | def _to_string(inp: str) -> str:
""" Convert a URL or file name to a string """
if '://' in inp:
req = requests.get(inp)
if not req.ok:
raise ValueError(f'Unable to read {inp}') # depends on [control=['if'], data=[]]
return req.text # depends on [control=['if'], data=['inp'... |
def et2lst(et, body, lon, typein, timlen=_default_len_out, ampmlen=_default_len_out):
"""
Given an ephemeris epoch, compute the local solar time for
an object on the surface of a body at a specified longitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html
:param et: Epoch i... | def function[et2lst, parameter[et, body, lon, typein, timlen, ampmlen]]:
constant[
Given an ephemeris epoch, compute the local solar time for
an object on the surface of a body at a specified longitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html
:param et: Epoch in s... | keyword[def] identifier[et2lst] ( identifier[et] , identifier[body] , identifier[lon] , identifier[typein] , identifier[timlen] = identifier[_default_len_out] , identifier[ampmlen] = identifier[_default_len_out] ):
literal[string]
identifier[et] = identifier[ctypes] . identifier[c_double] ( identifier[et] ... | def et2lst(et, body, lon, typein, timlen=_default_len_out, ampmlen=_default_len_out):
"""
Given an ephemeris epoch, compute the local solar time for
an object on the surface of a body at a specified longitude.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/et2lst_c.html
:param et: Epoch i... |
def query_yes_no(question, default=None): # pragma: no cover
"""
Ask a yes/no question via `raw_input()` and return their answer.
:param question: A string that is presented to the user.
:param default: The presumed answer if the user just hits <Enter>.
It must be "yes" (the defaul... | def function[query_yes_no, parameter[question, default]]:
constant[
Ask a yes/no question via `raw_input()` and return their answer.
:param question: A string that is presented to the user.
:param default: The presumed answer if the user just hits <Enter>.
It must be "yes" (the ... | keyword[def] identifier[query_yes_no] ( identifier[question] , identifier[default] = keyword[None] ):
literal[string]
identifier[valid] ={ literal[string] : keyword[True] , literal[string] : keyword[True] , literal[string] : keyword[True] , literal[string] : keyword[False] , literal[string] : keyword[False... | def query_yes_no(question, default=None): # pragma: no cover
'\n Ask a yes/no question via `raw_input()` and return their answer.\n\n :param question: A string that is presented to the user.\n :param default: The presumed answer if the user just hits <Enter>.\n It must be "yes" (the def... |
def initialise_modified_data(self):
"""
Initialise the modified_data if necessary
"""
if self.__modified_data__ is None:
if self.__original_data__:
self.__modified_data__ = list(self.__original_data__)
else:
self.__modified_data__ =... | def function[initialise_modified_data, parameter[self]]:
constant[
Initialise the modified_data if necessary
]
if compare[name[self].__modified_data__ is constant[None]] begin[:]
if name[self].__original_data__ begin[:]
name[self].__modified_data__... | keyword[def] identifier[initialise_modified_data] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[__modified_data__] keyword[is] keyword[None] :
keyword[if] identifier[self] . identifier[__original_data__] :
identifier[self] . identi... | def initialise_modified_data(self):
"""
Initialise the modified_data if necessary
"""
if self.__modified_data__ is None:
if self.__original_data__:
self.__modified_data__ = list(self.__original_data__) # depends on [control=['if'], data=[]]
else:
self.__m... |
def apply (self, img):
yup,uup,vup = self.getUpLimit()
ydwn,udwn,vdwn = self.getDownLimit()
''' We convert RGB as BGR because OpenCV
with RGB pass to YVU instead of YUV'''
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
minValues = np.array([ydwn,udwn,vdw... | def function[apply, parameter[self, img]]:
<ast.Tuple object at 0x7da1b26aff10> assign[=] call[name[self].getUpLimit, parameter[]]
<ast.Tuple object at 0x7da1b26ae050> assign[=] call[name[self].getDownLimit, parameter[]]
constant[ We convert RGB as BGR because OpenCV
with RGB pass to YV... | keyword[def] identifier[apply] ( identifier[self] , identifier[img] ):
identifier[yup] , identifier[uup] , identifier[vup] = identifier[self] . identifier[getUpLimit] ()
identifier[ydwn] , identifier[udwn] , identifier[vdwn] = identifier[self] . identifier[getDownLimit] ()
literal[string... | def apply(self, img):
(yup, uup, vup) = self.getUpLimit()
(ydwn, udwn, vdwn) = self.getDownLimit()
' We convert RGB as BGR because OpenCV \n with RGB pass to YVU instead of YUV'
yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
minValues = np.array([ydwn, udwn, vdwn], dtype=np.uint8)
maxValues =... |
def get_nonlocal_ip(host, subnet=None):
"""
Search result of getaddrinfo() for a non-localhost-net address
"""
try:
ailist = socket.getaddrinfo(host, None)
except socket.gaierror:
raise exc.UnableToResolveError(host)
for ai in ailist:
# an ai is a 5-tuple; the last elemen... | def function[get_nonlocal_ip, parameter[host, subnet]]:
constant[
Search result of getaddrinfo() for a non-localhost-net address
]
<ast.Try object at 0x7da1b1634130>
for taget[name[ai]] in starred[name[ailist]] begin[:]
variable[ip] assign[=] call[call[name[ai]][constant[4]]]... | keyword[def] identifier[get_nonlocal_ip] ( identifier[host] , identifier[subnet] = keyword[None] ):
literal[string]
keyword[try] :
identifier[ailist] = identifier[socket] . identifier[getaddrinfo] ( identifier[host] , keyword[None] )
keyword[except] identifier[socket] . identifier[gaierror] ... | def get_nonlocal_ip(host, subnet=None):
"""
Search result of getaddrinfo() for a non-localhost-net address
"""
try:
ailist = socket.getaddrinfo(host, None) # depends on [control=['try'], data=[]]
except socket.gaierror:
raise exc.UnableToResolveError(host) # depends on [control=['e... |
def newton_iterate(evaluate_fn, s, t):
r"""Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used be... | def function[newton_iterate, parameter[evaluate_fn, s, t]]:
constant[Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance ... | keyword[def] identifier[newton_iterate] ( identifier[evaluate_fn] , identifier[s] , identifier[t] ):
literal[string]
identifier[norm_update_prev] = keyword[None]
identifier[norm_update] = keyword[None]
identifier[linear_updates] = literal[int]
identifier[curr... | def newton_iterate(evaluate_fn, s, t):
"""Perform a Newton iteration.
In this function, we assume that :math:`s` and :math:`t` are nonzero,
this makes convergence easier to detect since "relative error" at
``0.0`` is not a useful measure.
There are several tolerance / threshold quantities used bel... |
def ssh_known_hosts_lines(application_name, user=None):
"""Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
kn... | def function[ssh_known_hosts_lines, parameter[application_name, user]]:
constant[Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:typ... | keyword[def] identifier[ssh_known_hosts_lines] ( identifier[application_name] , identifier[user] = keyword[None] ):
literal[string]
identifier[known_hosts_list] =[]
keyword[with] identifier[open] ( identifier[known_hosts] ( identifier[application_name] , identifier[user] )) keyword[as] identifier[ho... | def ssh_known_hosts_lines(application_name, user=None):
"""Return contents of known_hosts file for given application.
:param application_name: Name of application eg nova-compute-something
:type application_name: str
:param user: The user that the ssh asserts are for.
:type user: str
"""
kn... |
def _construct_message(self):
"""Build the message params."""
self.message["text"] = ""
if self.from_:
self.message["text"] += "From: " + self.from_ + "\n"
if self.subject:
self.message["text"] += "Subject: " + self.subject + "\n"
self.message["text"] += ... | def function[_construct_message, parameter[self]]:
constant[Build the message params.]
call[name[self].message][constant[text]] assign[=] constant[]
if name[self].from_ begin[:]
<ast.AugAssign object at 0x7da1b26ad360>
if name[self].subject begin[:]
<ast.AugAssign object ... | keyword[def] identifier[_construct_message] ( identifier[self] ):
literal[string]
identifier[self] . identifier[message] [ literal[string] ]= literal[string]
keyword[if] identifier[self] . identifier[from_] :
identifier[self] . identifier[message] [ literal[string] ]+= liter... | def _construct_message(self):
"""Build the message params."""
self.message['text'] = ''
if self.from_:
self.message['text'] += 'From: ' + self.from_ + '\n' # depends on [control=['if'], data=[]]
if self.subject:
self.message['text'] += 'Subject: ' + self.subject + '\n' # depends on [co... |
def run(self, *args):
"""Get and set configuration parameters.
This command gets or sets parameter values from the user configuration
file. On Linux systems, configuration will be stored in the file
'~/.sortinghat'.
"""
params = self.parser.parse_args(args)
conf... | def function[run, parameter[self]]:
constant[Get and set configuration parameters.
This command gets or sets parameter values from the user configuration
file. On Linux systems, configuration will be stored in the file
'~/.sortinghat'.
]
variable[params] assign[=] call[n... | keyword[def] identifier[run] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[params] = identifier[self] . identifier[parser] . identifier[parse_args] ( identifier[args] )
identifier[config_file] = identifier[os] . identifier[path] . identifier[expanduser] ( literal[st... | def run(self, *args):
"""Get and set configuration parameters.
This command gets or sets parameter values from the user configuration
file. On Linux systems, configuration will be stored in the file
'~/.sortinghat'.
"""
params = self.parser.parse_args(args)
config_file = os.... |
def compile_matchers(formatcode):
"""
Tests newick string against format types? and makes a re.compile
"""
matchers = {}
for node_type in ["leaf", "single", "internal"]:
if node_type == "leaf" or node_type == "single":
container1 = NW_FORMAT[formatcode][0][0]
containe... | def function[compile_matchers, parameter[formatcode]]:
constant[
Tests newick string against format types? and makes a re.compile
]
variable[matchers] assign[=] dictionary[[], []]
for taget[name[node_type]] in starred[list[[<ast.Constant object at 0x7da18ede7fd0>, <ast.Constant object at... | keyword[def] identifier[compile_matchers] ( identifier[formatcode] ):
literal[string]
identifier[matchers] ={}
keyword[for] identifier[node_type] keyword[in] [ literal[string] , literal[string] , literal[string] ]:
keyword[if] identifier[node_type] == literal[string] keyword[or] identifi... | def compile_matchers(formatcode):
"""
Tests newick string against format types? and makes a re.compile
"""
matchers = {}
for node_type in ['leaf', 'single', 'internal']:
if node_type == 'leaf' or node_type == 'single':
container1 = NW_FORMAT[formatcode][0][0]
containe... |
def run(args):
"""Runs the acorn setup/configuration commands.
"""
if args is None:
return
cmd = args["commands"][0]
if cmd == "configure":
if len(args["commands"]) < 2:# pragma: no cover
msg.err("'configure' command requires a second, sub-command "
... | def function[run, parameter[args]]:
constant[Runs the acorn setup/configuration commands.
]
if compare[name[args] is constant[None]] begin[:]
return[None]
variable[cmd] assign[=] call[call[name[args]][constant[commands]]][constant[0]]
if compare[name[cmd] equal[==] constant[c... | keyword[def] identifier[run] ( identifier[args] ):
literal[string]
keyword[if] identifier[args] keyword[is] keyword[None] :
keyword[return]
identifier[cmd] = identifier[args] [ literal[string] ][ literal[int] ]
keyword[if] identifier[cmd] == literal[string] :
keyword[if] ... | def run(args):
"""Runs the acorn setup/configuration commands.
"""
if args is None:
return # depends on [control=['if'], data=[]]
cmd = args['commands'][0]
if cmd == 'configure':
if len(args['commands']) < 2: # pragma: no cover
msg.err("'configure' command requires a se... |
def _sizes(self, package):
"""Package size summary
"""
data = Utils().read_file(self.meta.pkg_path + package)
for line in data.splitlines():
if line.startswith("UNCOMPRESSED PACKAGE SIZE:"):
digit = float((''.join(re.findall(
"[-+]?\d+[\.]?... | def function[_sizes, parameter[self, package]]:
constant[Package size summary
]
variable[data] assign[=] call[call[name[Utils], parameter[]].read_file, parameter[binary_operation[name[self].meta.pkg_path + name[package]]]]
for taget[name[line]] in starred[call[name[data].splitlines, para... | keyword[def] identifier[_sizes] ( identifier[self] , identifier[package] ):
literal[string]
identifier[data] = identifier[Utils] (). identifier[read_file] ( identifier[self] . identifier[meta] . identifier[pkg_path] + identifier[package] )
keyword[for] identifier[line] keyword[in] ident... | def _sizes(self, package):
"""Package size summary
"""
data = Utils().read_file(self.meta.pkg_path + package)
for line in data.splitlines():
if line.startswith('UNCOMPRESSED PACKAGE SIZE:'):
digit = float(''.join(re.findall('[-+]?\\d+[\\.]?\\d*[eE]?[-+]?\\d*', line[26:])))
... |
def add_functions(self, names, functions):
"""Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
names : (list of) s... | def function[add_functions, parameter[self, names, functions]]:
constant[Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
... | keyword[def] identifier[add_functions] ( identifier[self] , identifier[names] , identifier[functions] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[names] , identifier[string_types] ):
identifier[names] =[ identifier[names] ]
identifier[functions] =[ ... | def add_functions(self, names, functions):
"""Adds the given functions to the function library.
Functions are added to this instance of the array; all copies of
and slices of this array will also have the new functions included.
Parameters
----------
names : (list of) strin... |
def indices_for_body(self, name, step=3):
'''Get a list of the indices for a specific body.
Parameters
----------
name : str
The name of the body to look up.
step : int, optional
The number of numbers for each body. Defaults to 3, should be set
... | def function[indices_for_body, parameter[self, name, step]]:
constant[Get a list of the indices for a specific body.
Parameters
----------
name : str
The name of the body to look up.
step : int, optional
The number of numbers for each body. Defaults to 3,... | keyword[def] identifier[indices_for_body] ( identifier[self] , identifier[name] , identifier[step] = literal[int] ):
literal[string]
keyword[for] identifier[j] , identifier[body] keyword[in] identifier[enumerate] ( identifier[self] . identifier[bodies] ):
keyword[if] identifier[bod... | def indices_for_body(self, name, step=3):
"""Get a list of the indices for a specific body.
Parameters
----------
name : str
The name of the body to look up.
step : int, optional
The number of numbers for each body. Defaults to 3, should be set
to... |
def _parse_datetime_value(value):
"""Deserialize a DateTime object from its proper ISO-8601 representation."""
if value.endswith('Z'):
# Arrow doesn't support the "Z" literal to denote UTC time.
# Strip the "Z" and add an explicit time zone instead.
value = value[:-1] + '+00:00'
ret... | def function[_parse_datetime_value, parameter[value]]:
constant[Deserialize a DateTime object from its proper ISO-8601 representation.]
if call[name[value].endswith, parameter[constant[Z]]] begin[:]
variable[value] assign[=] binary_operation[call[name[value]][<ast.Slice object at 0x7da1b... | keyword[def] identifier[_parse_datetime_value] ( identifier[value] ):
literal[string]
keyword[if] identifier[value] . identifier[endswith] ( literal[string] ):
identifier[value] = identifier[value] [:- literal[int] ]+ literal[string]
keyword[return] identifier[arrow] . identifie... | def _parse_datetime_value(value):
"""Deserialize a DateTime object from its proper ISO-8601 representation."""
if value.endswith('Z'):
# Arrow doesn't support the "Z" literal to denote UTC time.
# Strip the "Z" and add an explicit time zone instead.
value = value[:-1] + '+00:00' # depen... |
def start_time(self):
"""Retrieves the start time of the incident/incidents from the output
response
Returns:
start_time(namedtuple): List of named tuples of start time of the
incident/incidents
"""
resource_list = self.traffic_incident()
start_ti... | def function[start_time, parameter[self]]:
constant[Retrieves the start time of the incident/incidents from the output
response
Returns:
start_time(namedtuple): List of named tuples of start time of the
incident/incidents
]
variable[resource_list] assign[... | keyword[def] identifier[start_time] ( identifier[self] ):
literal[string]
identifier[resource_list] = identifier[self] . identifier[traffic_incident] ()
identifier[start_time] = identifier[namedtuple] ( literal[string] , literal[string] )
keyword[if] identifier[len] ( identifier[... | def start_time(self):
"""Retrieves the start time of the incident/incidents from the output
response
Returns:
start_time(namedtuple): List of named tuples of start time of the
incident/incidents
"""
resource_list = self.traffic_incident()
start_time = namedtu... |
def get_next_notif_time(self, t_wished, status, creation_time, interval, escal_period):
"""Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type t_wished:
:param s... | def function[get_next_notif_time, parameter[self, t_wished, status, creation_time, interval, escal_period]]:
constant[Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type... | keyword[def] identifier[get_next_notif_time] ( identifier[self] , identifier[t_wished] , identifier[status] , identifier[creation_time] , identifier[interval] , identifier[escal_period] ):
literal[string]
identifier[short_states] ={ literal[string] : literal[string] , literal[string] : literal[stri... | def get_next_notif_time(self, t_wished, status, creation_time, interval, escal_period):
"""Get the next notification time for the escalation
Only legit for time based escalation
:param t_wished: time we would like to send a new notification (usually now)
:type t_wished:
:param statu... |
def __intermediate_bridge(self, interface, i):
"""
converts NetJSON bridge to
UCI intermediate data structure
"""
# ensure type "bridge" is only given to one logical interface
if interface['type'] == 'bridge' and i < 2:
bridge_members = ' '.join(interface.pop(... | def function[__intermediate_bridge, parameter[self, interface, i]]:
constant[
converts NetJSON bridge to
UCI intermediate data structure
]
if <ast.BoolOp object at 0x7da1b01418a0> begin[:]
variable[bridge_members] assign[=] call[constant[ ].join, parameter[call[na... | keyword[def] identifier[__intermediate_bridge] ( identifier[self] , identifier[interface] , identifier[i] ):
literal[string]
keyword[if] identifier[interface] [ literal[string] ]== literal[string] keyword[and] identifier[i] < literal[int] :
identifier[bridge_members] = lite... | def __intermediate_bridge(self, interface, i):
"""
converts NetJSON bridge to
UCI intermediate data structure
"""
# ensure type "bridge" is only given to one logical interface
if interface['type'] == 'bridge' and i < 2:
bridge_members = ' '.join(interface.pop('bridge_members'... |
def is_available(self):
"""
Returns `True` if *any* view handler in the class is currently
available via its `is_available` method.
"""
if self.is_always_available:
return True
for viewname in self.__views__:
if getattr(self, viewname).is_available... | def function[is_available, parameter[self]]:
constant[
Returns `True` if *any* view handler in the class is currently
available via its `is_available` method.
]
if name[self].is_always_available begin[:]
return[constant[True]]
for taget[name[viewname]] in starred[... | keyword[def] identifier[is_available] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[is_always_available] :
keyword[return] keyword[True]
keyword[for] identifier[viewname] keyword[in] identifier[self] . identifier[__views__] :
... | def is_available(self):
"""
Returns `True` if *any* view handler in the class is currently
available via its `is_available` method.
"""
if self.is_always_available:
return True # depends on [control=['if'], data=[]]
for viewname in self.__views__:
if getattr(self, vi... |
def mcp_als(X, rank, mask, random_state=None, init='randn', **options):
"""Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of... | def function[mcp_als, parameter[X, rank, mask, random_state, init]]:
constant[Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the nu... | keyword[def] identifier[mcp_als] ( identifier[X] , identifier[rank] , identifier[mask] , identifier[random_state] = keyword[None] , identifier[init] = literal[string] ,** identifier[options] ):
literal[string]
identifier[optim_utils] . identifier[_check_cpd_inputs] ( identifier[X] , identifier[rank] ... | def mcp_als(X, rank, mask, random_state=None, init='randn', **options):
"""Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of... |
def metric_ids(self):
""" Return the Metrics on this shelf in the order in which
they were used. """
return self._sorted_ingredients([
d.id for d in self.values() if isinstance(d, Metric)
]) | def function[metric_ids, parameter[self]]:
constant[ Return the Metrics on this shelf in the order in which
they were used. ]
return[call[name[self]._sorted_ingredients, parameter[<ast.ListComp object at 0x7da20c992b90>]]] | keyword[def] identifier[metric_ids] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_sorted_ingredients] ([
identifier[d] . identifier[id] keyword[for] identifier[d] keyword[in] identifier[self] . identifier[values] () keyword[if] identifier[isinst... | def metric_ids(self):
""" Return the Metrics on this shelf in the order in which
they were used. """
return self._sorted_ingredients([d.id for d in self.values() if isinstance(d, Metric)]) |
def channel(self, match):
""" Return Channel object for a given Slack ID or name """
if len(match) == 9 and match[0] in ('C','G','D'):
return self._lookup(Channel, 'id', match)
return self._lookup(Channel, 'name', match) | def function[channel, parameter[self, match]]:
constant[ Return Channel object for a given Slack ID or name ]
if <ast.BoolOp object at 0x7da20c6a85e0> begin[:]
return[call[name[self]._lookup, parameter[name[Channel], constant[id], name[match]]]]
return[call[name[self]._lookup, parameter[name... | keyword[def] identifier[channel] ( identifier[self] , identifier[match] ):
literal[string]
keyword[if] identifier[len] ( identifier[match] )== literal[int] keyword[and] identifier[match] [ literal[int] ] keyword[in] ( literal[string] , literal[string] , literal[string] ):
keyword[re... | def channel(self, match):
""" Return Channel object for a given Slack ID or name """
if len(match) == 9 and match[0] in ('C', 'G', 'D'):
return self._lookup(Channel, 'id', match) # depends on [control=['if'], data=[]]
return self._lookup(Channel, 'name', match) |
def _check_overlap(self, fragment):
"""
Check that the interval of the given fragment does not overlap
any existing interval in the list (except at its boundaries).
Raises an error if not OK.
"""
#
# NOTE bisect does not work if there is a configuration like:
... | def function[_check_overlap, parameter[self, fragment]]:
constant[
Check that the interval of the given fragment does not overlap
any existing interval in the list (except at its boundaries).
Raises an error if not OK.
]
for taget[name[existing_fragment]] in starred[name[... | keyword[def] identifier[_check_overlap] ( identifier[self] , identifier[fragment] ):
literal[string]
keyword[for] identifier[existing_fragment] keyword[in] identifier[self] . identifier[fragments] :
key... | def _check_overlap(self, fragment):
"""
Check that the interval of the given fragment does not overlap
any existing interval in the list (except at its boundaries).
Raises an error if not OK.
"""
#
# NOTE bisect does not work if there is a configuration like:
#
# ... |
def confirm(self, msg, _timeout=-1):
''' Send a confirm prompt to the GUI
Arguments:
msg (string):
The message to display to the user.
_timeout (int):
The optional amount of time for which the prompt
should be displayed to... | def function[confirm, parameter[self, msg, _timeout]]:
constant[ Send a confirm prompt to the GUI
Arguments:
msg (string):
The message to display to the user.
_timeout (int):
The optional amount of time for which the prompt
... | keyword[def] identifier[confirm] ( identifier[self] , identifier[msg] , identifier[_timeout] =- literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[msgBox] ( literal[string] , identifier[_timeout] = identifier[_timeout] , identifier[msg] = identifier[msg] ) | def confirm(self, msg, _timeout=-1):
""" Send a confirm prompt to the GUI
Arguments:
msg (string):
The message to display to the user.
_timeout (int):
The optional amount of time for which the prompt
should be displayed to the... |
def _calc_a(self, y_C, y_H, y_O, y_N, y_S):
"""
Calculate the mean atomic weight for the specified element mass
fractions.
:param y_C: Carbon mass fraction
:param y_H: Hydrogen mass fraction
:param y_O: Oxygen mass fraction
:param y_N: Nitrogen mass fract... | def function[_calc_a, parameter[self, y_C, y_H, y_O, y_N, y_S]]:
constant[
Calculate the mean atomic weight for the specified element mass
fractions.
:param y_C: Carbon mass fraction
:param y_H: Hydrogen mass fraction
:param y_O: Oxygen mass fraction
:par... | keyword[def] identifier[_calc_a] ( identifier[self] , identifier[y_C] , identifier[y_H] , identifier[y_O] , identifier[y_N] , identifier[y_S] ):
literal[string]
keyword[return] literal[int] /( identifier[y_C] / identifier[mm] ( literal[string] )+ identifier[y_H] / identifier[mm] ( literal[string]... | def _calc_a(self, y_C, y_H, y_O, y_N, y_S):
"""
Calculate the mean atomic weight for the specified element mass
fractions.
:param y_C: Carbon mass fraction
:param y_H: Hydrogen mass fraction
:param y_O: Oxygen mass fraction
:param y_N: Nitrogen mass fraction
... |
def put(self,
body: Body,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY,
ttr: int = DEFAULT_TTR) -> int:
"""Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priori... | def function[put, parameter[self, body, priority, delay, ttr]]:
constant[Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
... | keyword[def] identifier[put] ( identifier[self] ,
identifier[body] : identifier[Body] ,
identifier[priority] : identifier[int] = identifier[DEFAULT_PRIORITY] ,
identifier[delay] : identifier[int] = identifier[DEFAULT_DELAY] ,
identifier[ttr] : identifier[int] = identifier[DEFAULT_TTR] )-> identifier[int] :
... | def put(self, body: Body, priority: int=DEFAULT_PRIORITY, delay: int=DEFAULT_DELAY, ttr: int=DEFAULT_TTR) -> int:
"""Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
... |
def _getStringStream(self, filename, prefer='unicode'):
"""Gets a string representation of the requested filename.
Checks for both ASCII and Unicode representations and returns
a value if possible. If there are both ASCII and Unicode
versions, then the parameter /prefer/ specifies which... | def function[_getStringStream, parameter[self, filename, prefer]]:
constant[Gets a string representation of the requested filename.
Checks for both ASCII and Unicode representations and returns
a value if possible. If there are both ASCII and Unicode
versions, then the parameter /prefer... | keyword[def] identifier[_getStringStream] ( identifier[self] , identifier[filename] , identifier[prefer] = literal[string] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[filename] , identifier[list] ):
identifier[filename] = literal[string] . identifier[j... | def _getStringStream(self, filename, prefer='unicode'):
"""Gets a string representation of the requested filename.
Checks for both ASCII and Unicode representations and returns
a value if possible. If there are both ASCII and Unicode
versions, then the parameter /prefer/ specifies which wil... |
def _newPage(self, pno=-1, width=595, height=842):
"""_newPage(self, pno=-1, width=595, height=842) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
val = _fitz.Document__newPage(self, pno, width, height)
... | def function[_newPage, parameter[self, pno, width, height]]:
constant[_newPage(self, pno=-1, width=595, height=842) -> PyObject *]
if <ast.BoolOp object at 0x7da18f811450> begin[:]
<ast.Raise object at 0x7da18f810940>
variable[val] assign[=] call[name[_fitz].Document__newPage, parameter[... | keyword[def] identifier[_newPage] ( identifier[self] , identifier[pno] =- literal[int] , identifier[width] = literal[int] , identifier[height] = literal[int] ):
literal[string]
keyword[if] identifier[self] . identifier[isClosed] keyword[or] identifier[self] . identifier[isEncrypted] :
... | def _newPage(self, pno=-1, width=595, height=842):
"""_newPage(self, pno=-1, width=595, height=842) -> PyObject *"""
if self.isClosed or self.isEncrypted:
raise ValueError('operation illegal for closed / encrypted doc') # depends on [control=['if'], data=[]]
val = _fitz.Document__newPage(self, pno,... |
def positionlesscrop(self,x,y,sheet_coord_system):
"""
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge of the sheet).
"""
... | def function[positionlesscrop, parameter[self, x, y, sheet_coord_system]]:
constant[
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge... | keyword[def] identifier[positionlesscrop] ( identifier[self] , identifier[x] , identifier[y] , identifier[sheet_coord_system] ):
literal[string]
identifier[slice_inds] = identifier[self] . identifier[findinputslice] (
identifier[sheet_coord_system] . identifier[sheet2matrixidx] ( identifie... | def positionlesscrop(self, x, y, sheet_coord_system):
"""
Return the correct slice for a weights/mask matrix at this
ConnectionField's location on the sheet (i.e. for getting the
correct submatrix of the weights or mask in case the unit is
near the edge of the sheet).
"""
... |
def runSearchExpressionLevels(self, request):
"""
Returns a SearchExpressionLevelResponse for the specified
SearchExpressionLevelRequest object.
"""
return self.runSearchRequest(
request, protocol.SearchExpressionLevelsRequest,
protocol.SearchExpressionLev... | def function[runSearchExpressionLevels, parameter[self, request]]:
constant[
Returns a SearchExpressionLevelResponse for the specified
SearchExpressionLevelRequest object.
]
return[call[name[self].runSearchRequest, parameter[name[request], name[protocol].SearchExpressionLevelsRequest... | keyword[def] identifier[runSearchExpressionLevels] ( identifier[self] , identifier[request] ):
literal[string]
keyword[return] identifier[self] . identifier[runSearchRequest] (
identifier[request] , identifier[protocol] . identifier[SearchExpressionLevelsRequest] ,
identifier[pro... | def runSearchExpressionLevels(self, request):
"""
Returns a SearchExpressionLevelResponse for the specified
SearchExpressionLevelRequest object.
"""
return self.runSearchRequest(request, protocol.SearchExpressionLevelsRequest, protocol.SearchExpressionLevelsResponse, self.expressionLevel... |
def value_opt_step(i,
opt_state,
opt_update,
value_net_apply,
padded_observations,
padded_rewards,
reward_mask,
gamma=0.99):
"""Value optimizer step."""
value_params = trax_opt.get_pa... | def function[value_opt_step, parameter[i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma]]:
constant[Value optimizer step.]
variable[value_params] assign[=] call[name[trax_opt].get_params, parameter[name[opt_state]]]
variable[g] assign[=] call[cal... | keyword[def] identifier[value_opt_step] ( identifier[i] ,
identifier[opt_state] ,
identifier[opt_update] ,
identifier[value_net_apply] ,
identifier[padded_observations] ,
identifier[padded_rewards] ,
identifier[reward_mask] ,
identifier[gamma] = literal[int] ):
literal[string]
identifier[value_params] =... | def value_opt_step(i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma=0.99):
"""Value optimizer step."""
value_params = trax_opt.get_params(opt_state)
# Note this partial application here and argnums above in ppo_opt_step.
g = grad(functools.partial(value_... |
def create_subnet(self, snet):
"""Create subnet."""
snet_id = snet.get('id')
# This checks if the source of the subnet creation is FW,
# If yes, this event is ignored.
if self.fw_api.is_subnet_source_fw(snet.get('tenant_id'),
snet.get('... | def function[create_subnet, parameter[self, snet]]:
constant[Create subnet.]
variable[snet_id] assign[=] call[name[snet].get, parameter[constant[id]]]
if call[name[self].fw_api.is_subnet_source_fw, parameter[call[name[snet].get, parameter[constant[tenant_id]]], call[name[snet].get, parameter[con... | keyword[def] identifier[create_subnet] ( identifier[self] , identifier[snet] ):
literal[string]
identifier[snet_id] = identifier[snet] . identifier[get] ( literal[string] )
keyword[if] identifier[self] . identifier[fw_api] . identifier[is_subnet_source_fw] ( identifier[... | def create_subnet(self, snet):
"""Create subnet."""
snet_id = snet.get('id')
# This checks if the source of the subnet creation is FW,
# If yes, this event is ignored.
if self.fw_api.is_subnet_source_fw(snet.get('tenant_id'), snet.get('cidr')):
LOG.info('Service subnet %s, returning', snet.g... |
def _comparator_presence(_, tested_value):
"""
Tests a filter which simply a joker, i.e. a value presence test
"""
# The filter value is a joker : simple presence test
if tested_value is None:
return False
elif hasattr(tested_value, "__len__"):
# Refuse empty values
# pyl... | def function[_comparator_presence, parameter[_, tested_value]]:
constant[
Tests a filter which simply a joker, i.e. a value presence test
]
if compare[name[tested_value] is constant[None]] begin[:]
return[constant[False]]
return[constant[True]] | keyword[def] identifier[_comparator_presence] ( identifier[_] , identifier[tested_value] ):
literal[string]
keyword[if] identifier[tested_value] keyword[is] keyword[None] :
keyword[return] keyword[False]
keyword[elif] identifier[hasattr] ( identifier[tested_value] , literal[string]... | def _comparator_presence(_, tested_value):
"""
Tests a filter which simply a joker, i.e. a value presence test
"""
# The filter value is a joker : simple presence test
if tested_value is None:
return False # depends on [control=['if'], data=[]]
elif hasattr(tested_value, '__len__'):
... |
def download_file(url, filename):
"""Downloads file from url to a path with filename"""
r = _get_requests_session().get(url, stream=True)
if not r.ok:
raise IOError("Unable to download file")
with open(filename, "wb") as f:
f.write(r.content) | def function[download_file, parameter[url, filename]]:
constant[Downloads file from url to a path with filename]
variable[r] assign[=] call[call[name[_get_requests_session], parameter[]].get, parameter[name[url]]]
if <ast.UnaryOp object at 0x7da18ede5840> begin[:]
<ast.Raise object at 0x... | keyword[def] identifier[download_file] ( identifier[url] , identifier[filename] ):
literal[string]
identifier[r] = identifier[_get_requests_session] (). identifier[get] ( identifier[url] , identifier[stream] = keyword[True] )
keyword[if] keyword[not] identifier[r] . identifier[ok] :
keyword... | def download_file(url, filename):
"""Downloads file from url to a path with filename"""
r = _get_requests_session().get(url, stream=True)
if not r.ok:
raise IOError('Unable to download file') # depends on [control=['if'], data=[]]
with open(filename, 'wb') as f:
f.write(r.content) # de... |
def format_dict_to_str(dict, format):
"""
Format a dictionary to the string, param format is a specified format rule
such as dict = '{'name':'Sylvanas', 'gender':'Boy'}' format = '-'
so result is 'name-Sylvanas, gender-Boy'.
>>> dict = {'name': 'Sylvanas', 'gender': 'Boy'}
>>> format_dict_to_st... | def function[format_dict_to_str, parameter[dict, format]]:
constant[
Format a dictionary to the string, param format is a specified format rule
such as dict = '{'name':'Sylvanas', 'gender':'Boy'}' format = '-'
so result is 'name-Sylvanas, gender-Boy'.
>>> dict = {'name': 'Sylvanas', 'gender': '... | keyword[def] identifier[format_dict_to_str] ( identifier[dict] , identifier[format] ):
literal[string]
identifier[result] = literal[string]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[dict] . identifier[items] ():
identifier[result] = identifier[result] + identifier[... | def format_dict_to_str(dict, format):
"""
Format a dictionary to the string, param format is a specified format rule
such as dict = '{'name':'Sylvanas', 'gender':'Boy'}' format = '-'
so result is 'name-Sylvanas, gender-Boy'.
>>> dict = {'name': 'Sylvanas', 'gender': 'Boy'}
>>> format_dict_to_st... |
def make_index_unique(index: pd.Index, join: str = '-'):
"""Makes the index unique by appending '1', '2', etc.
The first occurance of a non-unique value is ignored.
Parameters
----------
join
The connecting string between name and integer.
Examples
--------
>>> adata1 = sc.An... | def function[make_index_unique, parameter[index, join]]:
constant[Makes the index unique by appending '1', '2', etc.
The first occurance of a non-unique value is ignored.
Parameters
----------
join
The connecting string between name and integer.
Examples
--------
>>> adat... | keyword[def] identifier[make_index_unique] ( identifier[index] : identifier[pd] . identifier[Index] , identifier[join] : identifier[str] = literal[string] ):
literal[string]
keyword[if] identifier[index] . identifier[is_unique] :
keyword[return] identifier[index]
keyword[from] identifier[... | def make_index_unique(index: pd.Index, join: str='-'):
"""Makes the index unique by appending '1', '2', etc.
The first occurance of a non-unique value is ignored.
Parameters
----------
join
The connecting string between name and integer.
Examples
--------
>>> adata1 = sc.AnnD... |
def remote_url(self, remotename='origin'):
"""
Determine the primary remote url for this Repository
Returns:
str: primary remote url for this Repository
(``git config remote.origin.url``)
"""
cmd = ['git', 'config', 'remote.%s.url' % remotename]
... | def function[remote_url, parameter[self, remotename]]:
constant[
Determine the primary remote url for this Repository
Returns:
str: primary remote url for this Repository
(``git config remote.origin.url``)
]
variable[cmd] assign[=] list[[<ast.Constant... | keyword[def] identifier[remote_url] ( identifier[self] , identifier[remotename] = literal[string] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] % identifier[remotename] ]
keyword[return] identifier[self] . identifier[sh] ( identifier[cmd] , iden... | def remote_url(self, remotename='origin'):
"""
Determine the primary remote url for this Repository
Returns:
str: primary remote url for this Repository
(``git config remote.origin.url``)
"""
cmd = ['git', 'config', 'remote.%s.url' % remotename]
return se... |
def symlink_to(orig, dest):
"""Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink.
"""
if is_windows:
import subprocess
subprocess.check_call(
["mklink", "/d", path2str(orig... | def function[symlink_to, parameter[orig, dest]]:
constant[Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink.
]
if name[is_windows] begin[:]
import module[subprocess]
cal... | keyword[def] identifier[symlink_to] ( identifier[orig] , identifier[dest] ):
literal[string]
keyword[if] identifier[is_windows] :
keyword[import] identifier[subprocess]
identifier[subprocess] . identifier[check_call] (
[ literal[string] , literal[string] , identifier[path2str]... | def symlink_to(orig, dest):
"""Create a symlink. Used for model shortcut links.
orig (unicode / Path): The origin path.
dest (unicode / Path): The destination path of the symlink.
"""
if is_windows:
import subprocess
subprocess.check_call(['mklink', '/d', path2str(orig), path2str(de... |
def get_panels(self):
"""Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
"""
all_panels = []
panel_groups = self.get_panel_groups()
for panel_group in panel_groups.values():
all_panels.extend(pa... | def function[get_panels, parameter[self]]:
constant[Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
]
variable[all_panels] assign[=] list[[]]
variable[panel_groups] assign[=] call[name[self].get_panel_groups, param... | keyword[def] identifier[get_panels] ( identifier[self] ):
literal[string]
identifier[all_panels] =[]
identifier[panel_groups] = identifier[self] . identifier[get_panel_groups] ()
keyword[for] identifier[panel_group] keyword[in] identifier[panel_groups] . identifier[values] ():
... | def get_panels(self):
"""Returns the Panel instances registered with this dashboard in order.
Panel grouping information is not included.
"""
all_panels = []
panel_groups = self.get_panel_groups()
for panel_group in panel_groups.values():
all_panels.extend(panel_group) # depend... |
def make_relative(cls, course_locator, block_type, block_id):
"""
Return a new instance which has the given block_id in the given course
:param course_locator: may be a BlockUsageLocator in the same snapshot
"""
if hasattr(course_locator, 'course_key'):
course_locator... | def function[make_relative, parameter[cls, course_locator, block_type, block_id]]:
constant[
Return a new instance which has the given block_id in the given course
:param course_locator: may be a BlockUsageLocator in the same snapshot
]
if call[name[hasattr], parameter[name[cours... | keyword[def] identifier[make_relative] ( identifier[cls] , identifier[course_locator] , identifier[block_type] , identifier[block_id] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[course_locator] , literal[string] ):
identifier[course_locator] = identifier[course_loc... | def make_relative(cls, course_locator, block_type, block_id):
"""
Return a new instance which has the given block_id in the given course
:param course_locator: may be a BlockUsageLocator in the same snapshot
"""
if hasattr(course_locator, 'course_key'):
course_locator = course_lo... |
def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev
return None | def function[find_device_by_name, parameter[name]]:
constant[Tries to find a board by board name.]
if <ast.UnaryOp object at 0x7da2047ebe50> begin[:]
return[name[DEFAULT_DEV]]
with name[DEV_LOCK] begin[:]
for taget[name[dev]] in starred[name[DEVS]] begin[:]
... | keyword[def] identifier[find_device_by_name] ( identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[name] :
keyword[return] identifier[DEFAULT_DEV]
keyword[with] identifier[DEV_LOCK] :
keyword[for] identifier[dev] keyword[in] identifier[DEVS] :
... | def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV # depends on [control=['if'], data=[]]
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev # depends on [control=['if'], data=[]] # depends on ... |
def addImage(self, image, mask=None):
'''
#########
mask -- optional
'''
self._last_diff = diff = image - self.noSTE
ste = diff > self.threshold
removeSinglePixels(ste)
self.mask_clean = clean = ~ste
if mask is not None:
... | def function[addImage, parameter[self, image, mask]]:
constant[
#########
mask -- optional
]
name[self]._last_diff assign[=] binary_operation[name[image] - name[self].noSTE]
variable[ste] assign[=] compare[name[diff] greater[>] name[self].threshold]
call[name[remo... | keyword[def] identifier[addImage] ( identifier[self] , identifier[image] , identifier[mask] = keyword[None] ):
literal[string]
identifier[self] . identifier[_last_diff] = identifier[diff] = identifier[image] - identifier[self] . identifier[noSTE]
identifier[ste] = identifier[diff] > ... | def addImage(self, image, mask=None):
"""
#########
mask -- optional
"""
self._last_diff = diff = image - self.noSTE
ste = diff > self.threshold
removeSinglePixels(ste)
self.mask_clean = clean = ~ste
if mask is not None:
clean = np.logical_and(mask, clean) # depe... |
def flaskify(response, headers=None, encoder=None):
"""Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Arg... | def function[flaskify, parameter[response, headers, encoder]]:
constant[Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset ... | keyword[def] identifier[flaskify] ( identifier[response] , identifier[headers] = keyword[None] , identifier[encoder] = keyword[None] ):
literal[string]
identifier[status_code] = identifier[response] . identifier[status]
identifier[data] = identifier[response] . identifier[errors] keyword[or] ident... | def flaskify(response, headers=None, encoder=None):
"""Format the response to be consumeable by flask.
The api returns mostly JSON responses. The format method converts the dicts
into a json object (as a string), and the right response is returned (with
the valid mimetype, charset and status.)
Arg... |
def catch_osd_errors(conn, logger, args):
"""
Look for possible issues when checking the status of an OSD and
report them back to the user.
"""
logger.info('checking OSD status...')
status = osd_status_check(conn, args.cluster)
osds = int(status.get('num_osds', 0))
up_osds = int(status.g... | def function[catch_osd_errors, parameter[conn, logger, args]]:
constant[
Look for possible issues when checking the status of an OSD and
report them back to the user.
]
call[name[logger].info, parameter[constant[checking OSD status...]]]
variable[status] assign[=] call[name[osd_statu... | keyword[def] identifier[catch_osd_errors] ( identifier[conn] , identifier[logger] , identifier[args] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
identifier[status] = identifier[osd_status_check] ( identifier[conn] , identifier[args] . identifier[cluster] )
identif... | def catch_osd_errors(conn, logger, args):
"""
Look for possible issues when checking the status of an OSD and
report them back to the user.
"""
logger.info('checking OSD status...')
status = osd_status_check(conn, args.cluster)
osds = int(status.get('num_osds', 0))
up_osds = int(status.g... |
def to_dict(self):
"""Convert back to the pstats dictionary representation (used for saving back as pstats binary file)"""
if self.subcall is not None:
if isinstance(self.subcall, dict):
subcalls = self.subcall
else:
subcalls = {}
f... | def function[to_dict, parameter[self]]:
constant[Convert back to the pstats dictionary representation (used for saving back as pstats binary file)]
if compare[name[self].subcall is_not constant[None]] begin[:]
if call[name[isinstance], parameter[name[self].subcall, name[dict]]] begin[:]
... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[subcall] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[isinstance] ( identifier[self] . identifier[subcall] , identifier[dict] ):
ide... | def to_dict(self):
"""Convert back to the pstats dictionary representation (used for saving back as pstats binary file)"""
if self.subcall is not None:
if isinstance(self.subcall, dict):
subcalls = self.subcall # depends on [control=['if'], data=[]]
else:
subcalls = {}
... |
def QA_util_get_trade_datetime(dt=datetime.datetime.now()):
"""交易的真实日期
Returns:
[type] -- [description]
"""
#dt= datetime.datetime.now()
if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0):
return str(dt.date())
else:
return QA_util_get_real_dat... | def function[QA_util_get_trade_datetime, parameter[dt]]:
constant[交易的真实日期
Returns:
[type] -- [description]
]
if <ast.BoolOp object at 0x7da1b1f770d0> begin[:]
return[call[name[str], parameter[call[name[dt].date, parameter[]]]]] | keyword[def] identifier[QA_util_get_trade_datetime] ( identifier[dt] = identifier[datetime] . identifier[datetime] . identifier[now] ()):
literal[string]
keyword[if] identifier[QA_util_if_trade] ( identifier[str] ( identifier[dt] . identifier[date] ())) keyword[and] identifier[dt] . identifier[tim... | def QA_util_get_trade_datetime(dt=datetime.datetime.now()):
"""交易的真实日期
Returns:
[type] -- [description]
"""
#dt= datetime.datetime.now()
if QA_util_if_trade(str(dt.date())) and dt.time() < datetime.time(15, 0, 0):
return str(dt.date()) # depends on [control=['if'], data=[]]
els... |
def calc_dewpoint(temp, hum):
'''
calculates the dewpoint via the formula from weatherwise.org
return the dewpoint in degrees F.
'''
c = fahrenheit_to_celsius(temp)
x = 1 - 0.01 * hum;
dewpoint = (14.55 + 0.114 * c) * x;
dewpoint = dewpoint + ((2.5 + 0.007 * c) * x) ** 3;
dewpoint ... | def function[calc_dewpoint, parameter[temp, hum]]:
constant[
calculates the dewpoint via the formula from weatherwise.org
return the dewpoint in degrees F.
]
variable[c] assign[=] call[name[fahrenheit_to_celsius], parameter[name[temp]]]
variable[x] assign[=] binary_operation[constant... | keyword[def] identifier[calc_dewpoint] ( identifier[temp] , identifier[hum] ):
literal[string]
identifier[c] = identifier[fahrenheit_to_celsius] ( identifier[temp] )
identifier[x] = literal[int] - literal[int] * identifier[hum] ;
identifier[dewpoint] =( literal[int] + literal[int] * identifier[... | def calc_dewpoint(temp, hum):
"""
calculates the dewpoint via the formula from weatherwise.org
return the dewpoint in degrees F.
"""
c = fahrenheit_to_celsius(temp)
x = 1 - 0.01 * hum
dewpoint = (14.55 + 0.114 * c) * x
dewpoint = dewpoint + ((2.5 + 0.007 * c) * x) ** 3
dewpoint = dew... |
def get_objective_requisite_assignment_session(self, *args, **kwargs):
"""Gets the session for managing objective requisites.
return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an
ObjectiveRequisiteAssignmentSession
raise: OperationFailed - unable to complete request... | def function[get_objective_requisite_assignment_session, parameter[self]]:
constant[Gets the session for managing objective requisites.
return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an
ObjectiveRequisiteAssignmentSession
raise: OperationFailed - unable to comple... | keyword[def] identifier[get_objective_requisite_assignment_session] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[supports_objective_requisite_assignment] ():
keyword[raise] identifier[Unimplem... | def get_objective_requisite_assignment_session(self, *args, **kwargs):
"""Gets the session for managing objective requisites.
return: (osid.learning.ObjectiveRequisiteAssignmentSession) - an
ObjectiveRequisiteAssignmentSession
raise: OperationFailed - unable to complete request
... |
def _get_9q_square_qvm(name: str, noisy: bool,
connection: ForestConnection = None,
qvm_type: str = 'qvm') -> QuantumComputer:
"""
A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do... | def function[_get_9q_square_qvm, parameter[name, noisy, connection, qvm_type]]:
constant[
A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do vaguely interesting algorithms and small enough to simulate quickly.
:param n... | keyword[def] identifier[_get_9q_square_qvm] ( identifier[name] : identifier[str] , identifier[noisy] : identifier[bool] ,
identifier[connection] : identifier[ForestConnection] = keyword[None] ,
identifier[qvm_type] : identifier[str] = literal[string] )-> identifier[QuantumComputer] :
literal[string]
iden... | def _get_9q_square_qvm(name: str, noisy: bool, connection: ForestConnection=None, qvm_type: str='qvm') -> QuantumComputer:
"""
A nine-qubit 3x3 square lattice.
This uses a "generic" lattice not tied to any specific device. 9 qubits is large enough
to do vaguely interesting algorithms and small enough t... |
def cluster_replicate(self, node_id):
"""Reconfigure a node as a slave of the specified master node."""
fut = self.execute(b'CLUSTER', b'REPLICATE', node_id)
return wait_ok(fut) | def function[cluster_replicate, parameter[self, node_id]]:
constant[Reconfigure a node as a slave of the specified master node.]
variable[fut] assign[=] call[name[self].execute, parameter[constant[b'CLUSTER'], constant[b'REPLICATE'], name[node_id]]]
return[call[name[wait_ok], parameter[name[fut]]]] | keyword[def] identifier[cluster_replicate] ( identifier[self] , identifier[node_id] ):
literal[string]
identifier[fut] = identifier[self] . identifier[execute] ( literal[string] , literal[string] , identifier[node_id] )
keyword[return] identifier[wait_ok] ( identifier[fut] ) | def cluster_replicate(self, node_id):
"""Reconfigure a node as a slave of the specified master node."""
fut = self.execute(b'CLUSTER', b'REPLICATE', node_id)
return wait_ok(fut) |
def _get_specifications(specifications):
"""
Computes the list of strings corresponding to the given specifications
:param specifications: A string, a class or a list of specifications
:return: A list of strings
:raise ValueError: Invalid specification found
"""
if not specifications or spe... | def function[_get_specifications, parameter[specifications]]:
constant[
Computes the list of strings corresponding to the given specifications
:param specifications: A string, a class or a list of specifications
:return: A list of strings
:raise ValueError: Invalid specification found
]
... | keyword[def] identifier[_get_specifications] ( identifier[specifications] ):
literal[string]
keyword[if] keyword[not] identifier[specifications] keyword[or] identifier[specifications] keyword[is] identifier[object] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[eli... | def _get_specifications(specifications):
"""
Computes the list of strings corresponding to the given specifications
:param specifications: A string, a class or a list of specifications
:return: A list of strings
:raise ValueError: Invalid specification found
"""
if not specifications or spe... |
def sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias,
sampled_values, remove_accidental_hits=True):
""" Sampled softmax via importance sampling.
This under-estimates the full softmax and is only used for training.
"""
# inputs = (n, in_dim)
... | def function[sampled_softmax, parameter[num_classes, num_samples, in_dim, inputs, weight, bias, sampled_values, remove_accidental_hits]]:
constant[ Sampled softmax via importance sampling.
This under-estimates the full softmax and is only used for training.
]
<ast.Tuple object at 0x7... | keyword[def] identifier[sampled_softmax] ( identifier[num_classes] , identifier[num_samples] , identifier[in_dim] , identifier[inputs] , identifier[weight] , identifier[bias] ,
identifier[sampled_values] , identifier[remove_accidental_hits] = keyword[True] ):
literal[string]
identifier[sa... | def sampled_softmax(num_classes, num_samples, in_dim, inputs, weight, bias, sampled_values, remove_accidental_hits=True):
""" Sampled softmax via importance sampling.
This under-estimates the full softmax and is only used for training.
"""
# inputs = (n, in_dim)
(sample, prob_sample, pro... |
def cast_object(self, interface_object, interface_class):
"""Cast the obj to the interface class
:rtype: interface_class(interface_object)
"""
name = interface_class.__name__
i = self.manager.queryInterface(interface_object._i, name)
return interface_class(interface=i) | def function[cast_object, parameter[self, interface_object, interface_class]]:
constant[Cast the obj to the interface class
:rtype: interface_class(interface_object)
]
variable[name] assign[=] name[interface_class].__name__
variable[i] assign[=] call[name[self].manager.queryInte... | keyword[def] identifier[cast_object] ( identifier[self] , identifier[interface_object] , identifier[interface_class] ):
literal[string]
identifier[name] = identifier[interface_class] . identifier[__name__]
identifier[i] = identifier[self] . identifier[manager] . identifier[queryInterface]... | def cast_object(self, interface_object, interface_class):
"""Cast the obj to the interface class
:rtype: interface_class(interface_object)
"""
name = interface_class.__name__
i = self.manager.queryInterface(interface_object._i, name)
return interface_class(interface=i) |
def wait_until(obj, att, desired, callback=None, interval=5, attempts=0,
verbose=False, verbose_atts=None):
"""
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att... | def function[wait_until, parameter[obj, att, desired, callback, interval, attempts, verbose, verbose_atts]]:
constant[
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `... | keyword[def] identifier[wait_until] ( identifier[obj] , identifier[att] , identifier[desired] , identifier[callback] = keyword[None] , identifier[interval] = literal[int] , identifier[attempts] = literal[int] ,
identifier[verbose] = keyword[False] , identifier[verbose_atts] = keyword[None] ):
literal[string]
... | def wait_until(obj, att, desired, callback=None, interval=5, attempts=0, verbose=False, verbose_atts=None):
"""
When changing the state of an object, it will commonly be in a transitional
state until the change is complete. This will reload the object every
`interval` seconds, and check its `att` attrib... |
def values(self, key=_absent):
"""
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
"""
if key is not _... | def function[values, parameter[self, key]]:
constant[
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
]
... | keyword[def] identifier[values] ( identifier[self] , identifier[key] = identifier[_absent] ):
literal[string]
keyword[if] identifier[key] keyword[is] keyword[not] identifier[_absent] keyword[and] identifier[key] keyword[in] identifier[self] . identifier[_map] :
keyword[return] ... | def values(self, key=_absent):
"""
Raises: KeyError if <key> is provided and not in the dictionary.
Returns: List created from itervalues(<key>).If <key> is provided and
is a dictionary key, only values of items with key <key> are
returned.
"""
if key is not _absent a... |
def _options_protobuf(self, retry_id):
"""Convert the current object to protobuf.
The ``retry_id`` value is used when retrying a transaction that
failed (e.g. due to contention). It is intended to be the "first"
transaction that failed (i.e. if multiple retries are needed).
Arg... | def function[_options_protobuf, parameter[self, retry_id]]:
constant[Convert the current object to protobuf.
The ``retry_id`` value is used when retrying a transaction that
failed (e.g. due to contention). It is intended to be the "first"
transaction that failed (i.e. if multiple retrie... | keyword[def] identifier[_options_protobuf] ( identifier[self] , identifier[retry_id] ):
literal[string]
keyword[if] identifier[retry_id] keyword[is] keyword[not] keyword[None] :
keyword[if] identifier[self] . identifier[_read_only] :
keyword[raise] identifier[Val... | def _options_protobuf(self, retry_id):
"""Convert the current object to protobuf.
The ``retry_id`` value is used when retrying a transaction that
failed (e.g. due to contention). It is intended to be the "first"
transaction that failed (i.e. if multiple retries are needed).
Args:
... |
def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
"""
super(SingleWidgetWindowController, self).register_view(view)
self.shortcut_manager = ShortcutManager(sel... | def function[register_view, parameter[self, view]]:
constant[Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
]
call[call[name[super], parameter[name[SingleWidgetWindowController], name[self]]].regist... | keyword[def] identifier[register_view] ( identifier[self] , identifier[view] ):
literal[string]
identifier[super] ( identifier[SingleWidgetWindowController] , identifier[self] ). identifier[register_view] ( identifier[view] )
identifier[self] . identifier[shortcut_manager] = identifier[Sho... | def register_view(self, view):
"""Called when the View was registered
Can be used e.g. to connect signals. Here, the destroy signal is connected to close the application
"""
super(SingleWidgetWindowController, self).register_view(view)
self.shortcut_manager = ShortcutManager(self.view['main... |
def split_lists(d, split_keys, new_name='split',
check_length=True, deepcopy=True):
"""split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
ne... | def function[split_lists, parameter[d, split_keys, new_name, check_length, deepcopy]]:
constant[split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
new_n... | keyword[def] identifier[split_lists] ( identifier[d] , identifier[split_keys] , identifier[new_name] = literal[string] ,
identifier[check_length] = keyword[True] , identifier[deepcopy] = keyword[True] ):
literal[string]
identifier[flattened] = identifier[flatten2d] ( identifier[d] )
identifier[new_d... | def split_lists(d, split_keys, new_name='split', check_length=True, deepcopy=True):
"""split_lists key:list pairs into dicts for each item in the lists
NB: will only split if all split_keys are present
Parameters
----------
d : dict
split_keys : list
keys to split
new_name : str
... |
def reward_battery(self):
"""
Add a battery level reward
"""
if not 'battery' in self.mode:
return
mode = self.mode['battery']
if mode and mode and self.__test_cond(mode):
self.logger.debug('Battery out')
self.player.stats['reward'] += ... | def function[reward_battery, parameter[self]]:
constant[
Add a battery level reward
]
if <ast.UnaryOp object at 0x7da1b2554730> begin[:]
return[None]
variable[mode] assign[=] call[name[self].mode][constant[battery]]
if <ast.BoolOp object at 0x7da1b2554a30> begin[:... | keyword[def] identifier[reward_battery] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] literal[string] keyword[in] identifier[self] . identifier[mode] :
keyword[return]
identifier[mode] = identifier[self] . identifier[mode] [ literal[string] ]
key... | def reward_battery(self):
"""
Add a battery level reward
"""
if not 'battery' in self.mode:
return # depends on [control=['if'], data=[]]
mode = self.mode['battery']
if mode and mode and self.__test_cond(mode):
self.logger.debug('Battery out')
self.player.stats['... |
def get_vnetwork_vms_input_vcenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_vnetwork_vms = ET.Element("get_vnetwork_vms")
config = get_vnetwork_vms
input = ET.SubElement(get_vnetwork_vms, "input")
vcenter = ET.SubElement(input,... | def function[get_vnetwork_vms_input_vcenter, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[get_vnetwork_vms] assign[=] call[name[ET].Element, parameter[constant[get_vnetwork_vms]]]
variable... | keyword[def] identifier[get_vnetwork_vms_input_vcenter] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[get_vnetwork_vms] = identifier[ET] . identifier[Element] ( literal[string] )
... | def get_vnetwork_vms_input_vcenter(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
get_vnetwork_vms = ET.Element('get_vnetwork_vms')
config = get_vnetwork_vms
input = ET.SubElement(get_vnetwork_vms, 'input')
vcenter = ET.SubElement(input, 'vcenter')
vcenter.... |
def hide_shortcuts(self, menu):
"""Hide action shortcuts in menu"""
for element in getattr(self, menu + '_menu_actions'):
if element and isinstance(element, QAction):
if element._shown_shortcut is not None:
element.setShortcut(QKeySequence()) | def function[hide_shortcuts, parameter[self, menu]]:
constant[Hide action shortcuts in menu]
for taget[name[element]] in starred[call[name[getattr], parameter[name[self], binary_operation[name[menu] + constant[_menu_actions]]]]] begin[:]
if <ast.BoolOp object at 0x7da18bcc95d0> begin[:]
... | keyword[def] identifier[hide_shortcuts] ( identifier[self] , identifier[menu] ):
literal[string]
keyword[for] identifier[element] keyword[in] identifier[getattr] ( identifier[self] , identifier[menu] + literal[string] ):
keyword[if] identifier[element] keyword[and] identifier[... | def hide_shortcuts(self, menu):
"""Hide action shortcuts in menu"""
for element in getattr(self, menu + '_menu_actions'):
if element and isinstance(element, QAction):
if element._shown_shortcut is not None:
element.setShortcut(QKeySequence()) # depends on [control=['if'], da... |
def CmdAuthenticate(self,
challenge_param,
app_param,
key_handle,
check_only=False):
"""Attempt to obtain an authentication signature.
Ask the security key to sign a challenge for a particular key handle
in order to aut... | def function[CmdAuthenticate, parameter[self, challenge_param, app_param, key_handle, check_only]]:
constant[Attempt to obtain an authentication signature.
Ask the security key to sign a challenge for a particular key handle
in order to authenticate the user.
Args:
challenge_param: SHA-256 h... | keyword[def] identifier[CmdAuthenticate] ( identifier[self] ,
identifier[challenge_param] ,
identifier[app_param] ,
identifier[key_handle] ,
identifier[check_only] = keyword[False] ):
literal[string]
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
keyword[if] identif... | def CmdAuthenticate(self, challenge_param, app_param, key_handle, check_only=False):
"""Attempt to obtain an authentication signature.
Ask the security key to sign a challenge for a particular key handle
in order to authenticate the user.
Args:
challenge_param: SHA-256 hash of client_data object... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.