code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def list_corpus_files(dotted_path):
"""
Return a list of file paths to each data file in the specified corpus.
"""
corpus_path = get_file_path(dotted_path, extension=CORPUS_EXTENSION)
paths = []
if os.path.isdir(corpus_path):
paths = glob.glob(corpus_path + '/**/*.' + CORPUS_EXTENSION, ... | Return a list of file paths to each data file in the specified corpus. |
def policy_and_value_net(rng_key,
batch_observations_shape,
num_actions,
bottom_layers=None):
"""A policy and value net function."""
# Layers.
cur_layers = []
if bottom_layers is not None:
cur_layers.extend(bottom_layers)
# Now, ... | A policy and value net function. |
def transformToNative(obj):
"""
Turn obj.value into an Address.
"""
if obj.isNative:
return obj
obj.isNative = True
obj.value = Address(**dict(zip(ADDRESS_ORDER, splitFields(obj.value))))
return obj | Turn obj.value into an Address. |
def count_tokens(tokens, to_lower=False, counter=None):
r"""Counts tokens in the specified string.
For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may
look like::
(td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd)
Parameters
----... | r"""Counts tokens in the specified string.
For token_delim='(td)' and seq_delim='(sd)', a specified string of two sequences of tokens may
look like::
(td)token1(td)token2(td)token3(td)(sd)(td)token4(td)token5(td)(sd)
Parameters
----------
tokens : list of str
A source list of tok... |
def by_user(self): # pragma: no cover
"""
Display group membership sorted by group.
Returns:
Array with a dictionary of group membership.
For example: {'test.user': ['testgroup', 'testgroup2']}
"""
users = [i for i in self.__get_users()]
use... | Display group membership sorted by group.
Returns:
Array with a dictionary of group membership.
For example: {'test.user': ['testgroup', 'testgroup2']} |
def period(self, value: float):
"""
Set the period.
Args:
value (float): seconds
"""
if value < 0:
raise ValueError("Period must be greater or equal than zero.")
self._period = timedelta(seconds=value) | Set the period.
Args:
value (float): seconds |
def Page_addScriptToEvaluateOnNewDocument(self, source):
"""
Function path: Page.addScriptToEvaluateOnNewDocument
Domain: Page
Method name: addScriptToEvaluateOnNewDocument
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'source' (type: string) -> No descr... | Function path: Page.addScriptToEvaluateOnNewDocument
Domain: Page
Method name: addScriptToEvaluateOnNewDocument
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'source' (type: string) -> No description
Returns:
'identifier' (type: ScriptIdentifier) -> I... |
def markdown(value, extensions=settings.MARKDOWN_EXTENSIONS,
extension_configs=settings.MARKDOWN_EXTENSION_CONFIGS,
safe=False):
""" Render markdown over a given value, optionally using varios extensions.
Default extensions could be defined which MARKDOWN_EXTENSIONS option.
:retu... | Render markdown over a given value, optionally using varios extensions.
Default extensions could be defined which MARKDOWN_EXTENSIONS option.
:returns: A rendered markdown |
def alias_log_entry(self, log_entry_id, alias_id):
"""Adds an ``Id`` to a ``LogEntry`` for the purpose of creating compatibility.
The primary ``Id`` of the ``LogEntry`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to... | Adds an ``Id`` to a ``LogEntry`` for the purpose of creating compatibility.
The primary ``Id`` of the ``LogEntry`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another log entry, it is
reassigned to the given log ... |
def modify_dbinstance(self, id, param_group=None, security_groups=None,
preferred_maintenance_window=None,
master_password=None, allocated_storage=None,
instance_class=None,
backup_retention_period=None,
... | Modify an existing DBInstance.
:type id: str
:param id: Unique identifier for the new instance.
:type security_groups: list of str or list of DBSecurityGroup objects
:param security_groups: List of names of DBSecurityGroup to authorize on
this DBInstance... |
def to_zarr(dataset, store=None, mode='w-', synchronizer=None, group=None,
encoding=None, compute=True, consolidated=False):
"""This function creates an appropriate datastore for writing a dataset to
a zarr ztore
See `Dataset.to_zarr` for full API docs.
"""
if isinstance(store, Path):
... | This function creates an appropriate datastore for writing a dataset to
a zarr ztore
See `Dataset.to_zarr` for full API docs. |
def put(self, local_path, path, atomic=True):
"""
Put file from local filesystem to (s)FTP.
"""
self._connect()
if self.sftp:
self._sftp_put(local_path, path, atomic)
else:
self._ftp_put(local_path, path, atomic)
self._close() | Put file from local filesystem to (s)FTP. |
def get_shard_map(self, force_refresh=False):
"""
You can change this function to get the shard-map from somewhere/somehow place else in conjuction with
save_shard_map().
"""
now = datetime.utcnow()
if force_refresh is True or \
self.shard_map is ... | You can change this function to get the shard-map from somewhere/somehow place else in conjuction with
save_shard_map(). |
def node_theta(nodelist, node):
"""
Maps node to Angle.
:param nodelist: Nodelist from the graph.
:type nodelist: list.
:param node: The node of interest. Must be in the nodelist.
:returns: theta -- the angle of the node in radians.
"""
assert len(nodelist) > 0, "nodelist must be a list... | Maps node to Angle.
:param nodelist: Nodelist from the graph.
:type nodelist: list.
:param node: The node of interest. Must be in the nodelist.
:returns: theta -- the angle of the node in radians. |
def rolling_sum(self, window_start, window_end, min_observations=None):
"""
Calculate a new SArray of the sum of different subsets over this
SArray.
Also known as a "moving sum" or "running sum". The subset that
the sum is calculated over is defined as an inclusive range relativ... | Calculate a new SArray of the sum of different subsets over this
SArray.
Also known as a "moving sum" or "running sum". The subset that
the sum is calculated over is defined as an inclusive range relative
to the position to each value in the SArray, using `window_start` and
`win... |
def authenticate(self):
'''
Authenticate using data in `options`
'''
if "username" in self.options and "password" in self.options:
self.login_oauth2(
self.options["username"],
self.options["password"],
self.options.get('mfa_code... | Authenticate using data in `options` |
def cli(self, eauth):
'''
Execute the CLI options to fill in the extra data needed for the
defined eauth system
'''
ret = {}
if not eauth:
print('External authentication system has not been specified')
return ret
fstr = '{0}.auth'.format(ea... | Execute the CLI options to fill in the extra data needed for the
defined eauth system |
def removeidfobject(self, idfobject):
"""Remove an IDF object from the IDF.
Parameters
----------
idfobject : EpBunch object
The IDF object to remove.
"""
key = idfobject.key.upper()
self.idfobjects[key].remove(idfobject) | Remove an IDF object from the IDF.
Parameters
----------
idfobject : EpBunch object
The IDF object to remove. |
def _cursor(self, name=None):
"""
Here it happens. We hope every Django db operation using PostgreSQL
must go through this to get the cursor handle. We change the path.
"""
if name:
# Only supported and required by Django 1.11 (server-side cursor)
cursor =... | Here it happens. We hope every Django db operation using PostgreSQL
must go through this to get the cursor handle. We change the path. |
def delete_org(self):
""" Uses sfdx force:org:delete to delete the org """
if not self.created:
self.logger.info(
"Skipping org deletion: the scratch org has not been created"
)
return
command = sarge.shell_format("sfdx force:org:delete -p -u ... | Uses sfdx force:org:delete to delete the org |
def chunk(self, size):
"""
Chunk the underlying collection.
:param size: The chunk size
:type size: int
:rtype: Collection
"""
chunks = self._chunk(size)
return self.__class__(list(map(self.__class__, chunks))) | Chunk the underlying collection.
:param size: The chunk size
:type size: int
:rtype: Collection |
def cell_nodes_x(self):
"""The unstructured x-boundaries with shape (N, m) where m > 2"""
decoder = self.decoder
xcoord = self.xcoord
data = self.data
xbounds = decoder.get_cell_node_coord(
data, coords=data.coords, axis='x')
if self.plotter.convert_radian:
... | The unstructured x-boundaries with shape (N, m) where m > 2 |
def read32(self, offset):
"""Read 32-bits from the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
Returns:
int: 32-bit value read.
Raises:
... | Read 32-bits from the specified `offset` in bytes, relative to the
base physical address of the MMIO region.
Args:
offset (int, long): offset from base physical address, in bytes.
Returns:
int: 32-bit value read.
Raises:
TypeError: if `offset` type ... |
def decode_body(cls, header, f):
"""Generates a `MqttUnsubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsubscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
... | Generates a `MqttUnsubscribe` packet given a
`MqttFixedHeader`. This method asserts that header.packet_type
is `unsubscribe`.
Parameters
----------
header: MqttFixedHeader
f: file
Object with a read method.
Raises
------
DecodeError
... |
def init(directory=None, multidb=False):
"""Creates a new migration repository"""
if directory is None:
directory = current_app.extensions['migrate'].directory
config = Config()
config.set_main_option('script_location', directory)
config.config_file_name = os.path.join(directory, 'alembic.in... | Creates a new migration repository |
def getAttribute(self, attr: str) -> _AttrValueType:
"""Get attribute of this node as string format.
If this node does not have ``attr``, return None.
"""
if attr == 'class':
if self.classList:
return self.classList.toString()
return None
... | Get attribute of this node as string format.
If this node does not have ``attr``, return None. |
def _get_candidate_swap(resources, location,
l2v, vertices_resources, fixed_vertices, machine):
"""Given a chip location, select a set of vertices which would have to be
moved elsewhere to accommodate the arrival of the specified set of
resources.
Parameters
----------
r... | Given a chip location, select a set of vertices which would have to be
moved elsewhere to accommodate the arrival of the specified set of
resources.
Parameters
----------
resources : {resource: value, ...}
The amount of resources which are required at the specified location.
location : ... |
def serialize(point: Mapping, measurement=None, **extra_tags) -> bytes:
"""Converts dictionary-like data into a single line protocol line (point)"""
tags = _serialize_tags(point, extra_tags)
return (
f'{_serialize_measurement(point, measurement)}'
f'{"," if tags else ""}{tags} '
f'{_... | Converts dictionary-like data into a single line protocol line (point) |
def is_periodically_contiguous( self ):
"""
logical check whether a cluster connects with itself across the
simulation periodic boundary conditions.
Args:
none
Returns
( Bool, Bool, Bool ): Contiguity along the x, y, and z coordinate axes
"""
... | logical check whether a cluster connects with itself across the
simulation periodic boundary conditions.
Args:
none
Returns
( Bool, Bool, Bool ): Contiguity along the x, y, and z coordinate axes |
def rpc_request(self, frame_out, connection_adapter=None):
"""Perform a RPC Request.
:param specification.Frame frame_out: Amqp frame.
:rtype: dict
"""
with self.rpc.lock:
uuid = self.rpc.register_request(frame_out.valid_responses)
self._connection.write_... | Perform a RPC Request.
:param specification.Frame frame_out: Amqp frame.
:rtype: dict |
def iterate(self, image, feature_extractor, feature_vector):
"""iterate(image, feature_extractor, feature_vector) -> bounding_box
Scales the given image, and extracts features from all possible bounding boxes.
For each of the sampled bounding boxes, this function fills the given pre-allocated feature vect... | iterate(image, feature_extractor, feature_vector) -> bounding_box
Scales the given image, and extracts features from all possible bounding boxes.
For each of the sampled bounding boxes, this function fills the given pre-allocated feature vector and yields the current bounding box.
**Parameters:**
``... |
def byteswap(s):
"""Swaps the endianness of the bytesting s, which must be an array
of shorts (16-bit signed integers). This is probably less efficient
than it should be.
"""
assert len(s) % 2 == 0
parts = []
for i in range(0, len(s), 2):
chunk = s[i:i + 2]
newchunk = struct.... | Swaps the endianness of the bytesting s, which must be an array
of shorts (16-bit signed integers). This is probably less efficient
than it should be. |
def secondary_spin(mass1, mass2, spin1, spin2):
"""Returns the dimensionless spin of the secondary mass."""
mass1, mass2, spin1, spin2, input_is_array = ensurearray(
mass1, mass2, spin1, spin2)
ss = copy.copy(spin2)
mask = mass1 < mass2
ss[mask] = spin1[mask]
return formatreturn(ss, inpu... | Returns the dimensionless spin of the secondary mass. |
def _handle_packed_metadata(self, node, scope, ctxt, stream):
"""Handle packed metadata
"""
keyvals = node.metadata.keyvals
if "packer" not in keyvals and ("pack" not in keyvals or "unpack" not in keyvals):
raise errors.PfpError("Packed fields require a packer function to be ... | Handle packed metadata |
def __process_by_ccore(self):
"""!
@brief Performs processing using C++ implementation.
"""
if isinstance(self.__initializer, kmeans_plusplus_initializer):
initializer = wrapper.elbow_center_initializer.KMEANS_PLUS_PLUS
else:
initializer = wrapper... | !
@brief Performs processing using C++ implementation. |
def push(self, key, value, priority=0):
""" Pushes a single or a sequence of key-value pairs into the store.
This function returns immediately after adding an operator to the engine.
The actual operation is executed asynchronously. If there are consecutive
pushes to the same key, there ... | Pushes a single or a sequence of key-value pairs into the store.
This function returns immediately after adding an operator to the engine.
The actual operation is executed asynchronously. If there are consecutive
pushes to the same key, there is no guarantee on the serialization of pushes.
... |
def get_slot_bindings(self):
"""
Returns slot bindings.
:returns: slot bindings (adapter names) list
"""
slot_bindings = yield from self._hypervisor.send('vm slot_bindings "{}"'.format(self._name))
return slot_bindings | Returns slot bindings.
:returns: slot bindings (adapter names) list |
def _match_excluded(self, filename, patterns):
"""Call match real directly to skip unnecessary `exists` check."""
return _wcparse._match_real(
filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks
) | Call match real directly to skip unnecessary `exists` check. |
def _traverse_relationship_rev_objs(self, rel2dst2srcs, goobj_parent, goids_seen):
"""Traverse from source GO down children."""
parent_id = goobj_parent.id
goids_seen.add(parent_id)
##A self.go2obj[parent_id] = goobj_parent
# Update goids_seen and go2obj with parent alt_ids
... | Traverse from source GO down children. |
def bounding_ellipsoid(points, pointvol=0.):
"""
Calculate the bounding ellipsoid containing a collection of points.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim)
A set of coordinates.
pointvol : float, optional
The minimum volume occupied by a sing... | Calculate the bounding ellipsoid containing a collection of points.
Parameters
----------
points : `~numpy.ndarray` with shape (npoints, ndim)
A set of coordinates.
pointvol : float, optional
The minimum volume occupied by a single point. When provided,
used to set a minimum bo... |
def sphere_triangle_cdf(dr, a, alpha):
""" Cumulative distribution function for the traingle distribution """
p0 = (dr+alpha)**2/(2*alpha**2)*(0 > dr)*(dr>-alpha)
p1 = 1*(dr>0)-(alpha-dr)**2/(2*alpha**2)*(0<dr)*(dr<alpha)
return (1-np.clip(p0+p1, 0, 1)) | Cumulative distribution function for the traingle distribution |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(UserScriptsCollector, self).get_default_config()
config.update({
'path': '.',
'scripts_path': '/etc/diamond/user_scripts/',
'floatprecision': 4,... | Returns the default collector settings |
def patch_match_hostname():
"""Fixes https://github.com/boto/boto/issues/2836"""
_old_match_hostname = ssl.match_hostname
def _new_match_hostname(cert, hostname):
if hostname.endswith('.s3.amazonaws.com'):
pos = hostname.find('.s3.amazonaws.com')
hostname = hostname[:pos].... | Fixes https://github.com/boto/boto/issues/2836 |
def average_spectrogram(timeseries, method_func, stride, *args, **kwargs):
"""Generate an average spectrogram using a method function
Each time bin of the resulting spectrogram is a PSD generated using
the method_func
"""
# unpack CSD TimeSeries pair, or single timeseries
try:
timeserie... | Generate an average spectrogram using a method function
Each time bin of the resulting spectrogram is a PSD generated using
the method_func |
def get(self, addr, count):
"""
Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside va... | Read list of ``count`` values at ``addr`` memory location in DataBank.
:param addr: Address to read from
:param count: Number of entries to retrieve
:return: list of entry values
:except IndexError: Raised if address range falls outside valid range |
def common_install_python_env(self):
"""
Install python virtualenv
"""
sudo('apt-get install python3 python3-pip -y')
sudo('pip3 install virtualenv')
run('virtualenv {0}'.format(self.python_env_dir))
print(green(' * Installed Python3 virtual environment in t... | Install python virtualenv |
def on_init(app): # pylint: disable=unused-argument
"""
Run sphinx-apidoc after Sphinx initialization.
Read the Docs won't run tox or custom shell commands, so we need this to
avoid checking in the generated reStructuredText files.
"""
docs_path = os.path.abspath(os.path.dirname(__file__))
... | Run sphinx-apidoc after Sphinx initialization.
Read the Docs won't run tox or custom shell commands, so we need this to
avoid checking in the generated reStructuredText files. |
def send_command_timing(self, *args, **kwargs):
"""
If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change.
"""
output = super(CiscoAsaSSH, self).send_command_timing(*args, **kwargs)
if len(args) >= 1:
command_s... | If the ASA is in multi-context mode, then the base_prompt needs to be
updated after each context change. |
def get_label_items(self, label_id, top=None, skip=None):
"""GetLabelItems.
Get items under a label.
:param str label_id: Unique identifier of label
:param int top: Max number of items to return
:param int skip: Number of items to skip
:rtype: [TfvcItem]
"""
... | GetLabelItems.
Get items under a label.
:param str label_id: Unique identifier of label
:param int top: Max number of items to return
:param int skip: Number of items to skip
:rtype: [TfvcItem] |
def updateLanguages(self, languages):
"""
You can use this operation to change which languages will have
content displayed in portal search results.
Parameters:
languages - The JSON object containing all of the possible
portal languages and their corresponding st... | You can use this operation to change which languages will have
content displayed in portal search results.
Parameters:
languages - The JSON object containing all of the possible
portal languages and their corresponding status (true or
false). |
def apply_path(self, repo):
""" Set path to where the repo is and return original path """
try:
# rewrite repo for consistency
if repo.endswith('.git'):
repo = repo.split('.git')[0]
# get org and repo name and path repo will be cloned to
o... | Set path to where the repo is and return original path |
def get_ligands(pdb_id):
"""Return ligands of given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a list of ligands associated with the entry
Examples
--------
... | Return ligands of given PDB ID
Parameters
----------
pdb_id : string
A 4 character string giving a pdb entry of interest
Returns
-------
out : dict
A dictionary containing a list of ligands associated with the entry
Examples
--------
>>> ligand_dict = get_ligand... |
def highlight(string, fg=None, bg=None, indices=[], end='\n',
target=sys.stdout):
"""Highlight characters using indices and print it to the target handle.
fg and bg specify foreground- and background colors, respectively. The
remaining keyword arguments are the same as for Python's built-in p... | Highlight characters using indices and print it to the target handle.
fg and bg specify foreground- and background colors, respectively. The
remaining keyword arguments are the same as for Python's built-in print
function. |
def transformer(self):
"""
Creates the internal transformer that maps the cluster center's high
dimensional space to its two dimensional space.
"""
ttype = self.embedding.lower() # transformer method type
if ttype == 'mds':
return MDS(n_components=2, random_s... | Creates the internal transformer that maps the cluster center's high
dimensional space to its two dimensional space. |
def parse_JSON(self, JSON_string):
"""
Parses a *StationHistory* instance out of raw JSON data. Only certain
properties of the data are used: if these properties are not found or
cannot be parsed, an error is issued.
:param JSON_string: a raw JSON string
:type JSON_strin... | Parses a *StationHistory* instance out of raw JSON data. Only certain
properties of the data are used: if these properties are not found or
cannot be parsed, an error is issued.
:param JSON_string: a raw JSON string
:type JSON_string: str
:returns: a *StationHistory* instance or... |
def _subperiod_tick(self, current_interval, intervals):
"""Tick each sub-period, copying group_decisions to subperiod_group_decisions."""
self.refresh_from_db()
for key, value in self.group_decisions.items():
self.subperiod_group_decisions[key] = value
self.send('group_decis... | Tick each sub-period, copying group_decisions to subperiod_group_decisions. |
def on_deleted(self, event):
"""
Event Handler when a file is deleted
"""
key = 'filesystem:file_deleted'
data = {
'filepath': event.src_path,
'is_directory': event.is_directory,
'dirpath': os.path.dirname(event.src_path)
}
bms... | Event Handler when a file is deleted |
def dates(self, desc=None):
'''Returns an iterable over ``datetime.date`` instances
in the timeseries.'''
c = self.dateinverse
for key in self.keys(desc=desc):
yield c(key) | Returns an iterable over ``datetime.date`` instances
in the timeseries. |
def notify_state_name_change(self, model, prop_name, info):
"""Checks whether the name of a state was changed and change the tab label accordingly
"""
# avoid updates or checks because of execution status updates
if is_execution_status_update_notification_from_state_machine_model(prop_na... | Checks whether the name of a state was changed and change the tab label accordingly |
def valid_url(url):
"""Validate url.
:rtype: str
:return: url
:param str url: package homepage url.
"""
regex = re.compile(
r'^(?:http)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+'
r'(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?))'
r'(?:/?|[/?]\S+)$', re.IGNORECA... | Validate url.
:rtype: str
:return: url
:param str url: package homepage url. |
def renormalize(self, modelparams):
"""
Renormalizes one or more states represented as model
parameter vectors, such that each state has trace 1.
:param np.ndarray modelparams: Array of shape ``(n_states,
dim ** 2)`` representing one or more states as
model para... | Renormalizes one or more states represented as model
parameter vectors, such that each state has trace 1.
:param np.ndarray modelparams: Array of shape ``(n_states,
dim ** 2)`` representing one or more states as
model parameter vectors.
:return: The same state, normaliz... |
def cons(self, i):
"""cons(i) is TRUE <=> b[i] is a consonant."""
if (self.b[i] == 'a' or self.b[i] == 'e' or self.b[i] == 'i' or
self.b[i] == 'o' or self.b[i] == 'u'):
return 0
if self.b[i] == 'y':
if i == self.k0:
return 1
... | cons(i) is TRUE <=> b[i] is a consonant. |
def init_realms(self, realms):
"""
:type realms: tuple
"""
# this eliminates the need for an authorizing_realms attribute:
self.realms = tuple(realm for realm in realms
if isinstance(realm, realm_abcs.AuthorizingRealm))
self.register_cache_clea... | :type realms: tuple |
def delete_datasource(datasourceid, orgname=None, profile='grafana'):
'''
Delete a datasource.
datasourceid
Id of the datasource.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
CLI Example:
.. code-block:: bash
sa... | Delete a datasource.
datasourceid
Id of the datasource.
profile
Configuration profile used to connect to the Grafana instance.
Default is 'grafana'.
CLI Example:
.. code-block:: bash
salt '*' grafana4.delete_datasource <datasource_id> |
def answer_inline_query(
self,
inline_query_id: str,
results: List[InlineQueryResult],
cache_time: int = 300,
is_personal: bool = None,
next_offset: str = "",
switch_pm_text: str = "",
switch_pm_parameter: str = ""
):
"""Use this method to send... | Use this method to send answers to an inline query.
No more than 50 results per query are allowed.
Args:
inline_query_id (``str``):
Unique identifier for the answered query.
results (List of :obj:`InlineQueryResult <pyrogram.InlineQueryResult>`):
... |
def wait_for_update(self, trigger_update=False):
"""Update canvas and handle all events in the gtk queue
:param bool trigger_update: Whether to call update_now() or not
"""
if trigger_update:
self.update_now()
from gi.repository import Gtk
from gi.repository... | Update canvas and handle all events in the gtk queue
:param bool trigger_update: Whether to call update_now() or not |
def infer_dtype_from_scalar(val, pandas_dtype=False):
"""
interpret the dtype from a scalar
Parameters
----------
pandas_dtype : bool, default False
whether to infer dtype including pandas extension types.
If False, scalar belongs to pandas extension types is inferred as
obj... | interpret the dtype from a scalar
Parameters
----------
pandas_dtype : bool, default False
whether to infer dtype including pandas extension types.
If False, scalar belongs to pandas extension types is inferred as
object |
def merged_packages(env_packages, names):
"""
Return union set of environment packages with given names
>>> sorted(merged_packages(
... {
... 'a': {'x': 1, 'y': 2},
... 'b': {'y': 2, 'z': 3},
... 'c': {'z': 3, 'w': 4}
... },
... ['a', 'b']
...... | Return union set of environment packages with given names
>>> sorted(merged_packages(
... {
... 'a': {'x': 1, 'y': 2},
... 'b': {'y': 2, 'z': 3},
... 'c': {'z': 3, 'w': 4}
... },
... ['a', 'b']
... ).items())
[('x', 1), ('y', 2), ('z', 3)] |
def execFontDialog(self):
""" Opens a QColorDialog for the user
"""
currentFont = self.getData()
newFont, ok = QtGui.QFontDialog.getFont(currentFont, self)
if ok:
self.setData(newFont)
else:
self.setData(currentFont)
self.commitAndClose() | Opens a QColorDialog for the user |
def get_dataset(self, key, info):
"""Load a dataset."""
if self.channel not in key.name:
return
logger.debug('Reading %s.', key.name)
if key.calibration == 'brightness_temperature':
variable = self.nc['{}_BT_{}{}'.format(self.channel, self.stripe, self.view)]
... | Load a dataset. |
def __update_upgrades_table(self, delta):
"""Add a new record into the upgrades information table about the
applied delta
Parameters
----------
delta: Delta
the applied delta file"""
query = """
INSERT INTO {} (
--id,
version,... | Add a new record into the upgrades information table about the
applied delta
Parameters
----------
delta: Delta
the applied delta file |
def get_querystring_for_page(
request, page_number, querystring_key, default_number=1):
"""Return a querystring pointing to *page_number*."""
querydict = request.GET.copy()
querydict[querystring_key] = page_number
# For the default page number (usually 1) the querystring is not required.
if ... | Return a querystring pointing to *page_number*. |
def hash_bytes(buf):
"""
Hash bytes using the same method the registry uses (currently SHA-256).
:param buf: Bytes to hash
:type buf: binary str
:rtype: str
:returns: Hex-encoded hash of file's content (prefixed by ``sha256:``)
"""
sha256 = hashlib.sha256()
sha256.update(buf)
r... | Hash bytes using the same method the registry uses (currently SHA-256).
:param buf: Bytes to hash
:type buf: binary str
:rtype: str
:returns: Hex-encoded hash of file's content (prefixed by ``sha256:``) |
def get_kbs(custom_kbs_files=None, cache={}): # noqa
"""Load kbs (with caching).
This function stores the loaded kbs into the cache variable
For the caching to work, it needs to receive an empty dictionary
as "cache" paramater.
"""
cache_key = make_cache_key(custom_kbs_files)
if cache_key... | Load kbs (with caching).
This function stores the loaded kbs into the cache variable
For the caching to work, it needs to receive an empty dictionary
as "cache" paramater. |
def usgs_eros(self, scene, path):
""" Downloads the image from USGS """
# download from usgs if login information is provided
if self.usgs_user and self.usgs_pass:
try:
api_key = api.login(self.usgs_user, self.usgs_pass)
except USGSError as e:
... | Downloads the image from USGS |
def mark_day(self, day, month=None, year=None):
"""Marks the specified month day with a visual marker
(typically by making the number bold).
If only day is specified and the calendar month and year
are changed, the marked day remain marked.
You can be more specific setting month ... | Marks the specified month day with a visual marker
(typically by making the number bold).
If only day is specified and the calendar month and year
are changed, the marked day remain marked.
You can be more specific setting month and year parameters. |
def play(state):
""" Play sound for a given state.
:param state: a State value.
"""
filename = None
if state == SoundService.State.welcome:
filename = "pad_glow_welcome1.wav"
elif state == SoundService.State.goodbye:
filename = "pad_glow_power_off... | Play sound for a given state.
:param state: a State value. |
def __load_omitted_predictions(self):
"""private: set the omitted_predictions attribute
"""
# if there are no base predictions
if self.predictions is None:
raise Exception("ErrVar.__load_omitted_predictions(): " +
"no 'included' predictions is None... | private: set the omitted_predictions attribute |
def enable(self, ids):
"""
Enable Pool Members Running Script
:param ids: List of ids
:return: None on success
:raise PoolMemberDoesNotExistException
:raise InvalidIdPoolMemberException
:raise ScriptEnablePoolException
:raise... | Enable Pool Members Running Script
:param ids: List of ids
:return: None on success
:raise PoolMemberDoesNotExistException
:raise InvalidIdPoolMemberException
:raise ScriptEnablePoolException
:raise NetworkAPIException |
def _setup_transport(self):
'''
Setup the transport.
'''
if 'RAW' in self.error_whitelist:
log.info('%s %d will publish partially parsed messages', self._transport_type, self.pub_id)
if 'UNKNOWN' in self.error_whitelist:
log.info('%s %d will publish unknow... | Setup the transport. |
def from_sec(class_, sec):
"""
Create a key from an sec bytestream (which is an encoding of a public pair).
"""
public_pair = sec_to_public_pair(sec, class_._generator)
return class_(public_pair=public_pair, is_compressed=is_sec_compressed(sec)) | Create a key from an sec bytestream (which is an encoding of a public pair). |
def clean(feed: "Feed") -> "Feed":
"""
Apply
#. :func:`drop_zombies`
#. :func:`clean_ids`
#. :func:`clean_times`
#. :func:`clean_route_short_names`
to the given "Feed" in that order.
Return the resulting "Feed".
"""
feed = feed.copy()
ops = [
"clean_ids",
"c... | Apply
#. :func:`drop_zombies`
#. :func:`clean_ids`
#. :func:`clean_times`
#. :func:`clean_route_short_names`
to the given "Feed" in that order.
Return the resulting "Feed". |
def is_variable(value):
""" Check if string is LESS variable
args:
value (str): string
returns:
bool
"""
if isinstance(value, string_types):
return (value.startswith('@') or value.startswith('-@'))
elif isinstance(value, tuple):
value = ''.join(value)
retu... | Check if string is LESS variable
args:
value (str): string
returns:
bool |
def mfccInitFilterBanks(fs, nfft):
"""
Computes the triangular filterbank for MFCC computation
(used in the stFeatureExtraction function before the stMFCC function call)
This function is taken from the scikits.talkbox library (MIT Licence):
https://pypi.python.org/pypi/scikits.talkbox
"""
... | Computes the triangular filterbank for MFCC computation
(used in the stFeatureExtraction function before the stMFCC function call)
This function is taken from the scikits.talkbox library (MIT Licence):
https://pypi.python.org/pypi/scikits.talkbox |
def dump(values):
"""
Dump a ValueTree instance, returning its dict representation.
:param values:
:type values: ValueTree
:return:
:rtype: dict
"""
root = {}
def _dump(_values, container):
for name,value in _values._values.items():
if isinstance(value, ValueTree... | Dump a ValueTree instance, returning its dict representation.
:param values:
:type values: ValueTree
:return:
:rtype: dict |
def pretty_version_text():
"""Return pretty version text listing all plugins."""
version_lines = ["dtool, version {}".format(dtool_version)]
version_lines.append("\nBase:")
version_lines.append("dtoolcore, version {}".format(dtoolcore.__version__))
version_lines.append("dtool-cli, version {}".format... | Return pretty version text listing all plugins. |
def _json_safe_float(number):
"""
JSON serialization for infinity can be problematic.
See https://docs.python.org/2/library/json.html#basic-usage
This function returns None if `number` is infinity or negative infinity.
If the `number` cannot be converted to float, this will raise an exception.
... | JSON serialization for infinity can be problematic.
See https://docs.python.org/2/library/json.html#basic-usage
This function returns None if `number` is infinity or negative infinity.
If the `number` cannot be converted to float, this will raise an exception. |
def request(self, method, url, params=None, data=None, headers=None, auth=None,
timeout=None, allow_redirects=False):
"""
Make an HTTP request.
"""
raise TwilioException('HttpClient is an abstract class') | Make an HTTP request. |
def add_multizone(self, group_cast):
""" Start managing a group """
self._groups[str(group_cast.uuid)] = {
'chromecast': group_cast,
'listener': Listener(group_cast, self._casts),
'members': set()} | Start managing a group |
def get_day_end(config):
"""
Get the day end time given the day start. This assumes full 24h day.
Args:
config (dict): Configdict. Needed to extract ``day_start``.
Note:
This is merely a convinience funtion so we do not have to deduct this from ``day_start``
by hand all the tim... | Get the day end time given the day start. This assumes full 24h day.
Args:
config (dict): Configdict. Needed to extract ``day_start``.
Note:
This is merely a convinience funtion so we do not have to deduct this from ``day_start``
by hand all the time. |
def blobs(self):
"""
Returns this DataFrame joined with the blobs DataSource.
>>> blobs_df = refs_df.blobs
:rtype: BlobsDataFrame
"""
return BlobsDataFrame(self._engine_dataframe.getBlobs(), self._session, self._implicits) | Returns this DataFrame joined with the blobs DataSource.
>>> blobs_df = refs_df.blobs
:rtype: BlobsDataFrame |
def get_session_key(self, username, password_hash):
"""
Retrieve a session key with a username and a md5 hash of the user's
password.
"""
params = {"username": username, "authToken": md5(username + password_hash)}
request = _Request(self.network, "auth.getMobileSession",... | Retrieve a session key with a username and a md5 hash of the user's
password. |
def Update(self, env, args=None):
"""
Update an environment with the option variables.
env - the environment to update.
"""
values = {}
# first set the defaults:
for option in self.options:
if not option.default is None:
values[optio... | Update an environment with the option variables.
env - the environment to update. |
def replace(self, child, replacement):
"""Replace a child chunk with something else."""
for i in range(len(self.chunks)):
if self.chunks[i] == child:
self.chunks[i] = replacement | Replace a child chunk with something else. |
def _init():
"""Initialize the furious context and registry.
NOTE: Do not directly run this method.
"""
# If there is a context and it is initialized to this request,
# return, otherwise reinitialize the _local_context.
if (hasattr(_local_context, '_initialized') and
_local_context.... | Initialize the furious context and registry.
NOTE: Do not directly run this method. |
def make_set_name(idx):
"""Creates a run set name based on ``idx``"""
GROUPSIZE = 1000
set_idx = idx // GROUPSIZE
if set_idx >= 0:
return pypetconstants.FORMATTED_SET_NAME % set_idx
else:
return pypetconstants.SET_NAME_DUMMY | Creates a run set name based on ``idx`` |
def _detach_childs(self, idx_from=None, idx_to=None):
"""Moves all the childs to a new father"""
idx_from = idx_from or 0
idx_to = idx_to or len(self.childs)
removed = self.childs[idx_from:idx_to]
for child in removed:
if issubclass(child.__class__, DOMElement):
... | Moves all the childs to a new father |
def report(
vulnerabilities,
fileobj,
print_sanitised,
):
"""
Prints issues in color-coded text format.
Args:
vulnerabilities: list of vulnerabilities to report
fileobj: The output file object, which may be sys.stdout
"""
n_vulnerabilities = len(vulnerabilities)
unsa... | Prints issues in color-coded text format.
Args:
vulnerabilities: list of vulnerabilities to report
fileobj: The output file object, which may be sys.stdout |
def mixedcase(path):
"""Removes underscores and capitalizes the neighbouring character"""
words = path.split('_')
return words[0] + ''.join(word.title() for word in words[1:]) | Removes underscores and capitalizes the neighbouring character |
def stop_filter(self, post_processing):
"""
Save the plot in the current canvas as a image and apply
the *post_processing* function.
def post_processing(image, dpi):
# ny, nx, depth = image.shape
# image (numpy array) has RGBA channels and has a depth of 4.
... | Save the plot in the current canvas as a image and apply
the *post_processing* function.
def post_processing(image, dpi):
# ny, nx, depth = image.shape
# image (numpy array) has RGBA channels and has a depth of 4.
...
# create a new_image (numpy ar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.