code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _make_persistent(self, model_name, pkg_name):
"""Monkey-patch object persistence (ex: to/from database) into a
bravado-core model class"""
#
# WARNING: ugly piece of monkey-patching below. Hopefully will replace
# with native bravado-core code in the future...
#
... | def function[_make_persistent, parameter[self, model_name, pkg_name]]:
constant[Monkey-patch object persistence (ex: to/from database) into a
bravado-core model class]
variable[c] assign[=] call[name[get_function], parameter[name[pkg_name]]]
for taget[name[name]] in starred[tuple[[<ast.C... | keyword[def] identifier[_make_persistent] ( identifier[self] , identifier[model_name] , identifier[pkg_name] ):
literal[string]
identifier[c] = identifier[get_function] ( identifier[pkg_name] )
keyword[for] identifier[name] keyword[in] ( lit... | def _make_persistent(self, model_name, pkg_name):
"""Monkey-patch object persistence (ex: to/from database) into a
bravado-core model class"""
#
# WARNING: ugly piece of monkey-patching below. Hopefully will replace
# with native bravado-core code in the future...
#
# Load class at path ... |
def _set_transport_service(self, v, load=False):
"""
Setter method for transport_service, mapped from YANG variable /interface_vlan/interface/vlan/transport_service (uint16)
If this variable is read-only (config: false) in the
source YANG file, then _set_transport_service is considered as a private
... | def function[_set_transport_service, parameter[self, v, load]]:
constant[
Setter method for transport_service, mapped from YANG variable /interface_vlan/interface/vlan/transport_service (uint16)
If this variable is read-only (config: false) in the
source YANG file, then _set_transport_service is con... | keyword[def] identifier[_set_transport_service] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
... | def _set_transport_service(self, v, load=False):
"""
Setter method for transport_service, mapped from YANG variable /interface_vlan/interface/vlan/transport_service (uint16)
If this variable is read-only (config: false) in the
source YANG file, then _set_transport_service is considered as a private
... |
def _make_cron_re():
"""
Make the regular expression that matches a crontab 'cron' line.
Each field has a set of allowed values, and can then be in a range, and be
listed with dashes. A range can be stepped with the '/' modifier, and
ranges can be in a list. A field can also be '*', or '*' divide... | def function[_make_cron_re, parameter[]]:
constant[
Make the regular expression that matches a crontab 'cron' line.
Each field has a set of allowed values, and can then be in a range, and be
listed with dashes. A range can be stepped with the '/' modifier, and
ranges can be in a list. A field... | keyword[def] identifier[_make_cron_re] ():
literal[string]
identifier[range_] = literal[string]
identifier[template] = literal[string] + literal[string] . identifier[format] ( identifier[r] = identifier[range_] )+ literal[string]
keyword[return] (
literal[string] +
identifier[template... | def _make_cron_re():
"""
Make the regular expression that matches a crontab 'cron' line.
Each field has a set of allowed values, and can then be in a range, and be
listed with dashes. A range can be stepped with the '/' modifier, and
ranges can be in a list. A field can also be '*', or '*' divide... |
def _create_scheduler(self, save_sensors):
"""Return function to schedule saving sensors."""
@asyncio.coroutine
def schedule_save():
"""Save sensors and schedule a new save."""
yield from self.loop.run_in_executor(None, save_sensors)
callback = partial(self.lo... | def function[_create_scheduler, parameter[self, save_sensors]]:
constant[Return function to schedule saving sensors.]
def function[schedule_save, parameter[]]:
constant[Save sensors and schedule a new save.]
<ast.YieldFrom object at 0x7da1b27bb2b0>
variabl... | keyword[def] identifier[_create_scheduler] ( identifier[self] , identifier[save_sensors] ):
literal[string]
@ identifier[asyncio] . identifier[coroutine]
keyword[def] identifier[schedule_save] ():
literal[string]
keyword[yield] keyword[from] identifier[self] .... | def _create_scheduler(self, save_sensors):
"""Return function to schedule saving sensors."""
@asyncio.coroutine
def schedule_save():
"""Save sensors and schedule a new save."""
yield from self.loop.run_in_executor(None, save_sensors)
callback = partial(self.loop.create_task, schedul... |
def delete_association(self, target, api_type=None, api_sub_type=None, unique_id=None):
"""
Deletes a association from a Indicator/Group/Victim
Args:
target:
api_type:
api_sub_type:
unique_id:
Returns:
"""
api_type = api_... | def function[delete_association, parameter[self, target, api_type, api_sub_type, unique_id]]:
constant[
Deletes a association from a Indicator/Group/Victim
Args:
target:
api_type:
api_sub_type:
unique_id:
Returns:
]
varia... | keyword[def] identifier[delete_association] ( identifier[self] , identifier[target] , identifier[api_type] = keyword[None] , identifier[api_sub_type] = keyword[None] , identifier[unique_id] = keyword[None] ):
literal[string]
identifier[api_type] = identifier[api_type] keyword[or] identifier[targe... | def delete_association(self, target, api_type=None, api_sub_type=None, unique_id=None):
"""
Deletes a association from a Indicator/Group/Victim
Args:
target:
api_type:
api_sub_type:
unique_id:
Returns:
"""
api_type = api_type or ... |
def parse(self, file, skipheader=False, outfile=None):
"""Parse a line-oriented association file into a list of association dict objects
Note the returned list is of dict objects. TODO: These will
later be specified using marshmallow and it should be possible
to generate objects
... | def function[parse, parameter[self, file, skipheader, outfile]]:
constant[Parse a line-oriented association file into a list of association dict objects
Note the returned list is of dict objects. TODO: These will
later be specified using marshmallow and it should be possible
to generate... | keyword[def] identifier[parse] ( identifier[self] , identifier[file] , identifier[skipheader] = keyword[False] , identifier[outfile] = keyword[None] ):
literal[string]
identifier[associations] = identifier[self] . identifier[association_generator] ( identifier[file] , identifier[skipheader] = ident... | def parse(self, file, skipheader=False, outfile=None):
"""Parse a line-oriented association file into a list of association dict objects
Note the returned list is of dict objects. TODO: These will
later be specified using marshmallow and it should be possible
to generate objects
Ar... |
def go_to_line(self, line=None):
"""Open 'go to line' dialog"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
editorstack.go_to_line(line) | def function[go_to_line, parameter[self, line]]:
constant[Open 'go to line' dialog]
variable[editorstack] assign[=] call[name[self].get_current_editorstack, parameter[]]
if compare[name[editorstack] is_not constant[None]] begin[:]
call[name[editorstack].go_to_line, parameter[name... | keyword[def] identifier[go_to_line] ( identifier[self] , identifier[line] = keyword[None] ):
literal[string]
identifier[editorstack] = identifier[self] . identifier[get_current_editorstack] ()
keyword[if] identifier[editorstack] keyword[is] keyword[not] keyword[None] :
... | def go_to_line(self, line=None):
"""Open 'go to line' dialog"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
editorstack.go_to_line(line) # depends on [control=['if'], data=['editorstack']] |
def apply_sdb(opts, sdb_opts=None):
'''
Recurse for sdb:// links for opts
'''
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts
if isinstance(sdb_opts, six.string_types) and sdb_opts.startswith('sdb://'):
return salt.utils.sdb.sdb... | def function[apply_sdb, parameter[opts, sdb_opts]]:
constant[
Recurse for sdb:// links for opts
]
import module[salt.utils.sdb]
if compare[name[sdb_opts] is constant[None]] begin[:]
variable[sdb_opts] assign[=] name[opts]
if <ast.BoolOp object at 0x7da1b1fa21d0> begin... | keyword[def] identifier[apply_sdb] ( identifier[opts] , identifier[sdb_opts] = keyword[None] ):
literal[string]
keyword[import] identifier[salt] . identifier[utils] . identifier[sdb]
keyword[if] identifier[sdb_opts] keyword[is] keyword[None] :
identifier[sdb_opts] = identifier[opts]... | def apply_sdb(opts, sdb_opts=None):
"""
Recurse for sdb:// links for opts
"""
# Late load of SDB to keep CLI light
import salt.utils.sdb
if sdb_opts is None:
sdb_opts = opts # depends on [control=['if'], data=['sdb_opts']]
if isinstance(sdb_opts, six.string_types) and sdb_opts.start... |
def roll_data(self, data):
"""Append new data to the right side of every line strip and remove
as much data from the left.
Parameters
----------
data : array-like
A data array to append.
"""
data = data.astype('float32')[..., np.newaxis]
... | def function[roll_data, parameter[self, data]]:
constant[Append new data to the right side of every line strip and remove
as much data from the left.
Parameters
----------
data : array-like
A data array to append.
]
variable[data] assign[=] ca... | keyword[def] identifier[roll_data] ( identifier[self] , identifier[data] ):
literal[string]
identifier[data] = identifier[data] . identifier[astype] ( literal[string] )[..., identifier[np] . identifier[newaxis] ]
identifier[s1] = identifier[self] . identifier[_data_shape] [ literal[int] ]-... | def roll_data(self, data):
"""Append new data to the right side of every line strip and remove
as much data from the left.
Parameters
----------
data : array-like
A data array to append.
"""
data = data.astype('float32')[..., np.newaxis]
s1 = self... |
def classinstances(cls):
"""Return all instances of the current class
JB_Gui will not return the instances of subclasses
A subclass will only return the instances that have the same
type as the subclass. So it won\'t return instances of further subclasses.
:returns: all instnac... | def function[classinstances, parameter[cls]]:
constant[Return all instances of the current class
JB_Gui will not return the instances of subclasses
A subclass will only return the instances that have the same
type as the subclass. So it won't return instances of further subclasses.
... | keyword[def] identifier[classinstances] ( identifier[cls] ):
literal[string]
identifier[l] =[ identifier[i] keyword[for] identifier[i] keyword[in] identifier[cls] . identifier[allinstances] () keyword[if] identifier[type] ( identifier[i] )== identifier[cls] ]
keyword[return] identifi... | def classinstances(cls):
"""Return all instances of the current class
JB_Gui will not return the instances of subclasses
A subclass will only return the instances that have the same
type as the subclass. So it won't return instances of further subclasses.
:returns: all instnaces of... |
def norm_l0(x, axis=None, eps=0.0):
r"""Compute the :math:`\ell_0` "norm" (it is not really a norm)
.. math::
\| \mathbf{x} \|_0 = \sum_i \left\{ \begin{array}{ccc}
0 & \text{if} & x_i = 0 \\ 1 &\text{if} & x_i \neq 0
\end{array} \right.
where :math:`x_i` is element :math:`i` of vector :ma... | def function[norm_l0, parameter[x, axis, eps]]:
constant[Compute the :math:`\ell_0` "norm" (it is not really a norm)
.. math::
\| \mathbf{x} \|_0 = \sum_i \left\{ \begin{array}{ccc}
0 & \text{if} & x_i = 0 \\ 1 &\text{if} & x_i \neq 0
\end{array} \right.
where :math:`x_i` is element :m... | keyword[def] identifier[norm_l0] ( identifier[x] , identifier[axis] = keyword[None] , identifier[eps] = literal[int] ):
literal[string]
identifier[nl0] = identifier[np] . identifier[sum] ( identifier[np] . identifier[abs] ( identifier[x] )> identifier[eps] , identifier[axis] = identifier[axis] , identifie... | def norm_l0(x, axis=None, eps=0.0):
"""Compute the :math:`\\ell_0` "norm" (it is not really a norm)
.. math::
\\| \\mathbf{x} \\|_0 = \\sum_i \\left\\{ \\begin{array}{ccc}
0 & \\text{if} & x_i = 0 \\\\ 1 &\\text{if} & x_i \\neq 0
\\end{array} \\right.
where :math:`x_i` is element :math:`i`... |
def advance(self, word_id: int) -> 'ConstrainedHypothesis':
"""
Updates the constraints object based on advancing on word_id.
There is a complication, in that we may have started but not
yet completed a multi-word constraint. We need to allow constraints
to be added as unconstra... | def function[advance, parameter[self, word_id]]:
constant[
Updates the constraints object based on advancing on word_id.
There is a complication, in that we may have started but not
yet completed a multi-word constraint. We need to allow constraints
to be added as unconstrained ... | keyword[def] identifier[advance] ( identifier[self] , identifier[word_id] : identifier[int] )-> literal[string] :
literal[string]
identifier[obj] = identifier[copy] . identifier[deepcopy] ( identifier[self] )
keyword[if] identifier[obj] . identifier[last_met] !=- literal[int] ... | def advance(self, word_id: int) -> 'ConstrainedHypothesis':
"""
Updates the constraints object based on advancing on word_id.
There is a complication, in that we may have started but not
yet completed a multi-word constraint. We need to allow constraints
to be added as unconstrained... |
async def get_ticket(self, request):
"""Called to return the ticket for a request.
Args:
request: aiohttp Request object.
Returns:
A ticket (string like) object, or None if no ticket is available
for the passed request.
"""
session = await ge... | <ast.AsyncFunctionDef object at 0x7da207f03f70> | keyword[async] keyword[def] identifier[get_ticket] ( identifier[self] , identifier[request] ):
literal[string]
identifier[session] = keyword[await] identifier[get_session] ( identifier[request] )
keyword[return] identifier[session] . identifier[get] ( identifier[self] . identifier[cooki... | async def get_ticket(self, request):
"""Called to return the ticket for a request.
Args:
request: aiohttp Request object.
Returns:
A ticket (string like) object, or None if no ticket is available
for the passed request.
"""
session = await get_sessio... |
def get(self, key, default=None):
""" Return the key if exists or a default value
:param str value: Value
:param str default: Default value if key not present
"""
if key in self:
return self.__getitem__(key)
else:
return default | def function[get, parameter[self, key, default]]:
constant[ Return the key if exists or a default value
:param str value: Value
:param str default: Default value if key not present
]
if compare[name[key] in name[self]] begin[:]
return[call[name[self].__getitem__,... | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[default] = keyword[None] ):
literal[string]
keyword[if] identifier[key] keyword[in] identifier[self] :
keyword[return] identifier[self] . identifier[__getitem__] ( identifier[key] )
keyword[else... | def get(self, key, default=None):
""" Return the key if exists or a default value
:param str value: Value
:param str default: Default value if key not present
"""
if key in self:
return self.__getitem__(key) # depends on [control=['if'], data=['key', 'self']]
else:
... |
def error(self, text):
"""
Posts an error message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their ... | def function[error, parameter[self, text]]:
constant[
Posts an error message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they ... | keyword[def] identifier[error] ( identifier[self] , identifier[text] ):
literal[string]
identifier[self] . identifier[queue] . identifier[put] ( identifier[dill] . identifier[dumps] ( identifier[LogMessageCommand] ( identifier[text] = identifier[text] , identifier[level] = identifier[logging] . ide... | def error(self, text):
"""
Posts an error message adding a timestamp and logging level to it for both file and console handlers.
Logger uses a redraw rate because of console flickering. That means it will not draw new messages or progress
at the very time they are being logged but their time... |
def flag_message(current):
"""
Flag inappropriate messages
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'message_key': key,
}
# response:
{
'
'status': 'Created',
'code': 201,
... | def function[flag_message, parameter[current]]:
constant[
Flag inappropriate messages
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'message_key': key,
}
# response:
{
'
'status': 'Created',
... | keyword[def] identifier[flag_message] ( identifier[current] ):
literal[string]
identifier[current] . identifier[output] ={ literal[string] : literal[string] , literal[string] : literal[int] }
identifier[FlaggedMessage] . identifier[objects] . identifier[get_or_create] ( identifier[user_id] = identifie... | def flag_message(current):
"""
Flag inappropriate messages
.. code-block:: python
# request:
{
'view':'_zops_flag_message',
'message_key': key,
}
# response:
{
'
'status': 'Created',
'code': 201,
... |
def binary(self):
"""
return encoded representation
"""
if isinstance(self.value, int):
return b_chr(_TAG_ATOM_CACHE_REF) + b_chr(self.value)
elif isinstance(self.value, TypeUnicode):
value_encoded = self.value.encode('utf-8')
length = len(valu... | def function[binary, parameter[self]]:
constant[
return encoded representation
]
if call[name[isinstance], parameter[name[self].value, name[int]]] begin[:]
return[binary_operation[call[name[b_chr], parameter[name[_TAG_ATOM_CACHE_REF]]] + call[name[b_chr], parameter[name[self].val... | keyword[def] identifier[binary] ( identifier[self] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[self] . identifier[value] , identifier[int] ):
keyword[return] identifier[b_chr] ( identifier[_TAG_ATOM_CACHE_REF] )+ identifier[b_chr] ( identifier[self] . identifie... | def binary(self):
"""
return encoded representation
"""
if isinstance(self.value, int):
return b_chr(_TAG_ATOM_CACHE_REF) + b_chr(self.value) # depends on [control=['if'], data=[]]
elif isinstance(self.value, TypeUnicode):
value_encoded = self.value.encode('utf-8')
l... |
def add_element(self, location, element, delete_elem=False):
"""
Create an entry located at ``location``.
Args:
location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for
instance).
element: Element... | def function[add_element, parameter[self, location, element, delete_elem]]:
constant[
Create an entry located at ``location``.
Args:
location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for
instance).
... | keyword[def] identifier[add_element] ( identifier[self] , identifier[location] , identifier[element] , identifier[delete_elem] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[_create_entry] ( identifier[location] , identifier[element] , identifier[unique] = keywor... | def add_element(self, location, element, delete_elem=False):
"""
Create an entry located at ``location``.
Args:
location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for
instance).
element: Element to ... |
def air_gap(self,
volume: float = None,
height: float = None) -> 'InstrumentContext':
"""
Pull air into the pipette current tip at the current location
:param volume: The amount in uL to aspirate air into the tube.
(Default will use all rem... | def function[air_gap, parameter[self, volume, height]]:
constant[
Pull air into the pipette current tip at the current location
:param volume: The amount in uL to aspirate air into the tube.
(Default will use all remaining volume in tip)
:type volume: float
... | keyword[def] identifier[air_gap] ( identifier[self] ,
identifier[volume] : identifier[float] = keyword[None] ,
identifier[height] : identifier[float] = keyword[None] )-> literal[string] :
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[hw_pipette] [ literal[string] ]:
... | def air_gap(self, volume: float=None, height: float=None) -> 'InstrumentContext':
"""
Pull air into the pipette current tip at the current location
:param volume: The amount in uL to aspirate air into the tube.
(Default will use all remaining volume in tip)
:type volu... |
def _check_in_cshm_polygon(self, rup):
"""
Checks if any part of the rupture surface mesh is located within the
intended boundaries of the Canterbury Seismic Hazard Model in
Gerstenberger et al. (2014), Seismic hazard modelling for the recovery
of Christchurch, Earthquake Spectra... | def function[_check_in_cshm_polygon, parameter[self, rup]]:
constant[
Checks if any part of the rupture surface mesh is located within the
intended boundaries of the Canterbury Seismic Hazard Model in
Gerstenberger et al. (2014), Seismic hazard modelling for the recovery
of Chris... | keyword[def] identifier[_check_in_cshm_polygon] ( identifier[self] , identifier[rup] ):
literal[string]
identifier[lats] = identifier[np] . identifier[ravel] ( identifier[rup] . identifier[surface] . identifier[mesh] . identifier[array] [ literal[int] ])
identifier[lons] = identifier[np] .... | def _check_in_cshm_polygon(self, rup):
"""
Checks if any part of the rupture surface mesh is located within the
intended boundaries of the Canterbury Seismic Hazard Model in
Gerstenberger et al. (2014), Seismic hazard modelling for the recovery
of Christchurch, Earthquake Spectra, 30... |
def get_task_result(self, task_id):
"""
Get task result from worker. If the task is not finished, return None.
It's prefered to use :class:`carotte.Task` object directly.
:param string task_id: Task ID
:returns: Task dict
:rtype: dict
"""
data = {
... | def function[get_task_result, parameter[self, task_id]]:
constant[
Get task result from worker. If the task is not finished, return None.
It's prefered to use :class:`carotte.Task` object directly.
:param string task_id: Task ID
:returns: Task dict
:rtype: dict
... | keyword[def] identifier[get_task_result] ( identifier[self] , identifier[task_id] ):
literal[string]
identifier[data] ={
literal[string] : literal[string] ,
literal[string] : identifier[task_id]
}
identifier[self] . identifier[__send_pyobj] ( identifier[data] )
... | def get_task_result(self, task_id):
"""
Get task result from worker. If the task is not finished, return None.
It's prefered to use :class:`carotte.Task` object directly.
:param string task_id: Task ID
:returns: Task dict
:rtype: dict
"""
data = {'action': 'get_... |
def get(self, key: str, default=None) -> Signature:
""" Get a signature instance by its internal_name """
item = default
if key in self._hsig:
item = self._hsig[key]
return item | def function[get, parameter[self, key, default]]:
constant[ Get a signature instance by its internal_name ]
variable[item] assign[=] name[default]
if compare[name[key] in name[self]._hsig] begin[:]
variable[item] assign[=] call[name[self]._hsig][name[key]]
return[name[item]] | keyword[def] identifier[get] ( identifier[self] , identifier[key] : identifier[str] , identifier[default] = keyword[None] )-> identifier[Signature] :
literal[string]
identifier[item] = identifier[default]
keyword[if] identifier[key] keyword[in] identifier[self] . identifier[_hsig] :
... | def get(self, key: str, default=None) -> Signature:
""" Get a signature instance by its internal_name """
item = default
if key in self._hsig:
item = self._hsig[key] # depends on [control=['if'], data=['key']]
return item |
def FloatProperty(name, default=0.0, readonly=False, docs=None):
'''
:name: string - property name
:default: float - property default value
:readonly: boolean - if True, setter method is NOT generated
Returns a property object that can be used to initialize a
class instance variable as a proper... | def function[FloatProperty, parameter[name, default, readonly, docs]]:
constant[
:name: string - property name
:default: float - property default value
:readonly: boolean - if True, setter method is NOT generated
Returns a property object that can be used to initialize a
class instance vari... | keyword[def] identifier[FloatProperty] ( identifier[name] , identifier[default] = literal[int] , identifier[readonly] = keyword[False] , identifier[docs] = keyword[None] ):
literal[string]
identifier[private_name] = literal[string] + identifier[name]
keyword[def] identifier[getf] ( identifier[self... | def FloatProperty(name, default=0.0, readonly=False, docs=None):
"""
:name: string - property name
:default: float - property default value
:readonly: boolean - if True, setter method is NOT generated
Returns a property object that can be used to initialize a
class instance variable as a proper... |
def binned_pixelrange(self, waverange, **kwargs):
"""Calculate the number of pixels within the given wavelength
range and `binset`.
Parameters
----------
waverange : tuple of float or `~astropy.units.quantity.Quantity`
Lower and upper limits of the desired wavelength... | def function[binned_pixelrange, parameter[self, waverange]]:
constant[Calculate the number of pixels within the given wavelength
range and `binset`.
Parameters
----------
waverange : tuple of float or `~astropy.units.quantity.Quantity`
Lower and upper limits of the d... | keyword[def] identifier[binned_pixelrange] ( identifier[self] , identifier[waverange] ,** identifier[kwargs] ):
literal[string]
identifier[x] = identifier[units] . identifier[validate_quantity] (
identifier[waverange] , identifier[self] . identifier[_internal_wave_unit] , identifier[equiva... | def binned_pixelrange(self, waverange, **kwargs):
"""Calculate the number of pixels within the given wavelength
range and `binset`.
Parameters
----------
waverange : tuple of float or `~astropy.units.quantity.Quantity`
Lower and upper limits of the desired wavelength ran... |
def select(self, crit):
"""
Select subset of values that match a given index criterion.
Parameters
----------
crit : function, list, str, int
Criterion function to map to indices, specific index value,
or list of indices.
"""
import types
... | def function[select, parameter[self, crit]]:
constant[
Select subset of values that match a given index criterion.
Parameters
----------
crit : function, list, str, int
Criterion function to map to indices, specific index value,
or list of indices.
... | keyword[def] identifier[select] ( identifier[self] , identifier[crit] ):
literal[string]
keyword[import] identifier[types]
keyword[if] keyword[not] identifier[isinstance] ( identifier[crit] , identifier[types] . identifier[FunctionType] ):
keyword[if] i... | def select(self, crit):
"""
Select subset of values that match a given index criterion.
Parameters
----------
crit : function, list, str, int
Criterion function to map to indices, specific index value,
or list of indices.
"""
import types
# ha... |
def add_transition_to_state(from_port, to_port):
"""Interface method between Gaphas and RAFCON core for adding transitions
The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary
parameters for the add_transition method of the RAFCON core. Also the ... | def function[add_transition_to_state, parameter[from_port, to_port]]:
constant[Interface method between Gaphas and RAFCON core for adding transitions
The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary
parameters for the add_transition metho... | keyword[def] identifier[add_transition_to_state] ( identifier[from_port] , identifier[to_port] ):
literal[string]
keyword[from] identifier[rafcon] . identifier[gui] . identifier[mygaphas] . identifier[items] . identifier[ports] keyword[import] identifier[IncomeView] , identifier[OutcomeView]
iden... | def add_transition_to_state(from_port, to_port):
"""Interface method between Gaphas and RAFCON core for adding transitions
The method checks the types of the given ports (IncomeView or OutcomeView) and from this determines the necessary
parameters for the add_transition method of the RAFCON core. Also the ... |
def __make_scubadir(self):
'''Make temp directory where all ancillary files are bind-mounted
'''
self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')
self.__scubadir_contpath = '/.scuba'
self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath) | def function[__make_scubadir, parameter[self]]:
constant[Make temp directory where all ancillary files are bind-mounted
]
name[self].__scubadir_hostpath assign[=] call[name[tempfile].mkdtemp, parameter[]]
name[self].__scubadir_contpath assign[=] constant[/.scuba]
call[name[self].... | keyword[def] identifier[__make_scubadir] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__scubadir_hostpath] = identifier[tempfile] . identifier[mkdtemp] ( identifier[prefix] = literal[string] )
identifier[self] . identifier[__scubadir_contpath] = literal[string]
... | def __make_scubadir(self):
"""Make temp directory where all ancillary files are bind-mounted
"""
self.__scubadir_hostpath = tempfile.mkdtemp(prefix='scubadir')
self.__scubadir_contpath = '/.scuba'
self.add_volume(self.__scubadir_hostpath, self.__scubadir_contpath) |
def _assess_resource_warnings(self, process, vals):
"""Assess whether the cpu load or memory usage is above the allocation
Parameters
----------
process : str
Process name
vals : vals
List of trace information for each tag of that process
Returns... | def function[_assess_resource_warnings, parameter[self, process, vals]]:
constant[Assess whether the cpu load or memory usage is above the allocation
Parameters
----------
process : str
Process name
vals : vals
List of trace information for each tag of th... | keyword[def] identifier[_assess_resource_warnings] ( identifier[self] , identifier[process] , identifier[vals] ):
literal[string]
identifier[cpu_warnings] ={}
identifier[mem_warnings] ={}
keyword[for] identifier[i] keyword[in] identifier[vals] :
keyword[try] :
... | def _assess_resource_warnings(self, process, vals):
"""Assess whether the cpu load or memory usage is above the allocation
Parameters
----------
process : str
Process name
vals : vals
List of trace information for each tag of that process
Returns
... |
def _load_idp_dynamic_entity_id(self, state):
"""
Loads an idp server with the entity id saved in state
:type state: satosa.state.State
:rtype: saml.server.Server
:param state: The current state
:return: An idp server
"""
# Change the idp entity id dynam... | def function[_load_idp_dynamic_entity_id, parameter[self, state]]:
constant[
Loads an idp server with the entity id saved in state
:type state: satosa.state.State
:rtype: saml.server.Server
:param state: The current state
:return: An idp server
]
variabl... | keyword[def] identifier[_load_idp_dynamic_entity_id] ( identifier[self] , identifier[state] ):
literal[string]
identifier[idp_config_file] = identifier[copy] . identifier[deepcopy] ( identifier[self] . identifier[idp_config] )
identifier[idp_config_file] [ literal[string] ]= liter... | def _load_idp_dynamic_entity_id(self, state):
"""
Loads an idp server with the entity id saved in state
:type state: satosa.state.State
:rtype: saml.server.Server
:param state: The current state
:return: An idp server
"""
# Change the idp entity id dynamically
... |
def process_request():
"""
Retrieve a CameraStatus, Event or FileRecord from the request, based on the supplied type and ID. If the type is
'cached_request' then the ID must be specified in 'cached_request_id' - if this ID is not for an entity in the
cache this method will return None an... | def function[process_request, parameter[]]:
constant[
Retrieve a CameraStatus, Event or FileRecord from the request, based on the supplied type and ID. If the type is
'cached_request' then the ID must be specified in 'cached_request_id' - if this ID is not for an entity in the
cache this... | keyword[def] identifier[process_request] ():
literal[string]
identifier[g] . identifier[request_dict] = identifier[safe_load] ( identifier[request] . identifier[get_data] ())
identifier[entity_type] = identifier[g] . identifier[request_dict] [ literal[string] ]
identifier[entity_i... | def process_request():
"""
Retrieve a CameraStatus, Event or FileRecord from the request, based on the supplied type and ID. If the type is
'cached_request' then the ID must be specified in 'cached_request_id' - if this ID is not for an entity in the
cache this method will return None and cl... |
def append(self, electrode_id):
'''
Append the specified electrode to the route.
The route is not modified (i.e., electrode is not appended) if
electrode is not connected to the last electrode in the existing route.
Parameters
----------
electrode_id : str
... | def function[append, parameter[self, electrode_id]]:
constant[
Append the specified electrode to the route.
The route is not modified (i.e., electrode is not appended) if
electrode is not connected to the last electrode in the existing route.
Parameters
----------
... | keyword[def] identifier[append] ( identifier[self] , identifier[electrode_id] ):
literal[string]
identifier[do_append] = keyword[False]
keyword[if] keyword[not] identifier[self] . identifier[electrode_ids] :
identifier[do_append] = keyword[True]
keyword[elif] id... | def append(self, electrode_id):
"""
Append the specified electrode to the route.
The route is not modified (i.e., electrode is not appended) if
electrode is not connected to the last electrode in the existing route.
Parameters
----------
electrode_id : str
... |
def submit_audit(self, item_list):
"""
将第三方提交的代码包提交审核
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param item_list: 提交审核项的一个列表(至少填写1项,至多填写5项)
:type item_list: list[dict]
:return: 审核编号
:rtype: int
"... | def function[submit_audit, parameter[self, item_list]]:
constant[
将第三方提交的代码包提交审核
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param item_list: 提交审核项的一个列表(至少填写1项,至多填写5项)
:type item_list: list[dict]
:return: 审核编号
... | keyword[def] identifier[submit_audit] ( identifier[self] , identifier[item_list] ):
literal[string]
keyword[return] identifier[self] . identifier[_post] (
literal[string] ,
identifier[data] ={
literal[string] : identifier[item_list] ,
},
identifier[resul... | def submit_audit(self, item_list):
"""
将第三方提交的代码包提交审核
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param item_list: 提交审核项的一个列表(至少填写1项,至多填写5项)
:type item_list: list[dict]
:return: 审核编号
:rtype: int
"""
... |
def get_tile_images_by_rect(self, rect):
""" Speed up data access
More efficient because data is accessed and cached locally
"""
def rev(seq, start, stop):
if start < 0:
start = 0
return enumerate(seq[start:stop + 1], start)
x1, y1, x2, ... | def function[get_tile_images_by_rect, parameter[self, rect]]:
constant[ Speed up data access
More efficient because data is accessed and cached locally
]
def function[rev, parameter[seq, start, stop]]:
if compare[name[start] less[<] constant[0]] begin[:]
... | keyword[def] identifier[get_tile_images_by_rect] ( identifier[self] , identifier[rect] ):
literal[string]
keyword[def] identifier[rev] ( identifier[seq] , identifier[start] , identifier[stop] ):
keyword[if] identifier[start] < literal[int] :
identifier[start] = lite... | def get_tile_images_by_rect(self, rect):
""" Speed up data access
More efficient because data is accessed and cached locally
"""
def rev(seq, start, stop):
if start < 0:
start = 0 # depends on [control=['if'], data=['start']]
return enumerate(seq[start:stop + 1], s... |
def _load_params_of(self, effect):
"""
Called only when a effect has created
Param changes calls :meth:`~pluginsmanager.observer.host_observer.host_observer.HostObserver.on_param_value_changed()`
"""
for param in effect.params:
if param.value != param.default:
... | def function[_load_params_of, parameter[self, effect]]:
constant[
Called only when a effect has created
Param changes calls :meth:`~pluginsmanager.observer.host_observer.host_observer.HostObserver.on_param_value_changed()`
]
for taget[name[param]] in starred[name[effect].params] ... | keyword[def] identifier[_load_params_of] ( identifier[self] , identifier[effect] ):
literal[string]
keyword[for] identifier[param] keyword[in] identifier[effect] . identifier[params] :
keyword[if] identifier[param] . identifier[value] != identifier[param] . identifier[default] :
... | def _load_params_of(self, effect):
"""
Called only when a effect has created
Param changes calls :meth:`~pluginsmanager.observer.host_observer.host_observer.HostObserver.on_param_value_changed()`
"""
for param in effect.params:
if param.value != param.default:
self._s... |
def rename(*args):
"""
Rename OLD_FILENAME to NEW_FILENAME or move OLD_FILENAME(s) to NEW_DIRECTORY
The rename and move commands are the same.
Files on disk, including unfollowed files, are moved, if they are not already in the new location.
"""
parser = argparse.ArgumentParser(prog="%s %s" % ... | def function[rename, parameter[]]:
constant[
Rename OLD_FILENAME to NEW_FILENAME or move OLD_FILENAME(s) to NEW_DIRECTORY
The rename and move commands are the same.
Files on disk, including unfollowed files, are moved, if they are not already in the new location.
]
variable[parser] ass... | keyword[def] identifier[rename] (* identifier[args] ):
literal[string]
identifier[parser] = identifier[argparse] . identifier[ArgumentParser] ( identifier[prog] = literal[string] %( identifier[__package__] , identifier[rename] . identifier[__name__] ), identifier[description] = identifier[rename] . identif... | def rename(*args):
"""
Rename OLD_FILENAME to NEW_FILENAME or move OLD_FILENAME(s) to NEW_DIRECTORY
The rename and move commands are the same.
Files on disk, including unfollowed files, are moved, if they are not already in the new location.
"""
parser = argparse.ArgumentParser(prog='%s %s' % ... |
def shepherd(x, y, n_boot=200):
"""
Shepherd's Pi correlation, equivalent to Spearman's rho after outliers
removal.
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
n_boot : int
Number of bootstrap samples to calculat... | def function[shepherd, parameter[x, y, n_boot]]:
constant[
Shepherd's Pi correlation, equivalent to Spearman's rho after outliers
removal.
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
n_boot : int
Number of bo... | keyword[def] identifier[shepherd] ( identifier[x] , identifier[y] , identifier[n_boot] = literal[int] ):
literal[string]
keyword[from] identifier[scipy] . identifier[stats] keyword[import] identifier[spearmanr]
identifier[X] = identifier[np] . identifier[column_stack] (( identifier[x] , identifie... | def shepherd(x, y, n_boot=200):
"""
Shepherd's Pi correlation, equivalent to Spearman's rho after outliers
removal.
Parameters
----------
x, y : array_like
First and second set of observations. x and y must be independent.
n_boot : int
Number of bootstrap samples to calculat... |
def __init_configrs(self, rs_cfg):
"""Create and start a config replica set."""
# Use 'rs_id' to set the id for consistency, but need to rename
# to 'id' to use with ReplicaSets.create()
rs_cfg['id'] = rs_cfg.pop('rs_id', None)
for member in rs_cfg.setdefault('members', [{}]):
... | def function[__init_configrs, parameter[self, rs_cfg]]:
constant[Create and start a config replica set.]
call[name[rs_cfg]][constant[id]] assign[=] call[name[rs_cfg].pop, parameter[constant[rs_id], constant[None]]]
for taget[name[member]] in starred[call[name[rs_cfg].setdefault, parameter[consta... | keyword[def] identifier[__init_configrs] ( identifier[self] , identifier[rs_cfg] ):
literal[string]
identifier[rs_cfg] [ literal[string] ]= identifier[rs_cfg] . identifier[pop] ( literal[string] , keyword[None] )
keyword[for] identifier[member] keyword[in] identifier[r... | def __init_configrs(self, rs_cfg):
"""Create and start a config replica set."""
# Use 'rs_id' to set the id for consistency, but need to rename
# to 'id' to use with ReplicaSets.create()
rs_cfg['id'] = rs_cfg.pop('rs_id', None)
for member in rs_cfg.setdefault('members', [{}]):
member['procPa... |
def get_lyric_by_songid(self, mid):
"""Get song lyric
:param mid: music id
:return: {
lrc: {
version: int,
lyric: str
},
tlyric: {
version: int,
lyric: str
}
sgc: bool,
... | def function[get_lyric_by_songid, parameter[self, mid]]:
constant[Get song lyric
:param mid: music id
:return: {
lrc: {
version: int,
lyric: str
},
tlyric: {
version: int,
lyric: str
}... | keyword[def] identifier[get_lyric_by_songid] ( identifier[self] , identifier[mid] ):
literal[string]
identifier[url] = identifier[uri] + literal[string] + literal[string] + identifier[str] ( identifier[mid] )+ literal[string]
keyword[return] identifier[self] . identifier[request... | def get_lyric_by_songid(self, mid):
"""Get song lyric
:param mid: music id
:return: {
lrc: {
version: int,
lyric: str
},
tlyric: {
version: int,
lyric: str
}
sgc: bool,
... |
def yum_install(self, packages, ignore_error=False):
"""Install some packages on the remote host.
:param packages: ist of packages to install.
"""
return self.run('yum install -y --quiet ' + ' '.join(packages), ignore_error=ignore_error, retry=5) | def function[yum_install, parameter[self, packages, ignore_error]]:
constant[Install some packages on the remote host.
:param packages: ist of packages to install.
]
return[call[name[self].run, parameter[binary_operation[constant[yum install -y --quiet ] + call[constant[ ].join, parameter[n... | keyword[def] identifier[yum_install] ( identifier[self] , identifier[packages] , identifier[ignore_error] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[run] ( literal[string] + literal[string] . identifier[join] ( identifier[packages] ), identifier[ignore_error]... | def yum_install(self, packages, ignore_error=False):
"""Install some packages on the remote host.
:param packages: ist of packages to install.
"""
return self.run('yum install -y --quiet ' + ' '.join(packages), ignore_error=ignore_error, retry=5) |
def dump(
state, host,
remote_filename, database=None,
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
'''
Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to d... | def function[dump, parameter[state, host, remote_filename, database, mysql_user, mysql_password, mysql_host, mysql_port]]:
constant[
Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.
+ database: name of the database to dump
+ remote_filename: name of the file to dump the SQL to
... | keyword[def] identifier[dump] (
identifier[state] , identifier[host] ,
identifier[remote_filename] , identifier[database] = keyword[None] ,
identifier[mysql_user] = keyword[None] , identifier[mysql_password] = keyword[None] ,
identifier[mysql_host] = keyword[None] , identifier[mysql_port] = keyword[None] ,
):
... | def dump(state, host, remote_filename, database=None, mysql_user=None, mysql_password=None, mysql_host=None, mysql_port=None):
# Details for speaking to MySQL via `mysql` CLI
'\n Dump a MySQL database into a ``.sql`` file. Requires ``mysqldump``.\n\n + database: name of the database to dump\n + remote_... |
def reload_pimms():
'''
reload_pimms() reloads the entire pimms module and returns it.
'''
import sys, six
try: from importlib import reload
except: from imp import reload
reload(sys.modules['pimms.util'])
reload(sys.modules['pimms.table'])
reload(sys.modules['pimms.immutabl... | def function[reload_pimms, parameter[]]:
constant[
reload_pimms() reloads the entire pimms module and returns it.
]
import module[sys], module[six]
<ast.Try object at 0x7da20c6a9960>
call[name[reload], parameter[call[name[sys].modules][constant[pimms.util]]]]
call[name[reload], p... | keyword[def] identifier[reload_pimms] ():
literal[string]
keyword[import] identifier[sys] , identifier[six]
keyword[try] : keyword[from] identifier[importlib] keyword[import] identifier[reload]
keyword[except] : keyword[from] identifier[imp] keyword[import] identifier[reload]
ident... | def reload_pimms():
"""
reload_pimms() reloads the entire pimms module and returns it.
"""
import sys, six
try:
from importlib import reload # depends on [control=['try'], data=[]]
except:
from imp import reload # depends on [control=['except'], data=[]]
reload(sys.modules[... |
def load_module(name, original_module):
"""
Load a copy of a module, distinct from what you'd get if you imported
it directly.
@param str name: The name of the new module.
@param original_module: The original module we're recreating.
@return: A new, distinct module.
"""
module = Module... | def function[load_module, parameter[name, original_module]]:
constant[
Load a copy of a module, distinct from what you'd get if you imported
it directly.
@param str name: The name of the new module.
@param original_module: The original module we're recreating.
@return: A new, distinct modu... | keyword[def] identifier[load_module] ( identifier[name] , identifier[original_module] ):
literal[string]
identifier[module] = identifier[ModuleType] ( identifier[name] )
keyword[if] identifier[PY3] :
keyword[import] identifier[importlib] . identifier[util]
identifier[spec] = ident... | def load_module(name, original_module):
"""
Load a copy of a module, distinct from what you'd get if you imported
it directly.
@param str name: The name of the new module.
@param original_module: The original module we're recreating.
@return: A new, distinct module.
"""
module = Module... |
def execOnSubArrays(arrs, fn, splitX, splitY):
"""
execute a function(on or multiple arrays)
only on sub sections
works only on 2d arrays at the moment
>>> a1 = np.ones((1000,1000))
>>> a2 = np.ones((1000,1000))
>>> out = execOnSubArrays((a1,a2), lambda sa1,sa2: sa1+as2, splitX=10, splitY=1... | def function[execOnSubArrays, parameter[arrs, fn, splitX, splitY]]:
constant[
execute a function(on or multiple arrays)
only on sub sections
works only on 2d arrays at the moment
>>> a1 = np.ones((1000,1000))
>>> a2 = np.ones((1000,1000))
>>> out = execOnSubArrays((a1,a2), lambda sa1,sa... | keyword[def] identifier[execOnSubArrays] ( identifier[arrs] , identifier[fn] , identifier[splitX] , identifier[splitY] ):
literal[string]
keyword[if] identifier[type] ( identifier[arrs] ) keyword[not] keyword[in] ( identifier[tuple] , identifier[list] ):
identifier[arrs] =( identifier[arrs] ,)
... | def execOnSubArrays(arrs, fn, splitX, splitY):
"""
execute a function(on or multiple arrays)
only on sub sections
works only on 2d arrays at the moment
>>> a1 = np.ones((1000,1000))
>>> a2 = np.ones((1000,1000))
>>> out = execOnSubArrays((a1,a2), lambda sa1,sa2: sa1+as2, splitX=10, splitY=1... |
def compileInterpolatableOTFsFromDS(
designSpaceDoc,
preProcessorClass=OTFPreProcessor,
outlineCompilerClass=OutlineOTFCompiler,
featureCompilerClass=None,
featureWriters=None,
glyphOrder=None,
useProductionNames=None,
roundTolerance=None,
inplace=False,
):
"""Create FontTools CF... | def function[compileInterpolatableOTFsFromDS, parameter[designSpaceDoc, preProcessorClass, outlineCompilerClass, featureCompilerClass, featureWriters, glyphOrder, useProductionNames, roundTolerance, inplace]]:
constant[Create FontTools CFF fonts from the DesignSpaceDocument UFO sources
with interpolatable o... | keyword[def] identifier[compileInterpolatableOTFsFromDS] (
identifier[designSpaceDoc] ,
identifier[preProcessorClass] = identifier[OTFPreProcessor] ,
identifier[outlineCompilerClass] = identifier[OutlineOTFCompiler] ,
identifier[featureCompilerClass] = keyword[None] ,
identifier[featureWriters] = keyword[None] ,... | def compileInterpolatableOTFsFromDS(designSpaceDoc, preProcessorClass=OTFPreProcessor, outlineCompilerClass=OutlineOTFCompiler, featureCompilerClass=None, featureWriters=None, glyphOrder=None, useProductionNames=None, roundTolerance=None, inplace=False):
"""Create FontTools CFF fonts from the DesignSpaceDocument UF... |
def destroy(device):
'''
Destroy a RAID device.
WARNING This will zero the superblock of all members of the RAID array..
CLI Example:
.. code-block:: bash
salt '*' raid.destroy /dev/md0
'''
try:
details = detail(device)
except CommandExecutionError:
return Fal... | def function[destroy, parameter[device]]:
constant[
Destroy a RAID device.
WARNING This will zero the superblock of all members of the RAID array..
CLI Example:
.. code-block:: bash
salt '*' raid.destroy /dev/md0
]
<ast.Try object at 0x7da1b1c45b40>
variable[stop_cmd]... | keyword[def] identifier[destroy] ( identifier[device] ):
literal[string]
keyword[try] :
identifier[details] = identifier[detail] ( identifier[device] )
keyword[except] identifier[CommandExecutionError] :
keyword[return] keyword[False]
identifier[stop_cmd] =[ literal[string] ... | def destroy(device):
"""
Destroy a RAID device.
WARNING This will zero the superblock of all members of the RAID array..
CLI Example:
.. code-block:: bash
salt '*' raid.destroy /dev/md0
"""
try:
details = detail(device) # depends on [control=['try'], data=[]]
except ... |
def _load_params(params, logger=logging):
"""Given a str as a path to the .params file or a pair of params,
returns two dictionaries representing arg_params and aux_params.
"""
if isinstance(params, str):
cur_path = os.path.dirname(os.path.realpath(__file__))
param_file_path = os.path.jo... | def function[_load_params, parameter[params, logger]]:
constant[Given a str as a path to the .params file or a pair of params,
returns two dictionaries representing arg_params and aux_params.
]
if call[name[isinstance], parameter[name[params], name[str]]] begin[:]
variable[cur_pa... | keyword[def] identifier[_load_params] ( identifier[params] , identifier[logger] = identifier[logging] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[params] , identifier[str] ):
identifier[cur_path] = identifier[os] . identifier[path] . identifier[dirname] ( identifier[os] . i... | def _load_params(params, logger=logging):
"""Given a str as a path to the .params file or a pair of params,
returns two dictionaries representing arg_params and aux_params.
"""
if isinstance(params, str):
cur_path = os.path.dirname(os.path.realpath(__file__))
param_file_path = os.path.jo... |
def send_markdown(self, agent_id, user_ids, content, party_ids='', tag_ids=''):
"""markdown消息
https://work.weixin.qq.com/api/doc#90000/90135/90236/markdown%E6%B6%88%E6%81%AF
> 目前仅支持markdown语法的子集
> 微工作台(原企业号)不支持展示markdown消息
:param agent_id: 企业应用的id,整型。可在应用的设置页面查看
:type ... | def function[send_markdown, parameter[self, agent_id, user_ids, content, party_ids, tag_ids]]:
constant[markdown消息
https://work.weixin.qq.com/api/doc#90000/90135/90236/markdown%E6%B6%88%E6%81%AF
> 目前仅支持markdown语法的子集
> 微工作台(原企业号)不支持展示markdown消息
:param agent_id: 企业应用的id,整型。可在应用的... | keyword[def] identifier[send_markdown] ( identifier[self] , identifier[agent_id] , identifier[user_ids] , identifier[content] , identifier[party_ids] = literal[string] , identifier[tag_ids] = literal[string] ):
literal[string]
identifier[msg] ={
literal[string] : literal[string] ,
... | def send_markdown(self, agent_id, user_ids, content, party_ids='', tag_ids=''):
"""markdown消息
https://work.weixin.qq.com/api/doc#90000/90135/90236/markdown%E6%B6%88%E6%81%AF
> 目前仅支持markdown语法的子集
> 微工作台(原企业号)不支持展示markdown消息
:param agent_id: 企业应用的id,整型。可在应用的设置页面查看
:type agen... |
def process_object(self, obj):
"""Process current object and push it to the ElasticSearch."""
document = self.document_class(meta={'id': self.generate_id(obj)})
for field in document._doc_type.mapping: # pylint: disable=protected-access
if field in ['users_with_permissions', 'group... | def function[process_object, parameter[self, obj]]:
constant[Process current object and push it to the ElasticSearch.]
variable[document] assign[=] call[name[self].document_class, parameter[]]
for taget[name[field]] in starred[name[document]._doc_type.mapping] begin[:]
if compare... | keyword[def] identifier[process_object] ( identifier[self] , identifier[obj] ):
literal[string]
identifier[document] = identifier[self] . identifier[document_class] ( identifier[meta] ={ literal[string] : identifier[self] . identifier[generate_id] ( identifier[obj] )})
keyword[for] ident... | def process_object(self, obj):
"""Process current object and push it to the ElasticSearch."""
document = self.document_class(meta={'id': self.generate_id(obj)})
for field in document._doc_type.mapping: # pylint: disable=protected-access
if field in ['users_with_permissions', 'groups_with_permission... |
def post(self, request, format=None):
"""
Add a new bot
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
serializer = BotSerializer... | def function[post, parameter[self, request, format]]:
constant[
Add a new bot
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
]
variab... | keyword[def] identifier[post] ( identifier[self] , identifier[request] , identifier[format] = keyword[None] ):
literal[string]
identifier[serializer] = identifier[BotSerializer] ( identifier[data] = identifier[request] . identifier[data] )
keyword[if] identifier[serializer] . identifier[i... | def post(self, request, format=None):
"""
Add a new bot
---
serializer: BotSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
serializer = BotSerializer(data=re... |
def _ParseDateTimeValue(self, byte_stream, file_offset):
"""Parses a CUPS IPP RFC2579 date-time value from a byte stream.
Args:
byte_stream (bytes): byte stream.
file_offset (int): offset of the attribute data relative to the start of
the file-like object.
Returns:
dfdatetime.R... | def function[_ParseDateTimeValue, parameter[self, byte_stream, file_offset]]:
constant[Parses a CUPS IPP RFC2579 date-time value from a byte stream.
Args:
byte_stream (bytes): byte stream.
file_offset (int): offset of the attribute data relative to the start of
the file-like object.
... | keyword[def] identifier[_ParseDateTimeValue] ( identifier[self] , identifier[byte_stream] , identifier[file_offset] ):
literal[string]
identifier[datetime_value_map] = identifier[self] . identifier[_GetDataTypeMap] ( literal[string] )
keyword[try] :
identifier[value] = identifier[self] . ident... | def _ParseDateTimeValue(self, byte_stream, file_offset):
"""Parses a CUPS IPP RFC2579 date-time value from a byte stream.
Args:
byte_stream (bytes): byte stream.
file_offset (int): offset of the attribute data relative to the start of
the file-like object.
Returns:
dfdatetime.R... |
def delete_namespaced_event(self, name, namespace, **kwargs): # noqa: E501
"""delete_namespaced_event # noqa: E501
delete an Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread... | def function[delete_namespaced_event, parameter[self, name, namespace]]:
constant[delete_namespaced_event # noqa: E501
delete an Event # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thr... | keyword[def] identifier[delete_namespaced_event] ( identifier[self] , identifier[name] , identifier[namespace] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] ):
... | def delete_namespaced_event(self, name, namespace, **kwargs): # noqa: E501
'delete_namespaced_event # noqa: E501\n\n delete an Event # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n asynchronous HTTP request, please pass async_req=True\n >>> thread ... |
def _login_azure_app_token(client_id=None, client_secret=None, tenant_id=None):
"""
Authenticate APP using token credentials:
https://docs.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python
:return: ~ServicePrincipalCredentials credentials
"""
... | def function[_login_azure_app_token, parameter[client_id, client_secret, tenant_id]]:
constant[
Authenticate APP using token credentials:
https://docs.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python
:return: ~ServicePrincipalCredentials credentials
... | keyword[def] identifier[_login_azure_app_token] ( identifier[client_id] = keyword[None] , identifier[client_secret] = keyword[None] , identifier[tenant_id] = keyword[None] ):
literal[string]
identifier[client_id] = identifier[os] . identifier[getenv] ( literal[string] ) keyword[if] keyword[not] i... | def _login_azure_app_token(client_id=None, client_secret=None, tenant_id=None):
"""
Authenticate APP using token credentials:
https://docs.microsoft.com/en-us/python/azure/python-sdk-azure-authenticate?view=azure-python
:return: ~ServicePrincipalCredentials credentials
"""
client... |
def _my_eps_formatter(logodata, format, ordered_alphabets) :
""" Generate a logo in Encapsulated Postscript (EPS)
Modified from weblogo version 3.4 source code.
*ordered_alphabets* is a dictionary keyed by zero-indexed
consecutive sites, with values giving order of characters
from bottom to t... | def function[_my_eps_formatter, parameter[logodata, format, ordered_alphabets]]:
constant[ Generate a logo in Encapsulated Postscript (EPS)
Modified from weblogo version 3.4 source code.
*ordered_alphabets* is a dictionary keyed by zero-indexed
consecutive sites, with values giving order of c... | keyword[def] identifier[_my_eps_formatter] ( identifier[logodata] , identifier[format] , identifier[ordered_alphabets] ):
literal[string]
identifier[substitutions] ={}
identifier[from_format] =[
literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] , literal... | def _my_eps_formatter(logodata, format, ordered_alphabets):
""" Generate a logo in Encapsulated Postscript (EPS)
Modified from weblogo version 3.4 source code.
*ordered_alphabets* is a dictionary keyed by zero-indexed
consecutive sites, with values giving order of characters
from bottom to to... |
def wait_any(futures, timeout=None):
'''Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One o... | def function[wait_any, parameter[futures, timeout]]:
constant[Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
... | keyword[def] identifier[wait_any] ( identifier[futures] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[for] identifier[fut] keyword[in] identifier[futures] :
keyword[if] identifier[fut] . identifier[complete] :
keyword[return] identifier[fut]
identifier[w... | def wait_any(futures, timeout=None):
"""Wait for the completion of any (the first) one of multiple futures
:param list futures: A list of :class:`Future`\\s
:param timeout:
The maximum time to wait. With ``None``, will block indefinitely.
:type timeout: float or None
:returns:
One ... |
def v_unique_name_leaf_list(ctx, stmt):
"""Make sure config true leaf-lists do nothave duplicate defaults"""
if not stmt.i_config:
return
seen = []
for defval in stmt.i_default:
if defval in seen:
err_add(ctx.errors, stmt.pos, 'DUPLICATE_DEFAULT', (defval))
else:
... | def function[v_unique_name_leaf_list, parameter[ctx, stmt]]:
constant[Make sure config true leaf-lists do nothave duplicate defaults]
if <ast.UnaryOp object at 0x7da204567880> begin[:]
return[None]
variable[seen] assign[=] list[[]]
for taget[name[defval]] in starred[name[stmt].i_... | keyword[def] identifier[v_unique_name_leaf_list] ( identifier[ctx] , identifier[stmt] ):
literal[string]
keyword[if] keyword[not] identifier[stmt] . identifier[i_config] :
keyword[return]
identifier[seen] =[]
keyword[for] identifier[defval] keyword[in] identifier[stmt] . identifie... | def v_unique_name_leaf_list(ctx, stmt):
"""Make sure config true leaf-lists do nothave duplicate defaults"""
if not stmt.i_config:
return # depends on [control=['if'], data=[]]
seen = []
for defval in stmt.i_default:
if defval in seen:
err_add(ctx.errors, stmt.pos, 'DUPLICAT... |
def from_json(cls, data):
"""Creat datetime from a dictionary.
Args:
data: {
'month': A value for month between 1-12. (Defualt: 1)
'day': A value for day between 1-31. (Defualt: 1)
'hour': A value for hour between 0-23. (Defualt: 0)
... | def function[from_json, parameter[cls, data]]:
constant[Creat datetime from a dictionary.
Args:
data: {
'month': A value for month between 1-12. (Defualt: 1)
'day': A value for day between 1-31. (Defualt: 1)
'hour': A value for hour between 0-... | keyword[def] identifier[from_json] ( identifier[cls] , identifier[data] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[data] :
identifier[data] [ literal[string] ]= literal[int]
keyword[if] literal[string] keyword[not] keyword[in] ... | def from_json(cls, data):
"""Creat datetime from a dictionary.
Args:
data: {
'month': A value for month between 1-12. (Defualt: 1)
'day': A value for day between 1-31. (Defualt: 1)
'hour': A value for hour between 0-23. (Defualt: 0)
... |
def normalize_r_value(self):
'''
Normalize r-value.
Override.
This method is called in each learning steps.
For example:
self.r_df = self.r_df.r_value / self.r_df.r_value.sum()
'''
if self.r_df is not None and self.r_df.shape[0]:
# z-sco... | def function[normalize_r_value, parameter[self]]:
constant[
Normalize r-value.
Override.
This method is called in each learning steps.
For example:
self.r_df = self.r_df.r_value / self.r_df.r_value.sum()
]
if <ast.BoolOp object at 0x7da204960a30> be... | keyword[def] identifier[normalize_r_value] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[r_df] keyword[is] keyword[not] keyword[None] keyword[and] identifier[self] . identifier[r_df] . identifier[shape] [ literal[int] ]:
identifier[self]... | def normalize_r_value(self):
"""
Normalize r-value.
Override.
This method is called in each learning steps.
For example:
self.r_df = self.r_df.r_value / self.r_df.r_value.sum()
"""
if self.r_df is not None and self.r_df.shape[0]:
# z-score normaliza... |
def _try_get_current_manager(cls):
""" Try to detect a package manager used in a current Gentoo system. """
if utils.get_distro_name().find('gentoo') == -1:
return None
if 'PACKAGE_MANAGER' in os.environ:
pm = os.environ['PACKAGE_MANAGER']
if pm == 'paludis':
... | def function[_try_get_current_manager, parameter[cls]]:
constant[ Try to detect a package manager used in a current Gentoo system. ]
if compare[call[call[name[utils].get_distro_name, parameter[]].find, parameter[constant[gentoo]]] equal[==] <ast.UnaryOp object at 0x7da1b10c5a50>] begin[:]
return... | keyword[def] identifier[_try_get_current_manager] ( identifier[cls] ):
literal[string]
keyword[if] identifier[utils] . identifier[get_distro_name] (). identifier[find] ( literal[string] )==- literal[int] :
keyword[return] keyword[None]
keyword[if] literal[string] keyword[... | def _try_get_current_manager(cls):
""" Try to detect a package manager used in a current Gentoo system. """
if utils.get_distro_name().find('gentoo') == -1:
return None # depends on [control=['if'], data=[]]
if 'PACKAGE_MANAGER' in os.environ:
pm = os.environ['PACKAGE_MANAGER']
if p... |
def call(self, params, _context, **kwargs):
'''Note that we're returning a Promise object here, and bypassing the
helper functionality that normally sets the results struct from the
returned object. Instead, we set _context.results directly inside of
another promise'''
assert le... | def function[call, parameter[self, params, _context]]:
constant[Note that we're returning a Promise object here, and bypassing the
helper functionality that normally sets the results struct from the
returned object. Instead, we set _context.results directly inside of
another promise]
... | keyword[def] identifier[call] ( identifier[self] , identifier[params] , identifier[_context] ,** identifier[kwargs] ):
literal[string]
keyword[assert] identifier[len] ( identifier[params] )== identifier[self] . identifier[paramCount]
keyword[return] identifier[evaluate_impl] (... | def call(self, params, _context, **kwargs):
"""Note that we're returning a Promise object here, and bypassing the
helper functionality that normally sets the results struct from the
returned object. Instead, we set _context.results directly inside of
another promise"""
assert len(params)... |
def _cancelScheduledRestart(self, justification=None) -> None:
"""
Cancels scheduled restart
:param when: time restart was scheduled to
:param version: version restart scheduled for
"""
if self.scheduledAction:
why_prefix = ": "
why = justificati... | def function[_cancelScheduledRestart, parameter[self, justification]]:
constant[
Cancels scheduled restart
:param when: time restart was scheduled to
:param version: version restart scheduled for
]
if name[self].scheduledAction begin[:]
variable[why_prefi... | keyword[def] identifier[_cancelScheduledRestart] ( identifier[self] , identifier[justification] = keyword[None] )-> keyword[None] :
literal[string]
keyword[if] identifier[self] . identifier[scheduledAction] :
identifier[why_prefix] = literal[string]
identifier[why] = id... | def _cancelScheduledRestart(self, justification=None) -> None:
"""
Cancels scheduled restart
:param when: time restart was scheduled to
:param version: version restart scheduled for
"""
if self.scheduledAction:
why_prefix = ': '
why = justification
if jus... |
def do_usufy(self, query, **kwargs):
"""
Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be app... | def function[do_usufy, parameter[self, query]]:
constant[
Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of e... | keyword[def] identifier[do_usufy] ( identifier[self] , identifier[query] ,** identifier[kwargs] ):
literal[string]
identifier[results] =[]
identifier[test] = identifier[self] . identifier[check_usufy] ( identifier[query] ,** identifier[kwargs] )
keyword[if] identifier[test] :
... | def do_usufy(self, query, **kwargs):
"""
Verifying a usufy query in this platform.
This might be redefined in any class inheriting from Platform.
Args:
-----
query: The element to be searched.
Return:
-------
A list of elements to be appende... |
def split_channels(image):
"""
Split channels of a multi-channel ANTsImage into a collection
of scalar ANTsImage types
Arguments
---------
image : ANTsImage
multi-channel image to split
Returns
-------
list of ANTsImage types
Example
-------
>>> import ants... | def function[split_channels, parameter[image]]:
constant[
Split channels of a multi-channel ANTsImage into a collection
of scalar ANTsImage types
Arguments
---------
image : ANTsImage
multi-channel image to split
Returns
-------
list of ANTsImage types
Example
... | keyword[def] identifier[split_channels] ( identifier[image] ):
literal[string]
identifier[inpixeltype] = identifier[image] . identifier[pixeltype]
identifier[dimension] = identifier[image] . identifier[dimension]
identifier[components] = literal[int]
identifier[libfn] = identifier[utils]... | def split_channels(image):
"""
Split channels of a multi-channel ANTsImage into a collection
of scalar ANTsImage types
Arguments
---------
image : ANTsImage
multi-channel image to split
Returns
-------
list of ANTsImage types
Example
-------
>>> import ants... |
def _get_indices(self, data):
""" Compute indices along temporal dimension corresponding to the sought percentile
:param data: Input 3D array holding the reference band
:type data: numpy array
:return: 2D array holding the temporal index corresponding to percentile
"... | def function[_get_indices, parameter[self, data]]:
constant[ Compute indices along temporal dimension corresponding to the sought percentile
:param data: Input 3D array holding the reference band
:type data: numpy array
:return: 2D array holding the temporal index correspond... | keyword[def] identifier[_get_indices] ( identifier[self] , identifier[data] ):
literal[string]
identifier[indices] = identifier[self] . identifier[_index_by_percentile] ( identifier[data] , identifier[self] . identifier[percentile] )
keyword[return] identifier[indices] | def _get_indices(self, data):
""" Compute indices along temporal dimension corresponding to the sought percentile
:param data: Input 3D array holding the reference band
:type data: numpy array
:return: 2D array holding the temporal index corresponding to percentile
"""
... |
def takeoff(self):
'''
Sends the takeoff command.
'''
self.send(at.REF(at.REF.input.start)) | def function[takeoff, parameter[self]]:
constant[
Sends the takeoff command.
]
call[name[self].send, parameter[call[name[at].REF, parameter[name[at].REF.input.start]]]] | keyword[def] identifier[takeoff] ( identifier[self] ):
literal[string]
identifier[self] . identifier[send] ( identifier[at] . identifier[REF] ( identifier[at] . identifier[REF] . identifier[input] . identifier[start] )) | def takeoff(self):
"""
Sends the takeoff command.
"""
self.send(at.REF(at.REF.input.start)) |
def _not_reentrant(func):
"""Decorator that prevents callbacks from calling into methods that are
not reentrant
"""
def wrap(self, *args, **kws):
if self._callback_lock and self._callback_lock.in_callback:
m = "Connection %s cannot be invoked from a callback!"... | def function[_not_reentrant, parameter[func]]:
constant[Decorator that prevents callbacks from calling into methods that are
not reentrant
]
def function[wrap, parameter[self]]:
if <ast.BoolOp object at 0x7da1b013dc60> begin[:]
variable[m] assign[=... | keyword[def] identifier[_not_reentrant] ( identifier[func] ):
literal[string]
keyword[def] identifier[wrap] ( identifier[self] ,* identifier[args] ,** identifier[kws] ):
keyword[if] identifier[self] . identifier[_callback_lock] keyword[and] identifier[self] . identifier[_callback_l... | def _not_reentrant(func):
"""Decorator that prevents callbacks from calling into methods that are
not reentrant
"""
def wrap(self, *args, **kws):
if self._callback_lock and self._callback_lock.in_callback:
m = 'Connection %s cannot be invoked from a callback!' % func
... |
def ast_imports(file_path):
"""get list of import from python module
:return: (list - tuple) (module, name, asname, level)
"""
with open(file_path, 'r') as fp:
text = fp.read()
mod_ast = ast.parse(text, file_path)
finder = _ImportsFinder()
finder.visit(mod_ast)
return finder.impo... | def function[ast_imports, parameter[file_path]]:
constant[get list of import from python module
:return: (list - tuple) (module, name, asname, level)
]
with call[name[open], parameter[name[file_path], constant[r]]] begin[:]
variable[text] assign[=] call[name[fp].read, parameter[]... | keyword[def] identifier[ast_imports] ( identifier[file_path] ):
literal[string]
keyword[with] identifier[open] ( identifier[file_path] , literal[string] ) keyword[as] identifier[fp] :
identifier[text] = identifier[fp] . identifier[read] ()
identifier[mod_ast] = identifier[ast] . identifier[... | def ast_imports(file_path):
"""get list of import from python module
:return: (list - tuple) (module, name, asname, level)
"""
with open(file_path, 'r') as fp:
text = fp.read() # depends on [control=['with'], data=['fp']]
mod_ast = ast.parse(text, file_path)
finder = _ImportsFinder()
... |
def list_parameters(self, parameter_type=None, page_size=None):
"""Lists the parameters visible to this client.
Parameters are returned in lexicographical order.
:param str parameter_type: The type of parameter
:rtype: :class:`.Parameter` iterator
"""
params = {'details... | def function[list_parameters, parameter[self, parameter_type, page_size]]:
constant[Lists the parameters visible to this client.
Parameters are returned in lexicographical order.
:param str parameter_type: The type of parameter
:rtype: :class:`.Parameter` iterator
]
var... | keyword[def] identifier[list_parameters] ( identifier[self] , identifier[parameter_type] = keyword[None] , identifier[page_size] = keyword[None] ):
literal[string]
identifier[params] ={ literal[string] : keyword[True] }
keyword[if] identifier[parameter_type] keyword[is] keyword[not] k... | def list_parameters(self, parameter_type=None, page_size=None):
"""Lists the parameters visible to this client.
Parameters are returned in lexicographical order.
:param str parameter_type: The type of parameter
:rtype: :class:`.Parameter` iterator
"""
params = {'details': True}... |
def _send_string_selection(self, string: str):
"""Use the mouse selection clipboard to send a string."""
backup = self.clipboard.selection # Keep a backup of current content, to restore the original afterwards.
if backup is None:
logger.warning("Tried to backup the X PRIMARY selecti... | def function[_send_string_selection, parameter[self, string]]:
constant[Use the mouse selection clipboard to send a string.]
variable[backup] assign[=] name[self].clipboard.selection
if compare[name[backup] is constant[None]] begin[:]
call[name[logger].warning, parameter[constant... | keyword[def] identifier[_send_string_selection] ( identifier[self] , identifier[string] : identifier[str] ):
literal[string]
identifier[backup] = identifier[self] . identifier[clipboard] . identifier[selection]
keyword[if] identifier[backup] keyword[is] keyword[None] :
ide... | def _send_string_selection(self, string: str):
"""Use the mouse selection clipboard to send a string."""
backup = self.clipboard.selection # Keep a backup of current content, to restore the original afterwards.
if backup is None:
logger.warning('Tried to backup the X PRIMARY selection content, but ... |
def _empty_resource_attributes(self):
'''
small method to empty values if resource is removed or absent
Args:
None
Return:
None: empties selected resource attributes
'''
self.status_code = 404
self.headers = {}
self.exists = False
# build RDF
self.rdf = self._build_rdf()
# if NonRDF, e... | def function[_empty_resource_attributes, parameter[self]]:
constant[
small method to empty values if resource is removed or absent
Args:
None
Return:
None: empties selected resource attributes
]
name[self].status_code assign[=] constant[404]
name[self].headers assign[=] dictionar... | keyword[def] identifier[_empty_resource_attributes] ( identifier[self] ):
literal[string]
identifier[self] . identifier[status_code] = literal[int]
identifier[self] . identifier[headers] ={}
identifier[self] . identifier[exists] = keyword[False]
identifier[self] . identifier[rdf] = identifier[... | def _empty_resource_attributes(self):
"""
small method to empty values if resource is removed or absent
Args:
None
Return:
None: empties selected resource attributes
"""
self.status_code = 404
self.headers = {}
self.exists = False # build RDF
self.rdf = self._build_rdf() # if NonRD... |
def _expand_dataset_packages(dataset_label_dict):
"""Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'.
In case the param is not pointing to multidataset returns only that label in a list.
:param str dataset_label_dict: label of multi dataset
:ret... | def function[_expand_dataset_packages, parameter[dataset_label_dict]]:
constant[Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'.
In case the param is not pointing to multidataset returns only that label in a list.
:param str dataset_label_dict: ... | keyword[def] identifier[_expand_dataset_packages] ( identifier[dataset_label_dict] ):
literal[string]
identifier[new_dataset_label_dict] =[]
keyword[for] identifier[label] keyword[in] identifier[dataset_label_dict] :
identifier[dataset_metadata] = identifier[data_urls] [ identifier[label] ... | def _expand_dataset_packages(dataset_label_dict):
"""Returns list of possible packages contained in dataset, in case the dataset is multi dataset, eg. 'lisa'.
In case the param is not pointing to multidataset returns only that label in a list.
:param str dataset_label_dict: label of multi dataset
:ret... |
def astext(data):
"""
Given a unicode/str/bytes always return str.
We prefer to work with the 'native' string type for the version of python
we run on, and this gets us that.
"""
if isinstance(data, str):
return data
elif isinstance(data, text_type):
return data.encode("utf-... | def function[astext, parameter[data]]:
constant[
Given a unicode/str/bytes always return str.
We prefer to work with the 'native' string type for the version of python
we run on, and this gets us that.
]
if call[name[isinstance], parameter[name[data], name[str]]] begin[:]
return... | keyword[def] identifier[astext] ( identifier[data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[str] ):
keyword[return] identifier[data]
keyword[elif] identifier[isinstance] ( identifier[data] , identifier[text_type] ):
keyword[return] id... | def astext(data):
"""
Given a unicode/str/bytes always return str.
We prefer to work with the 'native' string type for the version of python
we run on, and this gets us that.
"""
if isinstance(data, str):
return data # depends on [control=['if'], data=[]]
elif isinstance(data, text... |
def find_application(app_id=None, app_name=None):
"""
find the application according application id (prioritary) or application name
:param app_id: the application id
:param app_name: the application name
:return: found application or None if not found
"""
LOGGER.... | def function[find_application, parameter[app_id, app_name]]:
constant[
find the application according application id (prioritary) or application name
:param app_id: the application id
:param app_name: the application name
:return: found application or None if not found
]
... | keyword[def] identifier[find_application] ( identifier[app_id] = keyword[None] , identifier[app_name] = keyword[None] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
keyword[if] ( identifier[app_id] keyword[is] keyword[None] keyword[or] keyword[not] ident... | def find_application(app_id=None, app_name=None):
"""
find the application according application id (prioritary) or application name
:param app_id: the application id
:param app_name: the application name
:return: found application or None if not found
"""
LOGGER.debug('A... |
def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, ... | def function[narrow_to, parameter[self, featuremap]]:
constant[
Slice anchors to the spatial size of this featuremap.
]
variable[shape2d] assign[=] call[call[name[tf].shape, parameter[name[featuremap]]]][<ast.Slice object at 0x7da18f720040>]
variable[slice3d] assign[=] call[name[... | keyword[def] identifier[narrow_to] ( identifier[self] , identifier[featuremap] ):
literal[string]
identifier[shape2d] = identifier[tf] . identifier[shape] ( identifier[featuremap] )[ literal[int] :]
identifier[slice3d] = identifier[tf] . identifier[concat] ([ identifier[shape2d] ,[- litera... | def narrow_to(self, featuremap):
"""
Slice anchors to the spatial size of this featuremap.
"""
shape2d = tf.shape(featuremap)[2:] # h,w
slice3d = tf.concat([shape2d, [-1]], axis=0)
slice4d = tf.concat([shape2d, [-1, -1]], axis=0)
boxes = tf.slice(self.boxes, [0, 0, 0, 0], slice4d)
... |
def get(self, sid):
"""
Constructs a ExecutionContext
:param sid: Execution Sid.
:returns: twilio.rest.studio.v1.flow.execution.ExecutionContext
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext
"""
return ExecutionContext(self._version, flow_sid=sel... | def function[get, parameter[self, sid]]:
constant[
Constructs a ExecutionContext
:param sid: Execution Sid.
:returns: twilio.rest.studio.v1.flow.execution.ExecutionContext
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext
]
return[call[name[ExecutionCont... | keyword[def] identifier[get] ( identifier[self] , identifier[sid] ):
literal[string]
keyword[return] identifier[ExecutionContext] ( identifier[self] . identifier[_version] , identifier[flow_sid] = identifier[self] . identifier[_solution] [ literal[string] ], identifier[sid] = identifier[sid] ,) | def get(self, sid):
"""
Constructs a ExecutionContext
:param sid: Execution Sid.
:returns: twilio.rest.studio.v1.flow.execution.ExecutionContext
:rtype: twilio.rest.studio.v1.flow.execution.ExecutionContext
"""
return ExecutionContext(self._version, flow_sid=self._solut... |
def binaryEntropyVectorized(x):
"""
Calculate entropy for a list of binary random variables
:param x: (numpy array) the probability of the variable to be 1.
:return: entropy: (numpy array) entropy
"""
entropy = - x*np.log2(x) - (1-x)*np.log2(1-x)
entropy[x*(1 - x) == 0] = 0
return entropy | def function[binaryEntropyVectorized, parameter[x]]:
constant[
Calculate entropy for a list of binary random variables
:param x: (numpy array) the probability of the variable to be 1.
:return: entropy: (numpy array) entropy
]
variable[entropy] assign[=] binary_operation[binary_operation[<ast.Una... | keyword[def] identifier[binaryEntropyVectorized] ( identifier[x] ):
literal[string]
identifier[entropy] =- identifier[x] * identifier[np] . identifier[log2] ( identifier[x] )-( literal[int] - identifier[x] )* identifier[np] . identifier[log2] ( literal[int] - identifier[x] )
identifier[entropy] [ identifier... | def binaryEntropyVectorized(x):
"""
Calculate entropy for a list of binary random variables
:param x: (numpy array) the probability of the variable to be 1.
:return: entropy: (numpy array) entropy
"""
entropy = -x * np.log2(x) - (1 - x) * np.log2(1 - x)
entropy[x * (1 - x) == 0] = 0
return entro... |
def _set_group(self, v, load=False):
"""
Setter method for group, mapped from YANG variable /qos/cpu/slot/port_group/group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_group is considered as a private
method. Backends looking to populate this variable shoul... | def function[_set_group, parameter[self, v, load]]:
constant[
Setter method for group, mapped from YANG variable /qos/cpu/slot/port_group/group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_group is considered as a private
method. Backends looking to pop... | keyword[def] identifier[_set_group] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
identifi... | def _set_group(self, v, load=False):
"""
Setter method for group, mapped from YANG variable /qos/cpu/slot/port_group/group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_group is considered as a private
method. Backends looking to populate this variable shoul... |
def iso_payment_reference_validator(v: str):
"""
Validates ISO reference number checksum.
:param v: Reference number
"""
num = ''
v = STRIP_WHITESPACE.sub('', v)
for ch in v[4:] + v[0:4]:
x = ord(ch)
if ord('0') <= x <= ord('9'):
num += ch
else:
... | def function[iso_payment_reference_validator, parameter[v]]:
constant[
Validates ISO reference number checksum.
:param v: Reference number
]
variable[num] assign[=] constant[]
variable[v] assign[=] call[name[STRIP_WHITESPACE].sub, parameter[constant[], name[v]]]
for taget[nam... | keyword[def] identifier[iso_payment_reference_validator] ( identifier[v] : identifier[str] ):
literal[string]
identifier[num] = literal[string]
identifier[v] = identifier[STRIP_WHITESPACE] . identifier[sub] ( literal[string] , identifier[v] )
keyword[for] identifier[ch] keyword[in] identifier... | def iso_payment_reference_validator(v: str):
"""
Validates ISO reference number checksum.
:param v: Reference number
"""
num = ''
v = STRIP_WHITESPACE.sub('', v)
for ch in v[4:] + v[0:4]:
x = ord(ch)
if ord('0') <= x <= ord('9'):
num += ch # depends on [control=[... |
def RandomUniform(shape, dtype, seed):
"""
Random uniform op.
"""
if seed:
np.random.seed(seed)
return np.random.uniform(size=shape).astype(dtype_map[dtype]), | def function[RandomUniform, parameter[shape, dtype, seed]]:
constant[
Random uniform op.
]
if name[seed] begin[:]
call[name[np].random.seed, parameter[name[seed]]]
return[tuple[[<ast.Call object at 0x7da1b05bef80>]]] | keyword[def] identifier[RandomUniform] ( identifier[shape] , identifier[dtype] , identifier[seed] ):
literal[string]
keyword[if] identifier[seed] :
identifier[np] . identifier[random] . identifier[seed] ( identifier[seed] )
keyword[return] identifier[np] . identifier[random] . identifier[un... | def RandomUniform(shape, dtype, seed):
"""
Random uniform op.
"""
if seed:
np.random.seed(seed) # depends on [control=['if'], data=[]]
return (np.random.uniform(size=shape).astype(dtype_map[dtype]),) |
def generate(self):
"""
:return: A new token
:rtype: str
"""
random_data = os.urandom(100)
hash_gen = hashlib.new("sha512")
hash_gen.update(random_data)
return hash_gen.hexdigest()[:self.token_length] | def function[generate, parameter[self]]:
constant[
:return: A new token
:rtype: str
]
variable[random_data] assign[=] call[name[os].urandom, parameter[constant[100]]]
variable[hash_gen] assign[=] call[name[hashlib].new, parameter[constant[sha512]]]
call[name[hash_... | keyword[def] identifier[generate] ( identifier[self] ):
literal[string]
identifier[random_data] = identifier[os] . identifier[urandom] ( literal[int] )
identifier[hash_gen] = identifier[hashlib] . identifier[new] ( literal[string] )
identifier[hash_gen] . identifier[update] ( ide... | def generate(self):
"""
:return: A new token
:rtype: str
"""
random_data = os.urandom(100)
hash_gen = hashlib.new('sha512')
hash_gen.update(random_data)
return hash_gen.hexdigest()[:self.token_length] |
def count(self, X):
"""
Called from the fit method, this method gets all the
words from the corpus and their corresponding frequency
counts.
Parameters
----------
X : ndarray or masked ndarray
Pass in the matrix of vectorized documents, can be masked... | def function[count, parameter[self, X]]:
constant[
Called from the fit method, this method gets all the
words from the corpus and their corresponding frequency
counts.
Parameters
----------
X : ndarray or masked ndarray
Pass in the matrix of vectoriz... | keyword[def] identifier[count] ( identifier[self] , identifier[X] ):
literal[string]
keyword[return] identifier[np] . identifier[squeeze] ( identifier[np] . identifier[asarray] ( identifier[X] . identifier[sum] ( identifier[axis] = literal[int] ))) | def count(self, X):
"""
Called from the fit method, this method gets all the
words from the corpus and their corresponding frequency
counts.
Parameters
----------
X : ndarray or masked ndarray
Pass in the matrix of vectorized documents, can be masked in
... |
async def upload_image(self, image_file, filename=None, *,
return_uploaded_image=False):
"""Upload an image that can be later attached to a chat message.
Args:
image_file: A file-like object containing an image.
filename (str): (optional) Custom name f... | <ast.AsyncFunctionDef object at 0x7da2047e9d20> | keyword[async] keyword[def] identifier[upload_image] ( identifier[self] , identifier[image_file] , identifier[filename] = keyword[None] ,*,
identifier[return_uploaded_image] = keyword[False] ):
literal[string]
identifier[image_filename] = identifier[filename] keyword[or] identifier[os] . identi... | async def upload_image(self, image_file, filename=None, *, return_uploaded_image=False):
"""Upload an image that can be later attached to a chat message.
Args:
image_file: A file-like object containing an image.
filename (str): (optional) Custom name for the uploaded file.
... |
def _readuntil(f, end=_TYPE_END):
"""Helper function to read bytes until a certain end byte is hit"""
buf = bytearray()
byte = f.read(1)
while byte != end:
if byte == b'':
raise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end))
buf += byte
byte = f.read(1)
return buf | def function[_readuntil, parameter[f, end]]:
constant[Helper function to read bytes until a certain end byte is hit]
variable[buf] assign[=] call[name[bytearray], parameter[]]
variable[byte] assign[=] call[name[f].read, parameter[constant[1]]]
while compare[name[byte] not_equal[!=] name[... | keyword[def] identifier[_readuntil] ( identifier[f] , identifier[end] = identifier[_TYPE_END] ):
literal[string]
identifier[buf] = identifier[bytearray] ()
identifier[byte] = identifier[f] . identifier[read] ( literal[int] )
keyword[while] identifier[byte] != identifier[end] :
keyword[if] identifier[byt... | def _readuntil(f, end=_TYPE_END):
"""Helper function to read bytes until a certain end byte is hit"""
buf = bytearray()
byte = f.read(1)
while byte != end:
if byte == b'':
raise ValueError('File ended unexpectedly. Expected end byte {}.'.format(end)) # depends on [control=['if'], da... |
def disable_for_loaddata(signal_handler):
"""
Decorator for disabling signals sent by 'post_save'
on loaddata command.
http://code.djangoproject.com/ticket/8399
"""
@wraps(signal_handler)
def wrapper(*args, **kwargs):
for fr in inspect.stack():
if inspect.getmodulename(fr... | def function[disable_for_loaddata, parameter[signal_handler]]:
constant[
Decorator for disabling signals sent by 'post_save'
on loaddata command.
http://code.djangoproject.com/ticket/8399
]
def function[wrapper, parameter[]]:
for taget[name[fr]] in starred[call[name[inspe... | keyword[def] identifier[disable_for_loaddata] ( identifier[signal_handler] ):
literal[string]
@ identifier[wraps] ( identifier[signal_handler] )
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
keyword[for] identifier[fr] keyword[in] identifier[inspect] . iden... | def disable_for_loaddata(signal_handler):
"""
Decorator for disabling signals sent by 'post_save'
on loaddata command.
http://code.djangoproject.com/ticket/8399
"""
@wraps(signal_handler)
def wrapper(*args, **kwargs):
for fr in inspect.stack():
if inspect.getmodulename(f... |
def check_uniqueness_constraint(m, kind=None):
'''
Check the model for uniqueness constraint violations.
'''
if kind is None:
metaclasses = m.metaclasses.values()
else:
metaclasses = [m.find_metaclass(kind)]
res = 0
for metaclass in metaclasses:
id_map = dict()
... | def function[check_uniqueness_constraint, parameter[m, kind]]:
constant[
Check the model for uniqueness constraint violations.
]
if compare[name[kind] is constant[None]] begin[:]
variable[metaclasses] assign[=] call[name[m].metaclasses.values, parameter[]]
variable[res] a... | keyword[def] identifier[check_uniqueness_constraint] ( identifier[m] , identifier[kind] = keyword[None] ):
literal[string]
keyword[if] identifier[kind] keyword[is] keyword[None] :
identifier[metaclasses] = identifier[m] . identifier[metaclasses] . identifier[values] ()
keyword[else] :
... | def check_uniqueness_constraint(m, kind=None):
"""
Check the model for uniqueness constraint violations.
"""
if kind is None:
metaclasses = m.metaclasses.values() # depends on [control=['if'], data=[]]
else:
metaclasses = [m.find_metaclass(kind)]
res = 0
for metaclass in met... |
def acquire(self, timeout=10):
"""Acquire the lock.
:params timeout: Maximum time to wait before returning. `None` means
forever, any other value equal or greater than 0 is
the number of seconds.
:returns: True if the lock has been acquired, Fal... | def function[acquire, parameter[self, timeout]]:
constant[Acquire the lock.
:params timeout: Maximum time to wait before returning. `None` means
forever, any other value equal or greater than 0 is
the number of seconds.
:returns: True if the loc... | keyword[def] identifier[acquire] ( identifier[self] , identifier[timeout] = literal[int] ):
literal[string]
identifier[stop] =(
identifier[tenacity] . identifier[stop_never]
keyword[if] identifier[timeout] keyword[is] keyword[None] keyword[else] identifier[tenacity] . identi... | def acquire(self, timeout=10):
"""Acquire the lock.
:params timeout: Maximum time to wait before returning. `None` means
forever, any other value equal or greater than 0 is
the number of seconds.
:returns: True if the lock has been acquired, False o... |
def partitioned_repertoire(self, direction, partition):
"""Compute the repertoire over the partition in the given direction."""
system = self.system[direction]
return system.partitioned_repertoire(direction, partition) | def function[partitioned_repertoire, parameter[self, direction, partition]]:
constant[Compute the repertoire over the partition in the given direction.]
variable[system] assign[=] call[name[self].system][name[direction]]
return[call[name[system].partitioned_repertoire, parameter[name[direction], nam... | keyword[def] identifier[partitioned_repertoire] ( identifier[self] , identifier[direction] , identifier[partition] ):
literal[string]
identifier[system] = identifier[self] . identifier[system] [ identifier[direction] ]
keyword[return] identifier[system] . identifier[partitioned_repertoire... | def partitioned_repertoire(self, direction, partition):
"""Compute the repertoire over the partition in the given direction."""
system = self.system[direction]
return system.partitioned_repertoire(direction, partition) |
def _build_list_params(param_name, key, values):
"""Builds a list of POST parameters from a list or single value."""
params = {}
if hasattr(values, '__iter__'):
index = 0
for value in values:
params[str(param_name) + '[' + str(index) + '].' + str(key)] = s... | def function[_build_list_params, parameter[param_name, key, values]]:
constant[Builds a list of POST parameters from a list or single value.]
variable[params] assign[=] dictionary[[], []]
if call[name[hasattr], parameter[name[values], constant[__iter__]]] begin[:]
variable[index]... | keyword[def] identifier[_build_list_params] ( identifier[param_name] , identifier[key] , identifier[values] ):
literal[string]
identifier[params] ={}
keyword[if] identifier[hasattr] ( identifier[values] , literal[string] ):
identifier[index] = literal[int]
keywo... | def _build_list_params(param_name, key, values):
"""Builds a list of POST parameters from a list or single value."""
params = {}
if hasattr(values, '__iter__'):
index = 0
for value in values:
params[str(param_name) + '[' + str(index) + '].' + str(key)] = str(value)
in... |
def setDecel(self, vehID, decel):
"""setDecel(string, double) -> None
Sets the preferred maximal deceleration in m/s^2 for this vehicle.
"""
self._connection._sendDoubleCmd(
tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_DECEL, vehID, decel) | def function[setDecel, parameter[self, vehID, decel]]:
constant[setDecel(string, double) -> None
Sets the preferred maximal deceleration in m/s^2 for this vehicle.
]
call[name[self]._connection._sendDoubleCmd, parameter[name[tc].CMD_SET_VEHICLE_VARIABLE, name[tc].VAR_DECEL, name[vehID],... | keyword[def] identifier[setDecel] ( identifier[self] , identifier[vehID] , identifier[decel] ):
literal[string]
identifier[self] . identifier[_connection] . identifier[_sendDoubleCmd] (
identifier[tc] . identifier[CMD_SET_VEHICLE_VARIABLE] , identifier[tc] . identifier[VAR_DECEL] , identif... | def setDecel(self, vehID, decel):
"""setDecel(string, double) -> None
Sets the preferred maximal deceleration in m/s^2 for this vehicle.
"""
self._connection._sendDoubleCmd(tc.CMD_SET_VEHICLE_VARIABLE, tc.VAR_DECEL, vehID, decel) |
def post_event_discount(
self, event_id,
discount_code,
discount_amount_off=None,
discount_percent_off=None,
discount_ticket_ids=None,
discount_quantity_available=None,
discount_start_date=None,
discount_end_date=None):
... | def function[post_event_discount, parameter[self, event_id, discount_code, discount_amount_off, discount_percent_off, discount_ticket_ids, discount_quantity_available, discount_start_date, discount_end_date]]:
constant[
POST /events/:id/discounts/
discount_code string requir... | keyword[def] identifier[post_event_discount] (
identifier[self] , identifier[event_id] ,
identifier[discount_code] ,
identifier[discount_amount_off] = keyword[None] ,
identifier[discount_percent_off] = keyword[None] ,
identifier[discount_ticket_ids] = keyword[None] ,
identifier[discount_quantity_available] = ke... | def post_event_discount(self, event_id, discount_code, discount_amount_off=None, discount_percent_off=None, discount_ticket_ids=None, discount_quantity_available=None, discount_start_date=None, discount_end_date=None):
"""
POST /events/:id/discounts/
discount_code string require... |
def addEntry(self, key='', value=''):
"""
Creates a new entry item for this widget.
:param key | <str>
value | <variant>
"""
img = resources.find('img/close.png')
new_item = XTreeWidgetItem()
new_item.setText(1, nat... | def function[addEntry, parameter[self, key, value]]:
constant[
Creates a new entry item for this widget.
:param key | <str>
value | <variant>
]
variable[img] assign[=] call[name[resources].find, parameter[constant[img/close.png]]]
v... | keyword[def] identifier[addEntry] ( identifier[self] , identifier[key] = literal[string] , identifier[value] = literal[string] ):
literal[string]
identifier[img] = identifier[resources] . identifier[find] ( literal[string] )
identifier[new_item] = identifier[XTreeWidgetItem] ()
... | def addEntry(self, key='', value=''):
"""
Creates a new entry item for this widget.
:param key | <str>
value | <variant>
"""
img = resources.find('img/close.png')
new_item = XTreeWidgetItem()
new_item.setText(1, nativestring(key))
new_i... |
def network_security_group_absent(name, resource_group, connection_auth=None):
'''
.. versionadded:: 2019.2.0
Ensure a network security group does not exist in the resource group.
:param name:
Name of the network security group.
:param resource_group:
The resource group assigned t... | def function[network_security_group_absent, parameter[name, resource_group, connection_auth]]:
constant[
.. versionadded:: 2019.2.0
Ensure a network security group does not exist in the resource group.
:param name:
Name of the network security group.
:param resource_group:
The... | keyword[def] identifier[network_security_group_absent] ( identifier[name] , identifier[resource_group] , identifier[connection_auth] = keyword[None] ):
literal[string]
identifier[ret] ={
literal[string] : identifier[name] ,
literal[string] : keyword[False] ,
literal[string] : literal[string]... | def network_security_group_absent(name, resource_group, connection_auth=None):
"""
.. versionadded:: 2019.2.0
Ensure a network security group does not exist in the resource group.
:param name:
Name of the network security group.
:param resource_group:
The resource group assigned t... |
def handle_log_message(msg): # pylint: disable=useless-return
"""Process an internal log message."""
msg.gateway.can_log = True
_LOGGER.debug(
'n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type,
msg.sub_type, msg.payload)
return None | def function[handle_log_message, parameter[msg]]:
constant[Process an internal log message.]
name[msg].gateway.can_log assign[=] constant[True]
call[name[_LOGGER].debug, parameter[constant[n:%s c:%s t:%s s:%s p:%s], name[msg].node_id, name[msg].child_id, name[msg].type, name[msg].sub_type, name[... | keyword[def] identifier[handle_log_message] ( identifier[msg] ):
literal[string]
identifier[msg] . identifier[gateway] . identifier[can_log] = keyword[True]
identifier[_LOGGER] . identifier[debug] (
literal[string] , identifier[msg] . identifier[node_id] , identifier[msg] . identifier[child_id] ... | def handle_log_message(msg): # pylint: disable=useless-return
'Process an internal log message.'
msg.gateway.can_log = True
_LOGGER.debug('n:%s c:%s t:%s s:%s p:%s', msg.node_id, msg.child_id, msg.type, msg.sub_type, msg.payload)
return None |
def set_full_screen(self, keybind="<Escape>"):
"""Make this window full screen and bind the Escape key (or given key) to exit full screen mode"""
self.tk.attributes("-fullscreen", True)
self._full_screen = True
self.events.set_event("<FullScreen.Escape>", keybind, self.exit_full_screen) | def function[set_full_screen, parameter[self, keybind]]:
constant[Make this window full screen and bind the Escape key (or given key) to exit full screen mode]
call[name[self].tk.attributes, parameter[constant[-fullscreen], constant[True]]]
name[self]._full_screen assign[=] constant[True]
... | keyword[def] identifier[set_full_screen] ( identifier[self] , identifier[keybind] = literal[string] ):
literal[string]
identifier[self] . identifier[tk] . identifier[attributes] ( literal[string] , keyword[True] )
identifier[self] . identifier[_full_screen] = keyword[True]
identi... | def set_full_screen(self, keybind='<Escape>'):
"""Make this window full screen and bind the Escape key (or given key) to exit full screen mode"""
self.tk.attributes('-fullscreen', True)
self._full_screen = True
self.events.set_event('<FullScreen.Escape>', keybind, self.exit_full_screen) |
def are_symmetrically_related(self, point_a, point_b, tol=0.001):
"""
Checks if two points are symmetrically related.
Args:
point_a (3x1 array): First point.
point_b (3x1 array): Second point.
tol (float): Absolute tolerance for checking distance.
Re... | def function[are_symmetrically_related, parameter[self, point_a, point_b, tol]]:
constant[
Checks if two points are symmetrically related.
Args:
point_a (3x1 array): First point.
point_b (3x1 array): Second point.
tol (float): Absolute tolerance for checking ... | keyword[def] identifier[are_symmetrically_related] ( identifier[self] , identifier[point_a] , identifier[point_b] , identifier[tol] = literal[int] ):
literal[string]
keyword[if] identifier[np] . identifier[allclose] ( identifier[self] . identifier[operate] ( identifier[point_a] ), identifier[point... | def are_symmetrically_related(self, point_a, point_b, tol=0.001):
"""
Checks if two points are symmetrically related.
Args:
point_a (3x1 array): First point.
point_b (3x1 array): Second point.
tol (float): Absolute tolerance for checking distance.
Return... |
def setdefaults(d, d2):
"""
:type d: dict
:type d2: dict
:rtype: dict
"""
for k, v in d2.items():
d.setdefault(k, v)
return d | def function[setdefaults, parameter[d, d2]]:
constant[
:type d: dict
:type d2: dict
:rtype: dict
]
for taget[tuple[[<ast.Name object at 0x7da18f720520>, <ast.Name object at 0x7da18f720a30>]]] in starred[call[name[d2].items, parameter[]]] begin[:]
call[name[d].setdefault, ... | keyword[def] identifier[setdefaults] ( identifier[d] , identifier[d2] ):
literal[string]
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[d2] . identifier[items] ():
identifier[d] . identifier[setdefault] ( identifier[k] , identifier[v] )
keyword[return] identifier[d] | def setdefaults(d, d2):
"""
:type d: dict
:type d2: dict
:rtype: dict
"""
for (k, v) in d2.items():
d.setdefault(k, v) # depends on [control=['for'], data=[]]
return d |
def _render_batch(self,
non_fluents: NonFluents,
states: Fluents, actions: Fluents, interms: Fluents,
rewards: np.array,
horizon: Optional[int] = None) -> None:
'''Prints `non_fluents`, `states`, `actions`, `interms` and `rewards`
for given `horizon`.
... | def function[_render_batch, parameter[self, non_fluents, states, actions, interms, rewards, horizon]]:
constant[Prints `non_fluents`, `states`, `actions`, `interms` and `rewards`
for given `horizon`.
Args:
states (Sequence[Tuple[str, np.array]]): A state trajectory.
acti... | keyword[def] identifier[_render_batch] ( identifier[self] ,
identifier[non_fluents] : identifier[NonFluents] ,
identifier[states] : identifier[Fluents] , identifier[actions] : identifier[Fluents] , identifier[interms] : identifier[Fluents] ,
identifier[rewards] : identifier[np] . identifier[array] ,
identifier[ho... | def _render_batch(self, non_fluents: NonFluents, states: Fluents, actions: Fluents, interms: Fluents, rewards: np.array, horizon: Optional[int]=None) -> None:
"""Prints `non_fluents`, `states`, `actions`, `interms` and `rewards`
for given `horizon`.
Args:
states (Sequence[Tuple[str, np.... |
def get_iterator_type(script_settings, subscripts={}):
"""
figures out the iterator type based on the script settings and (optionally) subscripts
Args:
script_settings: iterator_type
subscripts: subscripts
Returns:
"""
if 'iterator_type' in scrip... | def function[get_iterator_type, parameter[script_settings, subscripts]]:
constant[
figures out the iterator type based on the script settings and (optionally) subscripts
Args:
script_settings: iterator_type
subscripts: subscripts
Returns:
]
if com... | keyword[def] identifier[get_iterator_type] ( identifier[script_settings] , identifier[subscripts] ={}):
literal[string]
keyword[if] literal[string] keyword[in] identifier[script_settings] :
keyword[if] identifier[script_settings] [ literal[string] ]== literal[string] :
... | def get_iterator_type(script_settings, subscripts={}):
"""
figures out the iterator type based on the script settings and (optionally) subscripts
Args:
script_settings: iterator_type
subscripts: subscripts
Returns:
"""
if 'iterator_type' in script_setting... |
def baseglob(pat, base):
"""Given a pattern and a base, return files that match the glob pattern
and also contain the base."""
return [f for f in glob(pat) if f.startswith(base)] | def function[baseglob, parameter[pat, base]]:
constant[Given a pattern and a base, return files that match the glob pattern
and also contain the base.]
return[<ast.ListComp object at 0x7da1b0a05180>] | keyword[def] identifier[baseglob] ( identifier[pat] , identifier[base] ):
literal[string]
keyword[return] [ identifier[f] keyword[for] identifier[f] keyword[in] identifier[glob] ( identifier[pat] ) keyword[if] identifier[f] . identifier[startswith] ( identifier[base] )] | def baseglob(pat, base):
"""Given a pattern and a base, return files that match the glob pattern
and also contain the base."""
return [f for f in glob(pat) if f.startswith(base)] |
def process_class_docstrings(app, what, name, obj, options, lines):
"""
For those classes for which we use ::
:template: autosummary/class_without_autosummary.rst
the documented attributes/methods have to be listed in the class
docstring. However, if one of those lists is empty, we use 'None',
... | def function[process_class_docstrings, parameter[app, what, name, obj, options, lines]]:
constant[
For those classes for which we use ::
:template: autosummary/class_without_autosummary.rst
the documented attributes/methods have to be listed in the class
docstring. However, if one of those lis... | keyword[def] identifier[process_class_docstrings] ( identifier[app] , identifier[what] , identifier[name] , identifier[obj] , identifier[options] , identifier[lines] ):
literal[string]
keyword[if] identifier[what] == literal[string] :
identifier[joined] = literal[string] . identifier[join] ( iden... | def process_class_docstrings(app, what, name, obj, options, lines):
"""
For those classes for which we use ::
:template: autosummary/class_without_autosummary.rst
the documented attributes/methods have to be listed in the class
docstring. However, if one of those lists is empty, we use 'None',
... |
def forward(self, agent_qs, states):
"""Forward pass for the mixer.
Arguments:
agent_qs: Tensor of shape [B, T, n_agents, n_actions]
states: Tensor of shape [B, T, state_dim]
"""
bs = agent_qs.size(0)
states = states.reshape(-1, self.state_dim)
ag... | def function[forward, parameter[self, agent_qs, states]]:
constant[Forward pass for the mixer.
Arguments:
agent_qs: Tensor of shape [B, T, n_agents, n_actions]
states: Tensor of shape [B, T, state_dim]
]
variable[bs] assign[=] call[name[agent_qs].size, parameter[... | keyword[def] identifier[forward] ( identifier[self] , identifier[agent_qs] , identifier[states] ):
literal[string]
identifier[bs] = identifier[agent_qs] . identifier[size] ( literal[int] )
identifier[states] = identifier[states] . identifier[reshape] (- literal[int] , identifier[self] . id... | def forward(self, agent_qs, states):
"""Forward pass for the mixer.
Arguments:
agent_qs: Tensor of shape [B, T, n_agents, n_actions]
states: Tensor of shape [B, T, state_dim]
"""
bs = agent_qs.size(0)
states = states.reshape(-1, self.state_dim)
agent_qs = agent_q... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.