code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_introspection_data(cls, tax_benefit_system):
"""
Get instrospection data about the code of the variable.
:returns: (comments, source file path, source code, start line number)
:rtype: tuple
"""
comments = inspect.getcomments(cls)
# Handle dynamically ge... | Get instrospection data about the code of the variable.
:returns: (comments, source file path, source code, start line number)
:rtype: tuple |
def _extract_object_params(self, name):
"""
Extract object params, return as dict
"""
params = self.request.query_params.lists()
params_map = {}
prefix = name[:-1]
offset = len(prefix)
for name, value in params:
if name.startswith(prefix):
... | Extract object params, return as dict |
def required_from_env(key):
"""
Retrieve a required variable from the current environment variables.
Raises a ValueError if the env variable is not found or has no value.
"""
val = os.environ.get(key)
if not val:
raise ValueError(
"Required argument '{}' not supplied and no... | Retrieve a required variable from the current environment variables.
Raises a ValueError if the env variable is not found or has no value. |
def system_qos_qos_service_policy_direction(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_qos = ET.SubElement(config, "system-qos", xmlns="urn:brocade.com:mgmt:brocade-policer")
qos = ET.SubElement(system_qos, "qos")
service_policy = ET.... | Auto Generated Code |
def clique(graph, id):
""" Returns the largest possible clique for the node with given id.
"""
clique = [id]
for n in graph.nodes:
friend = True
for id in clique:
if n.id == id or graph.edge(n.id, id) == None:
friend = False
break
... | Returns the largest possible clique for the node with given id. |
def status(cwd, opts=None, user=None):
'''
Show changed files of the given repository
cwd
The path to the Mercurial repository
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
CLI Example:
... | Show changed files of the given repository
cwd
The path to the Mercurial repository
opts : None
Any additional options to add to the command line
user : None
Run hg as a user other than what the minion runs as
CLI Example:
.. code-block:: bash
salt '*' hg.status... |
def getitem_es(self, key):
""" Override to support ACL filtering.
To do so: passes `self.request` to `get_item` and uses
`ACLFilterES`.
"""
from nefertari_guards.elasticsearch import ACLFilterES
es = ACLFilterES(self.item_model.__name__)
params = {
'i... | Override to support ACL filtering.
To do so: passes `self.request` to `get_item` and uses
`ACLFilterES`. |
def set(self, safe_len=False, **kwds):
'''Set one or more attributes.
'''
if kwds: # double check
d = self.kwds()
d.update(kwds)
self.reset(**d)
if safe_len and self.item:
self.leng = _len | Set one or more attributes. |
def real(self):
''' Get realtime data
:rtype: dict
:returns: 代碼可以參考:http://goristock.appspot.com/API#apiweight
'''
result = self.__raw['1'].copy()
result['c'] = self.__raw['1']['value']
result['value'] = self.__raw['200']['v2']
result['date'] = se... | Get realtime data
:rtype: dict
:returns: 代碼可以參考:http://goristock.appspot.com/API#apiweight |
def get_single(decl_matcher, decls, recursive=True):
"""
Returns a reference to declaration, that match `decl_matcher` defined
criteria.
If a unique declaration could not be found, an appropriate exception
will be raised.
:param decl_matcher: Python callable object, tha... | Returns a reference to declaration, that match `decl_matcher` defined
criteria.
If a unique declaration could not be found, an appropriate exception
will be raised.
:param decl_matcher: Python callable object, that takes one argument -
reference to a declaration
:pa... |
def location(self, tag=None, fromdate=None, todate=None):
"""
Gets an overview of which part of the email links were clicked from (HTML or Text).
This is only recorded when Link Tracking is enabled for that email.
"""
return self.call("GET", "/stats/outbound/clicks/location", tag... | Gets an overview of which part of the email links were clicked from (HTML or Text).
This is only recorded when Link Tracking is enabled for that email. |
def decode_response(status: int, headers: MutableMapping, body: bytes) -> dict:
"""
Decode incoming response
Args:
status: Response status
headers: Response headers
body: Response body
Returns:
Response data
"""
data = decode_body(headers, body)
raise_for_st... | Decode incoming response
Args:
status: Response status
headers: Response headers
body: Response body
Returns:
Response data |
def update_sql(table, filter, updates):
'''
>>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'})
('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a'])
'''
where_keys, where_vals = _split_dict(filter)
up_keys, up_vals = _split_dict(updates)
changes = _pa... | >>> update_sql('tbl', {'foo': 'a', 'bar': 1}, {'bar': 2, 'baz': 'b'})
('UPDATE tbl SET bar=$1, baz=$2 WHERE bar=$3 AND foo=$4', [2, 'b', 1, 'a']) |
def add_factuality(self,my_fact):
"""
Adds a factuality to the factuality layer
@type my_fact: L{Cfactuality}
@param my_fact: factuality object
"""
if self.factuality_layer is None:
self.factuality_layer = Cfactualities()
self.root.append(self.fact... | Adds a factuality to the factuality layer
@type my_fact: L{Cfactuality}
@param my_fact: factuality object |
def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]):
"""
Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances.
"""
if not identifiers:
return identifiers
def _create_o... | Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances. |
def dump(self):
"""Output all recorded metrics"""
with self.lock:
atexit.unregister(self.dump)
self.fh.close() | Output all recorded metrics |
def eval_constraints(self, constraints):
"""Returns whether the constraints is satisfied trivially by using the
last model."""
# eval_ast is concretizing symbols and evaluating them, this can raise
# exceptions.
try:
return all(self.eval_ast(c) for c in constraints)
... | Returns whether the constraints is satisfied trivially by using the
last model. |
def description(self):
""" Cursor description, see http://legacy.python.org/dev/peps/pep-0249/#description
"""
if self._session is None:
return None
res = self._session.res_info
if res:
return res.description
else:
return None | Cursor description, see http://legacy.python.org/dev/peps/pep-0249/#description |
def regular_to_sparse_from_sparse_mappings(regular_to_unmasked_sparse, unmasked_sparse_to_sparse):
"""Using the mapping between the regular-grid and unmasked pixelization grid, compute the mapping between each regular
pixel and the masked pixelization grid.
Parameters
-----------
regular_to_unmaske... | Using the mapping between the regular-grid and unmasked pixelization grid, compute the mapping between each regular
pixel and the masked pixelization grid.
Parameters
-----------
regular_to_unmasked_sparse : ndarray
The index mapping between every regular-pixel and masked pixelization pixel.
... |
def get_oembed(self, url):
"""Return an oEmbed format json dictionary
:param url: Image page URL (ex. http://gyazo.com/xxxxx)
"""
api_url = self.api_url + '/api/oembed'
parameters = {
'url': url
}
response = self._request_url(api_url, 'get', params=pa... | Return an oEmbed format json dictionary
:param url: Image page URL (ex. http://gyazo.com/xxxxx) |
def disease(self,
identifier=None,
ref_id=None,
ref_type=None,
name=None,
acronym=None,
description=None,
entry_name=None,
limit=None,
as_df=False
):
""... | Method to query :class:`.models.Disease` objects in database
:param identifier: disease UniProt identifier(s)
:type identifier: str or tuple(str) or None
:param ref_id: identifier(s) of referenced database
:type ref_id: str or tuple(str) or None
:param ref_type: database name... |
def del_option_by_number(self, number):
"""
Delete an option from the message by number
:type number: Integer
:param number: option naumber
"""
for o in list(self._options):
assert isinstance(o, Option)
if o.number == number:
self.... | Delete an option from the message by number
:type number: Integer
:param number: option naumber |
def get_form_label(self, request=None, obj=None, model=None, form=None):
"""Returns a customized form label, if condition is met,
otherwise returns the default form label.
* condition is an instance of CustomLabelCondition.
"""
label = form.base_fields[self.field].label
... | Returns a customized form label, if condition is met,
otherwise returns the default form label.
* condition is an instance of CustomLabelCondition. |
def cwt(ts, freqs=np.logspace(0, 2), wavelet=cwtmorlet, plot=True):
"""Continuous wavelet transform
Note the full results can use a huge amount of memory at 64-bit precision
Args:
ts: Timeseries of m variables, shape (n, m). Assumed constant timestep.
freqs: list of frequencies (in Hz) to use f... | Continuous wavelet transform
Note the full results can use a huge amount of memory at 64-bit precision
Args:
ts: Timeseries of m variables, shape (n, m). Assumed constant timestep.
freqs: list of frequencies (in Hz) to use for the tranform.
(default is 50 frequency bins logarithmic from 1H... |
def perimeter(patch, world_size=(60, 60),
neighbor_func=get_rook_neighbors_toroidal):
"""
Count cell faces in patch that do not connect to part of patch.
This preserves various square geometry features that would not
be preserved by merely counting the number of cells that touch
an edg... | Count cell faces in patch that do not connect to part of patch.
This preserves various square geometry features that would not
be preserved by merely counting the number of cells that touch
an edge. |
def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
in inspect.getmembers(self, predicate=inspect.ismethod)])
for message in global_callbacks:
global... | Remove the actor's methods from the callback registry. |
def get_regular_expressions(taxonomy_name, rebuild=False, no_cache=False):
"""Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed.
"""
# Translate the ontology name into a local path. Check if the name
# relates to an existing on... | Return a list of patterns compiled from the RDF/SKOS ontology.
Uses cache if it exists and if the taxonomy hasn't changed. |
def run_segment_operation(outdoc, filenames, segments, use_segment_table, operation, result_name = 'RESULT', preserve = True):
"""
Performs an operation (intersect or union) across a set of segments.
That is, given a set of files each with segment definers DMT-FLAG1,
DMT-FLAG2 etc and a list of segments... | Performs an operation (intersect or union) across a set of segments.
That is, given a set of files each with segment definers DMT-FLAG1,
DMT-FLAG2 etc and a list of segments DMT-FLAG1,DMT-FLAG1 this returns
RESULT = (table 1's DMT-FLAG1 union table 2's DMT-FLAG1 union ...)
operation
... |
def addVariant(self,variant):
'''Appends one Variant to variants
'''
if isinstance(variant, Variant):
self.variants.append(variant)
else:
raise (VariantError,
'variant Type should be Variant, not %s' % type(variant)) | Appends one Variant to variants |
def _throat_props(self):
r'''
Helper Function to calculate the throat normal vectors
'''
network = self.network
net_Ts = network.throats(self.name)
conns = network['throat.conns'][net_Ts]
p1 = conns[:, 0]
p2 = conns[:, 1]
coords = network['pore.coo... | r'''
Helper Function to calculate the throat normal vectors |
def translations_lists(self):
'''Iterator over lists of content translations'''
return (getattr(self.generator, name) for name in
self.info.get('translations_lists', [])) | Iterator over lists of content translations |
def new_process(self, consumer_name):
"""Create a new consumer instances
:param str consumer_name: The name of the consumer
:return tuple: (str, process.Process)
"""
process_name = '%s-%s' % (consumer_name,
self.new_process_number(consumer_name... | Create a new consumer instances
:param str consumer_name: The name of the consumer
:return tuple: (str, process.Process) |
def init(*, threshold_lvl=1, quiet_stdout=False, log_file):
"""
Initiate the log module
:param threshold_lvl: messages under this level won't be issued/logged
:param to_stdout: activate stdout log stream
"""
global _logger, _log_lvl
# translate lvl to those used by 'logging' module
_lo... | Initiate the log module
:param threshold_lvl: messages under this level won't be issued/logged
:param to_stdout: activate stdout log stream |
def spawn_shell(self, context_file, tmpdir, rcfile=None, norc=False,
stdin=False, command=None, env=None, quiet=False,
pre_command=None, add_rez=True,
package_commands_sourced_first=None, **Popen_args):
"""Spawn a possibly interactive subshell.
... | Spawn a possibly interactive subshell.
Args:
context:_file File that must be sourced in the new shell, this
configures the Rez environment.
tmpdir: Tempfiles, if needed, should be created within this path.
rcfile: Custom startup script.
norc: Don't... |
def _deserialize(self, value, attr, data, **kwargs):
"""Deserialize an ISO8601-formatted time to a :class:`datetime.time` object."""
if not value: # falsy values are invalid
self.fail('invalid')
try:
return utils.from_iso_time(value)
except (AttributeError, TypeE... | Deserialize an ISO8601-formatted time to a :class:`datetime.time` object. |
def evaluate(self, script):
"""
Evaluate script in page frame.
:param script: The script to evaluate.
"""
if WEBENGINE:
return self.dom.runJavaScript("{}".format(script))
else:
return self.dom.evaluateJavaScript("{}".format(script)) | Evaluate script in page frame.
:param script: The script to evaluate. |
def camel(theta):
"""Three-hump camel function"""
x, y = theta
obj = 2 * x ** 2 - 1.05 * x ** 4 + x ** 6 / 6 + x * y + y ** 2
grad = np.array([
4 * x - 4.2 * x ** 3 + x ** 5 + y,
x + 2 * y
])
return obj, grad | Three-hump camel function |
def path_exists_or_creatable(pathname: str) -> bool:
"""Checks whether the given path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
-------
`True` if the passed pathname is a valid pathname for the current OS _and_
either currently exists or is hypoth... | Checks whether the given path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
-------
`True` if the passed pathname is a valid pathname for the current OS _and_
either currently exists or is hypothetically creatable; `False` otherwise. |
def return_error(self, status, payload=None):
"""Error handler called by request handlers when an error occurs and the request
should be aborted.
Usage::
def handle_post_request(self, *args, **kwargs):
self.request_handler = self.get_request_handler()
... | Error handler called by request handlers when an error occurs and the request
should be aborted.
Usage::
def handle_post_request(self, *args, **kwargs):
self.request_handler = self.get_request_handler()
try:
self.request_handler.process(... |
def from_file(proto_file):
'''
Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception.
'''
if not proto_file.endswith('.proto'):
... | Take a filename |protoc_file|, compile it via the Protobuf
compiler, and import the module.
Return the module if successfully compiled, otherwise raise either
a ProtocNotFound or BadProtobuf exception. |
def mkp(*args, **kwargs):
"""
Generate a directory path, and create it if requested.
.. code-block:: Python
filepath = mkp('base', 'folder', 'file')
dirpath = mkp('root', 'path', 'folder', mk=True)
Args:
\*args: File or directory path segments to be concatenated
mk (bo... | Generate a directory path, and create it if requested.
.. code-block:: Python
filepath = mkp('base', 'folder', 'file')
dirpath = mkp('root', 'path', 'folder', mk=True)
Args:
\*args: File or directory path segments to be concatenated
mk (bool): Make the directory (if it doesn't... |
def flush_cache(self):
'''
Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed.
'''
logger.debug('Flushing cache {}'.format(self.db_path))
with self.db:
... | Use a cache to save state changes to avoid opening a session for every change.
The cache will be flushed at the end of the simulation, and when history is accessed. |
def peep_hash(argv):
"""Return the peep hash of one or more files, returning a shell status code
or raising a PipException.
:arg argv: The commandline args, starting after the subcommand
"""
parser = OptionParser(
usage='usage: %prog hash file [file ...]',
description='Print a peep... | Return the peep hash of one or more files, returning a shell status code
or raising a PipException.
:arg argv: The commandline args, starting after the subcommand |
def parse_report(self, lines, table_names):
""" Parse a GATK report https://software.broadinstitute.org/gatk/documentation/article.php?id=1244
Only GATTable entries are parsed. Tables are returned as a dict of tables.
Each table is a dict of arrays, where names correspond to column names, and ... | Parse a GATK report https://software.broadinstitute.org/gatk/documentation/article.php?id=1244
Only GATTable entries are parsed. Tables are returned as a dict of tables.
Each table is a dict of arrays, where names correspond to column names, and arrays
correspond to column values.
Arg... |
def get_partition(url, headers, source_id, container, partition):
"""Serializable function for fetching a data source partition
Parameters
----------
url: str
Server address
headers: dict
HTTP header parameters
source_id: str
ID of the source in the server's cache (uniqu... | Serializable function for fetching a data source partition
Parameters
----------
url: str
Server address
headers: dict
HTTP header parameters
source_id: str
ID of the source in the server's cache (unique per user)
container: str
Type of data, like "dataframe" one... |
def _set_interface_vlan_ospf_conf(self, v, load=False):
"""
Setter method for interface_vlan_ospf_conf, mapped from YANG variable /routing_system/interface/ve/ip/interface_vlan_ospf_conf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_vlan_ospf_conf... | Setter method for interface_vlan_ospf_conf, mapped from YANG variable /routing_system/interface/ve/ip/interface_vlan_ospf_conf (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface_vlan_ospf_conf is considered as a private
method. Backends looking to populate... |
def write(self, data):
"""Writes json data to the output directory."""
cnpj, data = data
path = os.path.join(self.output, '%s.json' % cnpj)
with open(path, 'w') as f:
json.dump(data, f, encoding='utf-8') | Writes json data to the output directory. |
def _get_unique_ch(text, all_common_encodes):
"""
text : encode sample strings
returns unique word / characters from input text encode strings.
"""
unique_chars = ''
if isinstance(text, str):
text = text.split("\n")
elif isinstance(text, (list, tuple)):
p... | text : encode sample strings
returns unique word / characters from input text encode strings. |
def update_alarm(self, alarm, criteria=None, disabled=False,
label=None, name=None, metadata=None):
"""
Updates an existing alarm on this entity.
"""
return self._alarm_manager.update(alarm, criteria=criteria,
disabled=disabled, label=label, name=name, metadat... | Updates an existing alarm on this entity. |
def get_paths(self, key):
"""
Same as `ConfigParser.get_path` for a list of paths.
Args:
key: str, the key to lookup the paths with
Returns:
list: The paths.
"""
final_paths = []
if key in self.__cli:
paths = self.__cli[key] ... | Same as `ConfigParser.get_path` for a list of paths.
Args:
key: str, the key to lookup the paths with
Returns:
list: The paths. |
def is_alive(self):
"""Returns a flag with the state of the SSH connection."""
null = chr(0)
try:
if self.device is None:
return {"is_alive": False}
else:
# Try sending ASCII null byte to maintain the connection alive
self._... | Returns a flag with the state of the SSH connection. |
def _create_prefix_notification(outgoing_msg, rpc_session):
"""Constructs prefix notification with data from given outgoing message.
Given RPC session is used to create RPC notification message.
"""
assert outgoing_msg
path = outgoing_msg.path
assert path
vpn_nlri = path.nlri
assert pa... | Constructs prefix notification with data from given outgoing message.
Given RPC session is used to create RPC notification message. |
def to_match(self):
"""Return a unicode object with the MATCH representation of this expression."""
self.validate()
mark_name, _ = self.fold_scope_location.get_location_name()
validate_safe_string(mark_name)
template = u'$%(mark_name)s.size()'
template_data = {
... | Return a unicode object with the MATCH representation of this expression. |
def flush(self):
"""Write all data from buffer to socket and reset write buffer."""
if self._wbuf:
buffer = ''.join(self._wbuf)
self._wbuf = []
self.write(buffer) | Write all data from buffer to socket and reset write buffer. |
def createModel(self, model, context, owner='', includeReferences=True):
"""
Creates a new table in the database based cff the inputted
schema information. If the dryRun flag is specified, then
the SQLConnection will only be logged to the current logger, and not
actually execute... | Creates a new table in the database based cff the inputted
schema information. If the dryRun flag is specified, then
the SQLConnection will only be logged to the current logger, and not
actually executed in the database.
:param model | <orb.Model>
context ... |
def find_pareto_front(metrics, metadata, columns, depth=1, epsilon=None, progress=None):
"""
Return the subset of the given metrics that are Pareto optimal with respect
to the given columns.
Arguments
=========
metrics: DataFrame
A dataframe where each row is a different model or desig... | Return the subset of the given metrics that are Pareto optimal with respect
to the given columns.
Arguments
=========
metrics: DataFrame
A dataframe where each row is a different model or design and each
column is a different score metric.
metadata: dict
Extra information... |
def import_profile(self):
""" Import minimum needs from an existing json file.
The minimum needs are loaded from a file into the table. This state
is only saved if the form is accepted.
"""
# noinspection PyCallByClass,PyTypeChecker
file_name_dialog = QFileDialog(self)
... | Import minimum needs from an existing json file.
The minimum needs are loaded from a file into the table. This state
is only saved if the form is accepted. |
def iter_shortcuts():
"""Iterate over keyboard shortcuts."""
for context_name, keystr in CONF.items('shortcuts'):
context, name = context_name.split("/", 1)
yield context, name, keystr | Iterate over keyboard shortcuts. |
def _init(self):
"""Read resource information into self._cache, for cached access.
See DAVResource._init()
"""
# TODO: recalc self.path from <self._file_path>, to fix correct file system case
# On windows this would lead to correct URLs
self.provider._count_get_res... | Read resource information into self._cache, for cached access.
See DAVResource._init() |
def inline(self) -> str:
"""
Return inline string format of the instance
:return:
"""
return "{0}:{1}".format(self.index, ' '.join([str(p) for p in self.parameters])) | Return inline string format of the instance
:return: |
def plot(message, duration=1, ax=None):
"""
Plot a message
Returns: ax a Matplotlib Axe
"""
lst_bin = _encode_binary(message)
x, y = _create_x_y(lst_bin, duration)
ax = _create_ax(ax)
ax.plot(x, y, linewidth=2.0)
delta_y = 0.1
ax.set_ylim(-delta_y, 1 + delta_y)
ax.set_yticks... | Plot a message
Returns: ax a Matplotlib Axe |
def _set_get_vnetwork_dvs(self, v, load=False):
"""
Setter method for get_vnetwork_dvs, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_dvs (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_vnetwork_dvs is considered as a private
method. Backends ... | Setter method for get_vnetwork_dvs, mapped from YANG variable /brocade_vswitch_rpc/get_vnetwork_dvs (rpc)
If this variable is read-only (config: false) in the
source YANG file, then _set_get_vnetwork_dvs is considered as a private
method. Backends looking to populate this variable should
do so via calli... |
def driver_for_path(path, drivers=None):
"""Returns the gdal.Driver for a path or None based on the file extension.
Arguments:
path -- file path as str with a GDAL supported file extension
"""
ext = (os.path.splitext(path)[1][1:] or path).lower()
drivers = drivers or ImageDriver.registry if ext... | Returns the gdal.Driver for a path or None based on the file extension.
Arguments:
path -- file path as str with a GDAL supported file extension |
def transit_generate_hmac(self, name, hmac_input, key_version=None, algorithm=None, mount_point='transit'):
"""POST /<mount_point>/hmac/<name>(/<algorithm>)
:param name:
:type name:
:param hmac_input:
:type hmac_input:
:param key_version:
:type key_version:
... | POST /<mount_point>/hmac/<name>(/<algorithm>)
:param name:
:type name:
:param hmac_input:
:type hmac_input:
:param key_version:
:type key_version:
:param algorithm:
:type algorithm:
:param mount_point:
:type mount_point:
:return:
... |
def calculate_columns(self):
"""Assuming the number of rows is constant, work out the best
number of columns to use."""
self.cols = int(math.ceil(len(self.elements) / float(self.rows))) | Assuming the number of rows is constant, work out the best
number of columns to use. |
def attachment(attachment: Attachment, text: str = None, speak: str = None,
input_hint: Union[InputHints, str] = None):
"""
Returns a single message activity containing an attachment.
:Example:
message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='... | Returns a single message activity containing an attachment.
:Example:
message = MessageFactory.attachment(CardFactory.hero_card(HeroCard(title='White T-Shirt',
images=[CardImage(url='https://example.com/whiteShirt.jpg')],
... |
def _load_source_model(self):
"""
Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting
orphan translations (translations without a parent object associated).
"""
# If source_model exists, return it
if hasattr(self, "source_model"):
return self.sou... | Loads and gets the source model of the FieldTranslation as a dynamic attribute. It is used only when deleting
orphan translations (translations without a parent object associated). |
def from_e164(text, origin=public_enum_domain):
"""Convert an E.164 number in textual form into a Name object whose
value is the ENUM domain name for that number.
@param text: an E.164 number in textual form.
@type text: str
@param origin: The domain in which the number should be constructed.
Th... | Convert an E.164 number in textual form into a Name object whose
value is the ENUM domain name for that number.
@param text: an E.164 number in textual form.
@type text: str
@param origin: The domain in which the number should be constructed.
The default is e164.arpa.
@type: dns.name.Name object... |
def init_sentry(self):
"""Install Sentry handler if config defines 'SENTRY_DSN'."""
dsn = self.config.get("SENTRY_DSN")
if not dsn:
return
try:
import sentry_sdk
except ImportError:
logger.error(
'SENTRY_DSN is defined in confi... | Install Sentry handler if config defines 'SENTRY_DSN'. |
def get_collection_rules_gpg(self, collection_rules):
"""
Download the collection rules gpg signature
"""
sig_text = self.fetch_gpg()
sig_response = NamedTemporaryFile(suffix=".asc")
sig_response.write(sig_text.encode('utf-8'))
sig_response.file.flush()
se... | Download the collection rules gpg signature |
def _find_multiple(self, match_class, **keywds):
"""implementation details"""
self._logger.debug('find all query execution - started')
start_time = timeit.default_timer()
norm_keywds = self.__normalize_args(**keywds)
decl_matcher = self.__create_matcher(match_class, **norm_keywds... | implementation details |
def map(lst, serialize_func):
"""
Applies serialize_func to every element in lst
"""
if not isinstance(lst, list):
return lst
return [serialize_func(e) for e in lst] | Applies serialize_func to every element in lst |
def create_identity(self, user, sp_mapping, **extra_config):
""" Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP
"""
return {
out_attr: getattr(user, user_attr)
for user_attr, out_attr in sp_mapping.items()
... | Generate an identity dictionary of the user based on the given mapping of desired user attributes by the SP |
def flexifunction_directory_ack_encode(self, target_system, target_component, directory_type, start_index, count, result):
'''
Acknowldge sucess or failure of a flexifunction command
target_system : System ID (uint8_t)
target_component ... | Acknowldge sucess or failure of a flexifunction command
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
directory_type : 0=inputs, 1=outputs (uint8_t)
start_index : index of first... |
def _convert_xml_to_queues(response):
'''
<?xml version="1.0" encoding="utf-8"?>
<EnumerationResults ServiceEndpoint="https://myaccount.queue.core.windows.net/">
<Prefix>string-value</Prefix>
<Marker>string-value</Marker>
<MaxResults>int-value</MaxResults>
<Queues>
<Queue>
... | <?xml version="1.0" encoding="utf-8"?>
<EnumerationResults ServiceEndpoint="https://myaccount.queue.core.windows.net/">
<Prefix>string-value</Prefix>
<Marker>string-value</Marker>
<MaxResults>int-value</MaxResults>
<Queues>
<Queue>
<Name>string-value</Name>
<Metad... |
def run_solr_on(solrInstance, category, id, fields):
"""
Return the result of a solr query on the given solrInstance (Enum ESOLR), for a certain document_category (ESOLRDoc) and id
"""
query = solrInstance.value + "select?q=*:*&fq=document_category:\"" + category.value + "\"&fq=id:\"" + id + "\"&fl=" + ... | Return the result of a solr query on the given solrInstance (Enum ESOLR), for a certain document_category (ESOLRDoc) and id |
def _encode_json(obj):
'''
Encode object as json str.
'''
def _dump_obj(obj):
if isinstance(obj, dict):
return obj
d = dict()
for k in dir(obj):
if not k.startswith('_'):
d[k] = getattr(obj, k)
return d
return json.dumps(obj, de... | Encode object as json str. |
def warning(self, message, print_location=True):
"""Displays warning message. Uses exshared for current location of parsing"""
msg = "Warning"
if print_location and (exshared.location != None):
wline = lineno(exshared.location, exshared.text)
wcol = col(exshared.loca... | Displays warning message. Uses exshared for current location of parsing |
def rand_crop(*args, padding_mode='reflection', p:float=1.):
"Randomized version of `crop_pad`."
return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p) | Randomized version of `crop_pad`. |
def burst_run(self):
""" Run CPU as fast as Python can... """
# https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Avoiding_dots...
get_and_call_next_op = self.get_and_call_next_op
for __ in range(self.outer_burst_op_count):
for __ in range(self.inner_burst_op_count):
... | Run CPU as fast as Python can... |
def remove_header(self, name):
"""Remove a field from the header"""
if name in self.info_dict:
self.info_dict.pop(name)
logger.info("Removed '{0}' from INFO".format(name))
if name in self.filter_dict:
self.filter_dict.pop(name)
logger.info("Removed... | Remove a field from the header |
def name(self): # pylint: disable=no-self-use
"""
Name returns user's name or user's email or user_id
:return: best guess of name to use to greet user
"""
if 'lis_person_sourcedid' in self.session:
return self.session['lis_person_sourcedid']
elif 'lis_person_... | Name returns user's name or user's email or user_id
:return: best guess of name to use to greet user |
def start(self):
""" Start running the interactive session (blocking) """
self.running = True
while self.running:
self.update_prompt()
try:
self.cmdloop()
except KeyboardInterrupt:
print()
except botocore.exceptions.... | Start running the interactive session (blocking) |
def _maybe_replace_path(self, match):
""" Regex replacement method that will sub paths when needed """
path = match.group(0)
if self._should_replace(path):
return self._replace_path(path)
else:
return path | Regex replacement method that will sub paths when needed |
def _collect_output(self, process, result, writer=None, stdin=None):
"""Drain the subprocesses output streams, writing the collected output
to the result. If a writer thread (writing to the subprocess) is given,
make sure it's joined before returning. If a stdin stream is given,
close it... | Drain the subprocesses output streams, writing the collected output
to the result. If a writer thread (writing to the subprocess) is given,
make sure it's joined before returning. If a stdin stream is given,
close it before returning. |
def expand_path(s):
"""Expand $VARS and ~names in a string, like a shell
:Examples:
In [2]: os.environ['FOO']='test'
In [3]: expand_path('variable FOO is $FOO')
Out[3]: 'variable FOO is test'
"""
# This is a pretty subtle hack. When expand user is given a UNC path
# on Window... | Expand $VARS and ~names in a string, like a shell
:Examples:
In [2]: os.environ['FOO']='test'
In [3]: expand_path('variable FOO is $FOO')
Out[3]: 'variable FOO is test' |
def list_hosts_by_cluster(kwargs=None, call=None):
'''
List hosts for each cluster; or hosts for a specified cluster in
this VMware environment
To list hosts for each cluster:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts_by_cluster my-vmware-config
To list hosts fo... | List hosts for each cluster; or hosts for a specified cluster in
this VMware environment
To list hosts for each cluster:
CLI Example:
.. code-block:: bash
salt-cloud -f list_hosts_by_cluster my-vmware-config
To list hosts for a specified cluster:
CLI Example:
.. code-block:: b... |
def start(self, on_done):
"""
Starts the genesis block creation process. Will call the given
`on_done` callback on successful completion.
Args:
on_done (function): a function called on completion
Raises:
InvalidGenesisStateError: raises this error if a ... | Starts the genesis block creation process. Will call the given
`on_done` callback on successful completion.
Args:
on_done (function): a function called on completion
Raises:
InvalidGenesisStateError: raises this error if a genesis block is
unable to be ... |
def _path_hash(path, transform, kwargs):
"""
Generate a hash of source file path + transform + args
"""
sortedargs = ["%s:%r:%s" % (key, value, type(value))
for key, value in sorted(iteritems(kwargs))]
srcinfo = "{path}:{transform}:{{{kwargs}}}".format(path=os.path.abspath(path),
... | Generate a hash of source file path + transform + args |
def fit(self, features, classes):
"""Constructs the MDR ensemble from the provided training data
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
classes: array-like {n_samples}
List of class labels for prediction
... | Constructs the MDR ensemble from the provided training data
Parameters
----------
features: array-like {n_samples, n_features}
Feature matrix
classes: array-like {n_samples}
List of class labels for prediction
Returns
-------
None |
def connect(receiver, signal=Any, sender=Any, weak=True):
"""Connect receiver to sender for signal
receiver -- a callable Python object which is to receive
messages/signals/events. Receivers must be hashable
objects.
if weak is True, then receiver must be weak-referencable
(mo... | Connect receiver to sender for signal
receiver -- a callable Python object which is to receive
messages/signals/events. Receivers must be hashable
objects.
if weak is True, then receiver must be weak-referencable
(more precisely saferef.safeRef() must be able to create
a r... |
def reuse_variables(method):
"""Wraps an arbitrary method so it does variable sharing.
This decorator creates variables the first time it calls `method`, and reuses
them for subsequent calls. The object that calls `method` provides a
`tf.VariableScope`, either as a `variable_scope` attribute or as the return
... | Wraps an arbitrary method so it does variable sharing.
This decorator creates variables the first time it calls `method`, and reuses
them for subsequent calls. The object that calls `method` provides a
`tf.VariableScope`, either as a `variable_scope` attribute or as the return
value of an `_enter_variable_scop... |
def add_callback(self, func):
""" Registers a call back function """
if func is None: return
func_list = to_list(func)
if not hasattr(self, 'callback_list'):
self.callback_list = func_list
else:
self.callback_list.extend(func_list) | Registers a call back function |
def _make_stream_reader(cls, stream):
"""
Return a |StreamReader| instance with wrapping *stream* and having
"endian-ness" determined by the 'MM' or 'II' indicator in the TIFF
stream header.
"""
endian = cls._detect_endian(stream)
return StreamReader(stream, endia... | Return a |StreamReader| instance with wrapping *stream* and having
"endian-ness" determined by the 'MM' or 'II' indicator in the TIFF
stream header. |
def _process_validation_function_s(validation_func, # type: ValidationFuncs
auto_and_wrapper=True # type: bool
):
# type: (...) -> Union[Callable, List[Callable]]
"""
This function handles the various ways that users may enter 'val... | This function handles the various ways that users may enter 'validation functions', so as to output a single
callable method. Setting "auto_and_wrapper" to False allows callers to get a list of callables instead.
valid8 supports the following expressions for 'validation functions'
* <ValidationFunc>
... |
def numberOfDistalSegments(self, cells=None):
"""
Returns the total number of distal segments for these cells.
A segment "exists" if its row in the matrix has any permanence values > 0.
Parameters:
----------------------------
@param cells (iterable)
Indices of the cells
"""
... | Returns the total number of distal segments for these cells.
A segment "exists" if its row in the matrix has any permanence values > 0.
Parameters:
----------------------------
@param cells (iterable)
Indices of the cells |
def post(method, hmc, uri, uri_parms, body, logon_required,
wait_for_completion):
"""Operation: Set CPC Power Capping (any CPC mode)."""
assert wait_for_completion is True # async not supported yet
cpc_oid = uri_parms[0]
try:
cpc = hmc.cpcs.lookup_by_oid(cpc_oid... | Operation: Set CPC Power Capping (any CPC mode). |
def handle_event(self, packet):
"""Handle incoming packet from rflink gateway."""
if packet.get('command'):
task = self.send_command_ack(packet['id'], packet['command'])
self.loop.create_task(task) | Handle incoming packet from rflink gateway. |
def form_sent(request, slug, template="forms/form_sent.html"):
"""
Show the response message.
"""
published = Form.objects.published(for_user=request.user)
context = {"form": get_object_or_404(published, slug=slug)}
return render_to_response(template, context, RequestContext(request)) | Show the response message. |
def trigger_methods(instance, args):
""""
Triggers specific class methods using a simple reflection
mechanism based on the given input dictionary params.
Arguments:
instance (object): target instance to dynamically trigger methods.
args (iterable): input arguments to trigger objects to
... | Triggers specific class methods using a simple reflection
mechanism based on the given input dictionary params.
Arguments:
instance (object): target instance to dynamically trigger methods.
args (iterable): input arguments to trigger objects to
Returns:
None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.