code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def load(self, line):
"""Load this keyword from a file-like object"""
words = line.split()
try:
float(words[0])
self.__name = ""
self.__value = " ".join(words)
except ValueError:
self.__name = words[0].upper()
if len(words) > 2 ... | def function[load, parameter[self, line]]:
constant[Load this keyword from a file-like object]
variable[words] assign[=] call[name[line].split, parameter[]]
<ast.Try object at 0x7da20c6aad70> | keyword[def] identifier[load] ( identifier[self] , identifier[line] ):
literal[string]
identifier[words] = identifier[line] . identifier[split] ()
keyword[try] :
identifier[float] ( identifier[words] [ literal[int] ])
identifier[self] . identifier[__name] = litera... | def load(self, line):
"""Load this keyword from a file-like object"""
words = line.split()
try:
float(words[0])
self.__name = ''
self.__value = ' '.join(words) # depends on [control=['try'], data=[]]
except ValueError:
self.__name = words[0].upper()
if len(words)... |
def extract_version_number(string: str) -> str:
"""
Extracts a version from a string in the form: `.*[0-9]+(_[0-9]+)*.*`, e.g. Irods4_1_9CompatibleController.
If the string contains multiple version numbers, the first (from left) is extracted.
Will raise a `ValueError` if there is no version number in... | def function[extract_version_number, parameter[string]]:
constant[
Extracts a version from a string in the form: `.*[0-9]+(_[0-9]+)*.*`, e.g. Irods4_1_9CompatibleController.
If the string contains multiple version numbers, the first (from left) is extracted.
Will raise a `ValueError` if there is n... | keyword[def] identifier[extract_version_number] ( identifier[string] : identifier[str] )-> identifier[str] :
literal[string]
identifier[matched] = identifier[_EXTRACT_VERSION_PATTERN] . identifier[search] ( identifier[string] )
keyword[if] identifier[matched] keyword[is] keyword[None] :
ke... | def extract_version_number(string: str) -> str:
"""
Extracts a version from a string in the form: `.*[0-9]+(_[0-9]+)*.*`, e.g. Irods4_1_9CompatibleController.
If the string contains multiple version numbers, the first (from left) is extracted.
Will raise a `ValueError` if there is no version number in... |
def configure(self, reboot=1):
"""
Assigns a name to the server accessible from user space.
Note, we add the name to /etc/hosts since not all programs use
/etc/hostname to reliably identify the server hostname.
"""
r = self.local_renderer
for ip, hostname in self... | def function[configure, parameter[self, reboot]]:
constant[
Assigns a name to the server accessible from user space.
Note, we add the name to /etc/hosts since not all programs use
/etc/hostname to reliably identify the server hostname.
]
variable[r] assign[=] name[self].... | keyword[def] identifier[configure] ( identifier[self] , identifier[reboot] = literal[int] ):
literal[string]
identifier[r] = identifier[self] . identifier[local_renderer]
keyword[for] identifier[ip] , identifier[hostname] keyword[in] identifier[self] . identifier[iter_hostnames] ():
... | def configure(self, reboot=1):
"""
Assigns a name to the server accessible from user space.
Note, we add the name to /etc/hosts since not all programs use
/etc/hostname to reliably identify the server hostname.
"""
r = self.local_renderer
for (ip, hostname) in self.iter_host... |
def prefetch_related(self, *args: str) -> "QuerySet":
"""
Like ``.fetch_related()`` on instance, but works on all objects in QuerySet.
"""
queryset = self._clone()
queryset._prefetch_map = {}
for relation in args:
if isinstance(relation, Prefetch):
... | def function[prefetch_related, parameter[self]]:
constant[
Like ``.fetch_related()`` on instance, but works on all objects in QuerySet.
]
variable[queryset] assign[=] call[name[self]._clone, parameter[]]
name[queryset]._prefetch_map assign[=] dictionary[[], []]
for taget[... | keyword[def] identifier[prefetch_related] ( identifier[self] ,* identifier[args] : identifier[str] )-> literal[string] :
literal[string]
identifier[queryset] = identifier[self] . identifier[_clone] ()
identifier[queryset] . identifier[_prefetch_map] ={}
keyword[for] identifier[r... | def prefetch_related(self, *args: str) -> 'QuerySet':
"""
Like ``.fetch_related()`` on instance, but works on all objects in QuerySet.
"""
queryset = self._clone()
queryset._prefetch_map = {}
for relation in args:
if isinstance(relation, Prefetch):
relation.resolve_fo... |
def non_fluents_scope(self) -> Dict[str, TensorFluent]:
'''Returns a partial scope with non-fluents.
Returns:
A mapping from non-fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
'''
if self.__dict__.get('non_fluents') is None:
self._initialize_non_fluents()
... | def function[non_fluents_scope, parameter[self]]:
constant[Returns a partial scope with non-fluents.
Returns:
A mapping from non-fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
]
if compare[call[name[self].__dict__.get, parameter[constant[non_fluents]]] is constant[None]... | keyword[def] identifier[non_fluents_scope] ( identifier[self] )-> identifier[Dict] [ identifier[str] , identifier[TensorFluent] ]:
literal[string]
keyword[if] identifier[self] . identifier[__dict__] . identifier[get] ( literal[string] ) keyword[is] keyword[None] :
identifier[self] . ... | def non_fluents_scope(self) -> Dict[str, TensorFluent]:
"""Returns a partial scope with non-fluents.
Returns:
A mapping from non-fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
"""
if self.__dict__.get('non_fluents') is None:
self._initialize_non_fluents() # depends on ... |
def get_args(obj):
"""Get a list of argument names for a callable."""
if inspect.isfunction(obj):
return inspect.getargspec(obj).args
elif inspect.ismethod(obj):
return inspect.getargspec(obj).args[1:]
elif inspect.isclass(obj):
return inspect.getargspec(obj.__init__).args[1:]
... | def function[get_args, parameter[obj]]:
constant[Get a list of argument names for a callable.]
if call[name[inspect].isfunction, parameter[name[obj]]] begin[:]
return[call[name[inspect].getargspec, parameter[name[obj]]].args] | keyword[def] identifier[get_args] ( identifier[obj] ):
literal[string]
keyword[if] identifier[inspect] . identifier[isfunction] ( identifier[obj] ):
keyword[return] identifier[inspect] . identifier[getargspec] ( identifier[obj] ). identifier[args]
keyword[elif] identifier[inspect] . ident... | def get_args(obj):
"""Get a list of argument names for a callable."""
if inspect.isfunction(obj):
return inspect.getargspec(obj).args # depends on [control=['if'], data=[]]
elif inspect.ismethod(obj):
return inspect.getargspec(obj).args[1:] # depends on [control=['if'], data=[]]
elif i... |
def read(self, size=None):
"""Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
re... | def function[read, parameter[self, size]]:
constant[Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, wher... | keyword[def] identifier[read] ( identifier[self] , identifier[size] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_is_open] :
keyword[raise] identifier[IOError] ( literal[string] )
keyword[if] identifier[self] . identifier[_fsntfs_data_stream] :
... | def read(self, size=None):
"""Reads a byte string from the file-like object at the current offset.
The function will read a byte string of the specified size or
all of the remaining data if no size was specified.
Args:
size (Optional[int]): number of bytes to read, where None is all
re... |
def setup_completer(cls):
"Get the dictionary of valid completions"
try:
for element in Store.options().keys():
options = Store.options()['.'.join(element)]
plotkws = options['plot'].allowed_keywords
stylekws = options['style'].allowed_keywords... | def function[setup_completer, parameter[cls]]:
constant[Get the dictionary of valid completions]
<ast.Try object at 0x7da1b1c66ce0>
return[name[cls]._completions] | keyword[def] identifier[setup_completer] ( identifier[cls] ):
literal[string]
keyword[try] :
keyword[for] identifier[element] keyword[in] identifier[Store] . identifier[options] (). identifier[keys] ():
identifier[options] = identifier[Store] . identifier[options] (... | def setup_completer(cls):
"""Get the dictionary of valid completions"""
try:
for element in Store.options().keys():
options = Store.options()['.'.join(element)]
plotkws = options['plot'].allowed_keywords
stylekws = options['style'].allowed_keywords
dotted ... |
def quoteDF(symbol, token='', version=''):
'''Get quote for ticker
https://iexcloud.io/docs/api/#quote
4:30am-8pm ET Mon-Fri
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
'''
... | def function[quoteDF, parameter[symbol, token, version]]:
constant[Get quote for ticker
https://iexcloud.io/docs/api/#quote
4:30am-8pm ET Mon-Fri
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataF... | keyword[def] identifier[quoteDF] ( identifier[symbol] , identifier[token] = literal[string] , identifier[version] = literal[string] ):
literal[string]
identifier[q] = identifier[quote] ( identifier[symbol] , identifier[token] , identifier[version] )
keyword[if] identifier[q] :
identifier[df]... | def quoteDF(symbol, token='', version=''):
"""Get quote for ticker
https://iexcloud.io/docs/api/#quote
4:30am-8pm ET Mon-Fri
Args:
symbol (string); Ticker to request
token (string); Access token
version (string); API version
Returns:
DataFrame: result
"""
... |
def assign_routes(self, app):
"""Register routes with the app."""
for grp in self.filters:
for f in self.filters[grp]:
if f.route_func:
f.register_route(app)
for c in self.charts:
if c.route_func:
c.register_route(app) | def function[assign_routes, parameter[self, app]]:
constant[Register routes with the app.]
for taget[name[grp]] in starred[name[self].filters] begin[:]
for taget[name[f]] in starred[call[name[self].filters][name[grp]]] begin[:]
if name[f].route_func begin[:]
... | keyword[def] identifier[assign_routes] ( identifier[self] , identifier[app] ):
literal[string]
keyword[for] identifier[grp] keyword[in] identifier[self] . identifier[filters] :
keyword[for] identifier[f] keyword[in] identifier[self] . identifier[filters] [ identifier[grp] ]:
... | def assign_routes(self, app):
"""Register routes with the app."""
for grp in self.filters:
for f in self.filters[grp]:
if f.route_func:
f.register_route(app) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['f']] # depends on [control=['for'], da... |
def MergeMembers(self):
"""Add shadow group members to the group if gshadow is used.
Normally group and shadow should be in sync, but no guarantees. Merges the
two stores as membership in either file may confer membership.
"""
for group_name, members in iteritems(self.gshadow_members):
group ... | def function[MergeMembers, parameter[self]]:
constant[Add shadow group members to the group if gshadow is used.
Normally group and shadow should be in sync, but no guarantees. Merges the
two stores as membership in either file may confer membership.
]
for taget[tuple[[<ast.Name object at 0x... | keyword[def] identifier[MergeMembers] ( identifier[self] ):
literal[string]
keyword[for] identifier[group_name] , identifier[members] keyword[in] identifier[iteritems] ( identifier[self] . identifier[gshadow_members] ):
identifier[group] = identifier[self] . identifier[entry] . identifier[get] ( ... | def MergeMembers(self):
"""Add shadow group members to the group if gshadow is used.
Normally group and shadow should be in sync, but no guarantees. Merges the
two stores as membership in either file may confer membership.
"""
for (group_name, members) in iteritems(self.gshadow_members):
gr... |
def has_any_permissions(self, user):
"""
Return a boolean to indicate whether the supplied user has any
permissions at all on the associated model
"""
for perm in self.get_all_model_permissions():
if self.has_specific_permission(user, perm.codename):
r... | def function[has_any_permissions, parameter[self, user]]:
constant[
Return a boolean to indicate whether the supplied user has any
permissions at all on the associated model
]
for taget[name[perm]] in starred[call[name[self].get_all_model_permissions, parameter[]]] begin[:]
... | keyword[def] identifier[has_any_permissions] ( identifier[self] , identifier[user] ):
literal[string]
keyword[for] identifier[perm] keyword[in] identifier[self] . identifier[get_all_model_permissions] ():
keyword[if] identifier[self] . identifier[has_specific_permission] ( identifi... | def has_any_permissions(self, user):
"""
Return a boolean to indicate whether the supplied user has any
permissions at all on the associated model
"""
for perm in self.get_all_model_permissions():
if self.has_specific_permission(user, perm.codename):
return True # de... |
async def walk_query(obj, object_resolver, connection_resolver, errors, current_user=None, __naut_name=None, obey_auth=True, **filters):
"""
This function traverses a query and collects the corresponding
information in a dictionary.
"""
# if the object has no selection set
if not hasattr... | <ast.AsyncFunctionDef object at 0x7da2044c3a30> | keyword[async] keyword[def] identifier[walk_query] ( identifier[obj] , identifier[object_resolver] , identifier[connection_resolver] , identifier[errors] , identifier[current_user] = keyword[None] , identifier[__naut_name] = keyword[None] , identifier[obey_auth] = keyword[True] ,** identifier[filters] ):
litera... | async def walk_query(obj, object_resolver, connection_resolver, errors, current_user=None, __naut_name=None, obey_auth=True, **filters):
"""
This function traverses a query and collects the corresponding
information in a dictionary.
"""
# if the object has no selection set
if not hasattr... |
def _bind(self, args, kwds):
"""Bind parameter values. Returns a new Query object."""
bindings = dict(kwds)
for i, arg in enumerate(args):
bindings[i + 1] = arg
used = {}
ancestor = self.ancestor
if isinstance(ancestor, ParameterizedThing):
ancestor = ancestor.resolve(bindings, used... | def function[_bind, parameter[self, args, kwds]]:
constant[Bind parameter values. Returns a new Query object.]
variable[bindings] assign[=] call[name[dict], parameter[name[kwds]]]
for taget[tuple[[<ast.Name object at 0x7da1b10d79a0>, <ast.Name object at 0x7da1b10d4640>]]] in starred[call[name[e... | keyword[def] identifier[_bind] ( identifier[self] , identifier[args] , identifier[kwds] ):
literal[string]
identifier[bindings] = identifier[dict] ( identifier[kwds] )
keyword[for] identifier[i] , identifier[arg] keyword[in] identifier[enumerate] ( identifier[args] ):
identifier[bindings] [ ... | def _bind(self, args, kwds):
"""Bind parameter values. Returns a new Query object."""
bindings = dict(kwds)
for (i, arg) in enumerate(args):
bindings[i + 1] = arg # depends on [control=['for'], data=[]]
used = {}
ancestor = self.ancestor
if isinstance(ancestor, ParameterizedThing):
... |
def _to_repeatmasker_string(pairwise_alignment, column_width=DEFAULT_COL_WIDTH,
m_name_width=DEFAULT_MAX_NAME_WIDTH):
"""
generate a repeatmasker formated representation of this pairwise alignment.
:param column_width: number of characters to output per line of alignment
:param m_na... | def function[_to_repeatmasker_string, parameter[pairwise_alignment, column_width, m_name_width]]:
constant[
generate a repeatmasker formated representation of this pairwise alignment.
:param column_width: number of characters to output per line of alignment
:param m_name_width: truncate names on alignmen... | keyword[def] identifier[_to_repeatmasker_string] ( identifier[pairwise_alignment] , identifier[column_width] = identifier[DEFAULT_COL_WIDTH] ,
identifier[m_name_width] = identifier[DEFAULT_MAX_NAME_WIDTH] ):
literal[string]
identifier[s1] = identifier[pairwise_alignment] . identifier[s1]
identifier[s2] = ... | def _to_repeatmasker_string(pairwise_alignment, column_width=DEFAULT_COL_WIDTH, m_name_width=DEFAULT_MAX_NAME_WIDTH):
"""
generate a repeatmasker formated representation of this pairwise alignment.
:param column_width: number of characters to output per line of alignment
:param m_name_width: truncate names o... |
def request_frame(self):
"""Construct initiating frame."""
self.session_id = get_new_session_id()
return FrameActivateSceneRequest(scene_id=self.scene_id, session_id=self.session_id) | def function[request_frame, parameter[self]]:
constant[Construct initiating frame.]
name[self].session_id assign[=] call[name[get_new_session_id], parameter[]]
return[call[name[FrameActivateSceneRequest], parameter[]]] | keyword[def] identifier[request_frame] ( identifier[self] ):
literal[string]
identifier[self] . identifier[session_id] = identifier[get_new_session_id] ()
keyword[return] identifier[FrameActivateSceneRequest] ( identifier[scene_id] = identifier[self] . identifier[scene_id] , identifier[se... | def request_frame(self):
"""Construct initiating frame."""
self.session_id = get_new_session_id()
return FrameActivateSceneRequest(scene_id=self.scene_id, session_id=self.session_id) |
def sample_distinct(self, n_to_sample, **kwargs):
"""Sample a sequence of items from the pool until a minimum number of
distinct items are queried
Parameters
----------
n_to_sample : int
number of distinct items to sample. If sampling with replacement,
th... | def function[sample_distinct, parameter[self, n_to_sample]]:
constant[Sample a sequence of items from the pool until a minimum number of
distinct items are queried
Parameters
----------
n_to_sample : int
number of distinct items to sample. If sampling with replacemen... | keyword[def] identifier[sample_distinct] ( identifier[self] , identifier[n_to_sample] ,** identifier[kwargs] ):
literal[string]
identifier[n_notsampled] = identifier[np] . identifier[sum] ( identifier[np] . identifier[isnan] ( identifier[self] . identifier[cached_labels_] ))
keyw... | def sample_distinct(self, n_to_sample, **kwargs):
"""Sample a sequence of items from the pool until a minimum number of
distinct items are queried
Parameters
----------
n_to_sample : int
number of distinct items to sample. If sampling with replacement,
this n... |
def get_operation_ast(
document_ast: DocumentNode, operation_name: Optional[str] = None
) -> Optional[OperationDefinitionNode]:
"""Get operation AST node.
Returns an operation AST given a document AST and optionally an operation
name. If a name is not provided, an operation is only returned if only one... | def function[get_operation_ast, parameter[document_ast, operation_name]]:
constant[Get operation AST node.
Returns an operation AST given a document AST and optionally an operation
name. If a name is not provided, an operation is only returned if only one
is provided in the document.
]
... | keyword[def] identifier[get_operation_ast] (
identifier[document_ast] : identifier[DocumentNode] , identifier[operation_name] : identifier[Optional] [ identifier[str] ]= keyword[None]
)-> identifier[Optional] [ identifier[OperationDefinitionNode] ]:
literal[string]
identifier[operation] = keyword[None]
... | def get_operation_ast(document_ast: DocumentNode, operation_name: Optional[str]=None) -> Optional[OperationDefinitionNode]:
"""Get operation AST node.
Returns an operation AST given a document AST and optionally an operation
name. If a name is not provided, an operation is only returned if only one
is ... |
def create_in_hdx(self):
# type: () -> None
"""Check if user exists in HDX and if so, update it, otherwise create user
Returns:
None
"""
capacity = self.data.get('capacity')
if capacity is not None:
del self.data['capacity']
self._create_i... | def function[create_in_hdx, parameter[self]]:
constant[Check if user exists in HDX and if so, update it, otherwise create user
Returns:
None
]
variable[capacity] assign[=] call[name[self].data.get, parameter[constant[capacity]]]
if compare[name[capacity] is_not const... | keyword[def] identifier[create_in_hdx] ( identifier[self] ):
literal[string]
identifier[capacity] = identifier[self] . identifier[data] . identifier[get] ( literal[string] )
keyword[if] identifier[capacity] keyword[is] keyword[not] keyword[None] :
keyword[del] identifier... | def create_in_hdx(self):
# type: () -> None
'Check if user exists in HDX and if so, update it, otherwise create user\n\n Returns:\n None\n '
capacity = self.data.get('capacity')
if capacity is not None:
del self.data['capacity'] # depends on [control=['if'], data=[]]
... |
def write_transaction(self, transaction, mode):
# This method offers backward compatibility with the Web API.
"""Submit a valid transaction to the mempool."""
response = self.post_transaction(transaction, mode)
return self._process_post_response(response.json(), mode) | def function[write_transaction, parameter[self, transaction, mode]]:
constant[Submit a valid transaction to the mempool.]
variable[response] assign[=] call[name[self].post_transaction, parameter[name[transaction], name[mode]]]
return[call[name[self]._process_post_response, parameter[call[name[respon... | keyword[def] identifier[write_transaction] ( identifier[self] , identifier[transaction] , identifier[mode] ):
literal[string]
identifier[response] = identifier[self] . identifier[post_transaction] ( identifier[transaction] , identifier[mode] )
keyword[return] identifier[self] . identifie... | def write_transaction(self, transaction, mode):
# This method offers backward compatibility with the Web API.
'Submit a valid transaction to the mempool.'
response = self.post_transaction(transaction, mode)
return self._process_post_response(response.json(), mode) |
def getShocks(self):
'''
Gets permanent and transitory income shocks for this period as well as medical need shocks
and the price of medical care.
Parameters
----------
None
Returns
-------
None
'''
PersistentShockConsumerType.get... | def function[getShocks, parameter[self]]:
constant[
Gets permanent and transitory income shocks for this period as well as medical need shocks
and the price of medical care.
Parameters
----------
None
Returns
-------
None
]
call[n... | keyword[def] identifier[getShocks] ( identifier[self] ):
literal[string]
identifier[PersistentShockConsumerType] . identifier[getShocks] ( identifier[self] )
identifier[MedShkNow] = identifier[np] . identifier[zeros] ( identifier[self] . identifier[AgentCount] )
identifier[MedPric... | def getShocks(self):
"""
Gets permanent and transitory income shocks for this period as well as medical need shocks
and the price of medical care.
Parameters
----------
None
Returns
-------
None
"""
PersistentShockConsumerType.getShocks(s... |
def BuildDefaultGlobals():
"""
Create a dictionary containing all the default globals for
SConstruct and SConscript files.
"""
global GlobalDict
if GlobalDict is None:
GlobalDict = {}
import SCons.Script
d = SCons.Script.__dict__
def not_a_module(m, d=d, mtype=t... | def function[BuildDefaultGlobals, parameter[]]:
constant[
Create a dictionary containing all the default globals for
SConstruct and SConscript files.
]
<ast.Global object at 0x7da18f58f250>
if compare[name[GlobalDict] is constant[None]] begin[:]
variable[GlobalDict] assig... | keyword[def] identifier[BuildDefaultGlobals] ():
literal[string]
keyword[global] identifier[GlobalDict]
keyword[if] identifier[GlobalDict] keyword[is] keyword[None] :
identifier[GlobalDict] ={}
keyword[import] identifier[SCons] . identifier[Script]
identifier[d] = i... | def BuildDefaultGlobals():
"""
Create a dictionary containing all the default globals for
SConstruct and SConscript files.
"""
global GlobalDict
if GlobalDict is None:
GlobalDict = {}
import SCons.Script
d = SCons.Script.__dict__
def not_a_module(m, d=d, mtype=ty... |
def update_positions(self, positions):
'''Update the sphere positions.
'''
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions | def function[update_positions, parameter[self, positions]]:
constant[Update the sphere positions.
]
variable[sphs_verts] assign[=] call[name[self].sphs_verts_radii.copy, parameter[]]
<ast.AugAssign object at 0x7da18f720070>
call[name[self].tr.update_vertices, parameter[name[sphs_vert... | keyword[def] identifier[update_positions] ( identifier[self] , identifier[positions] ):
literal[string]
identifier[sphs_verts] = identifier[self] . identifier[sphs_verts_radii] . identifier[copy] ()
identifier[sphs_verts] += identifier[positions] . identifier[reshape] ( identifier[self] . ... | def update_positions(self, positions):
"""Update the sphere positions.
"""
sphs_verts = self.sphs_verts_radii.copy()
sphs_verts += positions.reshape(self.n_spheres, 1, 3)
self.tr.update_vertices(sphs_verts)
self.poslist = positions |
def get_devices(self):
"""
Return the devices linked to the gateway.
Returns a Command.
"""
def process_result(result):
return [self.get_device(dev) for dev in result]
return Command('get', [ROOT_DEVICES], process_result=process_result) | def function[get_devices, parameter[self]]:
constant[
Return the devices linked to the gateway.
Returns a Command.
]
def function[process_result, parameter[result]]:
return[<ast.ListComp object at 0x7da18ede5810>]
return[call[name[Command], parameter[constant[get], l... | keyword[def] identifier[get_devices] ( identifier[self] ):
literal[string]
keyword[def] identifier[process_result] ( identifier[result] ):
keyword[return] [ identifier[self] . identifier[get_device] ( identifier[dev] ) keyword[for] identifier[dev] keyword[in] identifier[result] ]
... | def get_devices(self):
"""
Return the devices linked to the gateway.
Returns a Command.
"""
def process_result(result):
return [self.get_device(dev) for dev in result]
return Command('get', [ROOT_DEVICES], process_result=process_result) |
def _ProcessSources(
self, source_path_specs, extraction_worker, parser_mediator,
storage_writer, filter_find_specs=None):
"""Processes the sources.
Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications of
the sources to process.
extraction_worker (worker.Extract... | def function[_ProcessSources, parameter[self, source_path_specs, extraction_worker, parser_mediator, storage_writer, filter_find_specs]]:
constant[Processes the sources.
Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications of
the sources to process.
extraction_worker (w... | keyword[def] identifier[_ProcessSources] (
identifier[self] , identifier[source_path_specs] , identifier[extraction_worker] , identifier[parser_mediator] ,
identifier[storage_writer] , identifier[filter_find_specs] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_processing_... | def _ProcessSources(self, source_path_specs, extraction_worker, parser_mediator, storage_writer, filter_find_specs=None):
"""Processes the sources.
Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications of
the sources to process.
extraction_worker (worker.ExtractionWorker): e... |
def hybrid_meco_frequency(m1, m2, chi1, chi2, qm1=None, qm2=None):
"""Return the frequency of the hybrid MECO
Parameters
----------
m1 : float
Mass of the primary object in solar masses.
m2 : float
Mass of the secondary object in solar masses.
chi1: float
Dimensionless s... | def function[hybrid_meco_frequency, parameter[m1, m2, chi1, chi2, qm1, qm2]]:
constant[Return the frequency of the hybrid MECO
Parameters
----------
m1 : float
Mass of the primary object in solar masses.
m2 : float
Mass of the secondary object in solar masses.
chi1: float
... | keyword[def] identifier[hybrid_meco_frequency] ( identifier[m1] , identifier[m2] , identifier[chi1] , identifier[chi2] , identifier[qm1] = keyword[None] , identifier[qm2] = keyword[None] ):
literal[string]
keyword[if] identifier[qm1] keyword[is] keyword[None] :
identifier[qm1] = literal[int]
... | def hybrid_meco_frequency(m1, m2, chi1, chi2, qm1=None, qm2=None):
"""Return the frequency of the hybrid MECO
Parameters
----------
m1 : float
Mass of the primary object in solar masses.
m2 : float
Mass of the secondary object in solar masses.
chi1: float
Dimensionless s... |
def from_data(cls, blob):
"""Restore an object instance from a compressed datablob.
Returns an instance of a concrete subclass."""
version, data = decompress_datablob(DATA_BLOB_MAGIC_RETRY, blob)
if version == 1:
for clazz in cls._all_subclasses():
if clazz.... | def function[from_data, parameter[cls, blob]]:
constant[Restore an object instance from a compressed datablob.
Returns an instance of a concrete subclass.]
<ast.Tuple object at 0x7da204566cb0> assign[=] call[name[decompress_datablob], parameter[name[DATA_BLOB_MAGIC_RETRY], name[blob]]]
... | keyword[def] identifier[from_data] ( identifier[cls] , identifier[blob] ):
literal[string]
identifier[version] , identifier[data] = identifier[decompress_datablob] ( identifier[DATA_BLOB_MAGIC_RETRY] , identifier[blob] )
keyword[if] identifier[version] == literal[int] :
keyw... | def from_data(cls, blob):
"""Restore an object instance from a compressed datablob.
Returns an instance of a concrete subclass."""
(version, data) = decompress_datablob(DATA_BLOB_MAGIC_RETRY, blob)
if version == 1:
for clazz in cls._all_subclasses():
if clazz.__name__ == data['_... |
def get_summary_stats(items, attr):
"""
Returns a dictionary of aggregated statistics for 'items' filtered by
"attr'. For example, it will aggregate statistics for a host across all
the playbook runs it has been a member of, with the following structure:
data[host.id] = {
'ok': 4
... | def function[get_summary_stats, parameter[items, attr]]:
constant[
Returns a dictionary of aggregated statistics for 'items' filtered by
"attr'. For example, it will aggregate statistics for a host across all
the playbook runs it has been a member of, with the following structure:
data[host... | keyword[def] identifier[get_summary_stats] ( identifier[items] , identifier[attr] ):
literal[string]
identifier[data] ={}
keyword[for] identifier[item] keyword[in] identifier[items] :
identifier[stats] = identifier[models] . identifier[Stats] . identifier[query] . identifier[filter_by] (**... | def get_summary_stats(items, attr):
"""
Returns a dictionary of aggregated statistics for 'items' filtered by
"attr'. For example, it will aggregate statistics for a host across all
the playbook runs it has been a member of, with the following structure:
data[host.id] = {
'ok': 4
... |
def _load_config(self):
"""
Load project's config and return dict.
TODO: Convert the original dotted representation to hierarchical.
"""
config = import_module('config')
variables = [var for var in dir(config) if not var.startswith('_')]
return {var: getattr(conf... | def function[_load_config, parameter[self]]:
constant[
Load project's config and return dict.
TODO: Convert the original dotted representation to hierarchical.
]
variable[config] assign[=] call[name[import_module], parameter[constant[config]]]
variable[variables] assign[... | keyword[def] identifier[_load_config] ( identifier[self] ):
literal[string]
identifier[config] = identifier[import_module] ( literal[string] )
identifier[variables] =[ identifier[var] keyword[for] identifier[var] keyword[in] identifier[dir] ( identifier[config] ) keyword[if] keyword[n... | def _load_config(self):
"""
Load project's config and return dict.
TODO: Convert the original dotted representation to hierarchical.
"""
config = import_module('config')
variables = [var for var in dir(config) if not var.startswith('_')]
return {var: getattr(config, var) for var... |
def args(self) -> str:
"""Provides arguments for the command."""
return '{}{}{}{}{}{}{}{}{}{}{}'.format(
to_ascii_hex(self._index, 2),
to_ascii_hex(self._group_number, 2),
to_ascii_hex(self._unit_number, 2),
to_ascii_hex(int(self._enable_status), 4),
... | def function[args, parameter[self]]:
constant[Provides arguments for the command.]
return[call[constant[{}{}{}{}{}{}{}{}{}{}{}].format, parameter[call[name[to_ascii_hex], parameter[name[self]._index, constant[2]]], call[name[to_ascii_hex], parameter[name[self]._group_number, constant[2]]], call[name[to_asci... | keyword[def] identifier[args] ( identifier[self] )-> identifier[str] :
literal[string]
keyword[return] literal[string] . identifier[format] (
identifier[to_ascii_hex] ( identifier[self] . identifier[_index] , literal[int] ),
identifier[to_ascii_hex] ( identifier[self] . identifie... | def args(self) -> str:
"""Provides arguments for the command."""
return '{}{}{}{}{}{}{}{}{}{}{}'.format(to_ascii_hex(self._index, 2), to_ascii_hex(self._group_number, 2), to_ascii_hex(self._unit_number, 2), to_ascii_hex(int(self._enable_status), 4), to_ascii_hex(int(self._switches), 4), to_ascii_hex(self._curre... |
def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '' and 'ascii'.
If '' is specified, the primary d... | def function[list_files, parameter[tag, sat_id, data_path, format_str]]:
constant[Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '' and 'ascii'.
If '' is specified, th... | keyword[def] identifier[list_files] ( identifier[tag] = keyword[None] , identifier[sat_id] = keyword[None] , identifier[data_path] = keyword[None] , identifier[format_str] = keyword[None] ):
literal[string]
keyword[import] identifier[sys]
identifier[estr] = literal[stri... | def list_files(tag=None, sat_id=None, data_path=None, format_str=None):
"""Return a Pandas Series of every file for chosen satellite data
Parameters
-----------
tag : (string or NoneType)
Denotes type of file to load. Accepted types are '' and 'ascii'.
If '' is specified, the primary d... |
def iter_configurations(kafka_topology_base_path=None):
"""Cluster topology iterator.
Iterate over all the topologies available in config.
"""
if not kafka_topology_base_path:
config_dirs = get_conf_dirs()
else:
config_dirs = [kafka_topology_base_path]
types = set()
for conf... | def function[iter_configurations, parameter[kafka_topology_base_path]]:
constant[Cluster topology iterator.
Iterate over all the topologies available in config.
]
if <ast.UnaryOp object at 0x7da1b07b3a60> begin[:]
variable[config_dirs] assign[=] call[name[get_conf_dirs], paramete... | keyword[def] identifier[iter_configurations] ( identifier[kafka_topology_base_path] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[kafka_topology_base_path] :
identifier[config_dirs] = identifier[get_conf_dirs] ()
keyword[else] :
identifier[config_dirs] =[ i... | def iter_configurations(kafka_topology_base_path=None):
"""Cluster topology iterator.
Iterate over all the topologies available in config.
"""
if not kafka_topology_base_path:
config_dirs = get_conf_dirs() # depends on [control=['if'], data=[]]
else:
config_dirs = [kafka_topology_ba... |
def makedirs(path, mode=0o777, exist_ok=False):
"""A wrapper of os.makedirs()."""
os.makedirs(path, mode, exist_ok) | def function[makedirs, parameter[path, mode, exist_ok]]:
constant[A wrapper of os.makedirs().]
call[name[os].makedirs, parameter[name[path], name[mode], name[exist_ok]]] | keyword[def] identifier[makedirs] ( identifier[path] , identifier[mode] = literal[int] , identifier[exist_ok] = keyword[False] ):
literal[string]
identifier[os] . identifier[makedirs] ( identifier[path] , identifier[mode] , identifier[exist_ok] ) | def makedirs(path, mode=511, exist_ok=False):
"""A wrapper of os.makedirs()."""
os.makedirs(path, mode, exist_ok) |
def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20):
"""Update the list of Collections contained by this API Root.
This invokes the ``Get Collections`` endpoint.
"""
url = self.url + "collections/"
response = self._conn.get(url, headers={"Accept": accept})
self._... | def function[refresh_collections, parameter[self, accept]]:
constant[Update the list of Collections contained by this API Root.
This invokes the ``Get Collections`` endpoint.
]
variable[url] assign[=] binary_operation[name[self].url + constant[collections/]]
variable[response] a... | keyword[def] identifier[refresh_collections] ( identifier[self] , identifier[accept] = identifier[MEDIA_TYPE_TAXII_V20] ):
literal[string]
identifier[url] = identifier[self] . identifier[url] + literal[string]
identifier[response] = identifier[self] . identifier[_conn] . identifier[get] (... | def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20):
"""Update the list of Collections contained by this API Root.
This invokes the ``Get Collections`` endpoint.
"""
url = self.url + 'collections/'
response = self._conn.get(url, headers={'Accept': accept})
self._collections = []
... |
def can_use_process_cache(self, use_cache):
"""Returns True if the process cache can be used
:param bool use_cache: Override the logic to force non-cached values
:rtype: bool
"""
return (use_cache and
self._active_cache and
self._active_cache[0] ... | def function[can_use_process_cache, parameter[self, use_cache]]:
constant[Returns True if the process cache can be used
:param bool use_cache: Override the logic to force non-cached values
:rtype: bool
]
return[<ast.BoolOp object at 0x7da18dc06290>] | keyword[def] identifier[can_use_process_cache] ( identifier[self] , identifier[use_cache] ):
literal[string]
keyword[return] ( identifier[use_cache] keyword[and]
identifier[self] . identifier[_active_cache] keyword[and]
identifier[self] . identifier[_active_cache] [ literal[in... | def can_use_process_cache(self, use_cache):
"""Returns True if the process cache can be used
:param bool use_cache: Override the logic to force non-cached values
:rtype: bool
"""
return use_cache and self._active_cache and (self._active_cache[0] > time.time() - self.poll_interval) |
def run(self):
'''Run loop'''
logger.info("fetcher starting...")
def queue_loop():
if not self.outqueue or not self.inqueue:
return
while not self._quit:
try:
if self.outqueue.full():
break
... | def function[run, parameter[self]]:
constant[Run loop]
call[name[logger].info, parameter[constant[fetcher starting...]]]
def function[queue_loop, parameter[]]:
if <ast.BoolOp object at 0x7da1b1f72f80> begin[:]
return[None]
while <ast.UnaryOp object at ... | keyword[def] identifier[run] ( identifier[self] ):
literal[string]
identifier[logger] . identifier[info] ( literal[string] )
keyword[def] identifier[queue_loop] ():
keyword[if] keyword[not] identifier[self] . identifier[outqueue] keyword[or] keyword[not] identifier[self... | def run(self):
"""Run loop"""
logger.info('fetcher starting...')
def queue_loop():
if not self.outqueue or not self.inqueue:
return # depends on [control=['if'], data=[]]
while not self._quit:
try:
if self.outqueue.full():
break ... |
def get(self, path, default=None, check_type=None, module_name=None):
"""
Get option property
:param path: full path to the property with name
:param default: default value if original is not present
:param check_type: cast param to passed type, if fail, default will returned
:param module_name... | def function[get, parameter[self, path, default, check_type, module_name]]:
constant[
Get option property
:param path: full path to the property with name
:param default: default value if original is not present
:param check_type: cast param to passed type, if fail, default will returned
:p... | keyword[def] identifier[get] ( identifier[self] , identifier[path] , identifier[default] = keyword[None] , identifier[check_type] = keyword[None] , identifier[module_name] = keyword[None] ):
literal[string]
keyword[if] identifier[self] . identifier[_json] keyword[is] keyword[not] keyword[None] :
... | def get(self, path, default=None, check_type=None, module_name=None):
"""
Get option property
:param path: full path to the property with name
:param default: default value if original is not present
:param check_type: cast param to passed type, if fail, default will returned
:param module_name... |
def upload(file_path, dataset=None, public=False):
"""Use this function to upload data to Knoema dataset."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
return client.upload(file_path, dataset, public) | def function[upload, parameter[file_path, dataset, public]]:
constant[Use this function to upload data to Knoema dataset.]
variable[config] assign[=] call[name[ApiConfig], parameter[]]
variable[client] assign[=] call[name[ApiClient], parameter[name[config].host, name[config].app_id, name[config]... | keyword[def] identifier[upload] ( identifier[file_path] , identifier[dataset] = keyword[None] , identifier[public] = keyword[False] ):
literal[string]
identifier[config] = identifier[ApiConfig] ()
identifier[client] = identifier[ApiClient] ( identifier[config] . identifier[host] , identifier[conf... | def upload(file_path, dataset=None, public=False):
"""Use this function to upload data to Knoema dataset."""
config = ApiConfig()
client = ApiClient(config.host, config.app_id, config.app_secret)
return client.upload(file_path, dataset, public) |
def delete(self, using=None, soft=True, *args, **kwargs):
"""
Soft delete object (set its ``is_removed`` field to True).
Actually delete object if setting ``soft`` to False.
"""
if soft:
self.is_removed = True
self.save(using=using)
else:
... | def function[delete, parameter[self, using, soft]]:
constant[
Soft delete object (set its ``is_removed`` field to True).
Actually delete object if setting ``soft`` to False.
]
if name[soft] begin[:]
name[self].is_removed assign[=] constant[True]
ca... | keyword[def] identifier[delete] ( identifier[self] , identifier[using] = keyword[None] , identifier[soft] = keyword[True] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[soft] :
identifier[self] . identifier[is_removed] = keyword[True]
... | def delete(self, using=None, soft=True, *args, **kwargs):
"""
Soft delete object (set its ``is_removed`` field to True).
Actually delete object if setting ``soft`` to False.
"""
if soft:
self.is_removed = True
self.save(using=using) # depends on [control=['if'], data=[]]... |
def update(self, authorize_redirect_url=values.unset, company_name=values.unset,
deauthorize_callback_method=values.unset,
deauthorize_callback_url=values.unset, description=values.unset,
friendly_name=values.unset, homepage_url=values.unset,
permissions=value... | def function[update, parameter[self, authorize_redirect_url, company_name, deauthorize_callback_method, deauthorize_callback_url, description, friendly_name, homepage_url, permissions]]:
constant[
Update the ConnectAppInstance
:param unicode authorize_redirect_url: The URL to redirect the user ... | keyword[def] identifier[update] ( identifier[self] , identifier[authorize_redirect_url] = identifier[values] . identifier[unset] , identifier[company_name] = identifier[values] . identifier[unset] ,
identifier[deauthorize_callback_method] = identifier[values] . identifier[unset] ,
identifier[deauthorize_callback_ur... | def update(self, authorize_redirect_url=values.unset, company_name=values.unset, deauthorize_callback_method=values.unset, deauthorize_callback_url=values.unset, description=values.unset, friendly_name=values.unset, homepage_url=values.unset, permissions=values.unset):
"""
Update the ConnectAppInstance
... |
def _get_v_angle_guess(self, case):
""" Make the vector of voltage phase guesses.
"""
v_angle = array([bus.v_angle * (pi / 180.0)
for bus in case.connected_buses])
return v_angle | def function[_get_v_angle_guess, parameter[self, case]]:
constant[ Make the vector of voltage phase guesses.
]
variable[v_angle] assign[=] call[name[array], parameter[<ast.ListComp object at 0x7da18fe91930>]]
return[name[v_angle]] | keyword[def] identifier[_get_v_angle_guess] ( identifier[self] , identifier[case] ):
literal[string]
identifier[v_angle] = identifier[array] ([ identifier[bus] . identifier[v_angle] *( identifier[pi] / literal[int] )
keyword[for] identifier[bus] keyword[in] identifier[case] . identifier... | def _get_v_angle_guess(self, case):
""" Make the vector of voltage phase guesses.
"""
v_angle = array([bus.v_angle * (pi / 180.0) for bus in case.connected_buses])
return v_angle |
def call(self, method, *args, **kw):
"""
In context of a batch we return the request's ID
else we return the actual json
"""
if args and kw:
raise ValueError("JSON-RPC method calls allow only either named or positional arguments.")
if not method:
r... | def function[call, parameter[self, method]]:
constant[
In context of a batch we return the request's ID
else we return the actual json
]
if <ast.BoolOp object at 0x7da1b0abbfa0> begin[:]
<ast.Raise object at 0x7da1b0ab9ed0>
if <ast.UnaryOp object at 0x7da1b0804d00... | keyword[def] identifier[call] ( identifier[self] , identifier[method] ,* identifier[args] ,** identifier[kw] ):
literal[string]
keyword[if] identifier[args] keyword[and] identifier[kw] :
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] keyword[not] i... | def call(self, method, *args, **kw):
"""
In context of a batch we return the request's ID
else we return the actual json
"""
if args and kw:
raise ValueError('JSON-RPC method calls allow only either named or positional arguments.') # depends on [control=['if'], data=[]]
if n... |
def _unwrap_response_single(cls, obj, wrapper=None):
"""
:type obj: dict
:type wrapper: str|None
:rtype: dict
"""
if wrapper is not None:
return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST][wrapper]
return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST] | def function[_unwrap_response_single, parameter[cls, obj, wrapper]]:
constant[
:type obj: dict
:type wrapper: str|None
:rtype: dict
]
if compare[name[wrapper] is_not constant[None]] begin[:]
return[call[call[call[name[obj]][name[cls]._FIELD_RESPONSE]][name[cls]._... | keyword[def] identifier[_unwrap_response_single] ( identifier[cls] , identifier[obj] , identifier[wrapper] = keyword[None] ):
literal[string]
keyword[if] identifier[wrapper] keyword[is] keyword[not] keyword[None] :
keyword[return] identifier[obj] [ identifier[cls] . identifier[_F... | def _unwrap_response_single(cls, obj, wrapper=None):
"""
:type obj: dict
:type wrapper: str|None
:rtype: dict
"""
if wrapper is not None:
return obj[cls._FIELD_RESPONSE][cls._INDEX_FIRST][wrapper] # depends on [control=['if'], data=['wrapper']]
return obj[cls._FIELD... |
def _collect_data(directory, input_ext, target_ext):
"""Traverses directory collecting input and target files."""
# Directory from string to tuple pair of strings
# key: the filepath to a datafile including the datafile's basename. Example,
# if the datafile was "/path/to/datafile.wav" then the key would be
... | def function[_collect_data, parameter[directory, input_ext, target_ext]]:
constant[Traverses directory collecting input and target files.]
variable[data_files] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b2058e20>, <ast.Name object at 0x7da1b205a5c0>, <ast.Name object... | keyword[def] identifier[_collect_data] ( identifier[directory] , identifier[input_ext] , identifier[target_ext] ):
literal[string]
identifier[data_files] ={}
keyword[for] identifier[root] , identifier[_] , identifier[filenames] keyword[in] identifier[os] . identifier[walk] ( identifier[dir... | def _collect_data(directory, input_ext, target_ext):
"""Traverses directory collecting input and target files."""
# Directory from string to tuple pair of strings
# key: the filepath to a datafile including the datafile's basename. Example,
# if the datafile was "/path/to/datafile.wav" then the key wo... |
def get(interface, method, version=1,
apihost=DEFAULT_PARAMS['apihost'], https=DEFAULT_PARAMS['https'],
caller=None, session=None, params=None):
"""Send GET request to an API endpoint
.. versionadded:: 0.8.3
:param interface: interface name
:type interface: str
:param method: metho... | def function[get, parameter[interface, method, version, apihost, https, caller, session, params]]:
constant[Send GET request to an API endpoint
.. versionadded:: 0.8.3
:param interface: interface name
:type interface: str
:param method: method name
:type method: str
:param version: met... | keyword[def] identifier[get] ( identifier[interface] , identifier[method] , identifier[version] = literal[int] ,
identifier[apihost] = identifier[DEFAULT_PARAMS] [ literal[string] ], identifier[https] = identifier[DEFAULT_PARAMS] [ literal[string] ],
identifier[caller] = keyword[None] , identifier[session] = keywor... | def get(interface, method, version=1, apihost=DEFAULT_PARAMS['apihost'], https=DEFAULT_PARAMS['https'], caller=None, session=None, params=None):
"""Send GET request to an API endpoint
.. versionadded:: 0.8.3
:param interface: interface name
:type interface: str
:param method: method name
:type... |
def xml_report(self, file_path):
"""Generate and save XML report"""
self.logger.debug('Generating XML report')
report = self.zap.core.xmlreport()
self._write_report(report, file_path) | def function[xml_report, parameter[self, file_path]]:
constant[Generate and save XML report]
call[name[self].logger.debug, parameter[constant[Generating XML report]]]
variable[report] assign[=] call[name[self].zap.core.xmlreport, parameter[]]
call[name[self]._write_report, parameter[name... | keyword[def] identifier[xml_report] ( identifier[self] , identifier[file_path] ):
literal[string]
identifier[self] . identifier[logger] . identifier[debug] ( literal[string] )
identifier[report] = identifier[self] . identifier[zap] . identifier[core] . identifier[xmlreport] ()
ide... | def xml_report(self, file_path):
"""Generate and save XML report"""
self.logger.debug('Generating XML report')
report = self.zap.core.xmlreport()
self._write_report(report, file_path) |
def set_no_bandwidth_group_for_device(self, name, controller_port, device):
"""Sets no bandwidth group for an existing storage device.
The device must already exist; see :py:func:`IMachine.attach_device`
for how to attach a new device.
The @a controllerPort and @a device parameters spec... | def function[set_no_bandwidth_group_for_device, parameter[self, name, controller_port, device]]:
constant[Sets no bandwidth group for an existing storage device.
The device must already exist; see :py:func:`IMachine.attach_device`
for how to attach a new device.
The @a controllerPort an... | keyword[def] identifier[set_no_bandwidth_group_for_device] ( identifier[self] , identifier[name] , identifier[controller_port] , identifier[device] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[name] , identifier[basestring] ):
keyword[raise] identi... | def set_no_bandwidth_group_for_device(self, name, controller_port, device):
"""Sets no bandwidth group for an existing storage device.
The device must already exist; see :py:func:`IMachine.attach_device`
for how to attach a new device.
The @a controllerPort and @a device parameters specify ... |
def entity(self):
"""
Returns the object this grant is for. The objects type depends on the
type of object this grant is applied to, and the object returned is
not populated (accessing its attributes will trigger an api request).
:returns: This grant's entity
:rtype: Li... | def function[entity, parameter[self]]:
constant[
Returns the object this grant is for. The objects type depends on the
type of object this grant is applied to, and the object returned is
not populated (accessing its attributes will trigger an api request).
:returns: This grant'... | keyword[def] identifier[entity] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[issubclass] ( identifier[self] . identifier[cls] , identifier[Base] ) keyword[or] identifier[issubclass] ( identifier[self] . identifier[cls] , identifier[DerivedBase] ):
... | def entity(self):
"""
Returns the object this grant is for. The objects type depends on the
type of object this grant is applied to, and the object returned is
not populated (accessing its attributes will trigger an api request).
:returns: This grant's entity
:rtype: Linode... |
def prepare_plugins(plugins, parameters={}):
"""
Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins,
we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec.
:param plugins: list of sam... | def function[prepare_plugins, parameter[plugins, parameters]]:
constant[
Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins,
we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec.
... | keyword[def] identifier[prepare_plugins] ( identifier[plugins] , identifier[parameters] ={}):
literal[string]
identifier[required_plugins] =[
identifier[DefaultDefinitionBodyPlugin] (),
identifier[make_implicit_api_plugin] (),
identifier[GlobalsPlugin] (),
identifier[make_policy_templa... | def prepare_plugins(plugins, parameters={}):
"""
Creates & returns a plugins object with the given list of plugins installed. In addition to the given plugins,
we will also install a few "required" plugins that are necessary to provide complete support for SAM template spec.
:param plugins: list of sam... |
def version(*dbs):
'''
Server Version (select banner from v$version)
CLI Example:
.. code-block:: bash
salt '*' oracle.version
salt '*' oracle.version my_db
'''
pillar_dbs = __salt__['pillar.get']('oracle:dbs')
get_version = lambda x: [
r[0] for r in run_query(x, ... | def function[version, parameter[]]:
constant[
Server Version (select banner from v$version)
CLI Example:
.. code-block:: bash
salt '*' oracle.version
salt '*' oracle.version my_db
]
variable[pillar_dbs] assign[=] call[call[name[__salt__]][constant[pillar.get]], parame... | keyword[def] identifier[version] (* identifier[dbs] ):
literal[string]
identifier[pillar_dbs] = identifier[__salt__] [ literal[string] ]( literal[string] )
identifier[get_version] = keyword[lambda] identifier[x] :[
identifier[r] [ literal[int] ] keyword[for] identifier[r] keyword[in] identifi... | def version(*dbs):
"""
Server Version (select banner from v$version)
CLI Example:
.. code-block:: bash
salt '*' oracle.version
salt '*' oracle.version my_db
"""
pillar_dbs = __salt__['pillar.get']('oracle:dbs')
get_version = lambda x: [r[0] for r in run_query(x, 'select b... |
def hmtk_histogram_1D(values, intervals, offset=1.0E-10):
"""
So, here's the problem. We tend to refer to certain data (like magnitudes)
rounded to the nearest 0.1 (or similar, i.e. 4.1, 5.7, 8.3 etc.). We also
like our tables to fall on on the same interval, i.e. 3.1, 3.2, 3.3 etc.
We usually assum... | def function[hmtk_histogram_1D, parameter[values, intervals, offset]]:
constant[
So, here's the problem. We tend to refer to certain data (like magnitudes)
rounded to the nearest 0.1 (or similar, i.e. 4.1, 5.7, 8.3 etc.). We also
like our tables to fall on on the same interval, i.e. 3.1, 3.2, 3.3 et... | keyword[def] identifier[hmtk_histogram_1D] ( identifier[values] , identifier[intervals] , identifier[offset] = literal[int] ):
literal[string]
identifier[nbins] = identifier[len] ( identifier[intervals] )- literal[int]
identifier[counter] = identifier[np] . identifier[zeros] ( identifier[nbins] , ide... | def hmtk_histogram_1D(values, intervals, offset=1e-10):
"""
So, here's the problem. We tend to refer to certain data (like magnitudes)
rounded to the nearest 0.1 (or similar, i.e. 4.1, 5.7, 8.3 etc.). We also
like our tables to fall on on the same interval, i.e. 3.1, 3.2, 3.3 etc.
We usually assume ... |
def set_fill_color(self,r,g=-1,b=-1):
"Set color for all filling operations"
if((r==0 and g==0 and b==0) or g==-1):
self.fill_color=sprintf('%.3f g',r/255.0)
else:
self.fill_color=sprintf('%.3f %.3f %.3f rg',r/255.0,g/255.0,b/255.0)
self.color_flag=(self.fill_colo... | def function[set_fill_color, parameter[self, r, g, b]]:
constant[Set color for all filling operations]
if <ast.BoolOp object at 0x7da18f812020> begin[:]
name[self].fill_color assign[=] call[name[sprintf], parameter[constant[%.3f g], binary_operation[name[r] / constant[255.0]]]]
n... | keyword[def] identifier[set_fill_color] ( identifier[self] , identifier[r] , identifier[g] =- literal[int] , identifier[b] =- literal[int] ):
literal[string]
keyword[if] (( identifier[r] == literal[int] keyword[and] identifier[g] == literal[int] keyword[and] identifier[b] == literal[int] ) keyw... | def set_fill_color(self, r, g=-1, b=-1):
"""Set color for all filling operations"""
if r == 0 and g == 0 and (b == 0) or g == -1:
self.fill_color = sprintf('%.3f g', r / 255.0) # depends on [control=['if'], data=[]]
else:
self.fill_color = sprintf('%.3f %.3f %.3f rg', r / 255.0, g / 255.0, ... |
def _determine_beacon_config(self, current_beacon_config, key):
'''
Process a beacon configuration to determine its interval
'''
interval = False
if isinstance(current_beacon_config, dict):
interval = current_beacon_config.get(key, False)
return interval | def function[_determine_beacon_config, parameter[self, current_beacon_config, key]]:
constant[
Process a beacon configuration to determine its interval
]
variable[interval] assign[=] constant[False]
if call[name[isinstance], parameter[name[current_beacon_config], name[dict]]] beg... | keyword[def] identifier[_determine_beacon_config] ( identifier[self] , identifier[current_beacon_config] , identifier[key] ):
literal[string]
identifier[interval] = keyword[False]
keyword[if] identifier[isinstance] ( identifier[current_beacon_config] , identifier[dict] ):
i... | def _determine_beacon_config(self, current_beacon_config, key):
"""
Process a beacon configuration to determine its interval
"""
interval = False
if isinstance(current_beacon_config, dict):
interval = current_beacon_config.get(key, False) # depends on [control=['if'], data=[]]
r... |
def _finalize(self, chain=-1):
"""Finalize the chain for all tallyable objects."""
chain = range(self.chains)[chain]
for name in self.trace_names[chain]:
self._traces[name]._finalize(chain)
self.commit() | def function[_finalize, parameter[self, chain]]:
constant[Finalize the chain for all tallyable objects.]
variable[chain] assign[=] call[call[name[range], parameter[name[self].chains]]][name[chain]]
for taget[name[name]] in starred[call[name[self].trace_names][name[chain]]] begin[:]
... | keyword[def] identifier[_finalize] ( identifier[self] , identifier[chain] =- literal[int] ):
literal[string]
identifier[chain] = identifier[range] ( identifier[self] . identifier[chains] )[ identifier[chain] ]
keyword[for] identifier[name] keyword[in] identifier[self] . identifier[trace... | def _finalize(self, chain=-1):
"""Finalize the chain for all tallyable objects."""
chain = range(self.chains)[chain]
for name in self.trace_names[chain]:
self._traces[name]._finalize(chain) # depends on [control=['for'], data=['name']]
self.commit() |
def update_load_balancer(access_token, subscription_id, resource_group, lb_name, body):
'''Updates a load balancer model, i.e. PUT an updated LB body.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure ... | def function[update_load_balancer, parameter[access_token, subscription_id, resource_group, lb_name, body]]:
constant[Updates a load balancer model, i.e. PUT an updated LB body.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
... | keyword[def] identifier[update_load_balancer] ( identifier[access_token] , identifier[subscription_id] , identifier[resource_group] , identifier[lb_name] , identifier[body] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[join] ([ identifier[get_rm_endpoint] (),
literal[string] ,... | def update_load_balancer(access_token, subscription_id, resource_group, lb_name, body):
"""Updates a load balancer model, i.e. PUT an updated LB body.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure ... |
def init(self):
"""
Validates the given ``ovsdb_addr`` and connects to OVS instance.
If failed to connect to OVS instance or the given ``datapath_id`` does
not match with the Datapath ID of the connected OVS instance, raises
:py:mod:`ryu.lib.ovs.bridge.OVSBridgeNotFound` excepti... | def function[init, parameter[self]]:
constant[
Validates the given ``ovsdb_addr`` and connects to OVS instance.
If failed to connect to OVS instance or the given ``datapath_id`` does
not match with the Datapath ID of the connected OVS instance, raises
:py:mod:`ryu.lib.ovs.bridge... | keyword[def] identifier[init] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[valid_ovsdb_addr] ( identifier[self] . identifier[ovsdb_addr] ):
keyword[raise] identifier[ValueError] ( literal[string] % identifier[self] . identifier[ovsdb_addr] )
key... | def init(self):
"""
Validates the given ``ovsdb_addr`` and connects to OVS instance.
If failed to connect to OVS instance or the given ``datapath_id`` does
not match with the Datapath ID of the connected OVS instance, raises
:py:mod:`ryu.lib.ovs.bridge.OVSBridgeNotFound` exception.
... |
def __write_constant_class(self):
"""
Inserts new and replaces old (if any) constant declaration statements in the class that acts like a namespace
for constants.
"""
helper = ConstantClass(self._class_name, self._io)
content = helper.source_with_constants(self._constant... | def function[__write_constant_class, parameter[self]]:
constant[
Inserts new and replaces old (if any) constant declaration statements in the class that acts like a namespace
for constants.
]
variable[helper] assign[=] call[name[ConstantClass], parameter[name[self]._class_name, n... | keyword[def] identifier[__write_constant_class] ( identifier[self] ):
literal[string]
identifier[helper] = identifier[ConstantClass] ( identifier[self] . identifier[_class_name] , identifier[self] . identifier[_io] )
identifier[content] = identifier[helper] . identifier[source_with_consta... | def __write_constant_class(self):
"""
Inserts new and replaces old (if any) constant declaration statements in the class that acts like a namespace
for constants.
"""
helper = ConstantClass(self._class_name, self._io)
content = helper.source_with_constants(self._constants)
Util.w... |
def spacing(self, spacing):
"""Set the spacing in each axial direction. Pass a length three tuple of
floats"""
dx, dy, dz = spacing[0], spacing[1], spacing[2]
self.SetSpacing(dx, dy, dz)
self.Modified() | def function[spacing, parameter[self, spacing]]:
constant[Set the spacing in each axial direction. Pass a length three tuple of
floats]
<ast.Tuple object at 0x7da20c6a8b50> assign[=] tuple[[<ast.Subscript object at 0x7da20c6a9cf0>, <ast.Subscript object at 0x7da20c6aa560>, <ast.Subscript object ... | keyword[def] identifier[spacing] ( identifier[self] , identifier[spacing] ):
literal[string]
identifier[dx] , identifier[dy] , identifier[dz] = identifier[spacing] [ literal[int] ], identifier[spacing] [ literal[int] ], identifier[spacing] [ literal[int] ]
identifier[self] . identifier[Set... | def spacing(self, spacing):
"""Set the spacing in each axial direction. Pass a length three tuple of
floats"""
(dx, dy, dz) = (spacing[0], spacing[1], spacing[2])
self.SetSpacing(dx, dy, dz)
self.Modified() |
def dedup_search_results(search_results):
""" dedup results
"""
known = set()
deduped_results = []
for i in search_results:
username = i['username']
if username in known:
continue
deduped_results.append(i)
known.add(username)
return deduped_resu... | def function[dedup_search_results, parameter[search_results]]:
constant[ dedup results
]
variable[known] assign[=] call[name[set], parameter[]]
variable[deduped_results] assign[=] list[[]]
for taget[name[i]] in starred[name[search_results]] begin[:]
variable[username]... | keyword[def] identifier[dedup_search_results] ( identifier[search_results] ):
literal[string]
identifier[known] = identifier[set] ()
identifier[deduped_results] =[]
keyword[for] identifier[i] keyword[in] identifier[search_results] :
identifier[username] = identifier[i] [ literal[st... | def dedup_search_results(search_results):
""" dedup results
"""
known = set()
deduped_results = []
for i in search_results:
username = i['username']
if username in known:
continue # depends on [control=['if'], data=[]]
deduped_results.append(i)
known.add(... |
def load_stylesheet():
"""
Loads the stylesheet for use in a pyqt5 application.
:return the stylesheet string
"""
# Smart import of the rc file
f = QtCore.QFile(':qdarkgraystyle/style.qss')
if not f.exists():
_logger().error('Unable to load stylesheet, file not found in '
... | def function[load_stylesheet, parameter[]]:
constant[
Loads the stylesheet for use in a pyqt5 application.
:return the stylesheet string
]
variable[f] assign[=] call[name[QtCore].QFile, parameter[constant[:qdarkgraystyle/style.qss]]]
if <ast.UnaryOp object at 0x7da2041d8430> begin[:]... | keyword[def] identifier[load_stylesheet] ():
literal[string]
identifier[f] = identifier[QtCore] . identifier[QFile] ( literal[string] )
keyword[if] keyword[not] identifier[f] . identifier[exists] ():
identifier[_logger] (). identifier[error] ( literal[string]
literal[string]... | def load_stylesheet():
"""
Loads the stylesheet for use in a pyqt5 application.
:return the stylesheet string
"""
# Smart import of the rc file
f = QtCore.QFile(':qdarkgraystyle/style.qss')
if not f.exists():
_logger().error('Unable to load stylesheet, file not found in resources')
... |
def parse(self):
"""Parse pattern list."""
result = ['']
negative = False
p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars)
p = p.decode('latin-1') if self.is_bytes else p
if is_negative(p, self.flags):
negative = True
p = p[1:]... | def function[parse, parameter[self]]:
constant[Parse pattern list.]
variable[result] assign[=] list[[<ast.Constant object at 0x7da1b05687f0>]]
variable[negative] assign[=] constant[False]
variable[p] assign[=] call[name[util].norm_pattern, parameter[name[self].pattern, <ast.UnaryOp objec... | keyword[def] identifier[parse] ( identifier[self] ):
literal[string]
identifier[result] =[ literal[string] ]
identifier[negative] = keyword[False]
identifier[p] = identifier[util] . identifier[norm_pattern] ( identifier[self] . identifier[pattern] , keyword[not] identifier[sel... | def parse(self):
"""Parse pattern list."""
result = ['']
negative = False
p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars)
p = p.decode('latin-1') if self.is_bytes else p
if is_negative(p, self.flags):
negative = True
p = p[1:] # depends on [control=['if'], dat... |
def _generate_union_class_variant_creators(self, ns, data_type):
"""
Each non-symbol, non-any variant has a corresponding class method that
can be used to construct a union with that variant selected.
"""
for field in data_type.fields:
if not is_void_type(field.data_t... | def function[_generate_union_class_variant_creators, parameter[self, ns, data_type]]:
constant[
Each non-symbol, non-any variant has a corresponding class method that
can be used to construct a union with that variant selected.
]
for taget[name[field]] in starred[name[data_type].... | keyword[def] identifier[_generate_union_class_variant_creators] ( identifier[self] , identifier[ns] , identifier[data_type] ):
literal[string]
keyword[for] identifier[field] keyword[in] identifier[data_type] . identifier[fields] :
keyword[if] keyword[not] identifier[is_void_type] ... | def _generate_union_class_variant_creators(self, ns, data_type):
"""
Each non-symbol, non-any variant has a corresponding class method that
can be used to construct a union with that variant selected.
"""
for field in data_type.fields:
if not is_void_type(field.data_type):
... |
def swo_set_host_buffer_size(self, buf_size):
"""Sets the size of the buffer used by the host to collect SWO data.
Args:
self (JLink): the ``JLink`` instance
buf_size (int): the new size of the host buffer
Returns:
``None``
Raises:
JLinkExceptio... | def function[swo_set_host_buffer_size, parameter[self, buf_size]]:
constant[Sets the size of the buffer used by the host to collect SWO data.
Args:
self (JLink): the ``JLink`` instance
buf_size (int): the new size of the host buffer
Returns:
``None``
Rais... | keyword[def] identifier[swo_set_host_buffer_size] ( identifier[self] , identifier[buf_size] ):
literal[string]
identifier[buf] = identifier[ctypes] . identifier[c_uint32] ( identifier[buf_size] )
identifier[res] = identifier[self] . identifier[_dll] . identifier[JLINKARM_SWO_Control] ( ide... | def swo_set_host_buffer_size(self, buf_size):
"""Sets the size of the buffer used by the host to collect SWO data.
Args:
self (JLink): the ``JLink`` instance
buf_size (int): the new size of the host buffer
Returns:
``None``
Raises:
JLinkException: o... |
def get_site_packages(venv):
'''
Return the path to the site-packages directory of a virtualenv
venv
Path to the virtualenv.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_site_packages /path/to/my/venv
'''
bin_path = _verify_virtualenv(venv)
ret = __salt_... | def function[get_site_packages, parameter[venv]]:
constant[
Return the path to the site-packages directory of a virtualenv
venv
Path to the virtualenv.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_site_packages /path/to/my/venv
]
variable[bin_path] as... | keyword[def] identifier[get_site_packages] ( identifier[venv] ):
literal[string]
identifier[bin_path] = identifier[_verify_virtualenv] ( identifier[venv] )
identifier[ret] = identifier[__salt__] [ literal[string] ](
identifier[bin_path] ,
literal[string]
literal[string]
)
k... | def get_site_packages(venv):
"""
Return the path to the site-packages directory of a virtualenv
venv
Path to the virtualenv.
CLI Example:
.. code-block:: bash
salt '*' virtualenv.get_site_packages /path/to/my/venv
"""
bin_path = _verify_virtualenv(venv)
ret = __salt__... |
def fetch_all_first_values(session: Session,
select_statement: Select) -> List[Any]:
"""
Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
http://xion.io/post/code/sqlalchemy-query-values.html
Args:
... | def function[fetch_all_first_values, parameter[session, select_statement]]:
constant[
Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
http://xion.io/post/code/sqlalchemy-query-values.html
Args:
session: SQLAlchemy... | keyword[def] identifier[fetch_all_first_values] ( identifier[session] : identifier[Session] ,
identifier[select_statement] : identifier[Select] )-> identifier[List] [ identifier[Any] ]:
literal[string]
identifier[rows] = identifier[session] . identifier[execute] ( identifier[select_statement] )
keywo... | def fetch_all_first_values(session: Session, select_statement: Select) -> List[Any]:
"""
Returns a list of the first values in each row returned by a ``SELECT``
query.
A Core version of this sort of thing:
http://xion.io/post/code/sqlalchemy-query-values.html
Args:
session: SQLAlchemy ... |
def _create_encoding_layers(self):
"""Create the encoding layers for supervised finetuning.
:return: output of the final encoding layer.
"""
next_train = self.input_data
self.layer_nodes = []
for l, layer in enumerate(self.layers):
with tf.name_scope("encod... | def function[_create_encoding_layers, parameter[self]]:
constant[Create the encoding layers for supervised finetuning.
:return: output of the final encoding layer.
]
variable[next_train] assign[=] name[self].input_data
name[self].layer_nodes assign[=] list[[]]
for taget[... | keyword[def] identifier[_create_encoding_layers] ( identifier[self] ):
literal[string]
identifier[next_train] = identifier[self] . identifier[input_data]
identifier[self] . identifier[layer_nodes] =[]
keyword[for] identifier[l] , identifier[layer] keyword[in] identifier[enume... | def _create_encoding_layers(self):
"""Create the encoding layers for supervised finetuning.
:return: output of the final encoding layer.
"""
next_train = self.input_data
self.layer_nodes = []
for (l, layer) in enumerate(self.layers):
with tf.name_scope('encode-{}'.format(l)):
... |
def SetSchema(self, schema):
"""Use XSD Schema to validate the document as it is processed.
Activation is only possible before the first Read(). if
@schema is None, then Schema validation is desactivated. @
The @schema should not be freed until the reader is
deallocated ... | def function[SetSchema, parameter[self, schema]]:
constant[Use XSD Schema to validate the document as it is processed.
Activation is only possible before the first Read(). if
@schema is None, then Schema validation is desactivated. @
The @schema should not be freed until the reader... | keyword[def] identifier[SetSchema] ( identifier[self] , identifier[schema] ):
literal[string]
keyword[if] identifier[schema] keyword[is] keyword[None] : identifier[schema__o] = keyword[None]
keyword[else] : identifier[schema__o] = identifier[schema] . identifier[_o]
identifie... | def SetSchema(self, schema):
"""Use XSD Schema to validate the document as it is processed.
Activation is only possible before the first Read(). if
@schema is None, then Schema validation is desactivated. @
The @schema should not be freed until the reader is
deallocated or i... |
def setControl(
self, request_type, request, value, index, buffer_or_len,
callback=None, user_data=None, timeout=0):
"""
Setup transfer for control use.
request_type, request, value, index
See USBDeviceHandle.controlWrite.
request_type defines tra... | def function[setControl, parameter[self, request_type, request, value, index, buffer_or_len, callback, user_data, timeout]]:
constant[
Setup transfer for control use.
request_type, request, value, index
See USBDeviceHandle.controlWrite.
request_type defines transfer dire... | keyword[def] identifier[setControl] (
identifier[self] , identifier[request_type] , identifier[request] , identifier[value] , identifier[index] , identifier[buffer_or_len] ,
identifier[callback] = keyword[None] , identifier[user_data] = keyword[None] , identifier[timeout] = literal[int] ):
literal[string] ... | def setControl(self, request_type, request, value, index, buffer_or_len, callback=None, user_data=None, timeout=0):
"""
Setup transfer for control use.
request_type, request, value, index
See USBDeviceHandle.controlWrite.
request_type defines transfer direction (see
... |
def rmsd_eval(cls, specification, sequences, parameters, reference_ampal,
**kwargs):
"""Creates optimizer with default build and RMSD eval.
Notes
-----
Any keyword arguments will be propagated down to BaseOptimizer.
RMSD eval is restricted to a single core onl... | def function[rmsd_eval, parameter[cls, specification, sequences, parameters, reference_ampal]]:
constant[Creates optimizer with default build and RMSD eval.
Notes
-----
Any keyword arguments will be propagated down to BaseOptimizer.
RMSD eval is restricted to a single core only... | keyword[def] identifier[rmsd_eval] ( identifier[cls] , identifier[specification] , identifier[sequences] , identifier[parameters] , identifier[reference_ampal] ,
** identifier[kwargs] ):
literal[string]
identifier[eval_fn] = identifier[make_rmsd_eval] ( identifier[reference_ampal] )
identi... | def rmsd_eval(cls, specification, sequences, parameters, reference_ampal, **kwargs):
"""Creates optimizer with default build and RMSD eval.
Notes
-----
Any keyword arguments will be propagated down to BaseOptimizer.
RMSD eval is restricted to a single core only, due to restrictions... |
def search_handle(self, URL=None, prefix=None, **key_value_pairs):
'''
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, th... | def function[search_handle, parameter[self, URL, prefix]]:
constant[
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, the ... | keyword[def] identifier[search_handle] ( identifier[self] , identifier[URL] = keyword[None] , identifier[prefix] = keyword[None] ,** identifier[key_value_pairs] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] )
identifier[list_of_handles] = identifier[self] . i... | def search_handle(self, URL=None, prefix=None, **key_value_pairs):
"""
Search for handles containing the specified key with the specified
value. The search terms are passed on to the reverse lookup servlet
as-is. The servlet is supposed to be case-insensitive, but if it
isn't, the wr... |
def _worker_thread_transfer(self):
# type: (SyncCopy) -> None
"""Worker thread download
:param SyncCopy self: this
"""
while not self.termination_check:
try:
sd = self._transfer_queue.get(block=False, timeout=0.1)
except queue.Empty:
... | def function[_worker_thread_transfer, parameter[self]]:
constant[Worker thread download
:param SyncCopy self: this
]
while <ast.UnaryOp object at 0x7da207f9a6b0> begin[:]
<ast.Try object at 0x7da207f99f00>
<ast.Try object at 0x7da1b1082830> | keyword[def] identifier[_worker_thread_transfer] ( identifier[self] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[termination_check] :
keyword[try] :
identifier[sd] = identifier[self] . identifier[_transfer_queue] . identifier[get] ( i... | def _worker_thread_transfer(self):
# type: (SyncCopy) -> None
'Worker thread download\n :param SyncCopy self: this\n '
while not self.termination_check:
try:
sd = self._transfer_queue.get(block=False, timeout=0.1) # depends on [control=['try'], data=[]]
except queu... |
def wait_for_at_least_one_message(self, channel):
"""
Reads until we receive at least one message we can unpack. Return all found messages.
"""
unpacker = msgpack.Unpacker(encoding='utf-8')
while True:
try:
start = time.time()
chunk =... | def function[wait_for_at_least_one_message, parameter[self, channel]]:
constant[
Reads until we receive at least one message we can unpack. Return all found messages.
]
variable[unpacker] assign[=] call[name[msgpack].Unpacker, parameter[]]
while constant[True] begin[:]
<a... | keyword[def] identifier[wait_for_at_least_one_message] ( identifier[self] , identifier[channel] ):
literal[string]
identifier[unpacker] = identifier[msgpack] . identifier[Unpacker] ( identifier[encoding] = literal[string] )
keyword[while] keyword[True] :
keyword[try] :
... | def wait_for_at_least_one_message(self, channel):
"""
Reads until we receive at least one message we can unpack. Return all found messages.
"""
unpacker = msgpack.Unpacker(encoding='utf-8')
while True:
try:
start = time.time()
chunk = self.ssh_channel[channel]... |
def get_hardware_grains(service_instance):
'''
Return hardware info for standard minion grains if the service_instance is a HostAgent type
service_instance
The service instance object to get hardware info for
.. versionadded:: 2016.11.0
'''
hw_grain_data = {}
if get_inventory(servi... | def function[get_hardware_grains, parameter[service_instance]]:
constant[
Return hardware info for standard minion grains if the service_instance is a HostAgent type
service_instance
The service instance object to get hardware info for
.. versionadded:: 2016.11.0
]
variable[hw_... | keyword[def] identifier[get_hardware_grains] ( identifier[service_instance] ):
literal[string]
identifier[hw_grain_data] ={}
keyword[if] identifier[get_inventory] ( identifier[service_instance] ). identifier[about] . identifier[apiType] == literal[string] :
identifier[view] = identifier[serv... | def get_hardware_grains(service_instance):
"""
Return hardware info for standard minion grains if the service_instance is a HostAgent type
service_instance
The service instance object to get hardware info for
.. versionadded:: 2016.11.0
"""
hw_grain_data = {}
if get_inventory(servi... |
def write_hw_scgink(hw, filename='mathbrush-test.txt'):
"""
Parameters
----------
hw : HandwrittenData object
filename : string
Path, where the SCG INK file gets written
"""
with open(filename, 'w') as f:
f.write('SCG_INK\n')
f.write('%i\n' % len(hw.get_pointlist()))
... | def function[write_hw_scgink, parameter[hw, filename]]:
constant[
Parameters
----------
hw : HandwrittenData object
filename : string
Path, where the SCG INK file gets written
]
with call[name[open], parameter[name[filename], constant[w]]] begin[:]
call[name[f... | keyword[def] identifier[write_hw_scgink] ( identifier[hw] , identifier[filename] = literal[string] ):
literal[string]
keyword[with] identifier[open] ( identifier[filename] , literal[string] ) keyword[as] identifier[f] :
identifier[f] . identifier[write] ( literal[string] )
identifier[f]... | def write_hw_scgink(hw, filename='mathbrush-test.txt'):
"""
Parameters
----------
hw : HandwrittenData object
filename : string
Path, where the SCG INK file gets written
"""
with open(filename, 'w') as f:
f.write('SCG_INK\n')
f.write('%i\n' % len(hw.get_pointlist()))
... |
def needs_restart(self, option_fingerprint):
"""
Overrides ProcessManager.needs_restart, to account for the case where pantsd is running
but we want to shutdown after this run.
:param option_fingerprint: A fingeprint of the global bootstrap options.
:return: True if the daemon needs to restart.
... | def function[needs_restart, parameter[self, option_fingerprint]]:
constant[
Overrides ProcessManager.needs_restart, to account for the case where pantsd is running
but we want to shutdown after this run.
:param option_fingerprint: A fingeprint of the global bootstrap options.
:return: True if th... | keyword[def] identifier[needs_restart] ( identifier[self] , identifier[option_fingerprint] ):
literal[string]
identifier[should_shutdown_after_run] = identifier[self] . identifier[_bootstrap_options] . identifier[for_global_scope] (). identifier[shutdown_pantsd_after_run]
keyword[return] identifier[... | def needs_restart(self, option_fingerprint):
"""
Overrides ProcessManager.needs_restart, to account for the case where pantsd is running
but we want to shutdown after this run.
:param option_fingerprint: A fingeprint of the global bootstrap options.
:return: True if the daemon needs to restart.
... |
def _gen_indicator_class(self):
"""Generate Custom Indicator Classes."""
for entry in self.tcex.indicator_types_data.values():
name = entry.get('name')
class_name = name.replace(' ', '')
# temp fix for API issue where boolean are returned as strings
entry... | def function[_gen_indicator_class, parameter[self]]:
constant[Generate Custom Indicator Classes.]
for taget[name[entry]] in starred[call[name[self].tcex.indicator_types_data.values, parameter[]]] begin[:]
variable[name] assign[=] call[name[entry].get, parameter[constant[name]]]
... | keyword[def] identifier[_gen_indicator_class] ( identifier[self] ):
literal[string]
keyword[for] identifier[entry] keyword[in] identifier[self] . identifier[tcex] . identifier[indicator_types_data] . identifier[values] ():
identifier[name] = identifier[entry] . identifier[get] ( li... | def _gen_indicator_class(self):
"""Generate Custom Indicator Classes."""
for entry in self.tcex.indicator_types_data.values():
name = entry.get('name')
class_name = name.replace(' ', '')
# temp fix for API issue where boolean are returned as strings
entry['custom'] = self.tcex.ut... |
def append(self,text):
"""Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech)
"""
if text is Text:
... | def function[append, parameter[self, text]]:
constant[Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech)
]
i... | keyword[def] identifier[append] ( identifier[self] , identifier[text] ):
literal[string]
keyword[if] identifier[text] keyword[is] identifier[Text] :
identifier[text] = identifier[Text] ( identifier[self] , identifier[id] = identifier[self] . identifier[id] + literal[string] + identi... | def append(self, text):
"""Add a text (or speech) to the document:
Example 1::
doc.append(folia.Text)
Example 2::
doc.append( folia.Text(doc, id='example.text') )
Example 3::
doc.append(folia.Speech)
"""
if text is Text:
text = Te... |
def experiment_property(prop):
"""Get a property of the experiment by name."""
exp = Experiment(session)
try:
value = exp.public_properties[prop]
except KeyError:
abort(404)
return success_response(**{prop: value}) | def function[experiment_property, parameter[prop]]:
constant[Get a property of the experiment by name.]
variable[exp] assign[=] call[name[Experiment], parameter[name[session]]]
<ast.Try object at 0x7da1b04a4910>
return[call[name[success_response], parameter[]]] | keyword[def] identifier[experiment_property] ( identifier[prop] ):
literal[string]
identifier[exp] = identifier[Experiment] ( identifier[session] )
keyword[try] :
identifier[value] = identifier[exp] . identifier[public_properties] [ identifier[prop] ]
keyword[except] identifier[KeyError... | def experiment_property(prop):
"""Get a property of the experiment by name."""
exp = Experiment(session)
try:
value = exp.public_properties[prop] # depends on [control=['try'], data=[]]
except KeyError:
abort(404) # depends on [control=['except'], data=[]]
return success_response(*... |
def deactivatable(self, value):
"""
Setter for **self.__deactivatable** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format("deactivatable", val... | def function[deactivatable, parameter[self, value]]:
constant[
Setter for **self.__deactivatable** attribute.
:param value: Attribute value.
:type value: bool
]
if compare[name[value] is_not constant[None]] begin[:]
assert[compare[call[name[type], parameter[name[... | keyword[def] identifier[deactivatable] ( identifier[self] , identifier[value] ):
literal[string]
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
keyword[assert] identifier[type] ( identifier[value] ) keyword[is] identifier[bool] , literal[string] . identif... | def deactivatable(self, value):
"""
Setter for **self.__deactivatable** attribute.
:param value: Attribute value.
:type value: bool
"""
if value is not None:
assert type(value) is bool, "'{0}' attribute: '{1}' type is not 'bool'!".format('deactivatable', value) # depend... |
def wrap_output(output, encoding):
"""Return output with specified encoding."""
return codecs.getwriter(encoding)(output.buffer
if hasattr(output, 'buffer')
else output) | def function[wrap_output, parameter[output, encoding]]:
constant[Return output with specified encoding.]
return[call[call[name[codecs].getwriter, parameter[name[encoding]]], parameter[<ast.IfExp object at 0x7da18c4cc640>]]] | keyword[def] identifier[wrap_output] ( identifier[output] , identifier[encoding] ):
literal[string]
keyword[return] identifier[codecs] . identifier[getwriter] ( identifier[encoding] )( identifier[output] . identifier[buffer]
keyword[if] identifier[hasattr] ( identifier[output] , literal[string] )
... | def wrap_output(output, encoding):
"""Return output with specified encoding."""
return codecs.getwriter(encoding)(output.buffer if hasattr(output, 'buffer') else output) |
def cut_video_stream(stream, start, end, fmt):
""" cut video stream from `start` to `end` time
Parameters
----------
stream : bytes
video file content
start : float
start time
end : float
end time
Returns
-------
result : bytes
content of cut video
... | def function[cut_video_stream, parameter[stream, start, end, fmt]]:
constant[ cut video stream from `start` to `end` time
Parameters
----------
stream : bytes
video file content
start : float
start time
end : float
end time
Returns
-------
result : bytes... | keyword[def] identifier[cut_video_stream] ( identifier[stream] , identifier[start] , identifier[end] , identifier[fmt] ):
literal[string]
keyword[with] identifier[TemporaryDirectory] () keyword[as] identifier[tmp] :
identifier[in_file] = identifier[Path] ( identifier[tmp] )/ literal[string]
... | def cut_video_stream(stream, start, end, fmt):
""" cut video stream from `start` to `end` time
Parameters
----------
stream : bytes
video file content
start : float
start time
end : float
end time
Returns
-------
result : bytes
content of cut video
... |
def get_scoreboard(year, month, day):
"""Return the game file for a certain day matching certain criteria."""
try:
data = urlopen(BASE_URL.format(year, month, day) + 'scoreboard.xml')
except HTTPError:
data = os.path.join(PWD, 'default.xml')
return data | def function[get_scoreboard, parameter[year, month, day]]:
constant[Return the game file for a certain day matching certain criteria.]
<ast.Try object at 0x7da18f09f2b0>
return[name[data]] | keyword[def] identifier[get_scoreboard] ( identifier[year] , identifier[month] , identifier[day] ):
literal[string]
keyword[try] :
identifier[data] = identifier[urlopen] ( identifier[BASE_URL] . identifier[format] ( identifier[year] , identifier[month] , identifier[day] )+ literal[string] )
k... | def get_scoreboard(year, month, day):
"""Return the game file for a certain day matching certain criteria."""
try:
data = urlopen(BASE_URL.format(year, month, day) + 'scoreboard.xml') # depends on [control=['try'], data=[]]
except HTTPError:
data = os.path.join(PWD, 'default.xml') # depend... |
def get(self, pk, cascadeFetch=False):
'''
get - Get a single value with the internal primary key.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@param pk - internal ... | def function[get, parameter[self, pk, cascadeFetch]]:
constant[
get - Get a single value with the internal primary key.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access... | keyword[def] identifier[get] ( identifier[self] , identifier[pk] , identifier[cascadeFetch] = keyword[False] ):
literal[string]
identifier[conn] = identifier[self] . identifier[_get_connection] ()
identifier[key] = identifier[self] . identifier[_get_key_for_id] ( identifier[pk] )
identifier[res] = identi... | def get(self, pk, cascadeFetch=False):
"""
get - Get a single value with the internal primary key.
@param cascadeFetch <bool> Default False, If True, all Foreign objects associated with this model
will be fetched immediately. If False, foreign objects will be fetched on-access.
@param pk - interna... |
def aslctrl_data_encode(self, timestamp, aslctrl_mode, h, hRef, hRef_t, PitchAngle, PitchAngleRef, q, qRef, uElev, uThrot, uThrot2, nZ, AirspeedRef, SpoilersEngaged, YawAngle, YawAngleRef, RollAngle, RollAngleRef, p, pRef, r, rRef, uAil, uRud):
'''
ASL-fixed-wing controller data
... | def function[aslctrl_data_encode, parameter[self, timestamp, aslctrl_mode, h, hRef, hRef_t, PitchAngle, PitchAngleRef, q, qRef, uElev, uThrot, uThrot2, nZ, AirspeedRef, SpoilersEngaged, YawAngle, YawAngleRef, RollAngle, RollAngleRef, p, pRef, r, rRef, uAil, uRud]]:
constant[
ASL-fixed-wing contr... | keyword[def] identifier[aslctrl_data_encode] ( identifier[self] , identifier[timestamp] , identifier[aslctrl_mode] , identifier[h] , identifier[hRef] , identifier[hRef_t] , identifier[PitchAngle] , identifier[PitchAngleRef] , identifier[q] , identifier[qRef] , identifier[uElev] , identifier[uThrot] , identifier[uThro... | def aslctrl_data_encode(self, timestamp, aslctrl_mode, h, hRef, hRef_t, PitchAngle, PitchAngleRef, q, qRef, uElev, uThrot, uThrot2, nZ, AirspeedRef, SpoilersEngaged, YawAngle, YawAngleRef, RollAngle, RollAngleRef, p, pRef, r, rRef, uAil, uRud):
"""
ASL-fixed-wing controller data
tim... |
def compute_style_factor_exposures(positions, risk_factor):
"""
Returns style factor exposure of an algorithm's positions
Parameters
----------
positions : pd.DataFrame
Daily equity positions of algorithm, in dollars.
- See full explanation in create_risk_tear_sheet
risk_factor... | def function[compute_style_factor_exposures, parameter[positions, risk_factor]]:
constant[
Returns style factor exposure of an algorithm's positions
Parameters
----------
positions : pd.DataFrame
Daily equity positions of algorithm, in dollars.
- See full explanation in create_r... | keyword[def] identifier[compute_style_factor_exposures] ( identifier[positions] , identifier[risk_factor] ):
literal[string]
identifier[positions_wo_cash] = identifier[positions] . identifier[drop] ( literal[string] , identifier[axis] = literal[string] )
identifier[gross_exposure] = identifier[positi... | def compute_style_factor_exposures(positions, risk_factor):
"""
Returns style factor exposure of an algorithm's positions
Parameters
----------
positions : pd.DataFrame
Daily equity positions of algorithm, in dollars.
- See full explanation in create_risk_tear_sheet
risk_factor... |
def is_valid_value(value, type):
# type: (Any, Any) -> List
"""Given a type and any value, return True if that value is valid."""
if isinstance(type, GraphQLNonNull):
of_type = type.of_type
if value is None:
return [u'Expected "{}", found null.'.format(type)]
return is_v... | def function[is_valid_value, parameter[value, type]]:
constant[Given a type and any value, return True if that value is valid.]
if call[name[isinstance], parameter[name[type], name[GraphQLNonNull]]] begin[:]
variable[of_type] assign[=] name[type].of_type
if compare[name[v... | keyword[def] identifier[is_valid_value] ( identifier[value] , identifier[type] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[type] , identifier[GraphQLNonNull] ):
identifier[of_type] = identifier[type] . identifier[of_type]
keyword[if] identifier[value] keyword[i... | def is_valid_value(value, type):
# type: (Any, Any) -> List
'Given a type and any value, return True if that value is valid.'
if isinstance(type, GraphQLNonNull):
of_type = type.of_type
if value is None:
return [u'Expected "{}", found null.'.format(type)] # depends on [control=[... |
def replacement_template(rep, source, span, npar):
"""Takes the replacement template and some info about the match and returns filled template
"""
n = 0
res = ''
while n < len(rep) - 1:
char = rep[n]
if char == '$':
if rep[n + 1] == '$':
res += '$'
... | def function[replacement_template, parameter[rep, source, span, npar]]:
constant[Takes the replacement template and some info about the match and returns filled template
]
variable[n] assign[=] constant[0]
variable[res] assign[=] constant[]
while compare[name[n] less[<] binary_ope... | keyword[def] identifier[replacement_template] ( identifier[rep] , identifier[source] , identifier[span] , identifier[npar] ):
literal[string]
identifier[n] = literal[int]
identifier[res] = literal[string]
keyword[while] identifier[n] < identifier[len] ( identifier[rep] )- literal[int] :
... | def replacement_template(rep, source, span, npar):
"""Takes the replacement template and some info about the match and returns filled template
"""
n = 0
res = ''
while n < len(rep) - 1:
char = rep[n]
if char == '$':
if rep[n + 1] == '$':
res += '$'
... |
def optimize(self, n_iter, inplace=False, propagate_exception=False,
**gradient_descent_params):
"""Run optmization on the embedding for a given number of steps.
Parameters
----------
n_iter: int
The number of optimization iterations.
learning_rate:... | def function[optimize, parameter[self, n_iter, inplace, propagate_exception]]:
constant[Run optmization on the embedding for a given number of steps.
Parameters
----------
n_iter: int
The number of optimization iterations.
learning_rate: float
The learni... | keyword[def] identifier[optimize] ( identifier[self] , identifier[n_iter] , identifier[inplace] = keyword[False] , identifier[propagate_exception] = keyword[False] ,
** identifier[gradient_descent_params] ):
literal[string]
keyword[if] identifier[inplace] :
identifier[embeddi... | def optimize(self, n_iter, inplace=False, propagate_exception=False, **gradient_descent_params):
"""Run optmization on the embedding for a given number of steps.
Parameters
----------
n_iter: int
The number of optimization iterations.
learning_rate: float
Th... |
def all(self, start=0, amount=10):
"""
Return a list of all users
:rtype: list
"""
return self._get_json('user/all', start=start, amount=amount) | def function[all, parameter[self, start, amount]]:
constant[
Return a list of all users
:rtype: list
]
return[call[name[self]._get_json, parameter[constant[user/all]]]] | keyword[def] identifier[all] ( identifier[self] , identifier[start] = literal[int] , identifier[amount] = literal[int] ):
literal[string]
keyword[return] identifier[self] . identifier[_get_json] ( literal[string] , identifier[start] = identifier[start] , identifier[amount] = identifier[amount] ) | def all(self, start=0, amount=10):
"""
Return a list of all users
:rtype: list
"""
return self._get_json('user/all', start=start, amount=amount) |
def unhook_wnd_proc(self):
"""Restore previous Window message handler"""
if not self.__local_wnd_proc_wrapped:
return
SetWindowLong(self.__local_win_handle,
GWL_WNDPROC,
self.__old_wnd_proc)
## Allow the ctypes wrapper ... | def function[unhook_wnd_proc, parameter[self]]:
constant[Restore previous Window message handler]
if <ast.UnaryOp object at 0x7da1b06bd330> begin[:]
return[None]
call[name[SetWindowLong], parameter[name[self].__local_win_handle, name[GWL_WNDPROC], name[self].__old_wnd_proc]]
name... | keyword[def] identifier[unhook_wnd_proc] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[__local_wnd_proc_wrapped] :
keyword[return]
identifier[SetWindowLong] ( identifier[self] . identifier[__local_win_handle] ,
id... | def unhook_wnd_proc(self):
"""Restore previous Window message handler"""
if not self.__local_wnd_proc_wrapped:
return # depends on [control=['if'], data=[]]
SetWindowLong(self.__local_win_handle, GWL_WNDPROC, self.__old_wnd_proc) ## Allow the ctypes wrapper to be garbage collected
self.__local... |
def clean(self):
"""
Remove unused filters.
"""
for f in sorted(self.components.keys()):
unused = not any(self.switches[a][f] for a in self.analytes)
if unused:
self.remove(f) | def function[clean, parameter[self]]:
constant[
Remove unused filters.
]
for taget[name[f]] in starred[call[name[sorted], parameter[call[name[self].components.keys, parameter[]]]]] begin[:]
variable[unused] assign[=] <ast.UnaryOp object at 0x7da18f720460>
... | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
keyword[for] identifier[f] keyword[in] identifier[sorted] ( identifier[self] . identifier[components] . identifier[keys] ()):
identifier[unused] = keyword[not] identifier[any] ( identifier[self] . identifier[switc... | def clean(self):
"""
Remove unused filters.
"""
for f in sorted(self.components.keys()):
unused = not any((self.switches[a][f] for a in self.analytes))
if unused:
self.remove(f) # depends on [control=['if'], data=[]] # depends on [control=['for'], data=['f']] |
def setup_locale(lc_all: str,
first_weekday: int = None,
*,
lc_collate: str = None,
lc_ctype: str = None,
lc_messages: str = None,
lc_monetary: str = None,
lc_numeric: str = None,
lc_t... | def function[setup_locale, parameter[lc_all, first_weekday]]:
constant[Shortcut helper to setup locale for backend application.
:param lc_all: Locale to use.
:param first_weekday:
Weekday for start week. 0 for Monday, 6 for Sunday. By default: None
:param lc_collate: Collate locale to use. ... | keyword[def] identifier[setup_locale] ( identifier[lc_all] : identifier[str] ,
identifier[first_weekday] : identifier[int] = keyword[None] ,
*,
identifier[lc_collate] : identifier[str] = keyword[None] ,
identifier[lc_ctype] : identifier[str] = keyword[None] ,
identifier[lc_messages] : identifier[str] = keyword[No... | def setup_locale(lc_all: str, first_weekday: int=None, *, lc_collate: str=None, lc_ctype: str=None, lc_messages: str=None, lc_monetary: str=None, lc_numeric: str=None, lc_time: str=None) -> str:
"""Shortcut helper to setup locale for backend application.
:param lc_all: Locale to use.
:param first_weekday:
... |
def count_list(the_list):
"""
Generates a count of the number of times each unique item appears in a list
"""
count = the_list.count
result = [(item, count(item)) for item in set(the_list)]
result.sort()
return result | def function[count_list, parameter[the_list]]:
constant[
Generates a count of the number of times each unique item appears in a list
]
variable[count] assign[=] name[the_list].count
variable[result] assign[=] <ast.ListComp object at 0x7da207f03d30>
call[name[result].sort, paramet... | keyword[def] identifier[count_list] ( identifier[the_list] ):
literal[string]
identifier[count] = identifier[the_list] . identifier[count]
identifier[result] =[( identifier[item] , identifier[count] ( identifier[item] )) keyword[for] identifier[item] keyword[in] identifier[set] ( identifier[the_li... | def count_list(the_list):
"""
Generates a count of the number of times each unique item appears in a list
"""
count = the_list.count
result = [(item, count(item)) for item in set(the_list)]
result.sort()
return result |
def label(self, name):
"""Get the label specified by ``name``
:param str name: (required), name of the label
:returns: :class:`Label <github3.issues.label.Label>` if successful,
else None
"""
json = None
if name:
url = self._build_url('labels', na... | def function[label, parameter[self, name]]:
constant[Get the label specified by ``name``
:param str name: (required), name of the label
:returns: :class:`Label <github3.issues.label.Label>` if successful,
else None
]
variable[json] assign[=] constant[None]
if... | keyword[def] identifier[label] ( identifier[self] , identifier[name] ):
literal[string]
identifier[json] = keyword[None]
keyword[if] identifier[name] :
identifier[url] = identifier[self] . identifier[_build_url] ( literal[string] , identifier[name] , identifier[base_url] = i... | def label(self, name):
"""Get the label specified by ``name``
:param str name: (required), name of the label
:returns: :class:`Label <github3.issues.label.Label>` if successful,
else None
"""
json = None
if name:
url = self._build_url('labels', name, base_url=sel... |
def check_AP_deriv(abf,n=10):
"""X"""
timePoints=get_AP_timepoints(abf)[:10] #first 10
if len(timePoints)==0:
return
swhlab.plot.new(abf,True,title="AP velocity (n=%d)"%n,xlabel="ms",ylabel="V/S")
pylab.axhline(-50,color='r',lw=2,ls="--",alpha=.2)
pylab.axhline(-100,color='r',lw=2,ls="--... | def function[check_AP_deriv, parameter[abf, n]]:
constant[X]
variable[timePoints] assign[=] call[call[name[get_AP_timepoints], parameter[name[abf]]]][<ast.Slice object at 0x7da1afe196c0>]
if compare[call[name[len], parameter[name[timePoints]]] equal[==] constant[0]] begin[:]
return[None]... | keyword[def] identifier[check_AP_deriv] ( identifier[abf] , identifier[n] = literal[int] ):
literal[string]
identifier[timePoints] = identifier[get_AP_timepoints] ( identifier[abf] )[: literal[int] ]
keyword[if] identifier[len] ( identifier[timePoints] )== literal[int] :
keyword[return]
... | def check_AP_deriv(abf, n=10):
"""X"""
timePoints = get_AP_timepoints(abf)[:10] #first 10
if len(timePoints) == 0:
return # depends on [control=['if'], data=[]]
swhlab.plot.new(abf, True, title='AP velocity (n=%d)' % n, xlabel='ms', ylabel='V/S')
pylab.axhline(-50, color='r', lw=2, ls='--'... |
def __create_checksum(self, p):
"""
Calculates the checksum of the packet to be sent to the time clock
Copied from zkemsdk.c
"""
l = len(p)
checksum = 0
while l > 1:
checksum += unpack('H', pack('BB', p[0], p[1]))[0]
p = p[2:]
i... | def function[__create_checksum, parameter[self, p]]:
constant[
Calculates the checksum of the packet to be sent to the time clock
Copied from zkemsdk.c
]
variable[l] assign[=] call[name[len], parameter[name[p]]]
variable[checksum] assign[=] constant[0]
while compa... | keyword[def] identifier[__create_checksum] ( identifier[self] , identifier[p] ):
literal[string]
identifier[l] = identifier[len] ( identifier[p] )
identifier[checksum] = literal[int]
keyword[while] identifier[l] > literal[int] :
identifier[checksum] += identifier[un... | def __create_checksum(self, p):
"""
Calculates the checksum of the packet to be sent to the time clock
Copied from zkemsdk.c
"""
l = len(p)
checksum = 0
while l > 1:
checksum += unpack('H', pack('BB', p[0], p[1]))[0]
p = p[2:]
if checksum > const.USHRT_MAX... |
def finishConnection(self, accept=True):
"""
Finishes the active connection. If the accept value is \
true, then the connection requested signal will be emited, \
otherwise, it will simply clear the active connection \
data.
:param accept <bool>
... | def function[finishConnection, parameter[self, accept]]:
constant[
Finishes the active connection. If the accept value is true, then the connection requested signal will be emited, otherwise, it will simply clear the active connection data.
:param accept ... | keyword[def] identifier[finishConnection] ( identifier[self] , identifier[accept] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[_activeConnection] :
keyword[return]
keyword[if] identifier[accept] :
iden... | def finishConnection(self, accept=True):
"""
Finishes the active connection. If the accept value is true, then the connection requested signal will be emited, otherwise, it will simply clear the active connection data.
:param accept <bool>
"""
... |
def append(self, parent, content):
"""
Append the specified L{content} to the I{parent}.
@param parent: The parent node to append to.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Object}
"""
log.debug('appending parent:\... | def function[append, parameter[self, parent, content]]:
constant[
Append the specified L{content} to the I{parent}.
@param parent: The parent node to append to.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Object}
]
call... | keyword[def] identifier[append] ( identifier[self] , identifier[parent] , identifier[content] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] , identifier[parent] , identifier[content] )
keyword[if] identifier[self] . identifier[start] ( identifier[content] ):
... | def append(self, parent, content):
"""
Append the specified L{content} to the I{parent}.
@param parent: The parent node to append to.
@type parent: L{Element}
@param content: The content to append.
@type content: L{Object}
"""
log.debug('appending parent:\n%s\ncon... |
def _set_cluster(self):
"""
Compute and set the cluster of atoms as a Molecule object. The siteato
coordinates are translated such that the absorbing atom(aka central
atom) is at the origin.
Returns:
Molecule
"""
center = self.struct[self.center_index... | def function[_set_cluster, parameter[self]]:
constant[
Compute and set the cluster of atoms as a Molecule object. The siteato
coordinates are translated such that the absorbing atom(aka central
atom) is at the origin.
Returns:
Molecule
]
variable[cent... | keyword[def] identifier[_set_cluster] ( identifier[self] ):
literal[string]
identifier[center] = identifier[self] . identifier[struct] [ identifier[self] . identifier[center_index] ]. identifier[coords]
identifier[sphere] = identifier[self] . identifier[struct] . identifier[get_neighbors]... | def _set_cluster(self):
"""
Compute and set the cluster of atoms as a Molecule object. The siteato
coordinates are translated such that the absorbing atom(aka central
atom) is at the origin.
Returns:
Molecule
"""
center = self.struct[self.center_index].coords... |
def is_empty(self, indexes=None):
"""
Check if there is data within this tile.
Returns
-------
is empty : bool
"""
# empty if tile does not intersect with file bounding box
return not self.tile.bbox.intersects(
self.raster_file.bbox(out_crs=se... | def function[is_empty, parameter[self, indexes]]:
constant[
Check if there is data within this tile.
Returns
-------
is empty : bool
]
return[<ast.UnaryOp object at 0x7da1b0014d90>] | keyword[def] identifier[is_empty] ( identifier[self] , identifier[indexes] = keyword[None] ):
literal[string]
keyword[return] keyword[not] identifier[self] . identifier[tile] . identifier[bbox] . identifier[intersects] (
identifier[self] . identifier[raster_file] . identifier[bb... | def is_empty(self, indexes=None):
"""
Check if there is data within this tile.
Returns
-------
is empty : bool
"""
# empty if tile does not intersect with file bounding box
return not self.tile.bbox.intersects(self.raster_file.bbox(out_crs=self.tile.crs)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.