code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _Rforce(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... | def function[_Rforce, parameter[self, R, z, phi, t]]:
constant[
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
... | keyword[def] identifier[_Rforce] ( identifier[self] , identifier[R] , identifier[z] , identifier[phi] = literal[int] , identifier[t] = literal[int] ):
literal[string]
identifier[Rz] = identifier[R] ** literal[int] + identifier[z] ** literal[int]
identifier[sqrtRz] = identifier[numpy] . id... | def _Rforce(self, R, z, phi=0.0, t=0.0):
"""
NAME:
_Rforce
PURPOSE:
evaluate the radial force for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT:
... |
def _set_default_vertex_attributes(self) -> None:
"""Assign default values on attributes to all vertices."""
self.graph.vs["l2fc"] = 0
self.graph.vs["padj"] = 0.5
self.graph.vs["symbol"] = self.graph.vs["name"]
self.graph.vs["diff_expressed"] = False
self.graph.vs["up_reg... | def function[_set_default_vertex_attributes, parameter[self]]:
constant[Assign default values on attributes to all vertices.]
call[name[self].graph.vs][constant[l2fc]] assign[=] constant[0]
call[name[self].graph.vs][constant[padj]] assign[=] constant[0.5]
call[name[self].graph.vs][consta... | keyword[def] identifier[_set_default_vertex_attributes] ( identifier[self] )-> keyword[None] :
literal[string]
identifier[self] . identifier[graph] . identifier[vs] [ literal[string] ]= literal[int]
identifier[self] . identifier[graph] . identifier[vs] [ literal[string] ]= literal[int]
... | def _set_default_vertex_attributes(self) -> None:
"""Assign default values on attributes to all vertices."""
self.graph.vs['l2fc'] = 0
self.graph.vs['padj'] = 0.5
self.graph.vs['symbol'] = self.graph.vs['name']
self.graph.vs['diff_expressed'] = False
self.graph.vs['up_regulated'] = False
sel... |
def convert_msg(self, msg):
"""
Takes one POEntry object and converts it (adds a dummy translation to it)
msg is an instance of polib.POEntry
"""
source = msg.msgid
if not source:
# don't translate empty string
return
plural = msg.msgid_pl... | def function[convert_msg, parameter[self, msg]]:
constant[
Takes one POEntry object and converts it (adds a dummy translation to it)
msg is an instance of polib.POEntry
]
variable[source] assign[=] name[msg].msgid
if <ast.UnaryOp object at 0x7da20c795cc0> begin[:]
... | keyword[def] identifier[convert_msg] ( identifier[self] , identifier[msg] ):
literal[string]
identifier[source] = identifier[msg] . identifier[msgid]
keyword[if] keyword[not] identifier[source] :
keyword[return]
identifier[plural] = identifier[msg] . ide... | def convert_msg(self, msg):
"""
Takes one POEntry object and converts it (adds a dummy translation to it)
msg is an instance of polib.POEntry
"""
source = msg.msgid
if not source:
# don't translate empty string
return # depends on [control=['if'], data=[]]
plural... |
def _get_value(self):
"""
Return two delegating variables. Each variable should contain
a value attribute with the real value.
"""
x, y = self._point.x, self._point.y
self._px, self._py = self._item_point.canvas.get_matrix_i2i(self._item_point,
... | def function[_get_value, parameter[self]]:
constant[
Return two delegating variables. Each variable should contain
a value attribute with the real value.
]
<ast.Tuple object at 0x7da1b1aa4910> assign[=] tuple[[<ast.Attribute object at 0x7da1b1aa7c70>, <ast.Attribute object at 0x7... | keyword[def] identifier[_get_value] ( identifier[self] ):
literal[string]
identifier[x] , identifier[y] = identifier[self] . identifier[_point] . identifier[x] , identifier[self] . identifier[_point] . identifier[y]
identifier[self] . identifier[_px] , identifier[self] . identifier[_py] =... | def _get_value(self):
"""
Return two delegating variables. Each variable should contain
a value attribute with the real value.
"""
(x, y) = (self._point.x, self._point.y)
(self._px, self._py) = self._item_point.canvas.get_matrix_i2i(self._item_point, self._item_target).transform_poin... |
def res_to_str(res):
"""
:param res: :class:`requests.Response` object
Parse the given request and generate an informative string from it
"""
if 'Authorization' in res.request.headers:
res.request.headers['Authorization'] = "*****"
return """
####################################
url = %... | def function[res_to_str, parameter[res]]:
constant[
:param res: :class:`requests.Response` object
Parse the given request and generate an informative string from it
]
if compare[constant[Authorization] in name[res].request.headers] begin[:]
call[name[res].request.headers][co... | keyword[def] identifier[res_to_str] ( identifier[res] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[res] . identifier[request] . identifier[headers] :
identifier[res] . identifier[request] . identifier[headers] [ literal[string] ]= literal[string]
keyword[return] ... | def res_to_str(res):
"""
:param res: :class:`requests.Response` object
Parse the given request and generate an informative string from it
"""
if 'Authorization' in res.request.headers:
res.request.headers['Authorization'] = '*****' # depends on [control=['if'], data=[]]
return '\n#####... |
def _ppf(self, q, left, right, cache):
"""
Point percentile function.
Example:
>>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9]))
[0.1 0.2 0.9]
>>> print(chaospy.Pow(chaospy.Uniform(), 2).inv([0.1, 0.2, 0.9]))
[0.01 0.04 0.81]
>>> print... | def function[_ppf, parameter[self, q, left, right, cache]]:
constant[
Point percentile function.
Example:
>>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9]))
[0.1 0.2 0.9]
>>> print(chaospy.Pow(chaospy.Uniform(), 2).inv([0.1, 0.2, 0.9]))
[0.01 0.04 ... | keyword[def] identifier[_ppf] ( identifier[self] , identifier[q] , identifier[left] , identifier[right] , identifier[cache] ):
literal[string]
identifier[left] = identifier[evaluation] . identifier[get_inverse_cache] ( identifier[left] , identifier[cache] )
identifier[right] = identifier[e... | def _ppf(self, q, left, right, cache):
"""
Point percentile function.
Example:
>>> print(chaospy.Uniform().inv([0.1, 0.2, 0.9]))
[0.1 0.2 0.9]
>>> print(chaospy.Pow(chaospy.Uniform(), 2).inv([0.1, 0.2, 0.9]))
[0.01 0.04 0.81]
>>> print(cha... |
def get_plugins(directory):
"""
returns the list of plugins from the specified directory
:param directory: directory that contains the plugins. Files starting with _ will be ignored.
"""
# not just plugin_*.py
plugins = []
files = glob.glob(directory + "/*.py")
for p in files:
p ... | def function[get_plugins, parameter[directory]]:
constant[
returns the list of plugins from the specified directory
:param directory: directory that contains the plugins. Files starting with _ will be ignored.
]
variable[plugins] assign[=] list[[]]
variable[files] assign[=] call[name... | keyword[def] identifier[get_plugins] ( identifier[directory] ):
literal[string]
identifier[plugins] =[]
identifier[files] = identifier[glob] . identifier[glob] ( identifier[directory] + literal[string] )
keyword[for] identifier[p] keyword[in] identifier[files] :
identifier[p] = i... | def get_plugins(directory):
"""
returns the list of plugins from the specified directory
:param directory: directory that contains the plugins. Files starting with _ will be ignored.
"""
# not just plugin_*.py
plugins = []
files = glob.glob(directory + '/*.py')
for p in files:
p ... |
def prop_budget(self, budget):
"""
Set limit on the number of propagations.
"""
if self.glucose:
pysolvers.glucose3_pbudget(self.glucose, budget) | def function[prop_budget, parameter[self, budget]]:
constant[
Set limit on the number of propagations.
]
if name[self].glucose begin[:]
call[name[pysolvers].glucose3_pbudget, parameter[name[self].glucose, name[budget]]] | keyword[def] identifier[prop_budget] ( identifier[self] , identifier[budget] ):
literal[string]
keyword[if] identifier[self] . identifier[glucose] :
identifier[pysolvers] . identifier[glucose3_pbudget] ( identifier[self] . identifier[glucose] , identifier[budget] ) | def prop_budget(self, budget):
"""
Set limit on the number of propagations.
"""
if self.glucose:
pysolvers.glucose3_pbudget(self.glucose, budget) # depends on [control=['if'], data=[]] |
def _ThCond(rho, T, fase=None, drho=None):
"""Equation for the thermal conductivity
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
fase: dict, optional for calculate critical enhancement
phase properties
drho: float, optional for calcul... | def function[_ThCond, parameter[rho, T, fase, drho]]:
constant[Equation for the thermal conductivity
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
fase: dict, optional for calculate critical enhancement
phase properties
drho: float... | keyword[def] identifier[_ThCond] ( identifier[rho] , identifier[T] , identifier[fase] = keyword[None] , identifier[drho] = keyword[None] ):
literal[string]
identifier[d] = identifier[rho] / identifier[rhoc]
identifier[Tr] = identifier[T] / identifier[Tc]
identifier[no] =[ literal[int] , l... | def _ThCond(rho, T, fase=None, drho=None):
"""Equation for the thermal conductivity
Parameters
----------
rho : float
Density, [kg/m³]
T : float
Temperature, [K]
fase: dict, optional for calculate critical enhancement
phase properties
drho: float, optional for calcul... |
def to_dict(self) -> Dict[str, Any]:
"""
Creates a dictionary-based description of this exception, ready to be
serialised as JSON or YAML.
"""
jsn = {
'kind': self.__class__.__name__,
'message': self.message
} # type: Dict[str, Any]
data = ... | def function[to_dict, parameter[self]]:
constant[
Creates a dictionary-based description of this exception, ready to be
serialised as JSON or YAML.
]
variable[jsn] assign[=] dictionary[[<ast.Constant object at 0x7da1b0c8a3e0>, <ast.Constant object at 0x7da1b0c88bb0>], [<ast.Attri... | keyword[def] identifier[to_dict] ( identifier[self] )-> identifier[Dict] [ identifier[str] , identifier[Any] ]:
literal[string]
identifier[jsn] ={
literal[string] : identifier[self] . identifier[__class__] . identifier[__name__] ,
literal[string] : identifier[self] . identifier[me... | def to_dict(self) -> Dict[str, Any]:
"""
Creates a dictionary-based description of this exception, ready to be
serialised as JSON or YAML.
"""
jsn = {'kind': self.__class__.__name__, 'message': self.message} # type: Dict[str, Any]
data = self.data
if data:
jsn['data'] = ... |
def build_node_data_bag():
"""Builds one 'node' data bag item per file found in the 'nodes' directory
Automatic attributes for a node item:
'id': It adds data bag 'id', same as filename but with underscores
'name': same as the filename
'fqdn': same as the filename (LittleChef filenames ... | def function[build_node_data_bag, parameter[]]:
constant[Builds one 'node' data bag item per file found in the 'nodes' directory
Automatic attributes for a node item:
'id': It adds data bag 'id', same as filename but with underscores
'name': same as the filename
'fqdn': same as the ... | keyword[def] identifier[build_node_data_bag] ():
literal[string]
identifier[nodes] = identifier[lib] . identifier[get_nodes] ()
identifier[node_data_bag_path] = identifier[os] . identifier[path] . identifier[join] ( literal[string] , literal[string] )
identifier[remove_local_node_data_bag] (... | def build_node_data_bag():
"""Builds one 'node' data bag item per file found in the 'nodes' directory
Automatic attributes for a node item:
'id': It adds data bag 'id', same as filename but with underscores
'name': same as the filename
'fqdn': same as the filename (LittleChef filenames ... |
def transactions(self, *phids):
"""Retrieve tasks transactions.
:param phids: list of tasks identifiers
"""
params = {
self.PIDS: phids
}
response = self._call(self.MANIPHEST_TRANSACTIONS, params)
return response | def function[transactions, parameter[self]]:
constant[Retrieve tasks transactions.
:param phids: list of tasks identifiers
]
variable[params] assign[=] dictionary[[<ast.Attribute object at 0x7da1b020d120>], [<ast.Name object at 0x7da1b020d510>]]
variable[response] assign[=] call... | keyword[def] identifier[transactions] ( identifier[self] ,* identifier[phids] ):
literal[string]
identifier[params] ={
identifier[self] . identifier[PIDS] : identifier[phids]
}
identifier[response] = identifier[self] . identifier[_call] ( identifier[self] . identifier[MA... | def transactions(self, *phids):
"""Retrieve tasks transactions.
:param phids: list of tasks identifiers
"""
params = {self.PIDS: phids}
response = self._call(self.MANIPHEST_TRANSACTIONS, params)
return response |
def do_reduce(func_name, *sequence):
"""
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
Functions may be registered with ``native_tags``
or can be ``builtins`` or from the ``operator`` module
... | def function[do_reduce, parameter[func_name]]:
constant[
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
Functions may be registered with ``native_tags``
or can be ``builtins`` or from the ``oper... | keyword[def] identifier[do_reduce] ( identifier[func_name] ,* identifier[sequence] ):
literal[string]
keyword[if] identifier[len] ( identifier[sequence] )== literal[int] :
identifier[sequence] = identifier[sequence] [ literal[int] ]
keyword[return] identifier[reduce] ( identifier[get_func] ... | def do_reduce(func_name, *sequence):
"""
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
Functions may be registered with ``native_tags``
or can be ``builtins`` or from the ``operator`` module
... |
def _determine_notification_info(notification_arn,
notification_arn_from_pillar,
notification_types,
notification_types_from_pillar):
'''
helper method for present. ensure that notification_configs are set
''... | def function[_determine_notification_info, parameter[notification_arn, notification_arn_from_pillar, notification_types, notification_types_from_pillar]]:
constant[
helper method for present. ensure that notification_configs are set
]
variable[pillar_arn_list] assign[=] call[name[copy].deepcopy... | keyword[def] identifier[_determine_notification_info] ( identifier[notification_arn] ,
identifier[notification_arn_from_pillar] ,
identifier[notification_types] ,
identifier[notification_types_from_pillar] ):
literal[string]
identifier[pillar_arn_list] = identifier[copy] . identifier[deepcopy] (
id... | def _determine_notification_info(notification_arn, notification_arn_from_pillar, notification_types, notification_types_from_pillar):
"""
helper method for present. ensure that notification_configs are set
"""
pillar_arn_list = copy.deepcopy(__salt__['config.option'](notification_arn_from_pillar, {}))
... |
def _connected(service):
'''
Verify if a connman service is connected
'''
state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State')
return state == 'online' or state == 'ready' | def function[_connected, parameter[service]]:
constant[
Verify if a connman service is connected
]
variable[state] assign[=] call[call[name[pyconnman].ConnService, parameter[call[name[os].path.join, parameter[name[SERVICE_PATH], name[service]]]]].get_property, parameter[constant[State]]]
ret... | keyword[def] identifier[_connected] ( identifier[service] ):
literal[string]
identifier[state] = identifier[pyconnman] . identifier[ConnService] ( identifier[os] . identifier[path] . identifier[join] ( identifier[SERVICE_PATH] , identifier[service] )). identifier[get_property] ( literal[string] )
keyw... | def _connected(service):
"""
Verify if a connman service is connected
"""
state = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)).get_property('State')
return state == 'online' or state == 'ready' |
def local_2d_self_attention_spatial_blocks(query_antecedent,
kv_channels,
heads,
memory_h_dim=None,
memory_w_dim=None,
... | def function[local_2d_self_attention_spatial_blocks, parameter[query_antecedent, kv_channels, heads, memory_h_dim, memory_w_dim, mask_right, master_dtype, slice_dtype, name]]:
constant[Attention to the source position and a neighborhood to the left or right.
The sequence is divided into blocks of length bloc... | keyword[def] identifier[local_2d_self_attention_spatial_blocks] ( identifier[query_antecedent] ,
identifier[kv_channels] ,
identifier[heads] ,
identifier[memory_h_dim] = keyword[None] ,
identifier[memory_w_dim] = keyword[None] ,
identifier[mask_right] = keyword[False] ,
identifier[master_dtype] = identifier[tf]... | def local_2d_self_attention_spatial_blocks(query_antecedent, kv_channels, heads, memory_h_dim=None, memory_w_dim=None, mask_right=False, master_dtype=tf.float32, slice_dtype=tf.float32, name=None):
"""Attention to the source position and a neighborhood to the left or right.
The sequence is divided into blocks of... |
def update_aliases(self):
""" Get aliases information from room state
Returns:
boolean: True if the aliases changed, False if not
"""
changed = False
try:
response = self.client.api.get_room_state(self.room_id)
except MatrixRequestError:
... | def function[update_aliases, parameter[self]]:
constant[ Get aliases information from room state
Returns:
boolean: True if the aliases changed, False if not
]
variable[changed] assign[=] constant[False]
<ast.Try object at 0x7da1b1709270>
for taget[name[chunk]] in... | keyword[def] identifier[update_aliases] ( identifier[self] ):
literal[string]
identifier[changed] = keyword[False]
keyword[try] :
identifier[response] = identifier[self] . identifier[client] . identifier[api] . identifier[get_room_state] ( identifier[self] . identifier[room_i... | def update_aliases(self):
""" Get aliases information from room state
Returns:
boolean: True if the aliases changed, False if not
"""
changed = False
try:
response = self.client.api.get_room_state(self.room_id) # depends on [control=['try'], data=[]]
except MatrixRe... |
def accept(self):
"""Send a response disposition to the service to indicate that
a received message has been accepted. If the client is running in PeekLock
mode, the service will wait on this disposition. Otherwise it will
be ignored. Returns `True` is message was accepted, or `False` if... | def function[accept, parameter[self]]:
constant[Send a response disposition to the service to indicate that
a received message has been accepted. If the client is running in PeekLock
mode, the service will wait on this disposition. Otherwise it will
be ignored. Returns `True` is message ... | keyword[def] identifier[accept] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_can_settle_message] ():
identifier[self] . identifier[_response] = identifier[errors] . identifier[MessageAccepted] ()
identifier[self] . identifier[_settler] ... | def accept(self):
"""Send a response disposition to the service to indicate that
a received message has been accepted. If the client is running in PeekLock
mode, the service will wait on this disposition. Otherwise it will
be ignored. Returns `True` is message was accepted, or `False` if the... |
def get_roles_for_permission(permission, brain_or_object):
"""Get a list of granted roles for the given permission on the object.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Roles for the given Permiss... | def function[get_roles_for_permission, parameter[permission, brain_or_object]]:
constant[Get a list of granted roles for the given permission on the object.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:retur... | keyword[def] identifier[get_roles_for_permission] ( identifier[permission] , identifier[brain_or_object] ):
literal[string]
identifier[obj] = identifier[get_object] ( identifier[brain_or_object] )
identifier[allowed] = identifier[set] ( identifier[rolesForPermissionOn] ( identifier[permission] , ident... | def get_roles_for_permission(permission, brain_or_object):
"""Get a list of granted roles for the given permission on the object.
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Roles for the given Permiss... |
def signal_terminate(on_terminate):
"""a common case program termination signal"""
for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]:
signal.signal(i, on_terminate) | def function[signal_terminate, parameter[on_terminate]]:
constant[a common case program termination signal]
for taget[name[i]] in starred[list[[<ast.Attribute object at 0x7da20c6e5f30>, <ast.Attribute object at 0x7da20c6e77c0>, <ast.Attribute object at 0x7da20c6e67a0>, <ast.Attribute object at 0x7da18f0... | keyword[def] identifier[signal_terminate] ( identifier[on_terminate] ):
literal[string]
keyword[for] identifier[i] keyword[in] [ identifier[signal] . identifier[SIGINT] , identifier[signal] . identifier[SIGQUIT] , identifier[signal] . identifier[SIGUSR1] , identifier[signal] . identifier[SIGUSR2] , ident... | def signal_terminate(on_terminate):
"""a common case program termination signal"""
for i in [signal.SIGINT, signal.SIGQUIT, signal.SIGUSR1, signal.SIGUSR2, signal.SIGTERM]:
signal.signal(i, on_terminate) # depends on [control=['for'], data=['i']] |
def _parse_version_rule(loader, version, verspec):
"""
Parse a version rule. The first token is the name of the
application implementing that API version. The remaining tokens
are key="quoted value" pairs that specify parameters; these
parameters are ignored by AVersion, but may be used by the
... | def function[_parse_version_rule, parameter[loader, version, verspec]]:
constant[
Parse a version rule. The first token is the name of the
application implementing that API version. The remaining tokens
are key="quoted value" pairs that specify parameters; these
parameters are ignored by AVers... | keyword[def] identifier[_parse_version_rule] ( identifier[loader] , identifier[version] , identifier[verspec] ):
literal[string]
identifier[result] = identifier[dict] ( identifier[name] = identifier[version] , identifier[params] ={})
keyword[for] identifier[token] keyword[in] identifier[quoted_spl... | def _parse_version_rule(loader, version, verspec):
"""
Parse a version rule. The first token is the name of the
application implementing that API version. The remaining tokens
are key="quoted value" pairs that specify parameters; these
parameters are ignored by AVersion, but may be used by the
... |
async def grab(self, *, countries=None, limit=0):
"""Gather proxies from the providers without checking.
:param list countries: (optional) List of ISO country codes
where should be located proxies
:param int limit: (optional) The maximum number of proxies
... | <ast.AsyncFunctionDef object at 0x7da1b1b7bdc0> | keyword[async] keyword[def] identifier[grab] ( identifier[self] ,*, identifier[countries] = keyword[None] , identifier[limit] = literal[int] ):
literal[string]
identifier[self] . identifier[_countries] = identifier[countries]
identifier[self] . identifier[_limit] = identifier[limit]
... | async def grab(self, *, countries=None, limit=0):
"""Gather proxies from the providers without checking.
:param list countries: (optional) List of ISO country codes
where should be located proxies
:param int limit: (optional) The maximum number of proxies
:re... |
def customData( self, key, default = None ):
"""
Return the custom data that is stored on this node for the \
given key, returning the default parameter if none was found.
:param key <str>
:param default <variant>
:return <varia... | def function[customData, parameter[self, key, default]]:
constant[
Return the custom data that is stored on this node for the given key, returning the default parameter if none was found.
:param key <str>
:param default <variant>
:r... | keyword[def] identifier[customData] ( identifier[self] , identifier[key] , identifier[default] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[_customData] . identifier[get] ( identifier[nativestring] ( identifier[key] ), identifier[default] ) | def customData(self, key, default=None):
"""
Return the custom data that is stored on this node for the given key, returning the default parameter if none was found.
:param key <str>
:param default <variant>
:return <variant>
... |
def session_id(self):
"""
Return the session id of the current connection.
The session id is issued (through an API request) the first time it is requested, but no sooner. This is
because generating a session id puts it into the DKV on the server, which effectively locks the cluster. On... | def function[session_id, parameter[self]]:
constant[
Return the session id of the current connection.
The session id is issued (through an API request) the first time it is requested, but no sooner. This is
because generating a session id puts it into the DKV on the server, which effect... | keyword[def] identifier[session_id] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_session_id] keyword[is] keyword[None] :
identifier[req] = identifier[self] . identifier[request] ( literal[string] )
identifier[self] . identifier[_sessi... | def session_id(self):
"""
Return the session id of the current connection.
The session id is issued (through an API request) the first time it is requested, but no sooner. This is
because generating a session id puts it into the DKV on the server, which effectively locks the cluster. Once
... |
def _generate_file_set(self, var=None, start_date=None, end_date=None,
domain=None, intvl_in=None, dtype_in_vert=None,
dtype_in_time=None, intvl_out=None):
"""Returns the file_set for the given interval in."""
try:
return self.file_map[in... | def function[_generate_file_set, parameter[self, var, start_date, end_date, domain, intvl_in, dtype_in_vert, dtype_in_time, intvl_out]]:
constant[Returns the file_set for the given interval in.]
<ast.Try object at 0x7da1b0467f40> | keyword[def] identifier[_generate_file_set] ( identifier[self] , identifier[var] = keyword[None] , identifier[start_date] = keyword[None] , identifier[end_date] = keyword[None] ,
identifier[domain] = keyword[None] , identifier[intvl_in] = keyword[None] , identifier[dtype_in_vert] = keyword[None] ,
identifier[dtype_... | def _generate_file_set(self, var=None, start_date=None, end_date=None, domain=None, intvl_in=None, dtype_in_vert=None, dtype_in_time=None, intvl_out=None):
"""Returns the file_set for the given interval in."""
try:
return self.file_map[intvl_in] # depends on [control=['try'], data=[]]
except KeyErr... |
def make_triangle_mesh(points, size_u, size_v, **kwargs):
""" Generates a triangular mesh from an array of points.
This function generates a triangular mesh for a NURBS or B-Spline surface on its parametric space.
The input is the surface points and the number of points on the parametric dimensions u and v... | def function[make_triangle_mesh, parameter[points, size_u, size_v]]:
constant[ Generates a triangular mesh from an array of points.
This function generates a triangular mesh for a NURBS or B-Spline surface on its parametric space.
The input is the surface points and the number of points on the parametr... | keyword[def] identifier[make_triangle_mesh] ( identifier[points] , identifier[size_u] , identifier[size_v] ,** identifier[kwargs] ):
literal[string]
keyword[def] identifier[fix_numbering] ( identifier[vertex_list] , identifier[triangle_list] ):
identifier[final_vertices] =[]
... | def make_triangle_mesh(points, size_u, size_v, **kwargs):
""" Generates a triangular mesh from an array of points.
This function generates a triangular mesh for a NURBS or B-Spline surface on its parametric space.
The input is the surface points and the number of points on the parametric dimensions u and v... |
def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ens... | def function[connection_lost, parameter[self, exc]]:
constant[Log when connection is closed, if needed call callback.]
if name[exc] begin[:]
call[name[self].logger.error, parameter[constant[disconnected due to error]]]
if name[self].disconnect_callback begin[:]
ca... | keyword[def] identifier[connection_lost] ( identifier[self] , identifier[exc] ):
literal[string]
keyword[if] identifier[exc] :
identifier[self] . identifier[logger] . identifier[error] ( literal[string] )
keyword[else] :
identifier[self] . identifier[logger] . id... | def connection_lost(self, exc):
"""Log when connection is closed, if needed call callback."""
if exc:
self.logger.error('disconnected due to error') # depends on [control=['if'], data=[]]
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
... |
def logs(self):
""" Return relevant who-did-what pairs from the bug history """
for record in self.history:
if (record["when"] >= self.options.since.date
and record["when"] < self.options.until.date):
for change in record["changes"]:
yi... | def function[logs, parameter[self]]:
constant[ Return relevant who-did-what pairs from the bug history ]
for taget[name[record]] in starred[name[self].history] begin[:]
if <ast.BoolOp object at 0x7da1b20bded0> begin[:]
for taget[name[change]] in starred[call[name[... | keyword[def] identifier[logs] ( identifier[self] ):
literal[string]
keyword[for] identifier[record] keyword[in] identifier[self] . identifier[history] :
keyword[if] ( identifier[record] [ literal[string] ]>= identifier[self] . identifier[options] . identifier[since] . identifier[dat... | def logs(self):
""" Return relevant who-did-what pairs from the bug history """
for record in self.history:
if record['when'] >= self.options.since.date and record['when'] < self.options.until.date:
for change in record['changes']:
yield (record['who'], change) # depends on ... |
def synthesize(self, modules, use_string, x64, native):
"""Transform sources."""
# code_opts = CodeOpts(
# str.lower, None if use_string else hash_func,
# 'reloc_delta', '->',
# True)
# gen_opts = GenOpts('defs', transformed)
print(hash_func)
g... | def function[synthesize, parameter[self, modules, use_string, x64, native]]:
constant[Transform sources.]
call[name[print], parameter[name[hash_func]]]
variable[groups] assign[=] call[name[group_by], parameter[name[modules], name[ends_with_punctuation]]]
variable[sources] assign[=] call[... | keyword[def] identifier[synthesize] ( identifier[self] , identifier[modules] , identifier[use_string] , identifier[x64] , identifier[native] ):
literal[string]
identifier[print] ( identifier[hash_func] )
identifier[groups] = identifier[group_by]... | def synthesize(self, modules, use_string, x64, native):
"""Transform sources."""
# code_opts = CodeOpts(
# str.lower, None if use_string else hash_func,
# 'reloc_delta', '->',
# True)
# gen_opts = GenOpts('defs', transformed)
print(hash_func)
groups = group_by(modules, ends_w... |
def _basename(station_code, fmt=None):
"""region, country, weather_station, station_code, data_format, url."""
info = _station_info(station_code)
if not fmt:
fmt = info['data_format']
basename = '%s.%s' % (info['url'].rsplit('/', 1)[1].rsplit('.', 1)[0],
DATA_EXTENTIONS... | def function[_basename, parameter[station_code, fmt]]:
constant[region, country, weather_station, station_code, data_format, url.]
variable[info] assign[=] call[name[_station_info], parameter[name[station_code]]]
if <ast.UnaryOp object at 0x7da1b0a720e0> begin[:]
variable[fmt] as... | keyword[def] identifier[_basename] ( identifier[station_code] , identifier[fmt] = keyword[None] ):
literal[string]
identifier[info] = identifier[_station_info] ( identifier[station_code] )
keyword[if] keyword[not] identifier[fmt] :
identifier[fmt] = identifier[info] [ literal[string] ]
... | def _basename(station_code, fmt=None):
"""region, country, weather_station, station_code, data_format, url."""
info = _station_info(station_code)
if not fmt:
fmt = info['data_format'] # depends on [control=['if'], data=[]]
basename = '%s.%s' % (info['url'].rsplit('/', 1)[1].rsplit('.', 1)[0], D... |
def rm_keys_from_dict(d, keys):
"""
Given a dictionary and a key list, remove any data in the dictionary with the given keys.
:param dict d: Metadata
:param list keys: Keys to be removed
:return dict d: Metadata
"""
# Loop for each key given
for key in keys:
# Is the key in the ... | def function[rm_keys_from_dict, parameter[d, keys]]:
constant[
Given a dictionary and a key list, remove any data in the dictionary with the given keys.
:param dict d: Metadata
:param list keys: Keys to be removed
:return dict d: Metadata
]
for taget[name[key]] in starred[name[keys]... | keyword[def] identifier[rm_keys_from_dict] ( identifier[d] , identifier[keys] ):
literal[string]
keyword[for] identifier[key] keyword[in] identifier[keys] :
keyword[if] identifier[key] keyword[in] identifier[d] :
keyword[try] :
identifier[d] . identifi... | def rm_keys_from_dict(d, keys):
"""
Given a dictionary and a key list, remove any data in the dictionary with the given keys.
:param dict d: Metadata
:param list keys: Keys to be removed
:return dict d: Metadata
"""
# Loop for each key given
for key in keys:
# Is the key in the ... |
def make_key(observer):
"""Construct a unique, hashable, immutable key for an observer."""
if hasattr(observer, "__self__"):
inst = observer.__self__
method_name = observer.__name__
key = (id(inst), method_name)
else:
key = id(observer)
re... | def function[make_key, parameter[observer]]:
constant[Construct a unique, hashable, immutable key for an observer.]
if call[name[hasattr], parameter[name[observer], constant[__self__]]] begin[:]
variable[inst] assign[=] name[observer].__self__
variable[method_name] assign... | keyword[def] identifier[make_key] ( identifier[observer] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[observer] , literal[string] ):
identifier[inst] = identifier[observer] . identifier[__self__]
identifier[method_name] = identifier[observer] . identi... | def make_key(observer):
"""Construct a unique, hashable, immutable key for an observer."""
if hasattr(observer, '__self__'):
inst = observer.__self__
method_name = observer.__name__
key = (id(inst), method_name) # depends on [control=['if'], data=[]]
else:
key = id(observer)... |
def parse_python_paths(self, args):
"""
optparse doesn't manage stuff like this:
--pythonpath /my/modules/*
but it can manages
--pythonpath=/my/modules/*/
(but without handling globing)
This method handles correctly the one without "=" and manages globing
... | def function[parse_python_paths, parameter[self, args]]:
constant[
optparse doesn't manage stuff like this:
--pythonpath /my/modules/*
but it can manages
--pythonpath=/my/modules/*/
(but without handling globing)
This method handles correctly the one witho... | keyword[def] identifier[parse_python_paths] ( identifier[self] , identifier[args] ):
literal[string]
identifier[paths] =[]
identifier[do_paths] = keyword[False]
keyword[for] identifier[arg] keyword[in] identifier[args] :
keyword[if] identifier[arg] == literal[st... | def parse_python_paths(self, args):
"""
optparse doesn't manage stuff like this:
--pythonpath /my/modules/*
but it can manages
--pythonpath=/my/modules/*/
(but without handling globing)
This method handles correctly the one without "=" and manages globing
... |
def is_connected(self):
"""Indication of the connection state of all children"""
return all([r.is_connected() for r in dict.values(self.children)]) | def function[is_connected, parameter[self]]:
constant[Indication of the connection state of all children]
return[call[name[all], parameter[<ast.ListComp object at 0x7da1b054a830>]]] | keyword[def] identifier[is_connected] ( identifier[self] ):
literal[string]
keyword[return] identifier[all] ([ identifier[r] . identifier[is_connected] () keyword[for] identifier[r] keyword[in] identifier[dict] . identifier[values] ( identifier[self] . identifier[children] )]) | def is_connected(self):
"""Indication of the connection state of all children"""
return all([r.is_connected() for r in dict.values(self.children)]) |
def ensure_coordinator_ready(self):
"""Block until the coordinator for this group is known
(and we have an active connection -- java client uses unsent queue).
"""
with self._client._lock, self._lock:
while self.coordinator_unknown():
# Prior to 0.8.2 there w... | def function[ensure_coordinator_ready, parameter[self]]:
constant[Block until the coordinator for this group is known
(and we have an active connection -- java client uses unsent queue).
]
with name[self]._client._lock begin[:]
while call[name[self].coordinator_unknown, p... | keyword[def] identifier[ensure_coordinator_ready] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[_client] . identifier[_lock] , identifier[self] . identifier[_lock] :
keyword[while] identifier[self] . identifier[coordinator_unknown] ():
... | def ensure_coordinator_ready(self):
"""Block until the coordinator for this group is known
(and we have an active connection -- java client uses unsent queue).
"""
with self._client._lock, self._lock:
while self.coordinator_unknown():
# Prior to 0.8.2 there was no group coord... |
def list_available_beacons(self):
'''
List the available beacons
'''
_beacons = ['{0}'.format(_beacon.replace('.beacon', ''))
for _beacon in self.beacons if '.beacon' in _beacon]
# Fire the complete event back along with the list of beacons
evt = salt... | def function[list_available_beacons, parameter[self]]:
constant[
List the available beacons
]
variable[_beacons] assign[=] <ast.ListComp object at 0x7da1b21af4f0>
variable[evt] assign[=] call[name[salt].utils.event.get_event, parameter[constant[minion]]]
call[name[evt].fi... | keyword[def] identifier[list_available_beacons] ( identifier[self] ):
literal[string]
identifier[_beacons] =[ literal[string] . identifier[format] ( identifier[_beacon] . identifier[replace] ( literal[string] , literal[string] ))
keyword[for] identifier[_beacon] keyword[in] identifier[s... | def list_available_beacons(self):
"""
List the available beacons
"""
_beacons = ['{0}'.format(_beacon.replace('.beacon', '')) for _beacon in self.beacons if '.beacon' in _beacon]
# Fire the complete event back along with the list of beacons
evt = salt.utils.event.get_event('minion', opts... |
def set_geometry(im, width_height):
"""Rescale the image to the new geometry.
"""
width, height = width_height
if not width and not height:
return im
im_width, im_height = im.size
# Geometry match the current size?
if (width is None) or (im_width == width):
if (height is No... | def function[set_geometry, parameter[im, width_height]]:
constant[Rescale the image to the new geometry.
]
<ast.Tuple object at 0x7da1b085de10> assign[=] name[width_height]
if <ast.BoolOp object at 0x7da1b085f6d0> begin[:]
return[name[im]]
<ast.Tuple object at 0x7da1b085c970>... | keyword[def] identifier[set_geometry] ( identifier[im] , identifier[width_height] ):
literal[string]
identifier[width] , identifier[height] = identifier[width_height]
keyword[if] keyword[not] identifier[width] keyword[and] keyword[not] identifier[height] :
keyword[return] identifier[im... | def set_geometry(im, width_height):
"""Rescale the image to the new geometry.
"""
(width, height) = width_height
if not width and (not height):
return im # depends on [control=['if'], data=[]]
(im_width, im_height) = im.size
# Geometry match the current size?
if width is None or im_... |
def path(self, filename):
'''
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
... | def function[path, parameter[self, filename]]:
constant[
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set pr... | keyword[def] identifier[path] ( identifier[self] , identifier[filename] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[backend] . identifier[root] :
keyword[raise] identifier[OperationNotSupported] (
literal[string] +
identifier[s... | def path(self, filename):
"""
This returns the absolute path of a file uploaded to this set. It
doesn't actually check whether said file exists.
:param filename: The filename to return the path for.
:param folder: The subfolder within the upload set previously used
... |
def dollarfy(x):
"""Replaces Math elements in element list 'x' with a $-enclosed string.
stringify() passes through TeX math. Use dollarfy(x) first to replace
Math elements with math strings set in dollars. 'x' should be a deep copy
so that the underlying document is left untouched.
Returns 'x'.... | def function[dollarfy, parameter[x]]:
constant[Replaces Math elements in element list 'x' with a $-enclosed string.
stringify() passes through TeX math. Use dollarfy(x) first to replace
Math elements with math strings set in dollars. 'x' should be a deep copy
so that the underlying document is le... | keyword[def] identifier[dollarfy] ( identifier[x] ):
literal[string]
keyword[def] identifier[_dollarfy] ( identifier[key] , identifier[value] , identifier[fmt] , identifier[meta] ):
literal[string]
keyword[if] identifier[key] == literal[string] :
keyword[return] identifi... | def dollarfy(x):
"""Replaces Math elements in element list 'x' with a $-enclosed string.
stringify() passes through TeX math. Use dollarfy(x) first to replace
Math elements with math strings set in dollars. 'x' should be a deep copy
so that the underlying document is left untouched.
Returns 'x'.... |
def default_type_resolver(
value: Any, info: GraphQLResolveInfo, abstract_type: GraphQLAbstractType
) -> AwaitableOrValue[Optional[Union[GraphQLObjectType, str]]]:
"""Default type resolver function.
If a resolve_type function is not given, then a default resolve behavior is used
which attempts two stra... | def function[default_type_resolver, parameter[value, info, abstract_type]]:
constant[Default type resolver function.
If a resolve_type function is not given, then a default resolve behavior is used
which attempts two strategies:
First, See if the provided value has a `__typename` field defined, if... | keyword[def] identifier[default_type_resolver] (
identifier[value] : identifier[Any] , identifier[info] : identifier[GraphQLResolveInfo] , identifier[abstract_type] : identifier[GraphQLAbstractType]
)-> identifier[AwaitableOrValue] [ identifier[Optional] [ identifier[Union] [ identifier[GraphQLObjectType] , identif... | def default_type_resolver(value: Any, info: GraphQLResolveInfo, abstract_type: GraphQLAbstractType) -> AwaitableOrValue[Optional[Union[GraphQLObjectType, str]]]:
"""Default type resolver function.
If a resolve_type function is not given, then a default resolve behavior is used
which attempts two strategies... |
def update_relations(context, namespace_separator=':'):
"""Update the context with the relation data."""
# Add any relation data prefixed with the relation type.
relation_type = charmhelpers.core.hookenv.relation_type()
relations = []
context['current_relation'] = {}
if relation_type is not None... | def function[update_relations, parameter[context, namespace_separator]]:
constant[Update the context with the relation data.]
variable[relation_type] assign[=] call[name[charmhelpers].core.hookenv.relation_type, parameter[]]
variable[relations] assign[=] list[[]]
call[name[context]][cons... | keyword[def] identifier[update_relations] ( identifier[context] , identifier[namespace_separator] = literal[string] ):
literal[string]
identifier[relation_type] = identifier[charmhelpers] . identifier[core] . identifier[hookenv] . identifier[relation_type] ()
identifier[relations] =[]
identi... | def update_relations(context, namespace_separator=':'):
"""Update the context with the relation data."""
# Add any relation data prefixed with the relation type.
relation_type = charmhelpers.core.hookenv.relation_type()
relations = []
context['current_relation'] = {}
if relation_type is not None... |
def _advance_params(self):
"""
Explicitly generate new values for these parameters only
when appropriate.
"""
for p in ['x','y','direction']:
self.force_new_dynamic_value(p)
self.last_time = self.time_fn() | def function[_advance_params, parameter[self]]:
constant[
Explicitly generate new values for these parameters only
when appropriate.
]
for taget[name[p]] in starred[list[[<ast.Constant object at 0x7da1b2596bf0>, <ast.Constant object at 0x7da1b2596b90>, <ast.Constant object at 0x7... | keyword[def] identifier[_advance_params] ( identifier[self] ):
literal[string]
keyword[for] identifier[p] keyword[in] [ literal[string] , literal[string] , literal[string] ]:
identifier[self] . identifier[force_new_dynamic_value] ( identifier[p] )
identifier[self] . identifi... | def _advance_params(self):
"""
Explicitly generate new values for these parameters only
when appropriate.
"""
for p in ['x', 'y', 'direction']:
self.force_new_dynamic_value(p) # depends on [control=['for'], data=['p']]
self.last_time = self.time_fn() |
def after_epoch(self, **_) -> None:
"""
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
"""
if not self._total_batch_count_saved:
self._total_batch_count = self._current_batch_count.copy()
self._total_batch_count_saved = True
self.... | def function[after_epoch, parameter[self]]:
constant[
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
]
if <ast.UnaryOp object at 0x7da20c6e63e0> begin[:]
name[self]._total_batch_count assign[=] call[name[self]._current_batch_count.copy, parameter... | keyword[def] identifier[after_epoch] ( identifier[self] ,** identifier[_] )-> keyword[None] :
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_total_batch_count_saved] :
identifier[self] . identifier[_total_batch_count] = identifier[self] . identifier[_current_... | def after_epoch(self, **_) -> None:
"""
Reset progress counters. Save ``total_batch_count`` after the 1st epoch.
"""
if not self._total_batch_count_saved:
self._total_batch_count = self._current_batch_count.copy()
self._total_batch_count_saved = True # depends on [control=['if']... |
def adj_nodes_az(az_nodes):
"""Adjust details specific to Azure."""
for node in az_nodes:
node.cloud = "azure"
node.cloud_disp = "Azure"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['location']
... | def function[adj_nodes_az, parameter[az_nodes]]:
constant[Adjust details specific to Azure.]
for taget[name[node]] in starred[name[az_nodes]] begin[:]
name[node].cloud assign[=] constant[azure]
name[node].cloud_disp assign[=] constant[Azure]
name[node].pri... | keyword[def] identifier[adj_nodes_az] ( identifier[az_nodes] ):
literal[string]
keyword[for] identifier[node] keyword[in] identifier[az_nodes] :
identifier[node] . identifier[cloud] = literal[string]
identifier[node] . identifier[cloud_disp] = literal[string]
identifier[node... | def adj_nodes_az(az_nodes):
"""Adjust details specific to Azure."""
for node in az_nodes:
node.cloud = 'azure'
node.cloud_disp = 'Azure'
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['location']
... |
def load(self, source, mode='create', source_format='csv', csv_options=None,
ignore_unknown_values=False, max_bad_records=0):
""" Load the table from GCS.
Args:
source: the URL of the source objects(s). Can include a wildcard '*' at the end of the item
name. Can be a single source or ... | def function[load, parameter[self, source, mode, source_format, csv_options, ignore_unknown_values, max_bad_records]]:
constant[ Load the table from GCS.
Args:
source: the URL of the source objects(s). Can include a wildcard '*' at the end of the item
name. Can be a single source or a list.
... | keyword[def] identifier[load] ( identifier[self] , identifier[source] , identifier[mode] = literal[string] , identifier[source_format] = literal[string] , identifier[csv_options] = keyword[None] ,
identifier[ignore_unknown_values] = keyword[False] , identifier[max_bad_records] = literal[int] ):
literal[string] ... | def load(self, source, mode='create', source_format='csv', csv_options=None, ignore_unknown_values=False, max_bad_records=0):
""" Load the table from GCS.
Args:
source: the URL of the source objects(s). Can include a wildcard '*' at the end of the item
name. Can be a single source or a list.
... |
def coalesce(self):
"""
Coalesces any adjacent ScienceSegments. Returns the number of
ScienceSegments in the coalesced list.
"""
# check for an empty list
if len(self) == 0:
return 0
# sort the list of science segments
self.__sci_segs.sort()
# coalesce the list, checking eac... | def function[coalesce, parameter[self]]:
constant[
Coalesces any adjacent ScienceSegments. Returns the number of
ScienceSegments in the coalesced list.
]
if compare[call[name[len], parameter[name[self]]] equal[==] constant[0]] begin[:]
return[constant[0]]
call[name[self].__sc... | keyword[def] identifier[coalesce] ( identifier[self] ):
literal[string]
keyword[if] identifier[len] ( identifier[self] )== literal[int] :
keyword[return] literal[int]
identifier[self] . identifier[__sci_segs] . identifier[sort] ()
identifier[outlist] =[]
identif... | def coalesce(self):
"""
Coalesces any adjacent ScienceSegments. Returns the number of
ScienceSegments in the coalesced list.
"""
# check for an empty list
if len(self) == 0:
return 0 # depends on [control=['if'], data=[]]
# sort the list of science segments
self.__sci_segs.sort(... |
def delete(self, *args, **kwargs):
"""
Executes an HTTP DELETE.
:Parameters:
- `args`: Non-keyword arguments
- `kwargs`: Keyword arguments
"""
return self.session.delete(*args, **self.get_kwargs(**kwargs)) | def function[delete, parameter[self]]:
constant[
Executes an HTTP DELETE.
:Parameters:
- `args`: Non-keyword arguments
- `kwargs`: Keyword arguments
]
return[call[name[self].session.delete, parameter[<ast.Starred object at 0x7da1b06fd6f0>]]] | keyword[def] identifier[delete] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[return] identifier[self] . identifier[session] . identifier[delete] (* identifier[args] ,** identifier[self] . identifier[get_kwargs] (** identifier[kwargs] )) | def delete(self, *args, **kwargs):
"""
Executes an HTTP DELETE.
:Parameters:
- `args`: Non-keyword arguments
- `kwargs`: Keyword arguments
"""
return self.session.delete(*args, **self.get_kwargs(**kwargs)) |
def verbose_option(fn):
""" Decorator to add a --verbose option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'verbose' if the command needs it. To get the current value you can d... | def function[verbose_option, parameter[fn]]:
constant[ Decorator to add a --verbose option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'verbose' if the command needs it. To ... | keyword[def] identifier[verbose_option] ( identifier[fn] ):
literal[string]
keyword[def] identifier[set_verbose] ( identifier[ctx] , identifier[param] , identifier[value] ):
keyword[from] identifier[peltak] . identifier[core] keyword[import] identifier[context]
identifier[conte... | def verbose_option(fn):
""" Decorator to add a --verbose option to any click command.
The value won't be passed down to the command, but rather handled in the
callback. The value will be accessible through `peltak.core.context` under
'verbose' if the command needs it. To get the current value you can d... |
def get(self, key, default=None):
"""Get a key."""
key = "{0}{1}".format(self.prefix, key)
data = self.redis.get(key)
# Redis returns None not an exception
if data is None:
data = default
else:
data = json.loads(data)
return data | def function[get, parameter[self, key, default]]:
constant[Get a key.]
variable[key] assign[=] call[constant[{0}{1}].format, parameter[name[self].prefix, name[key]]]
variable[data] assign[=] call[name[self].redis.get, parameter[name[key]]]
if compare[name[data] is constant[None]] begin[:... | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[default] = keyword[None] ):
literal[string]
identifier[key] = literal[string] . identifier[format] ( identifier[self] . identifier[prefix] , identifier[key] )
identifier[data] = identifier[self] . identifier[re... | def get(self, key, default=None):
"""Get a key."""
key = '{0}{1}'.format(self.prefix, key)
data = self.redis.get(key)
# Redis returns None not an exception
if data is None:
data = default # depends on [control=['if'], data=['data']]
else:
data = json.loads(data)
return data |
def parse_flags(headers):
"""Copied from https://github.com/girishramnani/gmail/blob/master/gmail/message.py"""
if len(headers) == 0:
return []
if sys.version_info[0] == 3:
headers = bytes(headers, "ascii")
return list(imaplib.ParseFlags(headers)) | def function[parse_flags, parameter[headers]]:
constant[Copied from https://github.com/girishramnani/gmail/blob/master/gmail/message.py]
if compare[call[name[len], parameter[name[headers]]] equal[==] constant[0]] begin[:]
return[list[[]]]
if compare[call[name[sys].version_info][constant[... | keyword[def] identifier[parse_flags] ( identifier[headers] ):
literal[string]
keyword[if] identifier[len] ( identifier[headers] )== literal[int] :
keyword[return] []
keyword[if] identifier[sys] . identifier[version_info] [ literal[int] ]== literal[int] :
identifier[headers] = ident... | def parse_flags(headers):
"""Copied from https://github.com/girishramnani/gmail/blob/master/gmail/message.py"""
if len(headers) == 0:
return [] # depends on [control=['if'], data=[]]
if sys.version_info[0] == 3:
headers = bytes(headers, 'ascii') # depends on [control=['if'], data=[]]
r... |
def allow_filtering(self):
"""
Enables the (usually) unwise practive of querying on a clustering key without also defining a partition key
"""
clone = copy.deepcopy(self)
clone._allow_filtering = True
return clone | def function[allow_filtering, parameter[self]]:
constant[
Enables the (usually) unwise practive of querying on a clustering key without also defining a partition key
]
variable[clone] assign[=] call[name[copy].deepcopy, parameter[name[self]]]
name[clone]._allow_filtering assign[=... | keyword[def] identifier[allow_filtering] ( identifier[self] ):
literal[string]
identifier[clone] = identifier[copy] . identifier[deepcopy] ( identifier[self] )
identifier[clone] . identifier[_allow_filtering] = keyword[True]
keyword[return] identifier[clone] | def allow_filtering(self):
"""
Enables the (usually) unwise practive of querying on a clustering key without also defining a partition key
"""
clone = copy.deepcopy(self)
clone._allow_filtering = True
return clone |
def updatefile(self, project_id, file_path, branch_name, content, commit_message):
"""
Updates an existing file in the repository
:param project_id: project id
:param file_path: Full path to new file. Ex. lib/class.rb
:param branch_name: The name of branch
:param content... | def function[updatefile, parameter[self, project_id, file_path, branch_name, content, commit_message]]:
constant[
Updates an existing file in the repository
:param project_id: project id
:param file_path: Full path to new file. Ex. lib/class.rb
:param branch_name: The name of br... | keyword[def] identifier[updatefile] ( identifier[self] , identifier[project_id] , identifier[file_path] , identifier[branch_name] , identifier[content] , identifier[commit_message] ):
literal[string]
identifier[data] ={
literal[string] : identifier[file_path] ,
literal[string] : i... | def updatefile(self, project_id, file_path, branch_name, content, commit_message):
"""
Updates an existing file in the repository
:param project_id: project id
:param file_path: Full path to new file. Ex. lib/class.rb
:param branch_name: The name of branch
:param content: Fi... |
def set_last_value_to_one(probabilities):
"""!
@brief Update the last same probabilities to one.
@details All values of probability list equals to the last element are set to 1.
"""
# Start from the last elem
back_idx = - 1
# All values equal to the las... | def function[set_last_value_to_one, parameter[probabilities]]:
constant[!
@brief Update the last same probabilities to one.
@details All values of probability list equals to the last element are set to 1.
]
variable[back_idx] assign[=] <ast.UnaryOp object at 0x7da1b01905... | keyword[def] identifier[set_last_value_to_one] ( identifier[probabilities] ):
literal[string]
identifier[back_idx] =- literal[int]
identifier[last_val] = identifier[probabilities] [ identifier[back_idx] ]
keyword[for] identifier[_] keyword[in] ide... | def set_last_value_to_one(probabilities):
"""!
@brief Update the last same probabilities to one.
@details All values of probability list equals to the last element are set to 1.
"""
# Start from the last elem
back_idx = -1
# All values equal to the last elem should be se... |
def to_distribution_values(self, values):
"""
Returns numpy array of natural logarithms of ``values``.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
# avoid RuntimeWarning: divide by zero encountered in log
return numpy.log(values... | def function[to_distribution_values, parameter[self, values]]:
constant[
Returns numpy array of natural logarithms of ``values``.
]
with call[name[warnings].catch_warnings, parameter[]] begin[:]
call[name[warnings].simplefilter, parameter[constant[ignore]]]
return... | keyword[def] identifier[to_distribution_values] ( identifier[self] , identifier[values] ):
literal[string]
keyword[with] identifier[warnings] . identifier[catch_warnings] ():
identifier[warnings] . identifier[simplefilter] ( literal[string] )
keyword[return] ... | def to_distribution_values(self, values):
"""
Returns numpy array of natural logarithms of ``values``.
"""
with warnings.catch_warnings():
warnings.simplefilter('ignore')
# avoid RuntimeWarning: divide by zero encountered in log
return numpy.log(values) # depends on [con... |
def image(alt_text, link_url, title=""):
"""Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
''
>>>... | def function[image, parameter[alt_text, link_url, title]]:
constant[Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
':
literal[string]
identifier[image_string] = literal[string] + identifier[esc_format] ( identifier[alt_text] )+ literal[string] + identifier[link_url] + literal[string]
keyword[if] ide... | def image(alt_text, link_url, title=''):
"""Return an inline image.
Keyword arguments:
title -- Specify the title of the image, as seen when hovering over it.
>>> image("This is an image", "https://tinyurl.com/bright-green-tree")
''
>>>... |
def is_cache(cache):
"""Returns `True` if ``cache`` is a readable cache file or object
Parameters
----------
cache : `str`, `file`, `list`
Object to detect as cache
Returns
-------
iscache : `bool`
`True` if the input object is a cache, or a file in LAL cache format,
... | def function[is_cache, parameter[cache]]:
constant[Returns `True` if ``cache`` is a readable cache file or object
Parameters
----------
cache : `str`, `file`, `list`
Object to detect as cache
Returns
-------
iscache : `bool`
`True` if the input object is a cache, or a f... | keyword[def] identifier[is_cache] ( identifier[cache] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[cache] , identifier[string_types] + identifier[FILE_LIKE] ):
keyword[try] :
keyword[return] identifier[bool] ( identifier[len] ( identifier[read_cache] ( identifi... | def is_cache(cache):
"""Returns `True` if ``cache`` is a readable cache file or object
Parameters
----------
cache : `str`, `file`, `list`
Object to detect as cache
Returns
-------
iscache : `bool`
`True` if the input object is a cache, or a file in LAL cache format,
... |
def split_bgedge(self, bgedge, guidance=None, sorted_guidance=False,
account_for_colors_multiplicity_in_guidance=True,
key=None):
""" Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is pr... | def function[split_bgedge, parameter[self, bgedge, guidance, sorted_guidance, account_for_colors_multiplicity_in_guidance, key]]:
constant[ Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is provided) with respect to supplied gui... | keyword[def] identifier[split_bgedge] ( identifier[self] , identifier[bgedge] , identifier[guidance] = keyword[None] , identifier[sorted_guidance] = keyword[False] ,
identifier[account_for_colors_multiplicity_in_guidance] = keyword[True] ,
identifier[key] = keyword[None] ):
literal[string]
identi... | def split_bgedge(self, bgedge, guidance=None, sorted_guidance=False, account_for_colors_multiplicity_in_guidance=True, key=None):
""" Splits a :class:`bg.edge.BGEdge` in current :class:`BreakpointGraph` most similar to supplied one (if no unique identifier ``key`` is provided) with respect to supplied guidance.
... |
def get_canonical_encoding_name(name):
# type: (str) -> str
"""
Given an encoding name, get the canonical name from a codec lookup.
:param str name: The name of the codec to lookup
:return: The canonical version of the codec name
:rtype: str
"""
import codecs
try:
codec = ... | def function[get_canonical_encoding_name, parameter[name]]:
constant[
Given an encoding name, get the canonical name from a codec lookup.
:param str name: The name of the codec to lookup
:return: The canonical version of the codec name
:rtype: str
]
import module[codecs]
<ast.Try ob... | keyword[def] identifier[get_canonical_encoding_name] ( identifier[name] ):
literal[string]
keyword[import] identifier[codecs]
keyword[try] :
identifier[codec] = identifier[codecs] . identifier[lookup] ( identifier[name] )
keyword[except] identifier[LookupError] :
keyword[r... | def get_canonical_encoding_name(name):
# type: (str) -> str
'\n Given an encoding name, get the canonical name from a codec lookup.\n\n :param str name: The name of the codec to lookup\n :return: The canonical version of the codec name\n :rtype: str\n '
import codecs
try:
codec = ... |
def start(self):
""" :meth:`WStoppableTask.start` implementation that creates new thread
"""
start_event = self.start_event()
stop_event = self.stop_event()
ready_event = self.ready_event()
def thread_target():
try:
start_event.set()
self.thread_started()
if ready_event is not None:
re... | def function[start, parameter[self]]:
constant[ :meth:`WStoppableTask.start` implementation that creates new thread
]
variable[start_event] assign[=] call[name[self].start_event, parameter[]]
variable[stop_event] assign[=] call[name[self].stop_event, parameter[]]
variable[ready_event] ... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[start_event] = identifier[self] . identifier[start_event] ()
identifier[stop_event] = identifier[self] . identifier[stop_event] ()
identifier[ready_event] = identifier[self] . identifier[ready_event] ()
keyword[def] ide... | def start(self):
""" :meth:`WStoppableTask.start` implementation that creates new thread
"""
start_event = self.start_event()
stop_event = self.stop_event()
ready_event = self.ready_event()
def thread_target():
try:
start_event.set()
self.thread_started()
... |
def _p100(part, total, prec=1):
'''Return percentage as string.
'''
r = float(total)
if r:
r = part * 100.0 / r
return '%.*f%%' % (prec, r)
return 'n/a' | def function[_p100, parameter[part, total, prec]]:
constant[Return percentage as string.
]
variable[r] assign[=] call[name[float], parameter[name[total]]]
if name[r] begin[:]
variable[r] assign[=] binary_operation[binary_operation[name[part] * constant[100.0]] / name[r]]
... | keyword[def] identifier[_p100] ( identifier[part] , identifier[total] , identifier[prec] = literal[int] ):
literal[string]
identifier[r] = identifier[float] ( identifier[total] )
keyword[if] identifier[r] :
identifier[r] = identifier[part] * literal[int] / identifier[r]
keyword[ret... | def _p100(part, total, prec=1):
"""Return percentage as string.
"""
r = float(total)
if r:
r = part * 100.0 / r
return '%.*f%%' % (prec, r) # depends on [control=['if'], data=[]]
return 'n/a' |
def binary_ks_curve(y_true, y_probas):
"""This function generates the points necessary to calculate the KS
Statistic curve.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_probas (array-like, shape (n_samples)): Probability predictions of
the positive c... | def function[binary_ks_curve, parameter[y_true, y_probas]]:
constant[This function generates the points necessary to calculate the KS
Statistic curve.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_probas (array-like, shape (n_samples)): Probability prediction... | keyword[def] identifier[binary_ks_curve] ( identifier[y_true] , identifier[y_probas] ):
literal[string]
identifier[y_true] , identifier[y_probas] = identifier[np] . identifier[asarray] ( identifier[y_true] ), identifier[np] . identifier[asarray] ( identifier[y_probas] )
identifier[lb] = identifier[Lab... | def binary_ks_curve(y_true, y_probas):
"""This function generates the points necessary to calculate the KS
Statistic curve.
Args:
y_true (array-like, shape (n_samples)): True labels of the data.
y_probas (array-like, shape (n_samples)): Probability predictions of
the positive c... |
def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject,
parsing_plan_for_children: Dict[str, ParsingPlan], logger: Logger,
options: Dict[str, Dict[str, Any]]) -> T:
"""
First parse all children from the parsing plan, then calls _build_obj... | def function[_parse_multifile, parameter[self, desired_type, obj, parsing_plan_for_children, logger, options]]:
constant[
First parse all children from the parsing plan, then calls _build_object_from_parsed_children
:param desired_type:
:param obj:
:param parsing_plan_for_childr... | keyword[def] identifier[_parse_multifile] ( identifier[self] , identifier[desired_type] : identifier[Type] [ identifier[T] ], identifier[obj] : identifier[PersistedObject] ,
identifier[parsing_plan_for_children] : identifier[Dict] [ identifier[str] , identifier[ParsingPlan] ], identifier[logger] : identifier[Logger]... | def _parse_multifile(self, desired_type: Type[T], obj: PersistedObject, parsing_plan_for_children: Dict[str, ParsingPlan], logger: Logger, options: Dict[str, Dict[str, Any]]) -> T:
"""
First parse all children from the parsing plan, then calls _build_object_from_parsed_children
:param desired_type:... |
def ping(self):
""" Send a ping message. """
self.last_ping = time.time()
try:
self.send_message({MESSAGE_TYPE: TYPE_PING})
except NotConnected:
self._socket_client.logger.error("Chromecast is disconnected. " +
"Cannot ... | def function[ping, parameter[self]]:
constant[ Send a ping message. ]
name[self].last_ping assign[=] call[name[time].time, parameter[]]
<ast.Try object at 0x7da20c7c8700> | keyword[def] identifier[ping] ( identifier[self] ):
literal[string]
identifier[self] . identifier[last_ping] = identifier[time] . identifier[time] ()
keyword[try] :
identifier[self] . identifier[send_message] ({ identifier[MESSAGE_TYPE] : identifier[TYPE_PING] })
keyw... | def ping(self):
""" Send a ping message. """
self.last_ping = time.time()
try:
self.send_message({MESSAGE_TYPE: TYPE_PING}) # depends on [control=['try'], data=[]]
except NotConnected:
self._socket_client.logger.error('Chromecast is disconnected. ' + 'Cannot ping until reconnected.') #... |
def get_allocated_fragments(self, id_or_uri, count=-1, start=0):
"""
Gets all fragments that have been allocated in range.
Args:
id_or_uri:
ID or URI of range.
count:
The number of resources to return. A count of -1 requests all items. Th... | def function[get_allocated_fragments, parameter[self, id_or_uri, count, start]]:
constant[
Gets all fragments that have been allocated in range.
Args:
id_or_uri:
ID or URI of range.
count:
The number of resources to return. A count of -1 ... | keyword[def] identifier[get_allocated_fragments] ( identifier[self] , identifier[id_or_uri] , identifier[count] =- literal[int] , identifier[start] = literal[int] ):
literal[string]
identifier[uri] = identifier[self] . identifier[_client] . identifier[build_uri] ( identifier[id_or_uri] )+ literal[s... | def get_allocated_fragments(self, id_or_uri, count=-1, start=0):
"""
Gets all fragments that have been allocated in range.
Args:
id_or_uri:
ID or URI of range.
count:
The number of resources to return. A count of -1 requests all items. The ac... |
def tgread_bytes(self):
"""
Reads a Telegram-encoded byte array, without the need of
specifying its length.
"""
first_byte = self.read_byte()
if first_byte == 254:
length = self.read_byte() | (self.read_byte() << 8) | (
self.read_byte() << 16)
... | def function[tgread_bytes, parameter[self]]:
constant[
Reads a Telegram-encoded byte array, without the need of
specifying its length.
]
variable[first_byte] assign[=] call[name[self].read_byte, parameter[]]
if compare[name[first_byte] equal[==] constant[254]] begin[:]
... | keyword[def] identifier[tgread_bytes] ( identifier[self] ):
literal[string]
identifier[first_byte] = identifier[self] . identifier[read_byte] ()
keyword[if] identifier[first_byte] == literal[int] :
identifier[length] = identifier[self] . identifier[read_byte] ()|( identifier[... | def tgread_bytes(self):
"""
Reads a Telegram-encoded byte array, without the need of
specifying its length.
"""
first_byte = self.read_byte()
if first_byte == 254:
length = self.read_byte() | self.read_byte() << 8 | self.read_byte() << 16
padding = length % 4 # depen... |
def calc_requiredremoterelease_v1(self):
"""Guess the required release necessary to not fall below the threshold
value at a cross section far downstream with a certain level of certainty.
Required control parameter:
|RemoteDischargeSafety|
Required derived parameters:
|RemoteDischargeSmoot... | def function[calc_requiredremoterelease_v1, parameter[self]]:
constant[Guess the required release necessary to not fall below the threshold
value at a cross section far downstream with a certain level of certainty.
Required control parameter:
|RemoteDischargeSafety|
Required derived paramete... | keyword[def] identifier[calc_requiredremoterelease_v1] ( identifier[self] ):
literal[string]
identifier[con] = identifier[self] . identifier[parameters] . identifier[control] . identifier[fastaccess]
identifier[der] = identifier[self] . identifier[parameters] . identifier[derived] . identifier[fastac... | def calc_requiredremoterelease_v1(self):
"""Guess the required release necessary to not fall below the threshold
value at a cross section far downstream with a certain level of certainty.
Required control parameter:
|RemoteDischargeSafety|
Required derived parameters:
|RemoteDischargeSmoot... |
def walk_instructions(self, mapping=identity):
"""Iterate over instructions.
:return: an iterator over :class:`instructions in grid
<InstructionInGrid>`
:param mapping: funcion to map the result
.. code:: python
for pos, c in layout.walk_instructions(lambda i: (i... | def function[walk_instructions, parameter[self, mapping]]:
constant[Iterate over instructions.
:return: an iterator over :class:`instructions in grid
<InstructionInGrid>`
:param mapping: funcion to map the result
.. code:: python
for pos, c in layout.walk_instruc... | keyword[def] identifier[walk_instructions] ( identifier[self] , identifier[mapping] = identifier[identity] ):
literal[string]
identifier[instructions] = identifier[chain] (* identifier[self] . identifier[walk_rows] ( keyword[lambda] identifier[row] : identifier[row] . identifier[instructions] ))
... | def walk_instructions(self, mapping=identity):
"""Iterate over instructions.
:return: an iterator over :class:`instructions in grid
<InstructionInGrid>`
:param mapping: funcion to map the result
.. code:: python
for pos, c in layout.walk_instructions(lambda i: (i.xy,... |
def plot_results(
allresults, *,
xy_fn=default_xy_fn,
split_fn=default_split_fn,
group_fn=default_split_fn,
average_group=False,
shaded_std=True,
shaded_err=True,
figsize=None,
legend_outside=False,
resample=0,
smooth_step=1.0
):
'''
Plot multiple Results objects
... | def function[plot_results, parameter[allresults]]:
constant[
Plot multiple Results objects
xy_fn: function Result -> x,y - function that converts results objects into tuple of x and y values.
By default, x is cumsum of episode lengths, and y is ep... | keyword[def] identifier[plot_results] (
identifier[allresults] ,*,
identifier[xy_fn] = identifier[default_xy_fn] ,
identifier[split_fn] = identifier[default_split_fn] ,
identifier[group_fn] = identifier[default_split_fn] ,
identifier[average_group] = keyword[False] ,
identifier[shaded_std] = keyword[True] ,
id... | def plot_results(allresults, *, xy_fn=default_xy_fn, split_fn=default_split_fn, group_fn=default_split_fn, average_group=False, shaded_std=True, shaded_err=True, figsize=None, legend_outside=False, resample=0, smooth_step=1.0):
"""
Plot multiple Results objects
xy_fn: function Result -> x,y - fun... |
def validate(filename):
"""
Use W3C validator service: https://bitbucket.org/nmb10/py_w3c/ .
:param filename: the filename to validate
"""
import HTMLParser
from py_w3c.validators.html.validator import HTMLValidator
h = HTMLParser.HTMLParser() # for unescaping WC3 messages
vld = HTMLV... | def function[validate, parameter[filename]]:
constant[
Use W3C validator service: https://bitbucket.org/nmb10/py_w3c/ .
:param filename: the filename to validate
]
import module[HTMLParser]
from relative_module[py_w3c.validators.html.validator] import module[HTMLValidator]
variable[h... | keyword[def] identifier[validate] ( identifier[filename] ):
literal[string]
keyword[import] identifier[HTMLParser]
keyword[from] identifier[py_w3c] . identifier[validators] . identifier[html] . identifier[validator] keyword[import] identifier[HTMLValidator]
identifier[h] = identifier[HTMLP... | def validate(filename):
"""
Use W3C validator service: https://bitbucket.org/nmb10/py_w3c/ .
:param filename: the filename to validate
"""
import HTMLParser
from py_w3c.validators.html.validator import HTMLValidator
h = HTMLParser.HTMLParser() # for unescaping WC3 messages
vld = HTMLVal... |
def delete(self, key):
"""Delete method of CRUD operation for all data types.
Args:
key (string): The variable to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None:
data = self.db.delete(key.st... | def function[delete, parameter[self, key]]:
constant[Delete method of CRUD operation for all data types.
Args:
key (string): The variable to write to the DB.
Returns:
(string): Result of DB write.
]
variable[data] assign[=] constant[None]
if comp... | keyword[def] identifier[delete] ( identifier[self] , identifier[key] ):
literal[string]
identifier[data] = keyword[None]
keyword[if] identifier[key] keyword[is] keyword[not] keyword[None] :
identifier[data] = identifier[self] . identifier[db] . identifier[delete] ( identi... | def delete(self, key):
"""Delete method of CRUD operation for all data types.
Args:
key (string): The variable to write to the DB.
Returns:
(string): Result of DB write.
"""
data = None
if key is not None:
data = self.db.delete(key.strip()) # depend... |
def get_job_amounts(agent, project_name, spider_name=None):
"""
Get amounts that pending job amount, running job amount, finished job amount.
"""
job_list = agent.get_job_list(project_name)
pending_job_list = job_list['pending']
running_job_list = job_list['running']
finished_job_list = job_... | def function[get_job_amounts, parameter[agent, project_name, spider_name]]:
constant[
Get amounts that pending job amount, running job amount, finished job amount.
]
variable[job_list] assign[=] call[name[agent].get_job_list, parameter[name[project_name]]]
variable[pending_job_list] assi... | keyword[def] identifier[get_job_amounts] ( identifier[agent] , identifier[project_name] , identifier[spider_name] = keyword[None] ):
literal[string]
identifier[job_list] = identifier[agent] . identifier[get_job_list] ( identifier[project_name] )
identifier[pending_job_list] = identifier[job_list] [ li... | def get_job_amounts(agent, project_name, spider_name=None):
"""
Get amounts that pending job amount, running job amount, finished job amount.
"""
job_list = agent.get_job_list(project_name)
pending_job_list = job_list['pending']
running_job_list = job_list['running']
finished_job_list = job_... |
def extend(self, other):
"""
Adds the values from the iterable *other* to the end of this
collection.
"""
def extend_trans(pipe):
values = list(other.__iter__(pipe)) if use_redis else other
len_self = pipe.rpush(self.key, *(self._pickle(v) for v in values)... | def function[extend, parameter[self, other]]:
constant[
Adds the values from the iterable *other* to the end of this
collection.
]
def function[extend_trans, parameter[pipe]]:
variable[values] assign[=] <ast.IfExp object at 0x7da20e9b08b0>
variable... | keyword[def] identifier[extend] ( identifier[self] , identifier[other] ):
literal[string]
keyword[def] identifier[extend_trans] ( identifier[pipe] ):
identifier[values] = identifier[list] ( identifier[other] . identifier[__iter__] ( identifier[pipe] )) keyword[if] identifier[use_redi... | def extend(self, other):
"""
Adds the values from the iterable *other* to the end of this
collection.
"""
def extend_trans(pipe):
values = list(other.__iter__(pipe)) if use_redis else other
len_self = pipe.rpush(self.key, *(self._pickle(v) for v in values))
if se... |
def transfer_causal_edges(graph, source: BaseEntity, target: BaseEntity) -> Iterable[str]:
"""Transfer causal edges that the source has to the target and yield the resulting hashes."""
for _, v, data in graph.out_edges(source, data=True):
if data[RELATION] not in CAUSAL_RELATIONS:
continue
... | def function[transfer_causal_edges, parameter[graph, source, target]]:
constant[Transfer causal edges that the source has to the target and yield the resulting hashes.]
for taget[tuple[[<ast.Name object at 0x7da1b0cb46a0>, <ast.Name object at 0x7da1b0cb78b0>, <ast.Name object at 0x7da1b0cb6c80>]]] in st... | keyword[def] identifier[transfer_causal_edges] ( identifier[graph] , identifier[source] : identifier[BaseEntity] , identifier[target] : identifier[BaseEntity] )-> identifier[Iterable] [ identifier[str] ]:
literal[string]
keyword[for] identifier[_] , identifier[v] , identifier[data] keyword[in] identifie... | def transfer_causal_edges(graph, source: BaseEntity, target: BaseEntity) -> Iterable[str]:
"""Transfer causal edges that the source has to the target and yield the resulting hashes."""
for (_, v, data) in graph.out_edges(source, data=True):
if data[RELATION] not in CAUSAL_RELATIONS:
continue... |
def size(self):
"""Returns total number of gate operations in circuit.
Returns:
int: Total number of gate operations.
"""
gate_ops = 0
for instr, _, _ in self.data:
if instr.name not in ['barrier', 'snapshot']:
gate_ops += 1
return... | def function[size, parameter[self]]:
constant[Returns total number of gate operations in circuit.
Returns:
int: Total number of gate operations.
]
variable[gate_ops] assign[=] constant[0]
for taget[tuple[[<ast.Name object at 0x7da1b0535b40>, <ast.Name object at 0x7da... | keyword[def] identifier[size] ( identifier[self] ):
literal[string]
identifier[gate_ops] = literal[int]
keyword[for] identifier[instr] , identifier[_] , identifier[_] keyword[in] identifier[self] . identifier[data] :
keyword[if] identifier[instr] . identifier[name] keywo... | def size(self):
"""Returns total number of gate operations in circuit.
Returns:
int: Total number of gate operations.
"""
gate_ops = 0
for (instr, _, _) in self.data:
if instr.name not in ['barrier', 'snapshot']:
gate_ops += 1 # depends on [control=['if'], d... |
def root_sa_root_access(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
root_sa = ET.SubElement(config, "root-sa", xmlns="urn:brocade.com:mgmt:brocade-aaa")
root = ET.SubElement(root_sa, "root")
access = ET.SubElement(root, "access")
acce... | def function[root_sa_root_access, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[root_sa] assign[=] call[name[ET].SubElement, parameter[name[config], constant[root-sa]]]
variable[root] assig... | keyword[def] identifier[root_sa_root_access] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[root_sa] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , ide... | def root_sa_root_access(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
root_sa = ET.SubElement(config, 'root-sa', xmlns='urn:brocade.com:mgmt:brocade-aaa')
root = ET.SubElement(root_sa, 'root')
access = ET.SubElement(root, 'access')
access.text = kwargs.pop('ac... |
def recv_msg(body,
message):
"""recv_msg
Handler method - fires when a messages is consumed from
the ``FORWARD_QUEUE`` queue running in the ``FORWARD_BROKER_URL``
broker.
:param body: message body
:param message: message object can ack, requeue or reject
"""
log.info(("ca... | def function[recv_msg, parameter[body, message]]:
constant[recv_msg
Handler method - fires when a messages is consumed from
the ``FORWARD_QUEUE`` queue running in the ``FORWARD_BROKER_URL``
broker.
:param body: message body
:param message: message object can ack, requeue or reject
]
... | keyword[def] identifier[recv_msg] ( identifier[body] ,
identifier[message] ):
literal[string]
identifier[log] . identifier[info] (( literal[string] ))
identifier[agg] . identifier[handle_msg] (
identifier[body] = identifier[body] ,
identifier[org_message] = identifier[message] ) | def recv_msg(body, message):
"""recv_msg
Handler method - fires when a messages is consumed from
the ``FORWARD_QUEUE`` queue running in the ``FORWARD_BROKER_URL``
broker.
:param body: message body
:param message: message object can ack, requeue or reject
"""
log.info('callback received... |
def _GetVal(self, obj, key):
"""Recurse down an attribute chain to the actual result data."""
if "." in key:
lhs, rhs = key.split(".", 1)
obj2 = getattr(obj, lhs, None)
if obj2 is None:
return None
return self._GetVal(obj2, rhs)
else:
return getattr(obj, key, None) | def function[_GetVal, parameter[self, obj, key]]:
constant[Recurse down an attribute chain to the actual result data.]
if compare[constant[.] in name[key]] begin[:]
<ast.Tuple object at 0x7da1b1c1aa70> assign[=] call[name[key].split, parameter[constant[.], constant[1]]]
v... | keyword[def] identifier[_GetVal] ( identifier[self] , identifier[obj] , identifier[key] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[key] :
identifier[lhs] , identifier[rhs] = identifier[key] . identifier[split] ( literal[string] , literal[int] )
identifier[obj2] =... | def _GetVal(self, obj, key):
"""Recurse down an attribute chain to the actual result data."""
if '.' in key:
(lhs, rhs) = key.split('.', 1)
obj2 = getattr(obj, lhs, None)
if obj2 is None:
return None # depends on [control=['if'], data=[]]
return self._GetVal(obj2, rh... |
def set_centralized_assembled_values(self, a):
"""Set assembled matrix values on processor 0."""
if self.myid != 0:
return
assert a.size == self.id.nz
self._refs.update(a=a)
self.id.a = self.cast_array(a) | def function[set_centralized_assembled_values, parameter[self, a]]:
constant[Set assembled matrix values on processor 0.]
if compare[name[self].myid not_equal[!=] constant[0]] begin[:]
return[None]
assert[compare[name[a].size equal[==] name[self].id.nz]]
call[name[self]._refs.update,... | keyword[def] identifier[set_centralized_assembled_values] ( identifier[self] , identifier[a] ):
literal[string]
keyword[if] identifier[self] . identifier[myid] != literal[int] :
keyword[return]
keyword[assert] identifier[a] . identifier[size] == identifier[self] . identifie... | def set_centralized_assembled_values(self, a):
"""Set assembled matrix values on processor 0."""
if self.myid != 0:
return # depends on [control=['if'], data=[]]
assert a.size == self.id.nz
self._refs.update(a=a)
self.id.a = self.cast_array(a) |
def delete(args):
"""Delete NApps from server."""
mgr = NAppsManager()
for napp in args['<napp>']:
mgr.set_napp(*napp)
LOG.info('Deleting NApp %s from server...', mgr.napp_id)
try:
mgr.delete()
LOG.info(' Deleted.')
... | def function[delete, parameter[args]]:
constant[Delete NApps from server.]
variable[mgr] assign[=] call[name[NAppsManager], parameter[]]
for taget[name[napp]] in starred[call[name[args]][constant[<napp>]]] begin[:]
call[name[mgr].set_napp, parameter[<ast.Starred object at 0x7da20... | keyword[def] identifier[delete] ( identifier[args] ):
literal[string]
identifier[mgr] = identifier[NAppsManager] ()
keyword[for] identifier[napp] keyword[in] identifier[args] [ literal[string] ]:
identifier[mgr] . identifier[set_napp] (* identifier[napp] )
iden... | def delete(args):
"""Delete NApps from server."""
mgr = NAppsManager()
for napp in args['<napp>']:
mgr.set_napp(*napp)
LOG.info('Deleting NApp %s from server...', mgr.napp_id)
try:
mgr.delete()
LOG.info(' Deleted.') # depends on [control=['try'], data=[]]
... |
def update_record(self, domain, record, data=None, priority=None, ttl=None,
comment=None):
"""
Modifies an existing record for a domain.
"""
return domain.update_record(record, data=data, priority=priority,
ttl=ttl, comment=comment) | def function[update_record, parameter[self, domain, record, data, priority, ttl, comment]]:
constant[
Modifies an existing record for a domain.
]
return[call[name[domain].update_record, parameter[name[record]]]] | keyword[def] identifier[update_record] ( identifier[self] , identifier[domain] , identifier[record] , identifier[data] = keyword[None] , identifier[priority] = keyword[None] , identifier[ttl] = keyword[None] ,
identifier[comment] = keyword[None] ):
literal[string]
keyword[return] identifier[domai... | def update_record(self, domain, record, data=None, priority=None, ttl=None, comment=None):
"""
Modifies an existing record for a domain.
"""
return domain.update_record(record, data=data, priority=priority, ttl=ttl, comment=comment) |
def _validate_tileset(self, tileset):
"""Validate the tileset name and
ensure that it includes the username
"""
if '.' not in tileset:
tileset = "{0}.{1}".format(self.username, tileset)
pattern = '^[a-z0-9-_]{1,32}\.[a-z0-9-_]{1,32}$'
if not re.match(pattern,... | def function[_validate_tileset, parameter[self, tileset]]:
constant[Validate the tileset name and
ensure that it includes the username
]
if compare[constant[.] <ast.NotIn object at 0x7da2590d7190> name[tileset]] begin[:]
variable[tileset] assign[=] call[constant[{0}.{1}].... | keyword[def] identifier[_validate_tileset] ( identifier[self] , identifier[tileset] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[tileset] :
identifier[tileset] = literal[string] . identifier[format] ( identifier[self] . identifier[username] , i... | def _validate_tileset(self, tileset):
"""Validate the tileset name and
ensure that it includes the username
"""
if '.' not in tileset:
tileset = '{0}.{1}'.format(self.username, tileset) # depends on [control=['if'], data=['tileset']]
pattern = '^[a-z0-9-_]{1,32}\\.[a-z0-9-_]{1,32}$'... |
def authenticate(self, transport, account_name, password=None):
"""
Authenticates account using soap method.
"""
Authenticator.authenticate(self, transport, account_name, password)
if password == None:
return self.pre_auth(transport, account_name)
else:
... | def function[authenticate, parameter[self, transport, account_name, password]]:
constant[
Authenticates account using soap method.
]
call[name[Authenticator].authenticate, parameter[name[self], name[transport], name[account_name], name[password]]]
if compare[name[password] equal[... | keyword[def] identifier[authenticate] ( identifier[self] , identifier[transport] , identifier[account_name] , identifier[password] = keyword[None] ):
literal[string]
identifier[Authenticator] . identifier[authenticate] ( identifier[self] , identifier[transport] , identifier[account_name] , identifi... | def authenticate(self, transport, account_name, password=None):
"""
Authenticates account using soap method.
"""
Authenticator.authenticate(self, transport, account_name, password)
if password == None:
return self.pre_auth(transport, account_name) # depends on [control=['if'], data=... |
def send(self, obj):
"""Send object"""
buf = io.BytesIO()
ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj)
self.send_bytes(buf.getvalue()) | def function[send, parameter[self, obj]]:
constant[Send object]
variable[buf] assign[=] call[name[io].BytesIO, parameter[]]
call[call[name[ForkingPickler], parameter[name[buf], name[pickle].HIGHEST_PROTOCOL]].dump, parameter[name[obj]]]
call[name[self].send_bytes, parameter[call[name[buf... | keyword[def] identifier[send] ( identifier[self] , identifier[obj] ):
literal[string]
identifier[buf] = identifier[io] . identifier[BytesIO] ()
identifier[ForkingPickler] ( identifier[buf] , identifier[pickle] . identifier[HIGHEST_PROTOCOL] ). identifier[dump] ( identifier[obj] )
... | def send(self, obj):
"""Send object"""
buf = io.BytesIO()
ForkingPickler(buf, pickle.HIGHEST_PROTOCOL).dump(obj)
self.send_bytes(buf.getvalue()) |
async def set_chat_description(self, chat_id: typing.Union[base.Integer, base.String],
description: typing.Union[base.String, None] = None) -> base.Boolean:
"""
Use this method to change the description of a supergroup or a channel.
The bot must be an administr... | <ast.AsyncFunctionDef object at 0x7da1b17a94e0> | keyword[async] keyword[def] identifier[set_chat_description] ( identifier[self] , identifier[chat_id] : identifier[typing] . identifier[Union] [ identifier[base] . identifier[Integer] , identifier[base] . identifier[String] ],
identifier[description] : identifier[typing] . identifier[Union] [ identifier[base] . ide... | async def set_chat_description(self, chat_id: typing.Union[base.Integer, base.String], description: typing.Union[base.String, None]=None) -> base.Boolean:
"""
Use this method to change the description of a supergroup or a channel.
The bot must be an administrator in the chat for this to work and mus... |
def average_fft(self, fftlength=None, overlap=0, window=None):
"""Compute the averaged one-dimensional DFT of this `TimeSeries`.
This method computes a number of FFTs of duration ``fftlength``
and ``overlap`` (both given in seconds), and returns the mean
average. This method is analogou... | def function[average_fft, parameter[self, fftlength, overlap, window]]:
constant[Compute the averaged one-dimensional DFT of this `TimeSeries`.
This method computes a number of FFTs of duration ``fftlength``
and ``overlap`` (both given in seconds), and returns the mean
average. This met... | keyword[def] identifier[average_fft] ( identifier[self] , identifier[fftlength] = keyword[None] , identifier[overlap] = literal[int] , identifier[window] = keyword[None] ):
literal[string]
keyword[from] identifier[gwpy] . identifier[spectrogram] keyword[import] identifier[Spectrogram]
... | def average_fft(self, fftlength=None, overlap=0, window=None):
"""Compute the averaged one-dimensional DFT of this `TimeSeries`.
This method computes a number of FFTs of duration ``fftlength``
and ``overlap`` (both given in seconds), and returns the mean
average. This method is analogous to... |
def purge_db(self):
"""
Purge all database records for the current user.
"""
with self.engine.begin() as db:
purge_remote_checkpoints(db, self.user_id) | def function[purge_db, parameter[self]]:
constant[
Purge all database records for the current user.
]
with call[name[self].engine.begin, parameter[]] begin[:]
call[name[purge_remote_checkpoints], parameter[name[db], name[self].user_id]] | keyword[def] identifier[purge_db] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[engine] . identifier[begin] () keyword[as] identifier[db] :
identifier[purge_remote_checkpoints] ( identifier[db] , identifier[self] . identifier[user_id] ) | def purge_db(self):
"""
Purge all database records for the current user.
"""
with self.engine.begin() as db:
purge_remote_checkpoints(db, self.user_id) # depends on [control=['with'], data=['db']] |
def keyserverprefs(self):
"""
A ``list`` of :py:obj:`~constants.KeyServerPreferences` in this signature, if any. Otherwise, an empty ``list``.
"""
if 'KeyServerPreferences' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_KeyServerPreferences'])).... | def function[keyserverprefs, parameter[self]]:
constant[
A ``list`` of :py:obj:`~constants.KeyServerPreferences` in this signature, if any. Otherwise, an empty ``list``.
]
if compare[constant[KeyServerPreferences] in name[self]._signature.subpackets] begin[:]
return[call[name[nex... | keyword[def] identifier[keyserverprefs] ( identifier[self] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[self] . identifier[_signature] . identifier[subpackets] :
keyword[return] identifier[next] ( identifier[iter] ( identifier[self] . identifier[_signature]... | def keyserverprefs(self):
"""
A ``list`` of :py:obj:`~constants.KeyServerPreferences` in this signature, if any. Otherwise, an empty ``list``.
"""
if 'KeyServerPreferences' in self._signature.subpackets:
return next(iter(self._signature.subpackets['h_KeyServerPreferences'])).flags # dep... |
def segment(text: str, custom_dict: Trie = None) -> List[str]:
"""
Dictionary-based word segmentation, using maximal matching algorithm and Thai Character Cluster
:param str text: text to be tokenized to words
:return: list of words, tokenized from the text
"""
if not text or not isinstance(text... | def function[segment, parameter[text, custom_dict]]:
constant[
Dictionary-based word segmentation, using maximal matching algorithm and Thai Character Cluster
:param str text: text to be tokenized to words
:return: list of words, tokenized from the text
]
if <ast.BoolOp object at 0x7da1b... | keyword[def] identifier[segment] ( identifier[text] : identifier[str] , identifier[custom_dict] : identifier[Trie] = keyword[None] )-> identifier[List] [ identifier[str] ]:
literal[string]
keyword[if] keyword[not] identifier[text] keyword[or] keyword[not] identifier[isinstance] ( identifier[text] , id... | def segment(text: str, custom_dict: Trie=None) -> List[str]:
"""
Dictionary-based word segmentation, using maximal matching algorithm and Thai Character Cluster
:param str text: text to be tokenized to words
:return: list of words, tokenized from the text
"""
if not text or not isinstance(text, ... |
def close(self):
"""Close this connection."""
logger('HttpConnection').debug('Closing connection....')
self.writer.close()
self._closed = True | def function[close, parameter[self]]:
constant[Close this connection.]
call[call[name[logger], parameter[constant[HttpConnection]]].debug, parameter[constant[Closing connection....]]]
call[name[self].writer.close, parameter[]]
name[self]._closed assign[=] constant[True] | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[logger] ( literal[string] ). identifier[debug] ( literal[string] )
identifier[self] . identifier[writer] . identifier[close] ()
identifier[self] . identifier[_closed] = keyword[True] | def close(self):
"""Close this connection."""
logger('HttpConnection').debug('Closing connection....')
self.writer.close()
self._closed = True |
def render_log_filename(ti, try_number, filename_template):
"""
Given task instance, try_number, filename_template, return the rendered log
filename
:param ti: task instance
:param try_number: try_number of the task
:param filename_template: filename template, which can be jinja template or
... | def function[render_log_filename, parameter[ti, try_number, filename_template]]:
constant[
Given task instance, try_number, filename_template, return the rendered log
filename
:param ti: task instance
:param try_number: try_number of the task
:param filename_template: filename template, whi... | keyword[def] identifier[render_log_filename] ( identifier[ti] , identifier[try_number] , identifier[filename_template] ):
literal[string]
identifier[filename_template] , identifier[filename_jinja_template] = identifier[parse_template_string] ( identifier[filename_template] )
keyword[if] identifier[fi... | def render_log_filename(ti, try_number, filename_template):
"""
Given task instance, try_number, filename_template, return the rendered log
filename
:param ti: task instance
:param try_number: try_number of the task
:param filename_template: filename template, which can be jinja template or
... |
def push_notebook(document=None, state=None, handle=None):
''' Update Bokeh plots in a Jupyter notebook output cells with new data
or property values.
When working the the notebook, the ``show`` function can be passed the
argument ``notebook_handle=True``, which will cause it to return a
handle obj... | def function[push_notebook, parameter[document, state, handle]]:
constant[ Update Bokeh plots in a Jupyter notebook output cells with new data
or property values.
When working the the notebook, the ``show`` function can be passed the
argument ``notebook_handle=True``, which will cause it to return ... | keyword[def] identifier[push_notebook] ( identifier[document] = keyword[None] , identifier[state] = keyword[None] , identifier[handle] = keyword[None] ):
literal[string]
keyword[from] .. identifier[protocol] keyword[import] identifier[Protocol]
keyword[if] identifier[state] keyword[is] keyword[... | def push_notebook(document=None, state=None, handle=None):
""" Update Bokeh plots in a Jupyter notebook output cells with new data
or property values.
When working the the notebook, the ``show`` function can be passed the
argument ``notebook_handle=True``, which will cause it to return a
handle obj... |
def connect(self, *, db=None):
"""
Attempt to connect to device. If unable, attempt to connect to a controller database
(so the user can use previously saved data).
"""
if not self.properties.network:
self.new_state(DeviceFromDB)
else:
t... | def function[connect, parameter[self]]:
constant[
Attempt to connect to device. If unable, attempt to connect to a controller database
(so the user can use previously saved data).
]
if <ast.UnaryOp object at 0x7da1b040a020> begin[:]
call[name[self].new_state, p... | keyword[def] identifier[connect] ( identifier[self] ,*, identifier[db] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[properties] . identifier[network] :
identifier[self] . identifier[new_state] ( identifier[DeviceFromDB] )
keyw... | def connect(self, *, db=None):
"""
Attempt to connect to device. If unable, attempt to connect to a controller database
(so the user can use previously saved data).
"""
if not self.properties.network:
self.new_state(DeviceFromDB) # depends on [control=['if'], data=[]]
els... |
def clean_locks(root=None):
'''
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
'''
LCK = "removed"
out = {LCK: 0}... | def function[clean_locks, parameter[root]]:
constant[
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
]
variab... | keyword[def] identifier[clean_locks] ( identifier[root] = keyword[None] ):
literal[string]
identifier[LCK] = literal[string]
identifier[out] ={ identifier[LCK] : literal[int] }
identifier[locks] = identifier[os] . identifier[path] . identifier[join] ( identifier[root] , identifier[os] . identifi... | def clean_locks(root=None):
"""
Remove unused locks that do not currently (with regard to repositories
used) lock any package.
root
Operate on a different root directory.
CLI Example:
.. code-block:: bash
salt '*' pkg.clean_locks
"""
LCK = 'removed'
out = {LCK: 0}... |
def make(keyvals):
"""
Create new H2OTwoDimTable object from list of (key,value) tuples which are a pre-cursor to JSON dict.
:param keyvals: list of (key, value) tuples
:return: new H2OTwoDimTable object
"""
kwargs = {}
for key, value in keyvals:
if k... | def function[make, parameter[keyvals]]:
constant[
Create new H2OTwoDimTable object from list of (key,value) tuples which are a pre-cursor to JSON dict.
:param keyvals: list of (key, value) tuples
:return: new H2OTwoDimTable object
]
variable[kwargs] assign[=] dictionary[... | keyword[def] identifier[make] ( identifier[keyvals] ):
literal[string]
identifier[kwargs] ={}
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[keyvals] :
keyword[if] identifier[key] == literal[string] :
identifier[kwargs] [ literal[s... | def make(keyvals):
"""
Create new H2OTwoDimTable object from list of (key,value) tuples which are a pre-cursor to JSON dict.
:param keyvals: list of (key, value) tuples
:return: new H2OTwoDimTable object
"""
kwargs = {}
for (key, value) in keyvals:
if key == 'columns... |
def bundles():
"""Display bundles."""
per_page = int(request.args.get('per_page', 30))
page = int(request.args.get('page', 1))
query = store.bundles()
query_page = query.paginate(page, per_page=per_page)
data = []
for bundle_obj in query_page.items:
bundle_data = bundle_obj.to_dict(... | def function[bundles, parameter[]]:
constant[Display bundles.]
variable[per_page] assign[=] call[name[int], parameter[call[name[request].args.get, parameter[constant[per_page], constant[30]]]]]
variable[page] assign[=] call[name[int], parameter[call[name[request].args.get, parameter[constant[pag... | keyword[def] identifier[bundles] ():
literal[string]
identifier[per_page] = identifier[int] ( identifier[request] . identifier[args] . identifier[get] ( literal[string] , literal[int] ))
identifier[page] = identifier[int] ( identifier[request] . identifier[args] . identifier[get] ( literal[string] , l... | def bundles():
"""Display bundles."""
per_page = int(request.args.get('per_page', 30))
page = int(request.args.get('page', 1))
query = store.bundles()
query_page = query.paginate(page, per_page=per_page)
data = []
for bundle_obj in query_page.items:
bundle_data = bundle_obj.to_dict()... |
def daemons_stop(self, timeout=30, kill_children=False):
"""Stop the Alignak daemons
Iterate over the self-launched daemons and their children list to send a TERM
Wait for daemons to terminate and then send a KILL for those that are not yet stopped
As a default behavior, only the la... | def function[daemons_stop, parameter[self, timeout, kill_children]]:
constant[Stop the Alignak daemons
Iterate over the self-launched daemons and their children list to send a TERM
Wait for daemons to terminate and then send a KILL for those that are not yet stopped
As a default beh... | keyword[def] identifier[daemons_stop] ( identifier[self] , identifier[timeout] = literal[int] , identifier[kill_children] = keyword[False] ):
literal[string]
keyword[def] identifier[on_terminate] ( identifier[proc] ):
literal[string]
identifier[logger] . identifier[debug... | def daemons_stop(self, timeout=30, kill_children=False):
"""Stop the Alignak daemons
Iterate over the self-launched daemons and their children list to send a TERM
Wait for daemons to terminate and then send a KILL for those that are not yet stopped
As a default behavior, only the launch... |
def get_json(self):
""" Gets market chart data from today to a previous date """
today = dt.now()
DIRECTION = 'last'
epochs = date.get_end_start_epochs(today.year, today.month, today.day,
DIRECTION, self.unit, self.count)
return poloniex... | def function[get_json, parameter[self]]:
constant[ Gets market chart data from today to a previous date ]
variable[today] assign[=] call[name[dt].now, parameter[]]
variable[DIRECTION] assign[=] constant[last]
variable[epochs] assign[=] call[name[date].get_end_start_epochs, parameter[name... | keyword[def] identifier[get_json] ( identifier[self] ):
literal[string]
identifier[today] = identifier[dt] . identifier[now] ()
identifier[DIRECTION] = literal[string]
identifier[epochs] = identifier[date] . identifier[get_end_start_epochs] ( identifier[today] . identifier[year] ... | def get_json(self):
""" Gets market chart data from today to a previous date """
today = dt.now()
DIRECTION = 'last'
epochs = date.get_end_start_epochs(today.year, today.month, today.day, DIRECTION, self.unit, self.count)
return poloniex.chart_json(epochs['shifted'], epochs['initial'], self.period, ... |
def _set_default_format(self, vmin, vmax):
"Returns the default ticks spacing."
if self.plot_obj.date_axis_info is None:
self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq)
info = self.plot_obj.date_axis_info
if self.isminor:
format = np.compress(i... | def function[_set_default_format, parameter[self, vmin, vmax]]:
constant[Returns the default ticks spacing.]
if compare[name[self].plot_obj.date_axis_info is constant[None]] begin[:]
name[self].plot_obj.date_axis_info assign[=] call[name[self].finder, parameter[name[vmin], name[vmax], na... | keyword[def] identifier[_set_default_format] ( identifier[self] , identifier[vmin] , identifier[vmax] ):
literal[string]
keyword[if] identifier[self] . identifier[plot_obj] . identifier[date_axis_info] keyword[is] keyword[None] :
identifier[self] . identifier[plot_obj] . identifier... | def _set_default_format(self, vmin, vmax):
"""Returns the default ticks spacing."""
if self.plot_obj.date_axis_info is None:
self.plot_obj.date_axis_info = self.finder(vmin, vmax, self.freq) # depends on [control=['if'], data=[]]
info = self.plot_obj.date_axis_info
if self.isminor:
form... |
def image_resize(file_paths, new_dir, width, height):
'''Resizes all images with given paths to new dimensions.
Uses up/downscaling with antialiasing.
Parameters
----------
file_paths : List[str]
List of path strings for image to resize.
new_dir : str
Directory to place resi... | def function[image_resize, parameter[file_paths, new_dir, width, height]]:
constant[Resizes all images with given paths to new dimensions.
Uses up/downscaling with antialiasing.
Parameters
----------
file_paths : List[str]
List of path strings for image to resize.
new_dir : str
... | keyword[def] identifier[image_resize] ( identifier[file_paths] , identifier[new_dir] , identifier[width] , identifier[height] ):
literal[string]
keyword[if] identifier[new_dir] [- literal[int] ]!= literal[string] :
identifier[new_dir] += literal[string]
keyword[if] keyword[not] identifie... | def image_resize(file_paths, new_dir, width, height):
"""Resizes all images with given paths to new dimensions.
Uses up/downscaling with antialiasing.
Parameters
----------
file_paths : List[str]
List of path strings for image to resize.
new_dir : str
Directory to place resi... |
def link_down(self, ofp_port):
""" DESIGNATED_PORT/NON_DESIGNATED_PORT: change status to DISABLE.
ROOT_PORT: change status to DISABLE and recalculate STP. """
port = self.ports[ofp_port.port_no]
init_stp_flg = bool(port.role is ROOT_PORT)
port.down(PORT_STATE_DISABLE, msg_in... | def function[link_down, parameter[self, ofp_port]]:
constant[ DESIGNATED_PORT/NON_DESIGNATED_PORT: change status to DISABLE.
ROOT_PORT: change status to DISABLE and recalculate STP. ]
variable[port] assign[=] call[name[self].ports][name[ofp_port].port_no]
variable[init_stp_flg] assig... | keyword[def] identifier[link_down] ( identifier[self] , identifier[ofp_port] ):
literal[string]
identifier[port] = identifier[self] . identifier[ports] [ identifier[ofp_port] . identifier[port_no] ]
identifier[init_stp_flg] = identifier[bool] ( identifier[port] . identifier[role] keyword[... | def link_down(self, ofp_port):
""" DESIGNATED_PORT/NON_DESIGNATED_PORT: change status to DISABLE.
ROOT_PORT: change status to DISABLE and recalculate STP. """
port = self.ports[ofp_port.port_no]
init_stp_flg = bool(port.role is ROOT_PORT)
port.down(PORT_STATE_DISABLE, msg_init=True)
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.