code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def trigger_event(name,
event,
value1=None,
value2=None,
value3=None
):
'''
Trigger an event in IFTTT
.. code-block:: yaml
ifttt-event:
ifttt.trigger_event:
- event: TestEvent
... | Trigger an event in IFTTT
.. code-block:: yaml
ifttt-event:
ifttt.trigger_event:
- event: TestEvent
- value1: 'A value that we want to send.'
- value2: 'A second value that we want to send.'
- value3: 'A third value that we want to send.'
The ... |
def gini(data):
"""
Calculate the `Gini coefficient
<https://en.wikipedia.org/wiki/Gini_coefficient>`_ of a 2D array.
The Gini coefficient is calculated using the prescription from `Lotz
et al. 2004 <http://adsabs.harvard.edu/abs/2004AJ....128..163L>`_
as:
.. math::
G = \\frac{1}{\... | Calculate the `Gini coefficient
<https://en.wikipedia.org/wiki/Gini_coefficient>`_ of a 2D array.
The Gini coefficient is calculated using the prescription from `Lotz
et al. 2004 <http://adsabs.harvard.edu/abs/2004AJ....128..163L>`_
as:
.. math::
G = \\frac{1}{\\left | \\bar{x} \\right | n... |
def single_device(cl_device_type='GPU', platform=None, fallback_to_any_device_type=False):
"""Get a list containing a single device environment, for a device of the given type on the given platform.
This will only fetch devices that support double (possibly only double with a pragma
defined, bu... | Get a list containing a single device environment, for a device of the given type on the given platform.
This will only fetch devices that support double (possibly only double with a pragma
defined, but still, it should support double).
Args:
cl_device_type (cl.device_type.* or str... |
def get_device(self, id=None):
"""Returns details of either the first or specified device
:param int id: Identifier of desired device. If not given, first device
found will be returned
:returns tuple: Device ID, Device Address, Firmware Version
"""
if id is None:
... | Returns details of either the first or specified device
:param int id: Identifier of desired device. If not given, first device
found will be returned
:returns tuple: Device ID, Device Address, Firmware Version |
def tpictr(sample, lenout=_default_len_out, lenerr=_default_len_out):
"""
Given a sample time string, create a time format picture
suitable for use by the routine timout.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tpictr_c.html
:param sample: A sample time string.
:type sample: st... | Given a sample time string, create a time format picture
suitable for use by the routine timout.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/tpictr_c.html
:param sample: A sample time string.
:type sample: str
:param lenout: The length for the output picture string.
:type lenout: i... |
def search(self, **kwargs):
'''Query this object (and its descendants).
Parameters
----------
kwargs
Each `(key, value)` pair encodes a search field in `key`
and a target value in `value`.
`key` must be a string, and should correspond to a property i... | Query this object (and its descendants).
Parameters
----------
kwargs
Each `(key, value)` pair encodes a search field in `key`
and a target value in `value`.
`key` must be a string, and should correspond to a property in
the JAMS object hierarchy... |
def _load_root_directory(self):
"""
Load root directory, which has a cid of 0
"""
kwargs = self._req_directory(0)
self._root_directory = Directory(api=self, **kwargs) | Load root directory, which has a cid of 0 |
def forbild(space, resolution=False, ear=True, value_type='density',
scale='auto'):
"""Standard FORBILD phantom in 2 dimensions.
The FORBILD phantom is intended for testing CT algorithms and is intended
to be similar to a human head.
The phantom is defined using the following materials:
... | Standard FORBILD phantom in 2 dimensions.
The FORBILD phantom is intended for testing CT algorithms and is intended
to be similar to a human head.
The phantom is defined using the following materials:
========================= ===== ================
Material Index Density (g/... |
def sector(self, start_ray, end_ray, start_distance=None, end_distance=None, units='b'):
"""Slices a sector from the selected dataset.
Slice contains the start and end rays. If start and end rays are equal
one ray is returned. If the start_ray is greater than the end_ray
slicin... | Slices a sector from the selected dataset.
Slice contains the start and end rays. If start and end rays are equal
one ray is returned. If the start_ray is greater than the end_ray
slicing continues over the 359-0 border.
Parameters
----------
start_ra... |
def load_model(self, name=None):
'''
Loads a saved version of the model.
'''
if self.clobber:
return False
if name is None:
name = self.name
file = os.path.join(self.dir, '%s.npz' % name)
if os.path.exists(file):
if not self.... | Loads a saved version of the model. |
def open(filename, mode="rb",
format=None, check=-1, preset=None, filters=None,
encoding=None, errors=None, newline=None):
"""Open an LZMA-compressed file in binary or text mode.
filename can be either an actual file name (given as a str or bytes object),
in which case the named file is o... | Open an LZMA-compressed file in binary or text mode.
filename can be either an actual file name (given as a str or bytes object),
in which case the named file is opened, or it can be an existing file object
to read from or write to.
The mode argument can be "r", "rb" (default), "w", "wb", "a", or "ab"... |
def generate_tree_path(fileDigest, depth):
"""Generate a relative path from the given fileDigest
relative path has a numbers of directories levels according to @depth
Args:
fileDigest -- digest for which the relative path will be generate
depth -- number of levels t... | Generate a relative path from the given fileDigest
relative path has a numbers of directories levels according to @depth
Args:
fileDigest -- digest for which the relative path will be generate
depth -- number of levels to use in relative path generation
Returns:
... |
def _get_memory_banks_listed_in_dir(path):
"""Get all memory banks the kernel lists in a given directory.
Such a directory can be /sys/devices/system/node/ (contains all memory banks)
or /sys/devices/system/cpu/cpu*/ (contains all memory banks on the same NUMA node as that core)."""
# Such directories c... | Get all memory banks the kernel lists in a given directory.
Such a directory can be /sys/devices/system/node/ (contains all memory banks)
or /sys/devices/system/cpu/cpu*/ (contains all memory banks on the same NUMA node as that core). |
def read(self, source_path):
"""
Parse content and metadata of Org files
Keyword Arguments:
source_path -- Path to the Org file to parse
"""
with pelican_open(source_path) as text:
text_lines = list(text.splitlines())
header, content = self._separate_... | Parse content and metadata of Org files
Keyword Arguments:
source_path -- Path to the Org file to parse |
def save_token(token, domain='analytics.luminoso.com', token_file=None):
"""
Take a long-lived API token and store it to a local file. Long-lived
tokens can be retrieved through the UI. Optional arguments are the
domain for which the token is valid and the file in which to store the
... | Take a long-lived API token and store it to a local file. Long-lived
tokens can be retrieved through the UI. Optional arguments are the
domain for which the token is valid and the file in which to store the
token. |
def convert_timedelta(duration):
"""
Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers)
"""
days, seconds = duration.days, duration.seconds
... | Summary:
Convert duration into component time units
Args:
:duration (datetime.timedelta): time duration to convert
Returns:
days, hours, minutes, seconds | TYPE: tuple (integers) |
def create_dataset(parent, path, overwrite=False, **kwargs):
"""Create a new dataset inside the parent HDF5 object
Parameters
----------
parent : `h5py.Group`, `h5py.File`
the object in which to create a new dataset
path : `str`
the path at which to create the new dataset
over... | Create a new dataset inside the parent HDF5 object
Parameters
----------
parent : `h5py.Group`, `h5py.File`
the object in which to create a new dataset
path : `str`
the path at which to create the new dataset
overwrite : `bool`
if `True`, delete any existing dataset at the... |
def chess960_pos(self) -> Optional[int]:
"""
Gets the Chess960 starting position index between 0 and 959
or ``None``.
"""
if self.occupied_co[WHITE] != BB_RANK_1 | BB_RANK_2:
return None
if self.occupied_co[BLACK] != BB_RANK_7 | BB_RANK_8:
return N... | Gets the Chess960 starting position index between 0 and 959
or ``None``. |
def set_properties(self, properties):
"""
Updates the service properties
:param properties: The new properties
:raise TypeError: The argument is not a dictionary
"""
if not isinstance(properties, dict):
raise TypeError("Waiting for dictionary")
# Key... | Updates the service properties
:param properties: The new properties
:raise TypeError: The argument is not a dictionary |
def get_bin_query_session(self, proxy):
"""Gets the bin query session.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.BinQuerySession) - a ``BinQuerySession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
... | Gets the bin query session.
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.resource.BinQuerySession) - a ``BinQuerySession``
raise: NullArgument - ``proxy`` is ``null``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_bin_query()`... |
def get_file_hexdigest(filename, blocksize=1024*1024*10):
'''Get a hex digest of a file.'''
if hashlib.__name__ == 'hashlib':
m = hashlib.md5() # new - 'hashlib' module
else:
m = hashlib.new() # old - 'md5' module - remove once py2.4 gone
fd = open(filename, 'r')
while ... | Get a hex digest of a file. |
def initreadtxt(self, idftxt):
"""
Use the current IDD and read an IDF from text data. If the IDD has not
yet been initialised then this is done first.
Parameters
----------
idftxt : str
Text representing an IDF file.
"""
iddfhandle = StringI... | Use the current IDD and read an IDF from text data. If the IDD has not
yet been initialised then this is done first.
Parameters
----------
idftxt : str
Text representing an IDF file. |
def dot(vec1, vec2):
"""Calculate the dot product between two Vectors"""
if isinstance(vec1, Vector2) \
and isinstance(vec2, Vector2):
return ((vec1.X * vec2.X) + (vec1.Y * vec2.Y))
else:
raise TypeError("vec1 and vec2 must be Vector2's") | Calculate the dot product between two Vectors |
def to_ped(self):
"""
Return a generator with the info in ped format.
Yields:
An iterator with the family info in ped format
"""
ped_header = [
'#FamilyID',
'IndividualID',
'PaternalID',
'MaternalID',
... | Return a generator with the info in ped format.
Yields:
An iterator with the family info in ped format |
def merge_into_group(self, group):
"""
Redefines :meth:`~candv.base.Constant.merge_into_group` and adds
``verbose_name`` and ``help_text`` attributes to the target group.
"""
super(VerboseMixin, self).merge_into_group(group)
group.verbose_name = self.verbose_name
... | Redefines :meth:`~candv.base.Constant.merge_into_group` and adds
``verbose_name`` and ``help_text`` attributes to the target group. |
def main(sample_id, trace_file, workdir):
"""
Parses a nextflow trace file, searches for processes with a specific tag
and sends a JSON report with the relevant information
The expected fields for the trace file are::
0. task_id
1. process
2. tag
3. status
4. ex... | Parses a nextflow trace file, searches for processes with a specific tag
and sends a JSON report with the relevant information
The expected fields for the trace file are::
0. task_id
1. process
2. tag
3. status
4. exit code
5. start timestamp
6. containe... |
def parse_image_response(self, response):
"""
Parse a single object from the RETS feed
:param response: The response from the RETS server
:return: Object
"""
if 'xml' in response.headers.get('Content-Type'):
# Got an XML response, likely an error code.
... | Parse a single object from the RETS feed
:param response: The response from the RETS server
:return: Object |
def value(self):
"""Return sub type and sub value as binary data.
Returns:
:class:`~pyof.foundation.basic_types.BinaryData`:
BinaryData calculated.
"""
binary = UBInt8(self.sub_type).pack() + self.sub_value.pack()
return BinaryData(binary) | Return sub type and sub value as binary data.
Returns:
:class:`~pyof.foundation.basic_types.BinaryData`:
BinaryData calculated. |
def create_annotation(xml_file, from_fasst):
"""Create annotations by importing from FASST sleep scoring file.
Parameters
----------
xml_file : path to xml file
annotation file that will be created
from_fasst : path to FASST file
.mat file containing the scores
Returns
----... | Create annotations by importing from FASST sleep scoring file.
Parameters
----------
xml_file : path to xml file
annotation file that will be created
from_fasst : path to FASST file
.mat file containing the scores
Returns
-------
instance of Annotations
TODO
----
... |
def _split_markdown(text_url, tld_pos):
"""
Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int t... | Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int tld_pos: position of TLD
:return: URL that has remove... |
def get(self, field):
"""
Returns the value of a user field.
:param str field:
The name of the user field.
:returns: str -- the value
"""
if field in ('username', 'uuid', 'app_data'):
return self.data[field]
else:
return self.d... | Returns the value of a user field.
:param str field:
The name of the user field.
:returns: str -- the value |
def assert_is_instance(obj, cls, msg_fmt="{msg}"):
"""Fail if an object is not an instance of a class or tuple of classes.
>>> assert_is_instance(5, int)
>>> assert_is_instance('foo', (str, bytes))
>>> assert_is_instance(5, str)
Traceback (most recent call last):
...
AssertionError: 5 i... | Fail if an object is not an instance of a class or tuple of classes.
>>> assert_is_instance(5, int)
>>> assert_is_instance('foo', (str, bytes))
>>> assert_is_instance(5, str)
Traceback (most recent call last):
...
AssertionError: 5 is an instance of <class 'int'>, expected <class 'str'>
... |
def _check_constant_params(
a, has_const=False, use_const=True, rtol=1e-05, atol=1e-08
):
"""Helper func to interaction between has_const and use_const params.
has_const use_const outcome
--------- --------- -------
True True Confirm that a has constant; return a
F... | Helper func to interaction between has_const and use_const params.
has_const use_const outcome
--------- --------- -------
True True Confirm that a has constant; return a
False False Confirm that a doesn't have constant; return a
False True Confi... |
def service_set_tag(path, service_name, tag):
'''
Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
servi... | Change the tag of a docker-compose service
This does not pull or up the service
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_name
Name of the service to remove
tag
... |
def human_size(size, a_kilobyte_is_1024_bytes=False, precision=1, target=None):
'''Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 10... | Convert a file size to human-readable form.
Keyword arguments:
size -- file size in bytes
a_kilobyte_is_1024_bytes -- if True (default), use multiples of 1024
if False, use multiples of 1000
Returns: string
Credit: <http://diveintopython3.org/your-first-python-progr... |
def export(self, filename, offset=0, length=None):
"""Exports byte array to specified destination
Args:
filename (str): destination to output file
offset (int): byte offset (default: 0)
"""
self.__validate_offset(filename=filename, offset=offset, length=length)
... | Exports byte array to specified destination
Args:
filename (str): destination to output file
offset (int): byte offset (default: 0) |
def permitted_query(self, query, group, operations):
'''Change the ``query`` so that only instances for which
``group`` has roles with permission on ``operations`` are returned.'''
session = query.session
models = session.router
user = group.user
if user.is_superuser: # super-u... | Change the ``query`` so that only instances for which
``group`` has roles with permission on ``operations`` are returned. |
def get_devices(self):
"""
Helper that retuns a dict of devices for this server.
:return:
Returns a tuple of two elements:
- dict<tango class name : list of device names>
- dict<device names : tango class name>
:rtype: tuple<dict, dict>
""... | Helper that retuns a dict of devices for this server.
:return:
Returns a tuple of two elements:
- dict<tango class name : list of device names>
- dict<device names : tango class name>
:rtype: tuple<dict, dict> |
def Miqueu(T, Tc, Vc, omega):
r'''Calculates air-water surface tension using the methods of [1]_.
.. math::
\sigma = k T_c \left( \frac{N_a}{V_c}\right)^{2/3}
(4.35 + 4.14 \omega)t^{1.26}(1+0.19t^{0.5} - 0.487t)
Parameters
----------
T : float
Temperature of fluid [K]
T... | r'''Calculates air-water surface tension using the methods of [1]_.
.. math::
\sigma = k T_c \left( \frac{N_a}{V_c}\right)^{2/3}
(4.35 + 4.14 \omega)t^{1.26}(1+0.19t^{0.5} - 0.487t)
Parameters
----------
T : float
Temperature of fluid [K]
Tc : float
Critical tempera... |
def upload_files(self, container, src_dst_map, content_type=None):
"""Upload multiple files."""
if not content_type:
content_type = "application/octet.stream"
url = self.make_url(container, None, None)
headers = self._base_headers
multi_files = []
try:
... | Upload multiple files. |
def delete(self):
"""
Deletes resources of this widget that require manual cleanup.
Currently removes all actions, event handlers and the background.
The background itself should automatically remove all vertex lists to avoid visual artifacts.
Note that... | Deletes resources of this widget that require manual cleanup.
Currently removes all actions, event handlers and the background.
The background itself should automatically remove all vertex lists to avoid visual artifacts.
Note that this method is currently experimental... |
def _parse_resolution(self, tokens):
"""
Parse resolution from the GROUP BY statement.
E.g. GROUP BY time(10s) would mean a 10 second resolution
:param tokens:
:return:
"""
return self.resolution_parser.parse(self.parse_keyword(Keyword.GROUP_BY, tokens)) | Parse resolution from the GROUP BY statement.
E.g. GROUP BY time(10s) would mean a 10 second resolution
:param tokens:
:return: |
def replace_s(self, c_bra, c_ket, s):
'''
to replace chars between c_bra and c_ket in self.current by the
chars in s.
@type c_bra int
@type c_ket int
@type s: string
'''
adjustment = len(s) - (c_ket - c_bra)
self.current = self.current[0:c_bra] + ... | to replace chars between c_bra and c_ket in self.current by the
chars in s.
@type c_bra int
@type c_ket int
@type s: string |
def custom_role(self):
"""
| Comment: A custom role if the user is an agent on the Enterprise plan
"""
if self.api and self.custom_role_id:
return self.api._get_custom_role(self.custom_role_id) | | Comment: A custom role if the user is an agent on the Enterprise plan |
def isRegionValid(self):
""" Returns false if the whole region is not even partially inside any screen, otherwise true """
screens = PlatformManager.getScreenDetails()
for screen in screens:
s_x, s_y, s_w, s_h = screen["rect"]
if self.x+self.w >= s_x and s_x+s_w >= self.x... | Returns false if the whole region is not even partially inside any screen, otherwise true |
def is_layer_compatible(self, layer, layer_purpose=None, keywords=None):
"""Validate if a given layer is compatible for selected IF
as a given layer_purpose
:param layer: The layer to be validated
:type layer: QgsVectorLayer | QgsRasterLayer
:param layer_purpose: The layer_p... | Validate if a given layer is compatible for selected IF
as a given layer_purpose
:param layer: The layer to be validated
:type layer: QgsVectorLayer | QgsRasterLayer
:param layer_purpose: The layer_purpose the layer is validated for
:type layer_purpose: None, string
... |
def mergeCatalogs(catalog_list):
"""
Merge a list of Catalogs.
Parameters:
-----------
catalog_list : List of Catalog objects.
Returns:
--------
catalog : Combined Catalog object
"""
# Check the columns
for c in catalog_list:
if c.data.dtype.names != catalog_l... | Merge a list of Catalogs.
Parameters:
-----------
catalog_list : List of Catalog objects.
Returns:
--------
catalog : Combined Catalog object |
def binary_xloss(logits, labels, ignore=None):
"""
Binary Cross entropy loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
ignore: void class id
"""
logits, labels = flatten_binary_scores(logi... | Binary Cross entropy loss
logits: [B, H, W] Variable, logits at each pixel (between -\infty and +\infty)
labels: [B, H, W] Tensor, binary ground truth masks (0 or 1)
ignore: void class id |
def get_content_models(self):
""" Return all subclasses that are admin registered. """
models = []
for model in self.concrete_model.get_content_models():
try:
admin_url(model, "add")
except NoReverseMatch:
continue
else:
... | Return all subclasses that are admin registered. |
def to_time(self, phase, component=None, t0='t0_supconj', **kwargs):
"""
Get the time(s) of a phase(s) for a given ephemeris
:parameter phase: phase to convert to times (should be in
same system as t0s)
:type phase: float, list, or array
` :parameter str component: com... | Get the time(s) of a phase(s) for a given ephemeris
:parameter phase: phase to convert to times (should be in
same system as t0s)
:type phase: float, list, or array
` :parameter str component: component for which to get the ephemeris.
If not given, component will default t... |
def integrate_orbit(self, **time_spec):
"""
Integrate the initial conditions in the combined external potential
plus N-body forces.
This integration uses the `~gala.integrate.DOPRI853Integrator`.
Parameters
----------
**time_spec
Specification of how... | Integrate the initial conditions in the combined external potential
plus N-body forces.
This integration uses the `~gala.integrate.DOPRI853Integrator`.
Parameters
----------
**time_spec
Specification of how long to integrate. See documentation
for `~gala... |
def get_connection_logging(self, loadbalancer):
"""
Returns the connection logging setting for the given load balancer.
"""
uri = "/loadbalancers/%s/connectionlogging" % utils.get_id(loadbalancer)
resp, body = self.api.method_get(uri)
ret = body.get("connectionLogging", {... | Returns the connection logging setting for the given load balancer. |
def get_basic_profile(self, user_id, scope='profile/public'):
"""
Retrieve the Mxit user's basic profile
No user authentication required
"""
profile = _get(
token=self.oauth.get_app_token(scope),
uri='/user/profile/' + urllib.quote(user_id)
)
... | Retrieve the Mxit user's basic profile
No user authentication required |
def update_git_devstr(version, path=None):
"""
Updates the git revision string if and only if the path is being imported
directly from a git working copy. This ensures that the revision number in
the version string is accurate.
"""
try:
# Quick way to determine if we're in git or not -... | Updates the git revision string if and only if the path is being imported
directly from a git working copy. This ensures that the revision number in
the version string is accurate. |
def get_redshift(self, dist):
"""Returns the redshift for the given distance.
"""
dist, input_is_array = ensurearray(dist)
try:
zs = self.nearby_d2z(dist)
except TypeError:
# interpolant hasn't been setup yet
self.setup_interpolant()
... | Returns the redshift for the given distance. |
def get_games_by_season(self, season):
"""
Game schedule for a specified season.
"""
try:
season = int(season)
except ValueError:
raise FantasyDataError('Error: Invalid method parameters')
result = self._method_call("Games/{season}", "stats", seas... | Game schedule for a specified season. |
def execute_deploy_clone_from_vm(self, si, logger, vcenter_data_model, reservation_id, deployment_params, cancellation_context, folder_manager):
"""
Calls the deployer to deploy vm from another vm
:param cancellation_context:
:param str reservation_id:
:param si:
:param l... | Calls the deployer to deploy vm from another vm
:param cancellation_context:
:param str reservation_id:
:param si:
:param logger:
:type deployment_params: DeployFromTemplateDetails
:param vcenter_data_model:
:return: |
def type_names_mn(prefix, sizerangem, sizerangen):
"""
Helper for type name generation, like: fixed0x8 .. fixed0x256
"""
lm = []
ln = []
namelist = []
# construct lists out of ranges
for i in sizerangem: lm.append(i)
for i in sizerangen: ln.append... | Helper for type name generation, like: fixed0x8 .. fixed0x256 |
def get_shard_num_by_key_id(self, key_id):
"""
get_shard_num_by_key_id returns the Redis shard number (zero-indexed)
given a key id.
Keyword arguments:
key_id -- the key id (e.g. '12345' or 'anythingcangohere')
This method is critical in how the Redis cluster sharding wo... | get_shard_num_by_key_id returns the Redis shard number (zero-indexed)
given a key id.
Keyword arguments:
key_id -- the key id (e.g. '12345' or 'anythingcangohere')
This method is critical in how the Redis cluster sharding works. We
emulate twemproxy's md5 distribution algorithm. |
def volume_infos(pool=None, volume=None, **kwargs):
'''
Provide details on a storage volume. If no volume name is provided, the infos
all the volumes contained in the pool are provided. If no pool is provided,
the infos of the volumes of all pools are output.
:param pool: libvirt storage pool name ... | Provide details on a storage volume. If no volume name is provided, the infos
all the volumes contained in the pool are provided. If no pool is provided,
the infos of the volumes of all pools are output.
:param pool: libvirt storage pool name (default: ``None``)
:param volume: name of the volume to get... |
def _set_area_range(self, v, load=False):
"""
Setter method for area_range, mapped from YANG variable /rbridge_id/ipv6/router/ospf/area/area_range (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_range is considered as a private
method. Backends looking to... | Setter method for area_range, mapped from YANG variable /rbridge_id/ipv6/router/ospf/area/area_range (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_area_range is considered as a private
method. Backends looking to populate this variable should
do so via calling t... |
def make_coins(self, collection, text, subreference="", lang=None):
""" Creates a CoINS Title string from information
:param collection: Collection to create coins from
:param text: Text/Passage object
:param subreference: Subreference
:param lang: Locale information
:re... | Creates a CoINS Title string from information
:param collection: Collection to create coins from
:param text: Text/Passage object
:param subreference: Subreference
:param lang: Locale information
:return: Coins HTML title value |
def get_tags(blog_id, username, password):
"""
wp.getTags(blog_id, username, password)
=> tag structure[]
"""
authenticate(username, password)
site = Site.objects.get_current()
return [tag_structure(tag, site)
for tag in Tag.objects.usage_for_queryset(
Entry.publi... | wp.getTags(blog_id, username, password)
=> tag structure[] |
def post_dns_record(**kwargs):
'''
Creates a DNS record for the given name if the domain is managed with DO.
'''
if 'kwargs' in kwargs: # flatten kwargs if called via salt-cloud -f
f_kwargs = kwargs['kwargs']
del kwargs['kwargs']
kwargs.update(f_kwargs)
mandatory_kwargs = ('... | Creates a DNS record for the given name if the domain is managed with DO. |
def _win32_symlink2(path, link, allow_fallback=True, verbose=0):
"""
Perform a real symbolic link if possible. However, on most versions of
windows you need special privledges to create a real symlink. Therefore, we
try to create a symlink, but if that fails we fallback to using a junction.
AFAIK, ... | Perform a real symbolic link if possible. However, on most versions of
windows you need special privledges to create a real symlink. Therefore, we
try to create a symlink, but if that fails we fallback to using a junction.
AFAIK, the main difference between symlinks and junctions are that symlinks
can ... |
def push(self):
"""
Push the changes back to the remote(s) after fetching
"""
print('pushing...')
push_kwargs = {}
push_args = []
if self.settings['push.tags']:
push_kwargs['push'] = True
if self.settings['push.all']:
... | Push the changes back to the remote(s) after fetching |
def _spec_to_globs(address_mapper, specs):
"""Given a Specs object, return a PathGlobs object for the build files that it matches."""
patterns = set()
for spec in specs:
patterns.update(spec.make_glob_patterns(address_mapper))
return PathGlobs(include=patterns, exclude=address_mapper.build_ignore_patterns) | Given a Specs object, return a PathGlobs object for the build files that it matches. |
def _permute_aux_specs(self):
"""Generate all permutations of the non-core specifications."""
# Convert to attr names that Calc is expecting.
calc_aux_mapping = self._NAMES_SUITE_TO_CALC.copy()
# Special case: manually add 'library' to mapping
calc_aux_mapping[_OBJ_LIB_STR] = Non... | Generate all permutations of the non-core specifications. |
def send(self,
data: Object,
retries: int = Session.MAX_RETRIES,
timeout: float = Session.WAIT_TIMEOUT):
"""Use this method to send Raw Function queries.
This method makes possible to manually call every single Telegram API method in a low-level manner.
Av... | Use this method to send Raw Function queries.
This method makes possible to manually call every single Telegram API method in a low-level manner.
Available functions are listed in the :obj:`functions <pyrogram.api.functions>` package and may accept compound
data types from :obj:`types <pyrogram... |
def delete_item(self, item):
''' removes an item from the db '''
for relation, dst in self.relations_of(item, True):
self.delete_relation(item, relation, dst)
#print(item, relation, dst)
for src, relation in self.relations_to(item, True):
self.delete_relation(... | removes an item from the db |
def attributes_section(thing, doc, header_level):
"""
Generate an attributes section for classes.
Prefers type annotations, if they are present.
Parameters
----------
thing : class
Class to document
doc : dict
Numpydoc output
header_level : int
Number of `#`s to... | Generate an attributes section for classes.
Prefers type annotations, if they are present.
Parameters
----------
thing : class
Class to document
doc : dict
Numpydoc output
header_level : int
Number of `#`s to use for header
Returns
-------
list of str
... |
def _is_small_vcf(vcf_file):
"""Check for small VCFs which we want to analyze quicker.
"""
count = 0
small_thresh = 250
with utils.open_gzipsafe(vcf_file) as in_handle:
for line in in_handle:
if not line.startswith("#"):
count += 1
if count > small_thr... | Check for small VCFs which we want to analyze quicker. |
def sign_message(data_to_sign, digest_alg, sign_key,
use_signed_attributes=True):
"""Function signs the data and returns the generated ASN.1
:param data_to_sign: A byte string of the data to be signed.
:param digest_alg:
The digest algorithm to be used for generating the signatur... | Function signs the data and returns the generated ASN.1
:param data_to_sign: A byte string of the data to be signed.
:param digest_alg:
The digest algorithm to be used for generating the signature.
:param sign_key: The key to be used for generating the signature.
:param use_signed_attri... |
def _parse_categories(element):
"""
Returns a list with categories with relations.
"""
reference = {}
items = element.findall("./{%s}category" % WP_NAMESPACE)
for item in items:
term_id = item.find("./{%s}term_id" % WP_NAMESPACE).text
nicename = item.find("./{%s}category_nicenam... | Returns a list with categories with relations. |
def df_random(num_numeric=3, num_categorical=3, num_rows=100):
"""Generate a dataframe with random data. This is a general method
to easily generate a random dataframe, for more control of the
random 'distributions' use the column methods (df_numeric_column, df_categorical_column)
For other dis... | Generate a dataframe with random data. This is a general method
to easily generate a random dataframe, for more control of the
random 'distributions' use the column methods (df_numeric_column, df_categorical_column)
For other distributions you can use numpy methods directly (see example at bottom o... |
def rpc_get_account_record(self, address, token_type, **con_info):
"""
Get the current state of an account
"""
if not check_account_address(address):
return {'error': 'Invalid address', 'http_status': 400}
if not check_token_type(token_type):
return {'err... | Get the current state of an account |
def __initialize_ui(self):
"""
Initializes the Widget ui.
"""
self.Lines_Columns_label.setAlignment(Qt.AlignRight)
self.Lines_Columns_label.setText(self.__Lines_Columns_label_default_text.format(1, 1))
self.Languages_comboBox.setModel(self.__container.languages_model)
... | Initializes the Widget ui. |
def get_salt_interface(vm_, opts):
'''
Return the salt_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'.
'''
salt_host = salt.config.get_cloud_config_value(
'salt_interface', vm_, opts, default=False,
search_global=False
)
if salt_host is False:
... | Return the salt_interface type to connect to. Either 'public_ips' (default)
or 'private_ips'. |
def store_object(self, obj_name, data, content_type=None, etag=None,
content_encoding=None, ttl=None, return_none=False,
headers=None, extra_info=None):
"""
Creates a new object in this container, and populates it with the given
data. A StorageObject reference to the uplo... | Creates a new object in this container, and populates it with the given
data. A StorageObject reference to the uploaded file will be returned,
unless 'return_none' is set to True.
The 'extra_info' parameter is included for backwards compatibility. It
is no longer used at all, and will n... |
async def load(self, request, resource=None, **kwargs):
"""Load resource from given data."""
schema = self.get_schema(request, resource=resource, **kwargs)
data = await self.parse(request)
resource, errors = schema.load(
data, partial=resource is not None, many=isinstance(dat... | Load resource from given data. |
def weekdays(self):
"""A set of integers representing the weekdays the schedule recurs on,
with Monday = 0 and Sunday = 6."""
if not self.root.xpath('days'):
return set(range(7))
return set(int(d) - 1 for d in self.root.xpath('days/day/text()')) | A set of integers representing the weekdays the schedule recurs on,
with Monday = 0 and Sunday = 6. |
def check_lines(first, second):
"""Checks if two curves are lines and tries to intersect them.
.. note::
This is a helper for :func:`._all_intersections`.
If they are not lines / not linearized, immediately returns :data:`False`
with no "return value".
If they are lines, attempts to inter... | Checks if two curves are lines and tries to intersect them.
.. note::
This is a helper for :func:`._all_intersections`.
If they are not lines / not linearized, immediately returns :data:`False`
with no "return value".
If they are lines, attempts to intersect them (even if they are parallel
... |
def get_vprof_version(filename):
"""Returns actual version specified in filename."""
with open(filename) as src_file:
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
src_file.read(), re.M)
if version_match:
return version_match.group... | Returns actual version specified in filename. |
def cast(
source: Union[DataType, str], target: Union[DataType, str], **kwargs
) -> DataType:
"""Attempts to implicitly cast from source dtype to target dtype"""
source, result_target = dtype(source), dtype(target)
if not castable(source, result_target, **kwargs):
raise com.IbisTypeError(
... | Attempts to implicitly cast from source dtype to target dtype |
def t_bin_NUMBER(t):
r'[01]+' # A binary integer
t.value = int(t.value, 2)
t.lexer.begin('INITIAL')
return t | r'[01]+ |
def close(self, cancelled=False):
"""
Close this temporary pop-up.
:param cancelled: Whether the pop-up was cancelled (e.g. by pressing Esc).
"""
self._on_close(cancelled)
self._scene.remove_effect(self) | Close this temporary pop-up.
:param cancelled: Whether the pop-up was cancelled (e.g. by pressing Esc). |
def estimate_cpd(self, node):
"""
Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be estimated.
Returns
-------
CPD: Tabula... | Method to estimate the CPD for a given variable.
Parameters
----------
node: int, string (any hashable python object)
The name of the variable for which the CPD is to be estimated.
Returns
-------
CPD: TabularCPD
Examples
--------
>>... |
def ilsr_rankings(
n_items, data, alpha=0.0, initial_params=None, max_iter=100, tol=1e-8):
"""Compute the ML estimate of model parameters using I-LSR.
This function computes the maximum-likelihood (ML) estimate of model
parameters given ranking data (see :ref:`data-rankings`), using the
iterati... | Compute the ML estimate of model parameters using I-LSR.
This function computes the maximum-likelihood (ML) estimate of model
parameters given ranking data (see :ref:`data-rankings`), using the
iterative Luce Spectral Ranking algorithm [MG15]_.
The transition rates of the LSR Markov chain are initiali... |
def multi_replace(str_, search_list, repl_list):
r"""
Performs multiple replace functions foreach item in search_list and
repl_list.
Args:
str_ (str): string to search
search_list (list): list of search strings
repl_list (list or str): one or multiple replace strings
Return... | r"""
Performs multiple replace functions foreach item in search_list and
repl_list.
Args:
str_ (str): string to search
search_list (list): list of search strings
repl_list (list or str): one or multiple replace strings
Returns:
str: str_
CommandLine:
python... |
def setRecord( self, record ):
"""
Sets the record that is linked with this widget.
:param record | <orb.Table>
"""
super(XBasicCardWidget, self).setRecord(record)
browser = self.browserWidget()
if ( not browser ):
retu... | Sets the record that is linked with this widget.
:param record | <orb.Table> |
async def shutdown(self):
"""
This method attempts an orderly shutdown
If any exceptions are thrown, just ignore them.
:returns: No return value
"""
if self.log_output:
logging.info('Shutting down ...')
else:
print('Shutting down ...')
... | This method attempts an orderly shutdown
If any exceptions are thrown, just ignore them.
:returns: No return value |
def get_pane_index(self, pane):
" Return the index of the given pane. ValueError if not found. "
assert isinstance(pane, Pane)
return self.panes.index(pane) | Return the index of the given pane. ValueError if not found. |
def _set_topology_group(self, v, load=False):
"""
Setter method for topology_group, mapped from YANG variable /topology_group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_topology_group is considered as a private
method. Backends looking to populate this va... | Setter method for topology_group, mapped from YANG variable /topology_group (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_topology_group is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_topology_... |
def report(self, output_file=sys.stdout):
"""Report analysis outcome in human readable form."""
max_perf = self.results['max_perf']
if self._args and self._args.verbose >= 3:
print('{}'.format(pformat(self.results)), file=output_file)
if self._args and self._args.verbose >=... | Report analysis outcome in human readable form. |
def read_asynchronously(library, session, count):
"""Reads data from device or interface asynchronously.
Corresponds to viReadAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param count: Number of byte... | Reads data from device or interface asynchronously.
Corresponds to viReadAsync function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param count: Number of bytes to be read.
:return: result, jobid, return value of... |
def table(columns, names, page_size=None, format_strings=None):
""" Return an html table of this data
Parameters
----------
columns : list of numpy arrays
names : list of strings
The list of columns names
page_size : {int, None}, optional
The number of items to show on each page... | Return an html table of this data
Parameters
----------
columns : list of numpy arrays
names : list of strings
The list of columns names
page_size : {int, None}, optional
The number of items to show on each page of the table
format_strings : {lists of strings, None}, optional
... |
def resize_file_to(self, in_path, out_path, keep_filename=False):
""" Given a filename, resize and save the image per the specification into out_path
:param in_path: path to image file to save. Must be supported by PIL
:param out_path: path to the directory root for the outputted thumbnails to... | Given a filename, resize and save the image per the specification into out_path
:param in_path: path to image file to save. Must be supported by PIL
:param out_path: path to the directory root for the outputted thumbnails to be stored
:return: None |
def trusted_permission(f):
"""Access only by D1 infrastructure."""
@functools.wraps(f)
def wrapper(request, *args, **kwargs):
trusted(request)
return f(request, *args, **kwargs)
return wrapper | Access only by D1 infrastructure. |
def _py_expand_short(subsequence, sequence, max_l_dist):
"""Straightforward implementation of partial match expansion."""
# The following diagram shows the score calculation step.
#
# Each new score is the minimum of:
# * a OR a + 1 (substitution, if needed)
# * b + 1 (deletion, i.e. skipping ... | Straightforward implementation of partial match expansion. |
def get_data_frame_transform_stats(self, transform_id=None, params=None):
"""
`<https://www.elastic.co/guide/en/elasticsearch/reference/current/get-data-frame-transform-stats.html>`_
:arg transform_id: The id of the transform for which to get stats.
'_all' or '*' implies all transfo... | `<https://www.elastic.co/guide/en/elasticsearch/reference/current/get-data-frame-transform-stats.html>`_
:arg transform_id: The id of the transform for which to get stats.
'_all' or '*' implies all transforms |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.