code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def at_line(self, line: FileLine) -> Iterator[InsertionPoint]:
"""
Returns an iterator over all of the insertion points located at a
given line.
"""
logger.debug("finding insertion points at line: %s", str(line))
filename = line.filename # type: str
line_num = li... | def function[at_line, parameter[self, line]]:
constant[
Returns an iterator over all of the insertion points located at a
given line.
]
call[name[logger].debug, parameter[constant[finding insertion points at line: %s], call[name[str], parameter[name[line]]]]]
variable[fil... | keyword[def] identifier[at_line] ( identifier[self] , identifier[line] : identifier[FileLine] )-> identifier[Iterator] [ identifier[InsertionPoint] ]:
literal[string]
identifier[logger] . identifier[debug] ( literal[string] , identifier[str] ( identifier[line] ))
identifier[filename] = ide... | def at_line(self, line: FileLine) -> Iterator[InsertionPoint]:
"""
Returns an iterator over all of the insertion points located at a
given line.
"""
logger.debug('finding insertion points at line: %s', str(line))
filename = line.filename # type: str
line_num = line.num # type: ... |
def theano_compiler(model):
"""Take a triflow model and return optimized theano routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(theano function, theano_function):
Optimized routine that compute the evolution equations and their
... | def function[theano_compiler, parameter[model]]:
constant[Take a triflow model and return optimized theano routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(theano function, theano_function):
Optimized routine that compute the evolu... | keyword[def] identifier[theano_compiler] ( identifier[model] ):
literal[string]
keyword[from] identifier[theano] keyword[import] identifier[tensor] keyword[as] identifier[T]
keyword[from] identifier[theano] . identifier[ifelse] keyword[import] identifier[ifelse]
keyword[import] identif... | def theano_compiler(model):
"""Take a triflow model and return optimized theano routines.
Parameters
----------
model: triflow.Model:
Model to compile
Returns
-------
(theano function, theano_function):
Optimized routine that compute the evolution equations and their
... |
def _appendReportKeys(keys, prefix, results):
"""
Generate a set of possible report keys for an experiment's results.
A report key is a string of key names separated by colons, each key being one
level deeper into the experiment results dict. For example, 'key1:key2'.
This routine is called recursively to bu... | def function[_appendReportKeys, parameter[keys, prefix, results]]:
constant[
Generate a set of possible report keys for an experiment's results.
A report key is a string of key names separated by colons, each key being one
level deeper into the experiment results dict. For example, 'key1:key2'.
This ro... | keyword[def] identifier[_appendReportKeys] ( identifier[keys] , identifier[prefix] , identifier[results] ):
literal[string]
identifier[allKeys] = identifier[results] . identifier[keys] ()
identifier[allKeys] . identifier[sort] ()
keyword[for] identifier[key] keyword[in] identifier[allKeys] :
key... | def _appendReportKeys(keys, prefix, results):
"""
Generate a set of possible report keys for an experiment's results.
A report key is a string of key names separated by colons, each key being one
level deeper into the experiment results dict. For example, 'key1:key2'.
This routine is called recursively to ... |
def _refresh_nvr(self):
""" Refresh our name-version-release attributes. """
rpm_info = juicer.utils.rpm_info(self.path)
self.name = rpm_info['name']
self.version = rpm_info['version']
self.release = rpm_info['release'] | def function[_refresh_nvr, parameter[self]]:
constant[ Refresh our name-version-release attributes. ]
variable[rpm_info] assign[=] call[name[juicer].utils.rpm_info, parameter[name[self].path]]
name[self].name assign[=] call[name[rpm_info]][constant[name]]
name[self].version assign[=] cal... | keyword[def] identifier[_refresh_nvr] ( identifier[self] ):
literal[string]
identifier[rpm_info] = identifier[juicer] . identifier[utils] . identifier[rpm_info] ( identifier[self] . identifier[path] )
identifier[self] . identifier[name] = identifier[rpm_info] [ literal[string] ]
i... | def _refresh_nvr(self):
""" Refresh our name-version-release attributes. """
rpm_info = juicer.utils.rpm_info(self.path)
self.name = rpm_info['name']
self.version = rpm_info['version']
self.release = rpm_info['release'] |
def check_packet(self):
'''is there a valid packet (from another thread) for this app/instance?'''
if not os.path.exists(self.packet_file()):
# No packet file, we're good
return True
else:
# There's already a file, but is it still running?
try:
... | def function[check_packet, parameter[self]]:
constant[is there a valid packet (from another thread) for this app/instance?]
if <ast.UnaryOp object at 0x7da18f00d150> begin[:]
return[constant[True]] | keyword[def] identifier[check_packet] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[exists] ( identifier[self] . identifier[packet_file] ()):
keyword[return] keyword[True]
keyword[else] :
... | def check_packet(self):
"""is there a valid packet (from another thread) for this app/instance?"""
if not os.path.exists(self.packet_file()):
# No packet file, we're good
return True # depends on [control=['if'], data=[]]
else:
# There's already a file, but is it still running?
... |
def decrypt_PBEWithSHAAndTwofishCBC(encrypted_data, password, salt, iteration_count):
"""
Decrypts PBEWithSHAAndTwofishCBC, assuming PKCS#12-generated PBE parameters.
(Not explicitly defined as an algorithm in RFC 7292, but defined here nevertheless because of the assumption of PKCS#12 parameters).
"""
... | def function[decrypt_PBEWithSHAAndTwofishCBC, parameter[encrypted_data, password, salt, iteration_count]]:
constant[
Decrypts PBEWithSHAAndTwofishCBC, assuming PKCS#12-generated PBE parameters.
(Not explicitly defined as an algorithm in RFC 7292, but defined here nevertheless because of the assumption o... | keyword[def] identifier[decrypt_PBEWithSHAAndTwofishCBC] ( identifier[encrypted_data] , identifier[password] , identifier[salt] , identifier[iteration_count] ):
literal[string]
identifier[iv] = identifier[derive_key] ( identifier[hashlib] . identifier[sha1] , identifier[PURPOSE_IV_MATERIAL] , identifier[pa... | def decrypt_PBEWithSHAAndTwofishCBC(encrypted_data, password, salt, iteration_count):
"""
Decrypts PBEWithSHAAndTwofishCBC, assuming PKCS#12-generated PBE parameters.
(Not explicitly defined as an algorithm in RFC 7292, but defined here nevertheless because of the assumption of PKCS#12 parameters).
"""
... |
def retry_with_delay(f, delay=60):
"""
Retry the wrapped requests.request function in case of ConnectionError.
Optionally limit the number of retries or set the delay between retries.
"""
@wraps(f)
def inner(*args, **kwargs):
kwargs['timeout'] = 5
remaining = get_retries() + 1
... | def function[retry_with_delay, parameter[f, delay]]:
constant[
Retry the wrapped requests.request function in case of ConnectionError.
Optionally limit the number of retries or set the delay between retries.
]
def function[inner, parameter[]]:
call[name[kwargs]][constant[time... | keyword[def] identifier[retry_with_delay] ( identifier[f] , identifier[delay] = literal[int] ):
literal[string]
@ identifier[wraps] ( identifier[f] )
keyword[def] identifier[inner] (* identifier[args] ,** identifier[kwargs] ):
identifier[kwargs] [ literal[string] ]= literal[int]
ide... | def retry_with_delay(f, delay=60):
"""
Retry the wrapped requests.request function in case of ConnectionError.
Optionally limit the number of retries or set the delay between retries.
"""
@wraps(f)
def inner(*args, **kwargs):
kwargs['timeout'] = 5
remaining = get_retries() + 1
... |
def _get_rest_key_parts(cls, attr_key):
"""Get the RestAPI key of this attr, split it and decode part
:param str attr_key: Attribute key must be in attribute_map.
:returns: A list of RestAPI part
:rtype: list
"""
rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key... | def function[_get_rest_key_parts, parameter[cls, attr_key]]:
constant[Get the RestAPI key of this attr, split it and decode part
:param str attr_key: Attribute key must be in attribute_map.
:returns: A list of RestAPI part
:rtype: list
]
variable[rest_split_key] assign[=]... | keyword[def] identifier[_get_rest_key_parts] ( identifier[cls] , identifier[attr_key] ):
literal[string]
identifier[rest_split_key] = identifier[_FLATTEN] . identifier[split] ( identifier[cls] . identifier[_attribute_map] [ identifier[attr_key] ][ literal[string] ])
keyword[return] [ ident... | def _get_rest_key_parts(cls, attr_key):
"""Get the RestAPI key of this attr, split it and decode part
:param str attr_key: Attribute key must be in attribute_map.
:returns: A list of RestAPI part
:rtype: list
"""
rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]['key']... |
async def preprocess_request(
self, request_context: Optional[RequestContext]=None,
) -> Optional[ResponseReturnValue]:
"""Preprocess the request i.e. call before_request functions.
Arguments:
request_context: The request context, optional as Flask
omits this arg... | <ast.AsyncFunctionDef object at 0x7da20e9b0dc0> | keyword[async] keyword[def] identifier[preprocess_request] (
identifier[self] , identifier[request_context] : identifier[Optional] [ identifier[RequestContext] ]= keyword[None] ,
)-> identifier[Optional] [ identifier[ResponseReturnValue] ]:
literal[string]
identifier[request_] =( identifier[reque... | async def preprocess_request(self, request_context: Optional[RequestContext]=None) -> Optional[ResponseReturnValue]:
"""Preprocess the request i.e. call before_request functions.
Arguments:
request_context: The request context, optional as Flask
omits this argument.
"""
... |
def terminating_sip_domains(self):
"""
Access the terminating_sip_domains
:returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList
:rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList
"""
if self._terminatin... | def function[terminating_sip_domains, parameter[self]]:
constant[
Access the terminating_sip_domains
:returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList
:rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList
]
... | keyword[def] identifier[terminating_sip_domains] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_terminating_sip_domains] keyword[is] keyword[None] :
identifier[self] . identifier[_terminating_sip_domains] = identifier[TerminatingSipDomainList] (
... | def terminating_sip_domains(self):
"""
Access the terminating_sip_domains
:returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList
:rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainList
"""
if self._terminating_sip_do... |
def add_image_info_cb(self, gshell, channel, iminfo):
"""Add entries related to an added image."""
timestamp = iminfo.time_modified
if timestamp is None:
# Not an image we are interested in tracking
return
self.add_entry(channel.name, iminfo) | def function[add_image_info_cb, parameter[self, gshell, channel, iminfo]]:
constant[Add entries related to an added image.]
variable[timestamp] assign[=] name[iminfo].time_modified
if compare[name[timestamp] is constant[None]] begin[:]
return[None]
call[name[self].add_entry, para... | keyword[def] identifier[add_image_info_cb] ( identifier[self] , identifier[gshell] , identifier[channel] , identifier[iminfo] ):
literal[string]
identifier[timestamp] = identifier[iminfo] . identifier[time_modified]
keyword[if] identifier[timestamp] keyword[is] keyword[None] :
... | def add_image_info_cb(self, gshell, channel, iminfo):
"""Add entries related to an added image."""
timestamp = iminfo.time_modified
if timestamp is None:
# Not an image we are interested in tracking
return # depends on [control=['if'], data=[]]
self.add_entry(channel.name, iminfo) |
def any_char_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CharField(max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length)
return xuni... | def function[any_char_field, parameter[field]]:
constant[
Return random value for CharField
>>> result = any_field(models.CharField(max_length=10))
>>> type(result)
<type 'str'>
]
variable[min_length] assign[=] call[name[kwargs].get, parameter[constant[min_length], constant[1]]]
... | keyword[def] identifier[any_char_field] ( identifier[field] ,** identifier[kwargs] ):
literal[string]
identifier[min_length] = identifier[kwargs] . identifier[get] ( literal[string] , literal[int] )
identifier[max_length] = identifier[kwargs] . identifier[get] ( literal[string] , identifier[field] ... | def any_char_field(field, **kwargs):
"""
Return random value for CharField
>>> result = any_field(models.CharField(max_length=10))
>>> type(result)
<type 'str'>
"""
min_length = kwargs.get('min_length', 1)
max_length = kwargs.get('max_length', field.max_length)
return xunit.any_stri... |
def make_yaml_patterns():
"Strongly inspired from sublime highlighter "
kw = any("keyword", [r":|>|-|\||\[|\]|[A-Za-z][\w\s\-\_ ]+(?=:)"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
... | def function[make_yaml_patterns, parameter[]]:
constant[Strongly inspired from sublime highlighter ]
variable[kw] assign[=] call[name[any], parameter[constant[keyword], list[[<ast.Constant object at 0x7da20c7c95a0>]]]]
variable[links] assign[=] call[name[any], parameter[constant[normal], list[[<... | keyword[def] identifier[make_yaml_patterns] ():
literal[string]
identifier[kw] = identifier[any] ( literal[string] ,[ literal[string] ])
identifier[links] = identifier[any] ( literal[string] ,[ literal[string] ])
identifier[comment] = identifier[any] ( literal[string] ,[ literal[string] ])
... | def make_yaml_patterns():
"""Strongly inspired from sublime highlighter """
kw = any('keyword', [':|>|-|\\||\\[|\\]|[A-Za-z][\\w\\s\\-\\_ ]+(?=:)'])
links = any('normal', ['#:[^\\n]*'])
comment = any('comment', ['#[^\\n]*'])
number = any('number', ['\\b[+-]?[0-9]+[lL]?\\b', '\\b[+-]?0[xX][0-9A-Fa-f]... |
def convert_utc_time(datetime_str):
"""
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
dateti... | def function[convert_utc_time, parameter[datetime_str]]:
constant[
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDT... | keyword[def] identifier[convert_utc_time] ( identifier[datetime_str] ):
literal[string]
keyword[if] keyword[not] identifier[datetime_str] :
keyword[return] keyword[None]
keyword[if] keyword[not] identifier[set] ([ literal[string] , literal[string] ])& identifier[set] ( identifier[dateti... | def convert_utc_time(datetime_str):
"""
Handles datetime argument conversion to the GNIP API format, which is
`YYYYMMDDHHSS`. Flexible passing of date formats in the following types::
- YYYYmmDDHHMM
- YYYY-mm-DD
- YYYY-mm-DD HH:MM
- YYYY-mm-DDTHH:MM
Args:
dateti... |
def find_team(self, color: str = None):
"""Find the :class:`~.Team` with the given properties
Returns the team whose attributes match the given properties, or
``None`` if no match is found.
:param color: The :class:`~.Team.Color` of the Team
"""
if color != None:
... | def function[find_team, parameter[self, color]]:
constant[Find the :class:`~.Team` with the given properties
Returns the team whose attributes match the given properties, or
``None`` if no match is found.
:param color: The :class:`~.Team.Color` of the Team
]
if compare[... | keyword[def] identifier[find_team] ( identifier[self] , identifier[color] : identifier[str] = keyword[None] ):
literal[string]
keyword[if] identifier[color] != keyword[None] :
keyword[if] identifier[color] keyword[is] identifier[Team] . identifier[Color] . identifier[BLUE] :
... | def find_team(self, color: str=None):
"""Find the :class:`~.Team` with the given properties
Returns the team whose attributes match the given properties, or
``None`` if no match is found.
:param color: The :class:`~.Team.Color` of the Team
"""
if color != None:
if color... |
def nr_cases(self, institute_id=None):
"""Return the number of cases
This function will change when we migrate to 3.7.1
Args:
collaborator(str): Institute id
Returns:
nr_cases(int)
"""
query = {}
if institute_id:
query['coll... | def function[nr_cases, parameter[self, institute_id]]:
constant[Return the number of cases
This function will change when we migrate to 3.7.1
Args:
collaborator(str): Institute id
Returns:
nr_cases(int)
]
variable[query] assign[=] dictionary[[],... | keyword[def] identifier[nr_cases] ( identifier[self] , identifier[institute_id] = keyword[None] ):
literal[string]
identifier[query] ={}
keyword[if] identifier[institute_id] :
identifier[query] [ literal[string] ]= identifier[institute_id]
identifier[LOG] . identi... | def nr_cases(self, institute_id=None):
"""Return the number of cases
This function will change when we migrate to 3.7.1
Args:
collaborator(str): Institute id
Returns:
nr_cases(int)
"""
query = {}
if institute_id:
query['collaborators'] = ins... |
def run(cmds, **kwargs):
"""
Wrapper around subprocess.run, with unicode decoding of output.
Additional kwargs are passed to subprocess.run.
"""
proc = sp.Popen(cmds, bufsize=-1, stdout=sp.PIPE, stderr=sp.STDOUT,
close_fds=sys.platform != 'win32')
for line in proc.stdout:
... | def function[run, parameter[cmds]]:
constant[
Wrapper around subprocess.run, with unicode decoding of output.
Additional kwargs are passed to subprocess.run.
]
variable[proc] assign[=] call[name[sp].Popen, parameter[name[cmds]]]
for taget[name[line]] in starred[name[proc].stdout] be... | keyword[def] identifier[run] ( identifier[cmds] ,** identifier[kwargs] ):
literal[string]
identifier[proc] = identifier[sp] . identifier[Popen] ( identifier[cmds] , identifier[bufsize] =- literal[int] , identifier[stdout] = identifier[sp] . identifier[PIPE] , identifier[stderr] = identifier[sp] . identifie... | def run(cmds, **kwargs):
"""
Wrapper around subprocess.run, with unicode decoding of output.
Additional kwargs are passed to subprocess.run.
"""
proc = sp.Popen(cmds, bufsize=-1, stdout=sp.PIPE, stderr=sp.STDOUT, close_fds=sys.platform != 'win32')
for line in proc.stdout:
print(line[:-1... |
def get_template_names(self):
'''
Build the list of templates related to this user
'''
# Get user template
template_model = getattr(self, 'template_model', "{0}/{1}_{2}".format(self._appname.lower(), self._modelname.lower(), self.get_template_names_key))
template_model_e... | def function[get_template_names, parameter[self]]:
constant[
Build the list of templates related to this user
]
variable[template_model] assign[=] call[name[getattr], parameter[name[self], constant[template_model], call[constant[{0}/{1}_{2}].format, parameter[call[name[self]._appname.low... | keyword[def] identifier[get_template_names] ( identifier[self] ):
literal[string]
identifier[template_model] = identifier[getattr] ( identifier[self] , literal[string] , literal[string] . identifier[format] ( identifier[self] . identifier[_appname] . identifier[lower] (), identifier[self]... | def get_template_names(self):
"""
Build the list of templates related to this user
"""
# Get user template
template_model = getattr(self, 'template_model', '{0}/{1}_{2}'.format(self._appname.lower(), self._modelname.lower(), self.get_template_names_key))
template_model_ext = getattr(self... |
def get_enumeration(rq, v, endpoint, metadata={}, auth=None):
"""
Returns a list of enumerated values for variable 'v' in query 'rq'
"""
# glogger.debug("Metadata before processing enums: {}".format(metadata))
# We only fire the enum filling queries if indicated by the query metadata
if 'enumera... | def function[get_enumeration, parameter[rq, v, endpoint, metadata, auth]]:
constant[
Returns a list of enumerated values for variable 'v' in query 'rq'
]
if compare[constant[enumerate] <ast.NotIn object at 0x7da2590d7190> name[metadata]] begin[:]
return[constant[None]]
variable[e... | keyword[def] identifier[get_enumeration] ( identifier[rq] , identifier[v] , identifier[endpoint] , identifier[metadata] ={}, identifier[auth] = keyword[None] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[metadata] :
keyword[return] keyword[None] ... | def get_enumeration(rq, v, endpoint, metadata={}, auth=None):
"""
Returns a list of enumerated values for variable 'v' in query 'rq'
"""
# glogger.debug("Metadata before processing enums: {}".format(metadata))
# We only fire the enum filling queries if indicated by the query metadata
if 'enumera... |
def republish_collection(cursor, ident_hash, version):
"""Republish the collection identified as ``ident_hash`` with
the given ``version``.
"""
if not isinstance(version, (list, tuple,)):
split_version = version.split('.')
if len(split_version) == 1:
split_version.append(None... | def function[republish_collection, parameter[cursor, ident_hash, version]]:
constant[Republish the collection identified as ``ident_hash`` with
the given ``version``.
]
if <ast.UnaryOp object at 0x7da1aff8d450> begin[:]
variable[split_version] assign[=] call[name[version].split, ... | keyword[def] identifier[republish_collection] ( identifier[cursor] , identifier[ident_hash] , identifier[version] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[version] ,( identifier[list] , identifier[tuple] ,)):
identifier[split_version] = identifier[version] ... | def republish_collection(cursor, ident_hash, version):
"""Republish the collection identified as ``ident_hash`` with
the given ``version``.
"""
if not isinstance(version, (list, tuple)):
split_version = version.split('.')
if len(split_version) == 1:
split_version.append(None)... |
def LFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):
r'''This function handles the retrieval or calculation of a chemical's
Lower Flammability Limit. Lookup is based on CASRNs. Two predictive methods
are currently implemented. Will automatically select a data source to use
if no Me... | def function[LFL, parameter[Hc, atoms, CASRN, AvailableMethods, Method]]:
constant[This function handles the retrieval or calculation of a chemical's
Lower Flammability Limit. Lookup is based on CASRNs. Two predictive methods
are currently implemented. Will automatically select a data source to use
... | keyword[def] identifier[LFL] ( identifier[Hc] = keyword[None] , identifier[atoms] ={}, identifier[CASRN] = literal[string] , identifier[AvailableMethods] = keyword[False] , identifier[Method] = keyword[None] ):
literal[string]
keyword[def] identifier[list_methods] ():
identifier[methods] =[]
... | def LFL(Hc=None, atoms={}, CASRN='', AvailableMethods=False, Method=None):
"""This function handles the retrieval or calculation of a chemical's
Lower Flammability Limit. Lookup is based on CASRNs. Two predictive methods
are currently implemented. Will automatically select a data source to use
if no Met... |
def writeAnn(filename, catalog, fmt):
"""
Write an annotation file that can be read by Kvis (.ann) or DS9 (.reg).
Uses ra/dec from catalog.
Draws ellipses if bmaj/bmin/pa are in catalog. Draws 30" circles otherwise.
Only :class:`AegeanTools.models.OutputSource` will appear in the annotation file
... | def function[writeAnn, parameter[filename, catalog, fmt]]:
constant[
Write an annotation file that can be read by Kvis (.ann) or DS9 (.reg).
Uses ra/dec from catalog.
Draws ellipses if bmaj/bmin/pa are in catalog. Draws 30" circles otherwise.
Only :class:`AegeanTools.models.OutputSource` will a... | keyword[def] identifier[writeAnn] ( identifier[filename] , identifier[catalog] , identifier[fmt] ):
literal[string]
keyword[if] identifier[fmt] keyword[not] keyword[in] [ literal[string] , literal[string] ]:
identifier[log] . identifier[warning] ( literal[string] . identifier[format] ( identifi... | def writeAnn(filename, catalog, fmt):
"""
Write an annotation file that can be read by Kvis (.ann) or DS9 (.reg).
Uses ra/dec from catalog.
Draws ellipses if bmaj/bmin/pa are in catalog. Draws 30" circles otherwise.
Only :class:`AegeanTools.models.OutputSource` will appear in the annotation file
... |
def makeFontBoundingBox(self):
"""
Make a bounding box for the font.
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
"""
if not hasattr(self, "glyphBoundingBoxes"):
... | def function[makeFontBoundingBox, parameter[self]]:
constant[
Make a bounding box for the font.
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
]
if <ast.UnaryOp object at ... | keyword[def] identifier[makeFontBoundingBox] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[self] . identifier[glyphBoundingBoxes] = identifier[self] . identifier[makeGlyphsBoundingBoxes] ()
... | def makeFontBoundingBox(self):
"""
Make a bounding box for the font.
**This should not be called externally.** Subclasses
may override this method to handle the bounds creation
in a different way if desired.
"""
if not hasattr(self, 'glyphBoundingBoxes'):
self.gl... |
def contextMenuEvent(self, event):
""" Creates and executes the context menu for the tree view
"""
menu = QtWidgets.QMenu(self)
for action in self.actions():
menu.addAction(action)
openAsMenu = self.createOpenAsMenu(parent=menu)
menu.insertMenu(self.closeIte... | def function[contextMenuEvent, parameter[self, event]]:
constant[ Creates and executes the context menu for the tree view
]
variable[menu] assign[=] call[name[QtWidgets].QMenu, parameter[name[self]]]
for taget[name[action]] in starred[call[name[self].actions, parameter[]]] begin[:]
... | keyword[def] identifier[contextMenuEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[menu] = identifier[QtWidgets] . identifier[QMenu] ( identifier[self] )
keyword[for] identifier[action] keyword[in] identifier[self] . identifier[actions] ():
iden... | def contextMenuEvent(self, event):
""" Creates and executes the context menu for the tree view
"""
menu = QtWidgets.QMenu(self)
for action in self.actions():
menu.addAction(action) # depends on [control=['for'], data=['action']]
openAsMenu = self.createOpenAsMenu(parent=menu)
menu.i... |
def _decorate(flush=True, attempts=1, only_authenticate=False):
"""
Wraps the given function such that conn.login() or conn.authenticate() is
executed.
Doing the real work for autologin and autoauthenticate to minimize code
duplication.
:type flush: bool
:param flush: Whether to flush the ... | def function[_decorate, parameter[flush, attempts, only_authenticate]]:
constant[
Wraps the given function such that conn.login() or conn.authenticate() is
executed.
Doing the real work for autologin and autoauthenticate to minimize code
duplication.
:type flush: bool
:param flush: Whe... | keyword[def] identifier[_decorate] ( identifier[flush] = keyword[True] , identifier[attempts] = literal[int] , identifier[only_authenticate] = keyword[False] ):
literal[string]
keyword[def] identifier[decorator] ( identifier[function] ):
keyword[def] identifier[decorated] ( identifier[job] , ide... | def _decorate(flush=True, attempts=1, only_authenticate=False):
"""
Wraps the given function such that conn.login() or conn.authenticate() is
executed.
Doing the real work for autologin and autoauthenticate to minimize code
duplication.
:type flush: bool
:param flush: Whether to flush the ... |
def show_first_and_last_lines(result):
"""Just print the first and last five lines of (pypi) output"""
lines = [line for line in result.split('\n')]
if len(lines) < 11:
for line in lines:
print(line)
return
print('Showing first few lines...')
for line in lines[:5]:
... | def function[show_first_and_last_lines, parameter[result]]:
constant[Just print the first and last five lines of (pypi) output]
variable[lines] assign[=] <ast.ListComp object at 0x7da20c6a9510>
if compare[call[name[len], parameter[name[lines]]] less[<] constant[11]] begin[:]
for ... | keyword[def] identifier[show_first_and_last_lines] ( identifier[result] ):
literal[string]
identifier[lines] =[ identifier[line] keyword[for] identifier[line] keyword[in] identifier[result] . identifier[split] ( literal[string] )]
keyword[if] identifier[len] ( identifier[lines] )< literal[int] :
... | def show_first_and_last_lines(result):
"""Just print the first and last five lines of (pypi) output"""
lines = [line for line in result.split('\n')]
if len(lines) < 11:
for line in lines:
print(line) # depends on [control=['for'], data=['line']]
return # depends on [control=['i... |
def _write_mef(self, key, extlist, outfile):
"""Write out regular multi-extension FITS data."""
channel = self.fv.get_channel(self.chname)
with fits.open(outfile, mode='update') as pf:
# Process each modified data extension
for idx in extlist:
k = '{0}[{1}... | def function[_write_mef, parameter[self, key, extlist, outfile]]:
constant[Write out regular multi-extension FITS data.]
variable[channel] assign[=] call[name[self].fv.get_channel, parameter[name[self].chname]]
with call[name[fits].open, parameter[name[outfile]]] begin[:]
for tag... | keyword[def] identifier[_write_mef] ( identifier[self] , identifier[key] , identifier[extlist] , identifier[outfile] ):
literal[string]
identifier[channel] = identifier[self] . identifier[fv] . identifier[get_channel] ( identifier[self] . identifier[chname] )
keyword[with] identifier[fits... | def _write_mef(self, key, extlist, outfile):
"""Write out regular multi-extension FITS data."""
channel = self.fv.get_channel(self.chname)
with fits.open(outfile, mode='update') as pf:
# Process each modified data extension
for idx in extlist:
k = '{0}[{1}]'.format(key, self._for... |
def insert(self, loc, item, value, allow_duplicates=False):
"""
Insert item at selected position.
Parameters
----------
loc : int
item : hashable
value : array_like
allow_duplicates: bool
If False, trying to insert non-unique item will raise
... | def function[insert, parameter[self, loc, item, value, allow_duplicates]]:
constant[
Insert item at selected position.
Parameters
----------
loc : int
item : hashable
value : array_like
allow_duplicates: bool
If False, trying to insert non-uni... | keyword[def] identifier[insert] ( identifier[self] , identifier[loc] , identifier[item] , identifier[value] , identifier[allow_duplicates] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[allow_duplicates] keyword[and] identifier[item] keyword[in] identifier[self] . ide... | def insert(self, loc, item, value, allow_duplicates=False):
"""
Insert item at selected position.
Parameters
----------
loc : int
item : hashable
value : array_like
allow_duplicates: bool
If False, trying to insert non-unique item will raise
... |
def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None):
"""Substitute construction variables in a string (or list or other
object) and separate the arguments into a command list.
The companion scons_subst() function (above) handles basic
substitutio... | def function[scons_subst_list, parameter[strSubst, env, mode, target, source, gvars, lvars, conv]]:
constant[Substitute construction variables in a string (or list or other
object) and separate the arguments into a command list.
The companion scons_subst() function (above) handles basic
substitutio... | keyword[def] identifier[scons_subst_list] ( identifier[strSubst] , identifier[env] , identifier[mode] = identifier[SUBST_RAW] , identifier[target] = keyword[None] , identifier[source] = keyword[None] , identifier[gvars] ={}, identifier[lvars] ={}, identifier[conv] = keyword[None] ):
literal[string]
keyword... | def scons_subst_list(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None):
"""Substitute construction variables in a string (or list or other
object) and separate the arguments into a command list.
The companion scons_subst() function (above) handles basic
substitutio... |
def sleep_if_necessary(cls, user, token, endpoint='search', msg=''):
"""Sleep a little if hit github recently to honor rate limit.
"""
my_kw = {'auth': (user, token)} if user else {}
info = requests.get('https://api.github.com/rate_limit', **my_kw)
info_dict = info.json()
... | def function[sleep_if_necessary, parameter[cls, user, token, endpoint, msg]]:
constant[Sleep a little if hit github recently to honor rate limit.
]
variable[my_kw] assign[=] <ast.IfExp object at 0x7da204961600>
variable[info] assign[=] call[name[requests].get, parameter[constant[https://... | keyword[def] identifier[sleep_if_necessary] ( identifier[cls] , identifier[user] , identifier[token] , identifier[endpoint] = literal[string] , identifier[msg] = literal[string] ):
literal[string]
identifier[my_kw] ={ literal[string] :( identifier[user] , identifier[token] )} keyword[if] identifie... | def sleep_if_necessary(cls, user, token, endpoint='search', msg=''):
"""Sleep a little if hit github recently to honor rate limit.
"""
my_kw = {'auth': (user, token)} if user else {}
info = requests.get('https://api.github.com/rate_limit', **my_kw)
info_dict = info.json()
remaining = info_di... |
def reset(self):
"""Clear the internal statistics to initial state."""
if getattr(self, 'num', None) is None:
self.num_inst = 0
self.sum_metric = 0.0
else:
self.num_inst = [0] * self.num
self.sum_metric = [0.0] * self.num
self.records = dic... | def function[reset, parameter[self]]:
constant[Clear the internal statistics to initial state.]
if compare[call[name[getattr], parameter[name[self], constant[num], constant[None]]] is constant[None]] begin[:]
name[self].num_inst assign[=] constant[0]
name[self].sum_metric... | keyword[def] identifier[reset] ( identifier[self] ):
literal[string]
keyword[if] identifier[getattr] ( identifier[self] , literal[string] , keyword[None] ) keyword[is] keyword[None] :
identifier[self] . identifier[num_inst] = literal[int]
identifier[self] . identifier[s... | def reset(self):
"""Clear the internal statistics to initial state."""
if getattr(self, 'num', None) is None:
self.num_inst = 0
self.sum_metric = 0.0 # depends on [control=['if'], data=[]]
else:
self.num_inst = [0] * self.num
self.sum_metric = [0.0] * self.num
self.recor... |
def arp():
'''
Return the arp table from the minion
.. versionchanged:: 2015.8.0
Added support for SunOS
CLI Example:
.. code-block:: bash
salt '*' network.arp
'''
ret = {}
out = __salt__['cmd.run']('arp -an')
for line in out.splitlines():
comps = line.spl... | def function[arp, parameter[]]:
constant[
Return the arp table from the minion
.. versionchanged:: 2015.8.0
Added support for SunOS
CLI Example:
.. code-block:: bash
salt '*' network.arp
]
variable[ret] assign[=] dictionary[[], []]
variable[out] assign[=] ... | keyword[def] identifier[arp] ():
literal[string]
identifier[ret] ={}
identifier[out] = identifier[__salt__] [ literal[string] ]( literal[string] )
keyword[for] identifier[line] keyword[in] identifier[out] . identifier[splitlines] ():
identifier[comps] = identifier[line] . identifier[s... | def arp():
"""
Return the arp table from the minion
.. versionchanged:: 2015.8.0
Added support for SunOS
CLI Example:
.. code-block:: bash
salt '*' network.arp
"""
ret = {}
out = __salt__['cmd.run']('arp -an')
for line in out.splitlines():
comps = line.spl... |
def run_ding0(self, session, mv_grid_districts_no=None, debug=False, export_figures=False):
""" Let DING0 run by shouting at this method (or just call
it from NetworkDing0 instance). This method is a wrapper
for the main functionality of DING0.
Parameters
----------
... | def function[run_ding0, parameter[self, session, mv_grid_districts_no, debug, export_figures]]:
constant[ Let DING0 run by shouting at this method (or just call
it from NetworkDing0 instance). This method is a wrapper
for the main functionality of DING0.
Parameters
-----... | keyword[def] identifier[run_ding0] ( identifier[self] , identifier[session] , identifier[mv_grid_districts_no] = keyword[None] , identifier[debug] = keyword[False] , identifier[export_figures] = keyword[False] ):
literal[string]
keyword[if] identifier[debug] :
identifier[start] = iden... | def run_ding0(self, session, mv_grid_districts_no=None, debug=False, export_figures=False):
""" Let DING0 run by shouting at this method (or just call
it from NetworkDing0 instance). This method is a wrapper
for the main functionality of DING0.
Parameters
----------
... |
def notification_selected_sm_changed(self, model, prop_name, info):
"""If a new state machine is selected, make sure the tab is open"""
selected_state_machine_id = self.model.selected_state_machine_id
if selected_state_machine_id is None:
return
page_id = self.get_page_num(s... | def function[notification_selected_sm_changed, parameter[self, model, prop_name, info]]:
constant[If a new state machine is selected, make sure the tab is open]
variable[selected_state_machine_id] assign[=] name[self].model.selected_state_machine_id
if compare[name[selected_state_machine_id] is ... | keyword[def] identifier[notification_selected_sm_changed] ( identifier[self] , identifier[model] , identifier[prop_name] , identifier[info] ):
literal[string]
identifier[selected_state_machine_id] = identifier[self] . identifier[model] . identifier[selected_state_machine_id]
keyword[if] ... | def notification_selected_sm_changed(self, model, prop_name, info):
"""If a new state machine is selected, make sure the tab is open"""
selected_state_machine_id = self.model.selected_state_machine_id
if selected_state_machine_id is None:
return # depends on [control=['if'], data=[]]
page_id = ... |
def components(self) -> List['DAGCircuit']:
"""Split DAGCircuit into independent components"""
comps = nx.weakly_connected_component_subgraphs(self.graph)
return [DAGCircuit(comp) for comp in comps] | def function[components, parameter[self]]:
constant[Split DAGCircuit into independent components]
variable[comps] assign[=] call[name[nx].weakly_connected_component_subgraphs, parameter[name[self].graph]]
return[<ast.ListComp object at 0x7da20c6c4700>] | keyword[def] identifier[components] ( identifier[self] )-> identifier[List] [ literal[string] ]:
literal[string]
identifier[comps] = identifier[nx] . identifier[weakly_connected_component_subgraphs] ( identifier[self] . identifier[graph] )
keyword[return] [ identifier[DAGCircuit] ( identif... | def components(self) -> List['DAGCircuit']:
"""Split DAGCircuit into independent components"""
comps = nx.weakly_connected_component_subgraphs(self.graph)
return [DAGCircuit(comp) for comp in comps] |
def fromDataFrameRDD(cls, rdd, sql_ctx):
"""Construct a DataFrame from an RDD of DataFrames.
No checking or validation occurs."""
result = DataFrame(None, sql_ctx)
return result.from_rdd_of_dataframes(rdd) | def function[fromDataFrameRDD, parameter[cls, rdd, sql_ctx]]:
constant[Construct a DataFrame from an RDD of DataFrames.
No checking or validation occurs.]
variable[result] assign[=] call[name[DataFrame], parameter[constant[None], name[sql_ctx]]]
return[call[name[result].from_rdd_of_dataframe... | keyword[def] identifier[fromDataFrameRDD] ( identifier[cls] , identifier[rdd] , identifier[sql_ctx] ):
literal[string]
identifier[result] = identifier[DataFrame] ( keyword[None] , identifier[sql_ctx] )
keyword[return] identifier[result] . identifier[from_rdd_of_dataframes] ( identifier[rd... | def fromDataFrameRDD(cls, rdd, sql_ctx):
"""Construct a DataFrame from an RDD of DataFrames.
No checking or validation occurs."""
result = DataFrame(None, sql_ctx)
return result.from_rdd_of_dataframes(rdd) |
def alias_asset(self, asset_id, alias_id):
"""Adds an ``Id`` to an ``Asset`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Asset`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another asse... | def function[alias_asset, parameter[self, asset_id, alias_id]]:
constant[Adds an ``Id`` to an ``Asset`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Asset`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias i... | keyword[def] identifier[alias_asset] ( identifier[self] , identifier[asset_id] , identifier[alias_id] ):
literal[string]
identifier[self] . identifier[_alias_id] ( identifier[primary_id] = identifier[asset_id] , identifier[equivalent_id] = identifier[alias_id] ) | def alias_asset(self, asset_id, alias_id):
"""Adds an ``Id`` to an ``Asset`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Asset`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another asset, i... |
def update_source(ident, data):
'''Update an harvest source'''
source = get_source(ident)
source.modify(**data)
signals.harvest_source_updated.send(source)
return source | def function[update_source, parameter[ident, data]]:
constant[Update an harvest source]
variable[source] assign[=] call[name[get_source], parameter[name[ident]]]
call[name[source].modify, parameter[]]
call[name[signals].harvest_source_updated.send, parameter[name[source]]]
return[nam... | keyword[def] identifier[update_source] ( identifier[ident] , identifier[data] ):
literal[string]
identifier[source] = identifier[get_source] ( identifier[ident] )
identifier[source] . identifier[modify] (** identifier[data] )
identifier[signals] . identifier[harvest_source_updated] . identifier[s... | def update_source(ident, data):
"""Update an harvest source"""
source = get_source(ident)
source.modify(**data)
signals.harvest_source_updated.send(source)
return source |
def keywords(self) -> Set[str]:
"""A set of all keywords of all handled devices.
In addition to attribute access via device names, |Nodes| and
|Elements| objects allow for attribute access via keywords,
allowing for an efficient search of certain groups of devices.
Let us use th... | def function[keywords, parameter[self]]:
constant[A set of all keywords of all handled devices.
In addition to attribute access via device names, |Nodes| and
|Elements| objects allow for attribute access via keywords,
allowing for an efficient search of certain groups of devices.
... | keyword[def] identifier[keywords] ( identifier[self] )-> identifier[Set] [ identifier[str] ]:
literal[string]
keyword[return] identifier[set] ( identifier[keyword] keyword[for] identifier[device] keyword[in] identifier[self]
keyword[for] identifier[keyword] keyword[in] identifier[... | def keywords(self) -> Set[str]:
"""A set of all keywords of all handled devices.
In addition to attribute access via device names, |Nodes| and
|Elements| objects allow for attribute access via keywords,
allowing for an efficient search of certain groups of devices.
Let us use the ex... |
def _proj_l1_sortsum(v, gamma, axis=None):
r"""Projection operator of the :math:`\ell_1` norm. The solution is
computed via the method of :cite:`duchi-2008-efficient`.
Parameters
----------
v : array_like
Input array :math:`\mathbf{v}`
gamma : float
Parameter :math:`\gamma`
axi... | def function[_proj_l1_sortsum, parameter[v, gamma, axis]]:
constant[Projection operator of the :math:`\ell_1` norm. The solution is
computed via the method of :cite:`duchi-2008-efficient`.
Parameters
----------
v : array_like
Input array :math:`\mathbf{v}`
gamma : float
Paramet... | keyword[def] identifier[_proj_l1_sortsum] ( identifier[v] , identifier[gamma] , identifier[axis] = keyword[None] ):
literal[string]
keyword[if] identifier[axis] keyword[is] keyword[None] keyword[and] identifier[norm_l1] ( identifier[v] )<= identifier[gamma] :
keyword[return] identifier[v]
... | def _proj_l1_sortsum(v, gamma, axis=None):
"""Projection operator of the :math:`\\ell_1` norm. The solution is
computed via the method of :cite:`duchi-2008-efficient`.
Parameters
----------
v : array_like
Input array :math:`\\mathbf{v}`
gamma : float
Parameter :math:`\\gamma`
a... |
def soap_action(self, service, action, payloadbody):
"""Do a soap request """
payload = self.soapenvelope.format(body=payloadbody).encode('utf-8')
headers = ['SOAPAction: ' + action,
'Content-Type: application/soap+xml; charset=UTF-8',
'Content-Length: ' + s... | def function[soap_action, parameter[self, service, action, payloadbody]]:
constant[Do a soap request ]
variable[payload] assign[=] call[call[name[self].soapenvelope.format, parameter[]].encode, parameter[constant[utf-8]]]
variable[headers] assign[=] list[[<ast.BinOp object at 0x7da1b23e5900>, <a... | keyword[def] identifier[soap_action] ( identifier[self] , identifier[service] , identifier[action] , identifier[payloadbody] ):
literal[string]
identifier[payload] = identifier[self] . identifier[soapenvelope] . identifier[format] ( identifier[body] = identifier[payloadbody] ). identifier[encode] (... | def soap_action(self, service, action, payloadbody):
"""Do a soap request """
payload = self.soapenvelope.format(body=payloadbody).encode('utf-8')
headers = ['SOAPAction: ' + action, 'Content-Type: application/soap+xml; charset=UTF-8', 'Content-Length: ' + str(len(payload))]
try:
curl = pycurl.C... |
def override_ssh_auth_env():
"""Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent."""
ssh_auth_sock = "SSH_AUTH_SOCK"
old_ssh_auth_sock = os.environ.get(ssh_auth_sock)
del os.environ[ssh_auth_sock]
yield
if old_ssh_auth_sock:
os.environ[ssh_auth_sock] = ol... | def function[override_ssh_auth_env, parameter[]]:
constant[Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent.]
variable[ssh_auth_sock] assign[=] constant[SSH_AUTH_SOCK]
variable[old_ssh_auth_sock] assign[=] call[name[os].environ.get, parameter[name[ssh_auth_sock]]]
... | keyword[def] identifier[override_ssh_auth_env] ():
literal[string]
identifier[ssh_auth_sock] = literal[string]
identifier[old_ssh_auth_sock] = identifier[os] . identifier[environ] . identifier[get] ( identifier[ssh_auth_sock] )
keyword[del] identifier[os] . identifier[environ] [ identifier[ssh... | def override_ssh_auth_env():
"""Override the `$SSH_AUTH_SOCK `env variable to mock the absence of an SSH agent."""
ssh_auth_sock = 'SSH_AUTH_SOCK'
old_ssh_auth_sock = os.environ.get(ssh_auth_sock)
del os.environ[ssh_auth_sock]
yield
if old_ssh_auth_sock:
os.environ[ssh_auth_sock] = old_s... |
def rst_blocks(script_blocks, output_blocks, file_conf, gallery_conf):
"""Generates the rst string containing the script prose, code and output
Parameters
----------
script_blocks : list
(label, content, line_number)
List where each element is a tuple with the label ('text' or 'code'),
... | def function[rst_blocks, parameter[script_blocks, output_blocks, file_conf, gallery_conf]]:
constant[Generates the rst string containing the script prose, code and output
Parameters
----------
script_blocks : list
(label, content, line_number)
List where each element is a tuple with... | keyword[def] identifier[rst_blocks] ( identifier[script_blocks] , identifier[output_blocks] , identifier[file_conf] , identifier[gallery_conf] ):
literal[string]
identifier[is_example_notebook_like] = identifier[len] ( identifier[script_blocks] )> literal[int]
identifier[example_rst] = lit... | def rst_blocks(script_blocks, output_blocks, file_conf, gallery_conf):
"""Generates the rst string containing the script prose, code and output
Parameters
----------
script_blocks : list
(label, content, line_number)
List where each element is a tuple with the label ('text' or 'code'),
... |
def read_model(self):
""" Read the model and the couplings from the model file.
"""
if self.verbosity > 0:
settings.m(0,'reading model',self.model)
# read model
boolRules = []
for line in open(self.model):
if line.startswith('#') and 'modelType =' ... | def function[read_model, parameter[self]]:
constant[ Read the model and the couplings from the model file.
]
if compare[name[self].verbosity greater[>] constant[0]] begin[:]
call[name[settings].m, parameter[constant[0], constant[reading model], name[self].model]]
variable... | keyword[def] identifier[read_model] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[verbosity] > literal[int] :
identifier[settings] . identifier[m] ( literal[int] , literal[string] , identifier[self] . identifier[model] )
identifi... | def read_model(self):
""" Read the model and the couplings from the model file.
"""
if self.verbosity > 0:
settings.m(0, 'reading model', self.model) # depends on [control=['if'], data=[]]
# read model
boolRules = []
for line in open(self.model):
if line.startswith('#') and ... |
def formatar_cep(cep):
"""Formata CEP, removendo qualquer caractere não numérico.
Arguments:
cep {str} -- CEP a ser formatado.
Raises:
ValueError -- Quando a string esta vazia ou não contem numeros.
Returns:
str -- string contendo o CEP formatado.
"""
if not isinstance... | def function[formatar_cep, parameter[cep]]:
constant[Formata CEP, removendo qualquer caractere não numérico.
Arguments:
cep {str} -- CEP a ser formatado.
Raises:
ValueError -- Quando a string esta vazia ou não contem numeros.
Returns:
str -- string contendo o CEP formatado... | keyword[def] identifier[formatar_cep] ( identifier[cep] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[cep] , identifier[str] ) keyword[or] keyword[not] identifier[cep] :
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] )
... | def formatar_cep(cep):
"""Formata CEP, removendo qualquer caractere não numérico.
Arguments:
cep {str} -- CEP a ser formatado.
Raises:
ValueError -- Quando a string esta vazia ou não contem numeros.
Returns:
str -- string contendo o CEP formatado.
"""
if not isinstance... |
def common_arg_parser():
"""
Create an argparse.ArgumentParser for run_mujoco.py.
"""
parser = arg_parser()
parser.add_argument('--env', help='environment ID', type=str, default='Reacher-v2')
parser.add_argument('--env_type', help='type of environment, used when the environment type cannot be au... | def function[common_arg_parser, parameter[]]:
constant[
Create an argparse.ArgumentParser for run_mujoco.py.
]
variable[parser] assign[=] call[name[arg_parser], parameter[]]
call[name[parser].add_argument, parameter[constant[--env]]]
call[name[parser].add_argument, parameter[cons... | keyword[def] identifier[common_arg_parser] ():
literal[string]
identifier[parser] = identifier[arg_parser] ()
identifier[parser] . identifier[add_argument] ( literal[string] , identifier[help] = literal[string] , identifier[type] = identifier[str] , identifier[default] = literal[string] )
identif... | def common_arg_parser():
"""
Create an argparse.ArgumentParser for run_mujoco.py.
"""
parser = arg_parser()
parser.add_argument('--env', help='environment ID', type=str, default='Reacher-v2')
parser.add_argument('--env_type', help='type of environment, used when the environment type cannot be au... |
def from_netcdf(filename):
"""Initialize object from a netcdf file.
Expects that the file will have groups, each of which can be loaded by xarray.
Parameters
----------
filename : str
location of netcdf file
Returns
-------
InferenceData obj... | def function[from_netcdf, parameter[filename]]:
constant[Initialize object from a netcdf file.
Expects that the file will have groups, each of which can be loaded by xarray.
Parameters
----------
filename : str
location of netcdf file
Returns
------... | keyword[def] identifier[from_netcdf] ( identifier[filename] ):
literal[string]
identifier[groups] ={}
keyword[with] identifier[nc] . identifier[Dataset] ( identifier[filename] , identifier[mode] = literal[string] ) keyword[as] identifier[data] :
identifier[data_groups] = ide... | def from_netcdf(filename):
"""Initialize object from a netcdf file.
Expects that the file will have groups, each of which can be loaded by xarray.
Parameters
----------
filename : str
location of netcdf file
Returns
-------
InferenceData object
... |
def deregister_image(self, image_id, delete_snapshot=False):
"""
Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:type delete_snapshot: bool
:param delete_snapshot: Set to True if we should delete the
... | def function[deregister_image, parameter[self, image_id, delete_snapshot]]:
constant[
Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:type delete_snapshot: bool
:param delete_snapshot: Set to True if we should delete the
... | keyword[def] identifier[deregister_image] ( identifier[self] , identifier[image_id] , identifier[delete_snapshot] = keyword[False] ):
literal[string]
identifier[snapshot_id] = keyword[None]
keyword[if] identifier[delete_snapshot] :
identifier[image] = identifier[self] . iden... | def deregister_image(self, image_id, delete_snapshot=False):
"""
Unregister an AMI.
:type image_id: string
:param image_id: the ID of the Image to unregister
:type delete_snapshot: bool
:param delete_snapshot: Set to True if we should delete the
... |
def resolve_reference(self, ref):
"""
Resolve a JSON Pointer object reference to the object itself.
:param ref: Reference string (`#/foo/bar`, for instance)
:return: The object, if found
:raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the referenc... | def function[resolve_reference, parameter[self, ref]]:
constant[
Resolve a JSON Pointer object reference to the object itself.
:param ref: Reference string (`#/foo/bar`, for instance)
:return: The object, if found
:raises jsonschema.exceptions.RefResolutionError: if there is tro... | keyword[def] identifier[resolve_reference] ( identifier[self] , identifier[ref] ):
literal[string]
identifier[url] , identifier[resolved] = identifier[self] . identifier[resolver] . identifier[resolve] ( identifier[ref] )
keyword[return] identifier[resolved] | def resolve_reference(self, ref):
"""
Resolve a JSON Pointer object reference to the object itself.
:param ref: Reference string (`#/foo/bar`, for instance)
:return: The object, if found
:raises jsonschema.exceptions.RefResolutionError: if there is trouble resolving the reference
... |
def stop(self):
"""
Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop.
"""
super(Multi, self).stop()
self.monitor_thread.join()
logging.info("Multi-plugin health m... | def function[stop, parameter[self]]:
constant[
Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop.
]
call[call[name[super], parameter[name[Multi], name[self]]].stop, parameter[]]
... | keyword[def] identifier[stop] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[Multi] , identifier[self] ). identifier[stop] ()
identifier[self] . identifier[monitor_thread] . identifier[join] ()
identifier[logging] . identifier[info] ( literal[string] )
... | def stop(self):
"""
Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop.
"""
super(Multi, self).stop()
self.monitor_thread.join()
logging.info('Multi-plugin health monitor: Stopping ... |
def get_queryset(self):
'''
Only serve site-specific languages
'''
request = self.request
return (Languages.for_site(request.site)
.languages.filter().order_by('pk')) | def function[get_queryset, parameter[self]]:
constant[
Only serve site-specific languages
]
variable[request] assign[=] name[self].request
return[call[call[call[name[Languages].for_site, parameter[name[request].site]].languages.filter, parameter[]].order_by, parameter[constant[pk]]]] | keyword[def] identifier[get_queryset] ( identifier[self] ):
literal[string]
identifier[request] = identifier[self] . identifier[request]
keyword[return] ( identifier[Languages] . identifier[for_site] ( identifier[request] . identifier[site] )
. identifier[languages] . identifier[f... | def get_queryset(self):
"""
Only serve site-specific languages
"""
request = self.request
return Languages.for_site(request.site).languages.filter().order_by('pk') |
def add_to_emails(self, *emails):
"""
:calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_
:param email: string
:rtype: None
"""
assert all(isinstance(element, (str, unicode)) for element in emails), emails
post_parameters = emails
he... | def function[add_to_emails, parameter[self]]:
constant[
:calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_
:param email: string
:rtype: None
]
assert[call[name[all], parameter[<ast.GeneratorExp object at 0x7da1b1f486a0>]]]
variable[post_paramet... | keyword[def] identifier[add_to_emails] ( identifier[self] ,* identifier[emails] ):
literal[string]
keyword[assert] identifier[all] ( identifier[isinstance] ( identifier[element] ,( identifier[str] , identifier[unicode] )) keyword[for] identifier[element] keyword[in] identifier[emails] ), identi... | def add_to_emails(self, *emails):
"""
:calls: `POST /user/emails <http://developer.github.com/v3/users/emails>`_
:param email: string
:rtype: None
"""
assert all((isinstance(element, (str, unicode)) for element in emails)), emails
post_parameters = emails
(headers, data) ... |
def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type="auto"):
"""Run the given function in an independent python interpreter."""
import signal
reloader = reloader_loops[reloader_type](extra_files, interval)
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
try:
... | def function[run_with_reloader, parameter[main_func, extra_files, interval, reloader_type]]:
constant[Run the given function in an independent python interpreter.]
import module[signal]
variable[reloader] assign[=] call[call[name[reloader_loops]][name[reloader_type]], parameter[name[extra_files], na... | keyword[def] identifier[run_with_reloader] ( identifier[main_func] , identifier[extra_files] = keyword[None] , identifier[interval] = literal[int] , identifier[reloader_type] = literal[string] ):
literal[string]
keyword[import] identifier[signal]
identifier[reloader] = identifier[reloader_loops] [ ... | def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type='auto'):
"""Run the given function in an independent python interpreter."""
import signal
reloader = reloader_loops[reloader_type](extra_files, interval)
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
try:
... |
def _get_default_letters(model_admin=None):
"""
Returns the set of letters defined in the configuration variable
DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or
list and returns a set.
If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET
attribute and use... | def function[_get_default_letters, parameter[model_admin]]:
constant[
Returns the set of letters defined in the configuration variable
DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or
list and returns a set.
If a ModelAdmin class is passed, it will look for a DEFAULT_ALPH... | keyword[def] identifier[_get_default_letters] ( identifier[model_admin] = keyword[None] ):
literal[string]
keyword[from] identifier[django] . identifier[conf] keyword[import] identifier[settings]
keyword[import] identifier[string]
identifier[default_ltrs] = identifier[string] . identifier[d... | def _get_default_letters(model_admin=None):
"""
Returns the set of letters defined in the configuration variable
DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or
list and returns a set.
If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET
attribute and use... |
def get_agg_data(cls, obj, category=None):
"""
Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated.
"""
paths = []
if isinstance(obj, Graph):
obj = obj.edgepaths
kdims = list(obj.kdims)
vdims = list(... | def function[get_agg_data, parameter[cls, obj, category]]:
constant[
Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated.
]
variable[paths] assign[=] list[[]]
if call[name[isinstance], parameter[name[obj], name[Graph]]] begin[:... | keyword[def] identifier[get_agg_data] ( identifier[cls] , identifier[obj] , identifier[category] = keyword[None] ):
literal[string]
identifier[paths] =[]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[Graph] ):
identifier[obj] = identifier[obj] . identifier... | def get_agg_data(cls, obj, category=None):
"""
Reduces any Overlay or NdOverlay of Elements into a single
xarray Dataset that can be aggregated.
"""
paths = []
if isinstance(obj, Graph):
obj = obj.edgepaths # depends on [control=['if'], data=[]]
kdims = list(obj.kdims)
... |
def models(self, model=None):
"""
Returns the tables that this query is referencing.
:return [ <subclass of Table>, .. ]
"""
for query in self.__queries:
if isinstance(query, orb.Query):
yield query.model(model)
else:
f... | def function[models, parameter[self, model]]:
constant[
Returns the tables that this query is referencing.
:return [ <subclass of Table>, .. ]
]
for taget[name[query]] in starred[name[self].__queries] begin[:]
if call[name[isinstance], parameter[name[query], ... | keyword[def] identifier[models] ( identifier[self] , identifier[model] = keyword[None] ):
literal[string]
keyword[for] identifier[query] keyword[in] identifier[self] . identifier[__queries] :
keyword[if] identifier[isinstance] ( identifier[query] , identifier[orb] . identifier[Quer... | def models(self, model=None):
"""
Returns the tables that this query is referencing.
:return [ <subclass of Table>, .. ]
"""
for query in self.__queries:
if isinstance(query, orb.Query):
yield query.model(model) # depends on [control=['if'], data=[]]
els... |
def complete_opt_display(self, text, *_):
""" Autocomplete for display option """
return [t + " " for t in DISPLAYS if t.startswith(text)] | def function[complete_opt_display, parameter[self, text]]:
constant[ Autocomplete for display option ]
return[<ast.ListComp object at 0x7da1b0ccb940>] | keyword[def] identifier[complete_opt_display] ( identifier[self] , identifier[text] ,* identifier[_] ):
literal[string]
keyword[return] [ identifier[t] + literal[string] keyword[for] identifier[t] keyword[in] identifier[DISPLAYS] keyword[if] identifier[t] . identifier[startswith] ( identifier... | def complete_opt_display(self, text, *_):
""" Autocomplete for display option """
return [t + ' ' for t in DISPLAYS if t.startswith(text)] |
def argparse_dict(default_dict_, lbl=None, verbose=None,
only_specified=False, force_keys={}, type_hint=None,
alias_dict={}):
r"""
Gets values for a dict based on the command line
Args:
default_dict_ (?):
only_specified (bool): if True only returns keys t... | def function[argparse_dict, parameter[default_dict_, lbl, verbose, only_specified, force_keys, type_hint, alias_dict]]:
constant[
Gets values for a dict based on the command line
Args:
default_dict_ (?):
only_specified (bool): if True only returns keys that are specified on commandline.... | keyword[def] identifier[argparse_dict] ( identifier[default_dict_] , identifier[lbl] = keyword[None] , identifier[verbose] = keyword[None] ,
identifier[only_specified] = keyword[False] , identifier[force_keys] ={}, identifier[type_hint] = keyword[None] ,
identifier[alias_dict] ={}):
literal[string]
keywo... | def argparse_dict(default_dict_, lbl=None, verbose=None, only_specified=False, force_keys={}, type_hint=None, alias_dict={}):
"""
Gets values for a dict based on the command line
Args:
default_dict_ (?):
only_specified (bool): if True only returns keys that are specified on commandline. no ... |
def installed(cls):
"""
Used in ``yacms.pages.views.page`` to ensure
``PageMiddleware`` or a subclass has been installed. We cache
the result on the ``PageMiddleware._installed`` to only run
this once. Short path is to just check for the dotted path to
``PageMiddleware`` ... | def function[installed, parameter[cls]]:
constant[
Used in ``yacms.pages.views.page`` to ensure
``PageMiddleware`` or a subclass has been installed. We cache
the result on the ``PageMiddleware._installed`` to only run
this once. Short path is to just check for the dotted path to
... | keyword[def] identifier[installed] ( identifier[cls] ):
literal[string]
keyword[try] :
keyword[return] identifier[cls] . identifier[_installed]
keyword[except] identifier[AttributeError] :
identifier[name] = literal[string]
identifier[mw_setting] ... | def installed(cls):
"""
Used in ``yacms.pages.views.page`` to ensure
``PageMiddleware`` or a subclass has been installed. We cache
the result on the ``PageMiddleware._installed`` to only run
this once. Short path is to just check for the dotted path to
``PageMiddleware`` in `... |
def get_frame_list():
"""
Create the list of frames
"""
# TODO: use this function in IPS below (less code duplication)
frame_info_list = []
frame_list = []
frame = inspect.currentframe()
while frame is not None:
frame_list.append(frame)
info = inspect.getframeinfo(frame... | def function[get_frame_list, parameter[]]:
constant[
Create the list of frames
]
variable[frame_info_list] assign[=] list[[]]
variable[frame_list] assign[=] list[[]]
variable[frame] assign[=] call[name[inspect].currentframe, parameter[]]
while compare[name[frame] is_not c... | keyword[def] identifier[get_frame_list] ():
literal[string]
identifier[frame_info_list] =[]
identifier[frame_list] =[]
identifier[frame] = identifier[inspect] . identifier[currentframe] ()
keyword[while] identifier[frame] keyword[is] keyword[not] keyword[None] :
identifie... | def get_frame_list():
"""
Create the list of frames
"""
# TODO: use this function in IPS below (less code duplication)
frame_info_list = []
frame_list = []
frame = inspect.currentframe()
while frame is not None:
frame_list.append(frame)
info = inspect.getframeinfo(frame)
... |
def compute_slice_bounds(slices, scs, shape):
"""
Given a 2D selection consisting of slices/coordinates, a
SheetCoordinateSystem and the shape of the array returns a new
BoundingBox representing the sliced region.
"""
xidx, yidx = slices
ys, xs = shape
l, b, r, t = scs.bounds.lbrt()
... | def function[compute_slice_bounds, parameter[slices, scs, shape]]:
constant[
Given a 2D selection consisting of slices/coordinates, a
SheetCoordinateSystem and the shape of the array returns a new
BoundingBox representing the sliced region.
]
<ast.Tuple object at 0x7da1b1bed1b0> assign[=... | keyword[def] identifier[compute_slice_bounds] ( identifier[slices] , identifier[scs] , identifier[shape] ):
literal[string]
identifier[xidx] , identifier[yidx] = identifier[slices]
identifier[ys] , identifier[xs] = identifier[shape]
identifier[l] , identifier[b] , identifier[r] , identifier[t] ... | def compute_slice_bounds(slices, scs, shape):
"""
Given a 2D selection consisting of slices/coordinates, a
SheetCoordinateSystem and the shape of the array returns a new
BoundingBox representing the sliced region.
"""
(xidx, yidx) = slices
(ys, xs) = shape
(l, b, r, t) = scs.bounds.lbrt(... |
def _idx_to_bits(self, i):
"""Convert an group index to its bit representation."""
bits = bin(i)[2:].zfill(self.nb_hyperplanes) # Pad the bits str with 0
return [-1.0 if b == "0" else 1.0 for b in bits] | def function[_idx_to_bits, parameter[self, i]]:
constant[Convert an group index to its bit representation.]
variable[bits] assign[=] call[call[call[name[bin], parameter[name[i]]]][<ast.Slice object at 0x7da20c6e4850>].zfill, parameter[name[self].nb_hyperplanes]]
return[<ast.ListComp object at 0x7da2... | keyword[def] identifier[_idx_to_bits] ( identifier[self] , identifier[i] ):
literal[string]
identifier[bits] = identifier[bin] ( identifier[i] )[ literal[int] :]. identifier[zfill] ( identifier[self] . identifier[nb_hyperplanes] )
keyword[return] [- literal[int] keyword[if] identifier[b] == literal[... | def _idx_to_bits(self, i):
"""Convert an group index to its bit representation."""
bits = bin(i)[2:].zfill(self.nb_hyperplanes) # Pad the bits str with 0
return [-1.0 if b == '0' else 1.0 for b in bits] |
def _find_cont_fitfunc_regions(fluxes, ivars, contmask, deg, ranges, ffunc,
n_proc=1):
""" Run fit_cont, dealing with spectrum in regions or chunks
This is useful if a spectrum has gaps.
Parameters
----------
fluxes: ndarray of shape (nstars, npixels)
trainin... | def function[_find_cont_fitfunc_regions, parameter[fluxes, ivars, contmask, deg, ranges, ffunc, n_proc]]:
constant[ Run fit_cont, dealing with spectrum in regions or chunks
This is useful if a spectrum has gaps.
Parameters
----------
fluxes: ndarray of shape (nstars, npixels)
training ... | keyword[def] identifier[_find_cont_fitfunc_regions] ( identifier[fluxes] , identifier[ivars] , identifier[contmask] , identifier[deg] , identifier[ranges] , identifier[ffunc] ,
identifier[n_proc] = literal[int] ):
literal[string]
identifier[nstars] = identifier[fluxes] . identifier[shape] [ literal[int] ]... | def _find_cont_fitfunc_regions(fluxes, ivars, contmask, deg, ranges, ffunc, n_proc=1):
""" Run fit_cont, dealing with spectrum in regions or chunks
This is useful if a spectrum has gaps.
Parameters
----------
fluxes: ndarray of shape (nstars, npixels)
training set or test set pixel intensi... |
def identify_ibids(line):
"""Find IBIDs within the line, record their position and length,
and replace them with underscores.
@param line: (string) the working reference line
@return: (tuple) containing 2 dictionaries and a string:
Dictionary: matched IBID text: (Key: position of IBI... | def function[identify_ibids, parameter[line]]:
constant[Find IBIDs within the line, record their position and length,
and replace them with underscores.
@param line: (string) the working reference line
@return: (tuple) containing 2 dictionaries and a string:
Dictionary: matched I... | keyword[def] identifier[identify_ibids] ( identifier[line] ):
literal[string]
identifier[ibid_match_txt] ={}
keyword[for] identifier[m_ibid] keyword[in] identifier[re_ibid] . identifier[finditer] ( identifier[line] ):
identifier[ibid_match_txt] [ identifier[m_ibid] . identifier[start]... | def identify_ibids(line):
"""Find IBIDs within the line, record their position and length,
and replace them with underscores.
@param line: (string) the working reference line
@return: (tuple) containing 2 dictionaries and a string:
Dictionary: matched IBID text: (Key: position of IBI... |
def call(self, iface_name, func_name, params):
"""
Implements the call() function with same signature as Client.call(). Raises
a RpcException if send() has already been called on this batch. Otherwise
appends the request to an internal list.
This method is not commonly called ... | def function[call, parameter[self, iface_name, func_name, params]]:
constant[
Implements the call() function with same signature as Client.call(). Raises
a RpcException if send() has already been called on this batch. Otherwise
appends the request to an internal list.
This met... | keyword[def] identifier[call] ( identifier[self] , identifier[iface_name] , identifier[func_name] , identifier[params] ):
literal[string]
keyword[if] identifier[self] . identifier[sent] :
keyword[raise] identifier[Exception] ( literal[string] )
keyword[else] :
i... | def call(self, iface_name, func_name, params):
"""
Implements the call() function with same signature as Client.call(). Raises
a RpcException if send() has already been called on this batch. Otherwise
appends the request to an internal list.
This method is not commonly called dire... |
def euler_tour(G, node=None, seen=None, visited=None):
"""
definition from
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.192.8615&rep=rep1&type=pdf
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> edges = [
>>... | def function[euler_tour, parameter[G, node, seen, visited]]:
constant[
definition from
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.192.8615&rep=rep1&type=pdf
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> edge... | keyword[def] identifier[euler_tour] ( identifier[G] , identifier[node] = keyword[None] , identifier[seen] = keyword[None] , identifier[visited] = keyword[None] ):
literal[string]
keyword[if] identifier[node] keyword[is] keyword[None] :
identifier[node] = identifier[next] ( identifier[G] . ident... | def euler_tour(G, node=None, seen=None, visited=None):
"""
definition from
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.192.8615&rep=rep1&type=pdf
Example:
>>> # DISABLE_DOCTEST
>>> from utool.experimental.euler_tour_tree_avl import * # NOQA
>>> edges = [
>>... |
def get(self, setting_name, warn_only_if_overridden=False,
accept_deprecated='', suppress_warnings=False,
enforce_type=None, check_if_setting_deprecated=True,
warning_stacklevel=3):
"""
Returns a setting value for the setting named by ``setting_name``. The
ret... | def function[get, parameter[self, setting_name, warn_only_if_overridden, accept_deprecated, suppress_warnings, enforce_type, check_if_setting_deprecated, warning_stacklevel]]:
constant[
Returns a setting value for the setting named by ``setting_name``. The
returned value is actually a reference ... | keyword[def] identifier[get] ( identifier[self] , identifier[setting_name] , identifier[warn_only_if_overridden] = keyword[False] ,
identifier[accept_deprecated] = literal[string] , identifier[suppress_warnings] = keyword[False] ,
identifier[enforce_type] = keyword[None] , identifier[check_if_setting_deprecated] = ... | def get(self, setting_name, warn_only_if_overridden=False, accept_deprecated='', suppress_warnings=False, enforce_type=None, check_if_setting_deprecated=True, warning_stacklevel=3):
"""
Returns a setting value for the setting named by ``setting_name``. The
returned value is actually a reference to t... |
def estimategaps(args):
"""
%prog estimategaps JM-4 chr1 JMMale-1
Illustrate ALLMAPS gap estimation algorithm.
"""
p = OptionParser(estimategaps.__doc__)
opts, args, iopts = p.set_image_options(args, figsize="6x6", dpi=300)
if len(args) != 3:
sys.exit(not p.print_help())
pf, s... | def function[estimategaps, parameter[args]]:
constant[
%prog estimategaps JM-4 chr1 JMMale-1
Illustrate ALLMAPS gap estimation algorithm.
]
variable[p] assign[=] call[name[OptionParser], parameter[name[estimategaps].__doc__]]
<ast.Tuple object at 0x7da1b0887d30> assign[=] call[name[... | keyword[def] identifier[estimategaps] ( identifier[args] ):
literal[string]
identifier[p] = identifier[OptionParser] ( identifier[estimategaps] . identifier[__doc__] )
identifier[opts] , identifier[args] , identifier[iopts] = identifier[p] . identifier[set_image_options] ( identifier[args] , identifie... | def estimategaps(args):
"""
%prog estimategaps JM-4 chr1 JMMale-1
Illustrate ALLMAPS gap estimation algorithm.
"""
p = OptionParser(estimategaps.__doc__)
(opts, args, iopts) = p.set_image_options(args, figsize='6x6', dpi=300)
if len(args) != 3:
sys.exit(not p.print_help()) # depend... |
def delete_message(self, messageid="", folderid="", stackid=""):
"""Delete a message or a message stack
:param folderid: The folder to delete the message from, defaults to inbox
:param messageid: The message to delete
:param stackid: The stack to delete
"""
if self.sta... | def function[delete_message, parameter[self, messageid, folderid, stackid]]:
constant[Delete a message or a message stack
:param folderid: The folder to delete the message from, defaults to inbox
:param messageid: The message to delete
:param stackid: The stack to delete
]
... | keyword[def] identifier[delete_message] ( identifier[self] , identifier[messageid] = literal[string] , identifier[folderid] = literal[string] , identifier[stackid] = literal[string] ):
literal[string]
keyword[if] identifier[self] . identifier[standard_grant_type] keyword[is] keyword[not] lite... | def delete_message(self, messageid='', folderid='', stackid=''):
"""Delete a message or a message stack
:param folderid: The folder to delete the message from, defaults to inbox
:param messageid: The message to delete
:param stackid: The stack to delete
"""
if self.standard_gran... |
def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
"""
Add an entry to the system crontab.
"""
raise NotImplementedError | def function[add_cron, parameter[self, name, minute, hour, mday, month, wday, who, command, env]]:
constant[
Add an entry to the system crontab.
]
<ast.Raise object at 0x7da1b2658eb0> | keyword[def] identifier[add_cron] ( identifier[self] , identifier[name] , identifier[minute] , identifier[hour] , identifier[mday] , identifier[month] , identifier[wday] , identifier[who] , identifier[command] , identifier[env] = keyword[None] ):
literal[string]
keyword[raise] identifier[NotImplem... | def add_cron(self, name, minute, hour, mday, month, wday, who, command, env=None):
"""
Add an entry to the system crontab.
"""
raise NotImplementedError |
def get_job_input(self, job_id):
"""GetJobInput
https://apidocs.joyent.com/manta/api.html#GetJobInput
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival... | def function[get_job_input, parameter[self, job_id]]:
constant[GetJobInput
https://apidocs.joyent.com/manta/api.html#GetJobInput
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#... | keyword[def] identifier[get_job_input] ( identifier[self] , identifier[job_id] ):
literal[string]
keyword[try] :
keyword[return] identifier[RawMantaClient] . identifier[get_job_input] ( identifier[self] , identifier[job_id] )
keyword[except] identifier[errors] . identifier[M... | def get_job_input(self, job_id):
"""GetJobInput
https://apidocs.joyent.com/manta/api.html#GetJobInput
with the added sugar that it will retrieve the archived job if it has
been archived, per:
https://apidocs.joyent.com/manta/jobs-reference.html#job-completion-and-archival
... |
def show_hbonds(self):
"""Visualizes hydrogen bonds."""
hbonds = self.plcomplex.hbonds
for group in [['HBondDonor-P', hbonds.prot_don_id],
['HBondAccept-P', hbonds.prot_acc_id]]:
if not len(group[1]) == 0:
self.select_by_ids(group[0], group[1], r... | def function[show_hbonds, parameter[self]]:
constant[Visualizes hydrogen bonds.]
variable[hbonds] assign[=] name[self].plcomplex.hbonds
for taget[name[group]] in starred[list[[<ast.List object at 0x7da207f9a740>, <ast.List object at 0x7da207f993f0>]]] begin[:]
if <ast.UnaryOp obj... | keyword[def] identifier[show_hbonds] ( identifier[self] ):
literal[string]
identifier[hbonds] = identifier[self] . identifier[plcomplex] . identifier[hbonds]
keyword[for] identifier[group] keyword[in] [[ literal[string] , identifier[hbonds] . identifier[prot_don_id] ],
[ literal... | def show_hbonds(self):
"""Visualizes hydrogen bonds."""
hbonds = self.plcomplex.hbonds
for group in [['HBondDonor-P', hbonds.prot_don_id], ['HBondAccept-P', hbonds.prot_acc_id]]:
if not len(group[1]) == 0:
self.select_by_ids(group[0], group[1], restrict=self.protname) # depends on [cont... |
def hamming_distance(s1, s2):
"""Return the Hamming distance between equal-length sequences"""
# print(s1,s2)
if len(s1) != len(s2):
raise ValueError("Undefined for sequences of unequal length")
return sum(el1 != el2 for el1, el2 in zip(s1.upper(), s2.upper())) | def function[hamming_distance, parameter[s1, s2]]:
constant[Return the Hamming distance between equal-length sequences]
if compare[call[name[len], parameter[name[s1]]] not_equal[!=] call[name[len], parameter[name[s2]]]] begin[:]
<ast.Raise object at 0x7da1b1ff8430>
return[call[name[sum], par... | keyword[def] identifier[hamming_distance] ( identifier[s1] , identifier[s2] ):
literal[string]
keyword[if] identifier[len] ( identifier[s1] )!= identifier[len] ( identifier[s2] ):
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[return] identifier[sum] ( identifier[el... | def hamming_distance(s1, s2):
"""Return the Hamming distance between equal-length sequences"""
# print(s1,s2)
if len(s1) != len(s2):
raise ValueError('Undefined for sequences of unequal length') # depends on [control=['if'], data=[]]
return sum((el1 != el2 for (el1, el2) in zip(s1.upper(), ... |
def remove(self, arr):
"""Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array nam... | def function[remove, parameter[self, arr]]:
constant[Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array w... | keyword[def] identifier[remove] ( identifier[self] , identifier[arr] ):
literal[string]
identifier[name] = identifier[arr] keyword[if] identifier[isinstance] ( identifier[arr] , identifier[six] . identifier[string_types] ) keyword[else] identifier[arr] . identifier[psy] . identifier[arr_name]
... | def remove(self, arr):
"""Removes an array from the list
Parameters
----------
arr: str or :class:`InteractiveBase`
The array name or the data object in this list to remove
Raises
------
ValueError
If no array with the specified array name is... |
def getMyID(self,gist_name):
'''
Getting gistID of a gist in order to make the workflow
easy and uninterrupted.
'''
r = requests.get(
'%s'%BASE_URL+'/users/%s/gists' % self.user,
headers=self.gist.header
)
if (r.status_code == 200):
r_text = json.loads(r.text)
limit = len(r.json())
for g,... | def function[getMyID, parameter[self, gist_name]]:
constant[
Getting gistID of a gist in order to make the workflow
easy and uninterrupted.
]
variable[r] assign[=] call[name[requests].get, parameter[binary_operation[binary_operation[constant[%s] <ast.Mod object at 0x7da2590d6920> name[BASE_URL]] +... | keyword[def] identifier[getMyID] ( identifier[self] , identifier[gist_name] ):
literal[string]
identifier[r] = identifier[requests] . identifier[get] (
literal[string] % identifier[BASE_URL] + literal[string] % identifier[self] . identifier[user] ,
identifier[headers] = identifier[self] . identifier[gist... | def getMyID(self, gist_name):
"""
Getting gistID of a gist in order to make the workflow
easy and uninterrupted.
"""
r = requests.get('%s' % BASE_URL + '/users/%s/gists' % self.user, headers=self.gist.header)
if r.status_code == 200:
r_text = json.loads(r.text)
limit = len(r.json())
... |
def shell():
""" Start application-aware shell """
app = bootstrap.get_app()
context = dict(app=app)
# and push app context
app_context = app.app_context()
app_context.push()
# got ipython?
ipython = importlib.util.find_spec("IPython")
# run now
if ipython:
from IPytho... | def function[shell, parameter[]]:
constant[ Start application-aware shell ]
variable[app] assign[=] call[name[bootstrap].get_app, parameter[]]
variable[context] assign[=] call[name[dict], parameter[]]
variable[app_context] assign[=] call[name[app].app_context, parameter[]]
call[n... | keyword[def] identifier[shell] ():
literal[string]
identifier[app] = identifier[bootstrap] . identifier[get_app] ()
identifier[context] = identifier[dict] ( identifier[app] = identifier[app] )
identifier[app_context] = identifier[app] . identifier[app_context] ()
identifier[app_context... | def shell():
""" Start application-aware shell """
app = bootstrap.get_app()
context = dict(app=app)
# and push app context
app_context = app.app_context()
app_context.push()
# got ipython?
ipython = importlib.util.find_spec('IPython')
# run now
if ipython:
from IPython i... |
def set_attribute(library, session, attribute, attribute_state):
"""Sets the state of an attribute.
Corresponds to viSetAttribute function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param attribute: Attribute fo... | def function[set_attribute, parameter[library, session, attribute, attribute_state]]:
constant[Sets the state of an attribute.
Corresponds to viSetAttribute function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
... | keyword[def] identifier[set_attribute] ( identifier[library] , identifier[session] , identifier[attribute] , identifier[attribute_state] ):
literal[string]
keyword[return] identifier[library] . identifier[viSetAttribute] ( identifier[session] , identifier[attribute] , identifier[attribute_state] ) | def set_attribute(library, session, attribute, attribute_state):
"""Sets the state of an attribute.
Corresponds to viSetAttribute function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param attribute: Attribute fo... |
def close(self):
""" Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """
self.alive = False
self.rxThread.join()
self.serial.close() | def function[close, parameter[self]]:
constant[ Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port ]
name[self].alive assign[=] constant[False]
call[name[self].rxThread.join, parameter[]]
call[name[self].serial.close, parameter[]] | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[self] . identifier[alive] = keyword[False]
identifier[self] . identifier[rxThread] . identifier[join] ()
identifier[self] . identifier[serial] . identifier[close] () | def close(self):
""" Stops the read thread, waits for it to exit cleanly, then closes the underlying serial port """
self.alive = False
self.rxThread.join()
self.serial.close() |
def get_generated_project_files(self, tool):
""" Get generated project files, the content depends on a tool. Look at tool implementation """
exporter = ToolsSupported().get_tool(tool)
return exporter(self.generated_files[tool], self.settings).get_generated_project_files() | def function[get_generated_project_files, parameter[self, tool]]:
constant[ Get generated project files, the content depends on a tool. Look at tool implementation ]
variable[exporter] assign[=] call[call[name[ToolsSupported], parameter[]].get_tool, parameter[name[tool]]]
return[call[call[name[expor... | keyword[def] identifier[get_generated_project_files] ( identifier[self] , identifier[tool] ):
literal[string]
identifier[exporter] = identifier[ToolsSupported] (). identifier[get_tool] ( identifier[tool] )
keyword[return] identifier[exporter] ( identifier[self] . identifier[generated_fil... | def get_generated_project_files(self, tool):
""" Get generated project files, the content depends on a tool. Look at tool implementation """
exporter = ToolsSupported().get_tool(tool)
return exporter(self.generated_files[tool], self.settings).get_generated_project_files() |
def parse_input(args, kwargs=None, condition=True, no_parse=None):
'''
Parse out the args and kwargs from a list of input values. Optionally,
return the args and kwargs without passing them to condition_input().
Don't pull args with key=val apart if it has a newline in it.
'''
if no_parse is No... | def function[parse_input, parameter[args, kwargs, condition, no_parse]]:
constant[
Parse out the args and kwargs from a list of input values. Optionally,
return the args and kwargs without passing them to condition_input().
Don't pull args with key=val apart if it has a newline in it.
]
... | keyword[def] identifier[parse_input] ( identifier[args] , identifier[kwargs] = keyword[None] , identifier[condition] = keyword[True] , identifier[no_parse] = keyword[None] ):
literal[string]
keyword[if] identifier[no_parse] keyword[is] keyword[None] :
identifier[no_parse] =()
keyword[if] ... | def parse_input(args, kwargs=None, condition=True, no_parse=None):
"""
Parse out the args and kwargs from a list of input values. Optionally,
return the args and kwargs without passing them to condition_input().
Don't pull args with key=val apart if it has a newline in it.
"""
if no_parse is No... |
def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
raw = self._get_payload(key)
integer... | def function[increment, parameter[self, key, value]]:
constant[
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
]
variable[raw] assign[=... | keyword[def] identifier[increment] ( identifier[self] , identifier[key] , identifier[value] = literal[int] ):
literal[string]
identifier[raw] = identifier[self] . identifier[_get_payload] ( identifier[key] )
identifier[integer] = identifier[int] ( identifier[raw] [ literal[string] ])+ ide... | def increment(self, key, value=1):
"""
Increment the value of an item in the cache.
:param key: The cache key
:type key: str
:param value: The increment value
:type value: int
:rtype: int or bool
"""
raw = self._get_payload(key)
integer = int(raw['d... |
def set_reference(self, refobj, reference):
"""Connect the given reftrack node with the given refernce node
:param refobj: the reftrack node to update
:type refobj: str
:param reference: the reference node
:type reference: str
:returns: None
:rtype: None
... | def function[set_reference, parameter[self, refobj, reference]]:
constant[Connect the given reftrack node with the given refernce node
:param refobj: the reftrack node to update
:type refobj: str
:param reference: the reference node
:type reference: str
:returns: None
... | keyword[def] identifier[set_reference] ( identifier[self] , identifier[refobj] , identifier[reference] ):
literal[string]
identifier[refnodeattr] = literal[string] % identifier[refobj]
keyword[if] identifier[reference] :
identifier[cmds] . identifier[connectAttr] ( literal[s... | def set_reference(self, refobj, reference):
"""Connect the given reftrack node with the given refernce node
:param refobj: the reftrack node to update
:type refobj: str
:param reference: the reference node
:type reference: str
:returns: None
:rtype: None
:rai... |
def _numpy_to_python(obj):
""" Convert an nested dict/list/tuple that might contain numpy objects
to their python equivalents. Return converted object.
"""
if isinstance(obj, dict):
return {k: _numpy_to_python(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple, np.ndarray)):
... | def function[_numpy_to_python, parameter[obj]]:
constant[ Convert an nested dict/list/tuple that might contain numpy objects
to their python equivalents. Return converted object.
]
if call[name[isinstance], parameter[name[obj], name[dict]]] begin[:]
return[<ast.DictComp object at 0x7da18... | keyword[def] identifier[_numpy_to_python] ( identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] , identifier[dict] ):
keyword[return] { identifier[k] : identifier[_numpy_to_python] ( identifier[v] ) keyword[for] identifier[k] , identifier[v] keyword[in] iden... | def _numpy_to_python(obj):
""" Convert an nested dict/list/tuple that might contain numpy objects
to their python equivalents. Return converted object.
"""
if isinstance(obj, dict):
return {k: _numpy_to_python(v) for (k, v) in obj.items()} # depends on [control=['if'], data=[]]
elif isinsta... |
def _add_imported_module(self, node, importedmodname):
"""notify an imported module, used to analyze dependencies"""
module_file = node.root().file
context_name = node.root().name
base = os.path.splitext(os.path.basename(module_file))[0]
try:
importedmodname = astroi... | def function[_add_imported_module, parameter[self, node, importedmodname]]:
constant[notify an imported module, used to analyze dependencies]
variable[module_file] assign[=] call[name[node].root, parameter[]].file
variable[context_name] assign[=] call[name[node].root, parameter[]].name
v... | keyword[def] identifier[_add_imported_module] ( identifier[self] , identifier[node] , identifier[importedmodname] ):
literal[string]
identifier[module_file] = identifier[node] . identifier[root] (). identifier[file]
identifier[context_name] = identifier[node] . identifier[root] (). identi... | def _add_imported_module(self, node, importedmodname):
"""notify an imported module, used to analyze dependencies"""
module_file = node.root().file
context_name = node.root().name
base = os.path.splitext(os.path.basename(module_file))[0]
try:
importedmodname = astroid.modutils.get_module_par... |
def add_if_none_match(self):
"""
Add the if-none-match option to the request.
"""
option = Option()
option.number = defines.OptionRegistry.IF_NONE_MATCH.number
option.value = None
self.add_option(option) | def function[add_if_none_match, parameter[self]]:
constant[
Add the if-none-match option to the request.
]
variable[option] assign[=] call[name[Option], parameter[]]
name[option].number assign[=] name[defines].OptionRegistry.IF_NONE_MATCH.number
name[option].value assign[... | keyword[def] identifier[add_if_none_match] ( identifier[self] ):
literal[string]
identifier[option] = identifier[Option] ()
identifier[option] . identifier[number] = identifier[defines] . identifier[OptionRegistry] . identifier[IF_NONE_MATCH] . identifier[number]
identifier[optio... | def add_if_none_match(self):
"""
Add the if-none-match option to the request.
"""
option = Option()
option.number = defines.OptionRegistry.IF_NONE_MATCH.number
option.value = None
self.add_option(option) |
def update_hacluster_vip(service, relation_data):
""" Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
"""
cluster_config = get_hacluster_config()
vip_group = []
vips_to... | def function[update_hacluster_vip, parameter[service, relation_data]]:
constant[ Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
]
variable[cluster_config] assign[=] ca... | keyword[def] identifier[update_hacluster_vip] ( identifier[service] , identifier[relation_data] ):
literal[string]
identifier[cluster_config] = identifier[get_hacluster_config] ()
identifier[vip_group] =[]
identifier[vips_to_delete] =[]
keyword[for] identifier[vip] keyword[in] identifier[... | def update_hacluster_vip(service, relation_data):
""" Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
"""
cluster_config = get_hacluster_config()
vip_group = []
vips_to... |
def shift_click(self, locator, params=None, timeout=None):
"""
Shift-click web element.
:param locator: locator tuple or WebElement instance
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for element
:return: None
"""
... | def function[shift_click, parameter[self, locator, params, timeout]]:
constant[
Shift-click web element.
:param locator: locator tuple or WebElement instance
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for element
:return: None
... | keyword[def] identifier[shift_click] ( identifier[self] , identifier[locator] , identifier[params] = keyword[None] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[self] . identifier[_click] ( identifier[locator] , identifier[params] , identifier[timeout] , identifier[Keys] . ide... | def shift_click(self, locator, params=None, timeout=None):
"""
Shift-click web element.
:param locator: locator tuple or WebElement instance
:param params: (optional) locator parameters
:param timeout: (optional) time to wait for element
:return: None
"""
self._c... |
def concat_t_vars_np(self, vars_idx=None):
"""
Concatenate `self.np_t` with `self.np_vars` and return a single matrix.
The first column corresponds to time, and the rest of the matrix is the variables.
Returns
-------
np.array : concatenated matrix
"""
s... | def function[concat_t_vars_np, parameter[self, vars_idx]]:
constant[
Concatenate `self.np_t` with `self.np_vars` and return a single matrix.
The first column corresponds to time, and the rest of the matrix is the variables.
Returns
-------
np.array : concatenated matrix
... | keyword[def] identifier[concat_t_vars_np] ( identifier[self] , identifier[vars_idx] = keyword[None] ):
literal[string]
identifier[selected_np_vars] = identifier[self] . identifier[np_vars]
keyword[if] identifier[vars_idx] keyword[is] keyword[not] keyword[None] :
identifie... | def concat_t_vars_np(self, vars_idx=None):
"""
Concatenate `self.np_t` with `self.np_vars` and return a single matrix.
The first column corresponds to time, and the rest of the matrix is the variables.
Returns
-------
np.array : concatenated matrix
"""
selected_... |
def add_user(self, team, params={}, **options):
"""The user making this call must be a member of the team in order to add others.
The user to add must exist in the same organization as the team in order to be added.
The user to add can be referenced by their globally unique user ID or their ema... | def function[add_user, parameter[self, team, params]]:
constant[The user making this call must be a member of the team in order to add others.
The user to add must exist in the same organization as the team in order to be added.
The user to add can be referenced by their globally unique user ID ... | keyword[def] identifier[add_user] ( identifier[self] , identifier[team] , identifier[params] ={},** identifier[options] ):
literal[string]
identifier[path] = literal[string] %( identifier[team] )
keyword[return] identifier[self] . identifier[client] . identifier[post] ( identifier[path] ,... | def add_user(self, team, params={}, **options):
"""The user making this call must be a member of the team in order to add others.
The user to add must exist in the same organization as the team in order to be added.
The user to add can be referenced by their globally unique user ID or their email ad... |
def update_house(self, complex: str, id: str, **kwargs):
"""
Update the existing house
"""
self.check_house(complex, id)
self.put('developers/{developer}/complexes/{complex}/houses/{id}'.format(
developer=self.developer,
complex=complex,
id=id,... | def function[update_house, parameter[self, complex, id]]:
constant[
Update the existing house
]
call[name[self].check_house, parameter[name[complex], name[id]]]
call[name[self].put, parameter[call[constant[developers/{developer}/complexes/{complex}/houses/{id}].format, parameter[... | keyword[def] identifier[update_house] ( identifier[self] , identifier[complex] : identifier[str] , identifier[id] : identifier[str] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[check_house] ( identifier[complex] , identifier[id] )
identifier[self] . identifier[pu... | def update_house(self, complex: str, id: str, **kwargs):
"""
Update the existing house
"""
self.check_house(complex, id)
self.put('developers/{developer}/complexes/{complex}/houses/{id}'.format(developer=self.developer, complex=complex, id=id), data=kwargs) |
def next_frame_header(socket):
"""
Returns the stream and size of the next frame of data waiting to be read
from socket, according to the protocol defined here:
https://docs.docker.com/engine/api/v1.24/#attach-to-a-container
"""
try:
data = read_exactly(socket, 8)
except SocketError... | def function[next_frame_header, parameter[socket]]:
constant[
Returns the stream and size of the next frame of data waiting to be read
from socket, according to the protocol defined here:
https://docs.docker.com/engine/api/v1.24/#attach-to-a-container
]
<ast.Try object at 0x7da18ede7040>
... | keyword[def] identifier[next_frame_header] ( identifier[socket] ):
literal[string]
keyword[try] :
identifier[data] = identifier[read_exactly] ( identifier[socket] , literal[int] )
keyword[except] identifier[SocketError] :
keyword[return] (- literal[int] ,- literal[int] )
ident... | def next_frame_header(socket):
"""
Returns the stream and size of the next frame of data waiting to be read
from socket, according to the protocol defined here:
https://docs.docker.com/engine/api/v1.24/#attach-to-a-container
"""
try:
data = read_exactly(socket, 8) # depends on [control... |
def add_router_interface(self, context, router_info):
"""Adds an interface to a router created on Arista HW router.
This deals with both IPv6 and IPv4 configurations.
"""
if router_info:
self._select_dicts(router_info['ip_version'])
cidr = router_info['cidr']
... | def function[add_router_interface, parameter[self, context, router_info]]:
constant[Adds an interface to a router created on Arista HW router.
This deals with both IPv6 and IPv4 configurations.
]
if name[router_info] begin[:]
call[name[self]._select_dicts, parameter[call... | keyword[def] identifier[add_router_interface] ( identifier[self] , identifier[context] , identifier[router_info] ):
literal[string]
keyword[if] identifier[router_info] :
identifier[self] . identifier[_select_dicts] ( identifier[router_info] [ literal[string] ])
identifier... | def add_router_interface(self, context, router_info):
"""Adds an interface to a router created on Arista HW router.
This deals with both IPv6 and IPv4 configurations.
"""
if router_info:
self._select_dicts(router_info['ip_version'])
cidr = router_info['cidr']
subnet_mask... |
def nodes(self, frequency=None):
"""
Returns all nodes of the specified frequency that are related to
the given Session
Parameters
----------
frequency : str | None
The frequency of the nodes to return
Returns
-------
nodes : iterable... | def function[nodes, parameter[self, frequency]]:
constant[
Returns all nodes of the specified frequency that are related to
the given Session
Parameters
----------
frequency : str | None
The frequency of the nodes to return
Returns
-------
... | keyword[def] identifier[nodes] ( identifier[self] , identifier[frequency] = keyword[None] ):
literal[string]
keyword[if] identifier[frequency] keyword[is] keyword[None] :
[]
keyword[elif] identifier[frequency] == literal[string] :
keyword[return] [ identifier[s... | def nodes(self, frequency=None):
"""
Returns all nodes of the specified frequency that are related to
the given Session
Parameters
----------
frequency : str | None
The frequency of the nodes to return
Returns
-------
nodes : iterable[Tre... |
def get(self, key, default=None):
"""
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
"""
if key in self.__cli:
return self... | def function[get, parameter[self, key, default]]:
constant[
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
]
if compare[name[key] in n... | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[key] keyword[in] identifier[self] . identifier[__cli] :
keyword[return] identifier[self] . identifier[__cli] [ identifier[key] ]
... | def get(self, key, default=None):
"""
Get the value for `key`.
Gives priority to command-line overrides.
Args:
key: str, the key to get the value for.
Returns:
object: The value for `key`
"""
if key in self.__cli:
return self.__cli[key] ... |
def has_response(self, beacon_config, request, client_address):
""" :meth:`.WBeaconMessengerBase.has_response` method implementation. This method compares request
header with internal one.
"""
try:
self._message_address_parse(request, invert_hello=self.__invert_hello)
return True
except ValueError:
p... | def function[has_response, parameter[self, beacon_config, request, client_address]]:
constant[ :meth:`.WBeaconMessengerBase.has_response` method implementation. This method compares request
header with internal one.
]
<ast.Try object at 0x7da18bcc9de0>
return[constant[False]] | keyword[def] identifier[has_response] ( identifier[self] , identifier[beacon_config] , identifier[request] , identifier[client_address] ):
literal[string]
keyword[try] :
identifier[self] . identifier[_message_address_parse] ( identifier[request] , identifier[invert_hello] = identifier[self] . identifier[__... | def has_response(self, beacon_config, request, client_address):
""" :meth:`.WBeaconMessengerBase.has_response` method implementation. This method compares request
header with internal one.
"""
try:
self._message_address_parse(request, invert_hello=self.__invert_hello)
return True # depends ... |
def warn(warn_string, log=None):
"""Warning
This method creates custom warning messages.
Parameters
----------
warn_string : str
Warning message string
log : instance, optional
Logging structure instance
"""
if import_fail:
warn_txt = 'WARNING'
else:
... | def function[warn, parameter[warn_string, log]]:
constant[Warning
This method creates custom warning messages.
Parameters
----------
warn_string : str
Warning message string
log : instance, optional
Logging structure instance
]
if name[import_fail] begin[:]
... | keyword[def] identifier[warn] ( identifier[warn_string] , identifier[log] = keyword[None] ):
literal[string]
keyword[if] identifier[import_fail] :
identifier[warn_txt] = literal[string]
keyword[else] :
identifier[warn_txt] = identifier[colored] ( literal[string] , literal[string] ... | def warn(warn_string, log=None):
"""Warning
This method creates custom warning messages.
Parameters
----------
warn_string : str
Warning message string
log : instance, optional
Logging structure instance
"""
if import_fail:
warn_txt = 'WARNING' # depends on [c... |
def fill(self, text=""):
"Indent a piece of text, according to the current indentation level"
self.f.write(self.line_marker + " " * self._indent + text)
self.line_marker = "\n" | def function[fill, parameter[self, text]]:
constant[Indent a piece of text, according to the current indentation level]
call[name[self].f.write, parameter[binary_operation[binary_operation[name[self].line_marker + binary_operation[constant[ ] * name[self]._indent]] + name[text]]]]
name[self].... | keyword[def] identifier[fill] ( identifier[self] , identifier[text] = literal[string] ):
literal[string]
identifier[self] . identifier[f] . identifier[write] ( identifier[self] . identifier[line_marker] + literal[string] * identifier[self] . identifier[_indent] + identifier[text] )
identif... | def fill(self, text=''):
"""Indent a piece of text, according to the current indentation level"""
self.f.write(self.line_marker + ' ' * self._indent + text)
self.line_marker = '\n' |
def _extract_actions_unique_topics(self, movement_counts, max_movements, cluster_topology, max_movement_size):
"""Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Group actions by by topic-nam... | def function[_extract_actions_unique_topics, parameter[self, movement_counts, max_movements, cluster_topology, max_movement_size]]:
constant[Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Gr... | keyword[def] identifier[_extract_actions_unique_topics] ( identifier[self] , identifier[movement_counts] , identifier[max_movements] , identifier[cluster_topology] , identifier[max_movement_size] ):
literal[string]
identifier[topic_actions] = identifier[defaultdict] ( identifier[list] )
... | def _extract_actions_unique_topics(self, movement_counts, max_movements, cluster_topology, max_movement_size):
"""Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Group actions by by topic-name: {... |
def saveJSON(g, data, backup=False):
"""
Saves the current setup to disk.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
backup : bool
If we are saving a backup on close, don't prompt for filename
"""
... | def function[saveJSON, parameter[g, data, backup]]:
constant[
Saves the current setup to disk.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
backup : bool
If we are saving a backup on close, don't prom... | keyword[def] identifier[saveJSON] ( identifier[g] , identifier[data] , identifier[backup] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[backup] :
identifier[fname] = identifier[filedialog] . identifier[asksaveasfilename] (
identifier[defaultextension] = literal... | def saveJSON(g, data, backup=False):
"""
Saves the current setup to disk.
g : hcam_drivers.globals.Container
Container with globals
data : dict
The current setup in JSON compatible dictionary format.
backup : bool
If we are saving a backup on close, don't prompt for filename
"""
... |
def _ls2ar(inp, strinp):
r"""Convert float or linspace-input to arange/slice-input for brute."""
# Check if input is 1 or 3 elements (float, list, tuple, array)
if np.size(inp) == 1:
start = np.squeeze(inp)
stop = start+1
num = 1
elif np.size(inp) == 3:
start = inp[0]
... | def function[_ls2ar, parameter[inp, strinp]]:
constant[Convert float or linspace-input to arange/slice-input for brute.]
if compare[call[name[np].size, parameter[name[inp]]] equal[==] constant[1]] begin[:]
variable[start] assign[=] call[name[np].squeeze, parameter[name[inp]]]
... | keyword[def] identifier[_ls2ar] ( identifier[inp] , identifier[strinp] ):
literal[string]
keyword[if] identifier[np] . identifier[size] ( identifier[inp] )== literal[int] :
identifier[start] = identifier[np] . identifier[squeeze] ( identifier[inp] )
identifier[stop] = identifier[st... | def _ls2ar(inp, strinp):
"""Convert float or linspace-input to arange/slice-input for brute."""
# Check if input is 1 or 3 elements (float, list, tuple, array)
if np.size(inp) == 1:
start = np.squeeze(inp)
stop = start + 1
num = 1 # depends on [control=['if'], data=[]]
elif np.s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.