code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def queryTs(ts, expression):
"""
Find the indices of the time series entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| matches = queryTs(ts, "archiveType == marine sediment")
| matches = queryTs(ts, "geo_meanElev <= 2000")
:param str e... | Find the indices of the time series entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| matches = queryTs(ts, "archiveType == marine sediment")
| matches = queryTs(ts, "geo_meanElev <= 2000")
:param str expression: Expression
:param list ts:... |
def now(utc=False, tz=None):
"""
Get a current DateTime object. By default is local.
.. code:: python
reusables.now()
# DateTime(2016, 12, 8, 22, 5, 2, 517000)
reusables.now().format("It's {24-hour}:{min}")
# "It's 22:05"
:param utc: bool, default False, UTC time not ... | Get a current DateTime object. By default is local.
.. code:: python
reusables.now()
# DateTime(2016, 12, 8, 22, 5, 2, 517000)
reusables.now().format("It's {24-hour}:{min}")
# "It's 22:05"
:param utc: bool, default False, UTC time not local
:param tz: TimeZone as specifie... |
def includes(self):
"""Return all of the include directories for this chip as a list."""
incs = self.combined_properties('includes')
processed_incs = []
for prop in incs:
if isinstance(prop, str):
processed_incs.append(prop)
else:
... | Return all of the include directories for this chip as a list. |
def backwards(self, orm):
"Write your backwards methods here."
orm['samples.CohortSample'].objects.all().delete()
orm['samples.Cohort'].objects.exclude(name=DEFAULT_COHORT_NAME).delete() | Write your backwards methods here. |
def files(self, creds, options, dry_run):
# type: (SourcePath, StorageCredentials,
# blobxfer.models.options.Download, bool) -> StorageEntity
"""Generator of Azure remote files or blobs
:param SourcePath self: this
:param StorageCredentials creds: storage creds
:pa... | Generator of Azure remote files or blobs
:param SourcePath self: this
:param StorageCredentials creds: storage creds
:param blobxfer.models.options.Download options: download options
:param bool dry_run: dry run
:rtype: StorageEntity
:return: Azure storage entity object |
def serve(destination, port, config):
"""Run a simple web server."""
if os.path.exists(destination):
pass
elif os.path.exists(config):
settings = read_settings(config)
destination = settings.get('destination')
if not os.path.exists(destination):
sys.stderr.write("... | Run a simple web server. |
def copyfileobj(src, dst, length=None, exception=OSError):
"""Copy length bytes from fileobj src to fileobj dst.
If length is None, copy the entire content.
"""
if length == 0:
return
if length is None:
shutil.copyfileobj(src, dst)
return
# BUFSIZE = 16 * 1024
blo... | Copy length bytes from fileobj src to fileobj dst.
If length is None, copy the entire content. |
def set_data(self, frames):
"""
Prepare the input of model
"""
data_frames = []
for frame in frames:
#frame H x W x C
frame = frame.swapaxes(0, 1) # swap width and height to form format W x H x C
if len(frame.shape) < 3:
frame =... | Prepare the input of model |
def _get_upload_session_status(res):
"""Parse the image upload response to obtain status.
Args:
res: http_utils.FetchResponse instance, the upload response
Returns:
dict, sessionStatus of the response
Raises:
hangups.NetworkError: If the upload requ... | Parse the image upload response to obtain status.
Args:
res: http_utils.FetchResponse instance, the upload response
Returns:
dict, sessionStatus of the response
Raises:
hangups.NetworkError: If the upload request failed. |
def _fire_bundle_event(self, kind):
# type: (int) -> None
"""
Fires a bundle event of the given kind
:param kind: Kind of event
"""
self.__framework._dispatcher.fire_bundle_event(BundleEvent(kind, self)) | Fires a bundle event of the given kind
:param kind: Kind of event |
def get_object_cat1(con, token, cat, kwargs):
"""
Constructs the "GET" URL. The functions is used by the get_object method
First Category of "GET" URL construction. Again calling it first category because more
complex functions maybe added later.
"""
req_str = "/"+kwarg... | Constructs the "GET" URL. The functions is used by the get_object method
First Category of "GET" URL construction. Again calling it first category because more
complex functions maybe added later. |
def organize_objects(self):
"""Organize objects and namespaces"""
def _render_children(obj):
for child in obj.children_strings:
child_object = self.objects.get(child)
if child_object:
obj.item_map[child_object.plural].append(child_object)
... | Organize objects and namespaces |
def bounding_box(self):
"""
An axis aligned bounding box for the current mesh.
Returns
----------
aabb : trimesh.primitives.Box
Box object with transform and extents defined
representing the axis aligned bounding box of the mesh
"""
from . imp... | An axis aligned bounding box for the current mesh.
Returns
----------
aabb : trimesh.primitives.Box
Box object with transform and extents defined
representing the axis aligned bounding box of the mesh |
def priority_enqueue(self,
function,
name=None,
force_start=False,
times=1,
data=None):
"""
Like :class:`enqueue()`, but adds the given function at the top of the
queue.
... | Like :class:`enqueue()`, but adds the given function at the top of the
queue.
If force_start is True, the function is immediately started even when
the maximum number of concurrent threads is already reached.
:type function: callable
:param function: The function that is execut... |
def organisations(self):
'''The organisations of this composition.'''
class Org:
def __init__(self, sdo_id, org_id, members, obj):
self.sdo_id = sdo_id
self.org_id = org_id
self.members = members
self.obj = obj
with sel... | The organisations of this composition. |
def create_filters(model, filter_info, resource):
"""Apply filters from filters information to base query
:param DeclarativeMeta model: the model of the node
:param dict filter_info: current node filter information
:param Resource resource: the resource
"""
filters = []
for filter_ in filte... | Apply filters from filters information to base query
:param DeclarativeMeta model: the model of the node
:param dict filter_info: current node filter information
:param Resource resource: the resource |
def Plus(self, other):
"""
Returns a new point which is the pointwise sum of self and other.
"""
return Point(self.x + other.x,
self.y + other.y,
self.z + other.z) | Returns a new point which is the pointwise sum of self and other. |
def simulated_binary_crossover(random, mom, dad, args):
"""Return the offspring of simulated binary crossover on the candidates.
This function performs simulated binary crossover (SBX), following the
implementation in NSGA-II
`(Deb et al., ICANNGA 1999) <http://vision.ucsd.edu/~sagarwal/icannga.p... | Return the offspring of simulated binary crossover on the candidates.
This function performs simulated binary crossover (SBX), following the
implementation in NSGA-II
`(Deb et al., ICANNGA 1999) <http://vision.ucsd.edu/~sagarwal/icannga.pdf>`_.
.. Arguments:
random -- the random number g... |
def extract_error_message(cls, e):
"""Extract error message for queries"""
message = str(e)
try:
if isinstance(e.args, tuple) and len(e.args) > 1:
message = e.args[1]
except Exception:
pass
return message | Extract error message for queries |
def decode_fetch_response(cls, response):
"""
Decode FetchResponse struct to FetchResponsePayloads
Arguments:
response: FetchResponse
"""
return [
kafka.structs.FetchResponsePayload(
topic, partition, error, highwater_offset, [
... | Decode FetchResponse struct to FetchResponsePayloads
Arguments:
response: FetchResponse |
def head_coaches_by_game(self, year):
"""Returns head coach data by game.
:year: An int representing the season in question.
:returns: An array with an entry per game of the season that the team
played (including playoffs). Each entry is the head coach's ID for that
game in the ... | Returns head coach data by game.
:year: An int representing the season in question.
:returns: An array with an entry per game of the season that the team
played (including playoffs). Each entry is the head coach's ID for that
game in the season. |
def _collect_memory_descriptors(program: Program) -> Dict[str, ParameterSpec]:
"""Collect Declare instructions that are important for building the patch table.
This is secretly stored on BinaryExecutableResponse. We're careful to make sure
these objects are json serializable.
:return: A dictionary of ... | Collect Declare instructions that are important for building the patch table.
This is secretly stored on BinaryExecutableResponse. We're careful to make sure
these objects are json serializable.
:return: A dictionary of variable names to specs about the declared region. |
def get_authorizations_for_agent_and_function(self, agent_id, function_id):
"""Gets a list of ``Authorizations`` associated with a given agent.
Authorizations related to the given resource, including those
related through an ``Agent,`` are returned. In plenary mode, the
returned list co... | Gets a list of ``Authorizations`` associated with a given agent.
Authorizations related to the given resource, including those
related through an ``Agent,`` are returned. In plenary mode, the
returned list contains all known authorizations or an error
results. Otherwise, the returned li... |
def set_moving_image(self, image):
"""
Set Moving ANTsImage for metric
"""
if not isinstance(image, iio.ANTsImage):
raise ValueError('image must be ANTsImage type')
if image.dimension != self.dimension:
raise ValueError('image dim (%i) does not match metr... | Set Moving ANTsImage for metric |
def get_z_variable(nc):
'''
Returns the name of the variable that defines the Z axis or height/depth
:param netCDF4.Dataset nc: netCDF dataset
'''
z_variables = get_z_variables(nc)
if not z_variables:
return None
# Priority is standard_name, units
for var in z_variables:
... | Returns the name of the variable that defines the Z axis or height/depth
:param netCDF4.Dataset nc: netCDF dataset |
def call(self, cmd, **kwargs):
"""A simple subprocess wrapper"""
if isinstance(cmd, basestring):
cmd = cmd.split()
self.log.info('Running %s', cmd)
p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, **kwargs)
out, er... | A simple subprocess wrapper |
def mark_all_as_read(self, recipient=None):
"""Mark as read any unread messages in the current queryset.
Optionally, filter these by recipient first.
"""
# We want to filter out read ones, as later we will store
# the time they were marked as read.
qset = self.unread(Tru... | Mark as read any unread messages in the current queryset.
Optionally, filter these by recipient first. |
def map(self, width, height):
"""
Creates and returns a new randomly generated map
"""
template = ti.load(os.path.join(script_dir, 'assets', 'template.tmx'))['map0']
#template.set_view(0, 0, template.px_width, template.px_height)
template.set_view(0, 0, width*template.tw,... | Creates and returns a new randomly generated map |
def get_brandings(self):
"""
Get all account brandings
@return List of brandings
"""
connection = Connection(self.token)
connection.set_url(self.production, self.BRANDINGS_URL)
return connection.get_request() | Get all account brandings
@return List of brandings |
def get_closest(self, sma):
"""
Return the `~photutils.isophote.Isophote` instance that has the
closest semimajor axis length to the input semimajor axis.
Parameters
----------
sma : float
The semimajor axis length.
Returns
-------
is... | Return the `~photutils.isophote.Isophote` instance that has the
closest semimajor axis length to the input semimajor axis.
Parameters
----------
sma : float
The semimajor axis length.
Returns
-------
isophote : `~photutils.isophote.Isophote` instance... |
def contains(self, k):
"""Return True if key `k` exists"""
if self._changed():
self._read()
return k in self.store.keys() | Return True if key `k` exists |
def push(self, x):
"""
Push an I{object} onto the stack.
@param x: An object to push.
@type x: L{Frame}
@return: The pushed frame.
@rtype: L{Frame}
"""
if isinstance(x, Frame):
frame = x
else:
frame = Frame(x)
self.s... | Push an I{object} onto the stack.
@param x: An object to push.
@type x: L{Frame}
@return: The pushed frame.
@rtype: L{Frame} |
def get_types(self):
""" Returns the unordered list of data types
:return: list of data types
"""
types = [str, int, int]
if self.strandPos is not None:
types.append(str)
if self.otherPos:
for o in self.otherPos:
types.append(o[2])... | Returns the unordered list of data types
:return: list of data types |
def sensor(self, sensor_type):
"""Update and return sensor value."""
_LOGGER.debug("Reading %s sensor.", sensor_type)
return self._session.read_sensor(self.device_id, sensor_type) | Update and return sensor value. |
def root_rhx_gis(self) -> Optional[str]:
"""rhx_gis string returned in the / query."""
if self.is_logged_in:
# At the moment, rhx_gis seems to be required for anonymous requests only. By returning None when logged
# in, we can save the root_rhx_gis lookup query.
retur... | rhx_gis string returned in the / query. |
def blkid(device=None, token=None):
'''
Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
... | Return block device attributes: UUID, LABEL, etc. This function only works
on systems where blkid is available.
device
Device name from the system
token
Any valid token used for the search
CLI Example:
.. code-block:: bash
salt '*' disk.blkid
salt '*' disk.blkid ... |
def _parse_outgoing_mail(sender, to, msgstring):
"""
Parse an outgoing mail and put it into the OUTBOX.
Arguments:
- `sender`: str
- `to`: str
- `msgstring`: str
Return: None
Exceptions: None
"""
global OUTBOX
OUTBOX.append(email.message_from_string(msgstring))
return | Parse an outgoing mail and put it into the OUTBOX.
Arguments:
- `sender`: str
- `to`: str
- `msgstring`: str
Return: None
Exceptions: None |
def validate_path(xj_path):
"""Validates XJ path.
:param str xj_path: XJ Path
:raise: XJPathError if validation fails.
"""
if not isinstance(xj_path, str):
raise XJPathError('XJPath must be a string')
for path in split(xj_path, '.'):
if path == '*':
continue
... | Validates XJ path.
:param str xj_path: XJ Path
:raise: XJPathError if validation fails. |
def set_sp_template_updated(self, vlan_id, sp_template, device_id):
"""Sets update_on_ucs flag to True."""
entry = self.get_sp_template_vlan_entry(vlan_id,
sp_template,
device_id)
if entry:
... | Sets update_on_ucs flag to True. |
def on_for_degrees(self, steering, speed, degrees, brake=True, block=True):
"""
Rotate the motors according to the provided ``steering``.
The distance each motor will travel follows the rules of :meth:`MoveTank.on_for_degrees`.
"""
(left_speed, right_speed) = self.get_speed_stee... | Rotate the motors according to the provided ``steering``.
The distance each motor will travel follows the rules of :meth:`MoveTank.on_for_degrees`. |
def extract_domain(host):
"""
Domain name extractor. Turns host names into domain names, ported
from pwdhash javascript code"""
host = re.sub('https?://', '', host)
host = re.match('([^/]+)', host).groups()[0]
domain = '.'.join(host.split('.')[-2:])
if domain in _domains:
domain = '.... | Domain name extractor. Turns host names into domain names, ported
from pwdhash javascript code |
def insert(self, table, value, ignore=False, commit=True):
"""
Insert a dict into db.
:type table: string
:type value: dict
:type ignore: bool
:type commit: bool
:return: int. The row id of the insert.
"""
value_q, _args = self._value_parser(value,... | Insert a dict into db.
:type table: string
:type value: dict
:type ignore: bool
:type commit: bool
:return: int. The row id of the insert. |
def statistical_distances(samples1, samples2, earth_mover_dist=True,
energy_dist=True):
"""Compute measures of the statistical distance between samples.
Parameters
----------
samples1: 1d array
samples2: 1d array
earth_mover_dist: bool, optional
Whether or not ... | Compute measures of the statistical distance between samples.
Parameters
----------
samples1: 1d array
samples2: 1d array
earth_mover_dist: bool, optional
Whether or not to compute the Earth mover's distance between the
samples.
energy_dist: bool, optional
Whether or not... |
def get_answers(self, assessment_section_id, item_id):
"""Gets the acceptable answers to the associated item.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
return: (osid.assessment.Ans... | Gets the acceptable answers to the associated item.
arg: assessment_section_id (osid.id.Id): ``Id`` of the
``AssessmentSection``
arg: item_id (osid.id.Id): ``Id`` of the ``Item``
return: (osid.assessment.AnswerList) - the answers
raise: IllegalState - ``is_answer_... |
def load(cls, filename, project=None, delim=' | '):
r"""
Read in pore and throat data from a saved VTK file.
Parameters
----------
filename : string (optional)
The name of the file containing the data to import. The formatting
of this file is outlined be... | r"""
Read in pore and throat data from a saved VTK file.
Parameters
----------
filename : string (optional)
The name of the file containing the data to import. The formatting
of this file is outlined below.
project : OpenPNM Project object
A... |
def set_params(self, data):
""" resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector long = ResPQ """
bytes_io = BytesIO(data)
assert struct.unpack('<I', bytes_io.read(4))[0] == resPQ.constructor
self.nonce = bytes_io.read(16)
self.ser... | resPQ#05162463 nonce:int128 server_nonce:int128 pq:string server_public_key_fingerprints:Vector long = ResPQ |
def raw_pressure_encode(self, time_usec, press_abs, press_diff1, press_diff2, temperature):
'''
The RAW pressure readings for the typical setup of one absolute
pressure and one differential pressure sensor. The
sensor values should be the raw, UNSCALED ADC... | The RAW pressure readings for the typical setup of one absolute
pressure and one differential pressure sensor. The
sensor values should be the raw, UNSCALED ADC values.
time_usec : Timestamp (microseconds since UNIX epoch or microseconds since system boot... |
def __convert_json_to_projects_map(self, json):
""" Convert JSON format to the projects map format
map[ds][repository] = project
If a repository is in several projects assign to leaf
Check that all JSON data is in the database
:param json: data with the projects to repositories ... | Convert JSON format to the projects map format
map[ds][repository] = project
If a repository is in several projects assign to leaf
Check that all JSON data is in the database
:param json: data with the projects to repositories mapping
:returns: the repositories to projects mappi... |
def initialize_state(self):
""" Call this to initialize the state of the UI after everything has been connected. """
if self.__hardware_source:
self.__profile_changed_event_listener = self.__hardware_source.profile_changed_event.listen(self.__update_profile_index)
self.__frame_pa... | Call this to initialize the state of the UI after everything has been connected. |
def parse_v3_signing_block(self):
"""
Parse the V2 signing block and extract all features
"""
self._v3_signing_data = []
# calling is_signed_v3 should also load the signature, if any
if not self.is_signed_v3():
return
block_bytes = self._v2_blocks[s... | Parse the V2 signing block and extract all features |
def start(self):
"""
Starts running the timer. If the timer is currently running, then
this method will do nothing.
:sa stop, reset
"""
if self._timer.isActive():
return
self._starttime = datetime.datetime.now()
self._timer.st... | Starts running the timer. If the timer is currently running, then
this method will do nothing.
:sa stop, reset |
def _get_voltage_angle_var(self, refs, buses):
""" Returns the voltage angle variable set.
"""
Va = array([b.v_angle * (pi / 180.0) for b in buses])
Vau = Inf * ones(len(buses))
Val = -Vau
Vau[refs] = Va[refs]
Val[refs] = Va[refs]
return Variable("Va", l... | Returns the voltage angle variable set. |
def add_snmp(data, interfaces):
"""
Format data for adding SNMP to an engine.
:param list data: list of interfaces as provided by kw
:param list interfaces: interfaces to enable SNMP by id
"""
snmp_interface = []
if interfaces: # Not providing interfaces will enable SNMP on all NDIs
... | Format data for adding SNMP to an engine.
:param list data: list of interfaces as provided by kw
:param list interfaces: interfaces to enable SNMP by id |
def to_netcdf(ds, *args, **kwargs):
"""
Store the given dataset as a netCDF file
This functions works essentially the same as the usual
:meth:`xarray.Dataset.to_netcdf` method but can also encode absolute time
units
Parameters
----------
ds: xarray.Dataset
The dataset to store
... | Store the given dataset as a netCDF file
This functions works essentially the same as the usual
:meth:`xarray.Dataset.to_netcdf` method but can also encode absolute time
units
Parameters
----------
ds: xarray.Dataset
The dataset to store
%(xarray.Dataset.to_netcdf.parameters)s |
def bdh(self, tickers, flds, start_date, end_date, elms=None,
ovrds=None, longdata=False):
"""
Get tickers and fields, return pandas DataFrame with columns as
MultiIndex with levels "ticker" and "field" and indexed by "date".
If long data is requested return DataFrame with co... | Get tickers and fields, return pandas DataFrame with columns as
MultiIndex with levels "ticker" and "field" and indexed by "date".
If long data is requested return DataFrame with columns
["date", "ticker", "field", "value"].
Parameters
----------
tickers: {list, string}
... |
def _get_secrets_to_compare(old_baseline, new_baseline):
"""
:rtype: list(tuple)
:param: tuple is in the following format:
filename: str; filename where identified secret is found
secret: dict; PotentialSecret json representation
is_secret_removed: bool; has the secret been removed f... | :rtype: list(tuple)
:param: tuple is in the following format:
filename: str; filename where identified secret is found
secret: dict; PotentialSecret json representation
is_secret_removed: bool; has the secret been removed from the
new baseline? |
def gather_metadata(fn_glob, parser):
"""Given a glob and a parser object, create a metadata dataframe.
Parameters
----------
fn_glob : str
Glob string to find trajectory files.
parser : descendant of _Parser
Object that handles conversion of filenames to metadata rows.
"""
... | Given a glob and a parser object, create a metadata dataframe.
Parameters
----------
fn_glob : str
Glob string to find trajectory files.
parser : descendant of _Parser
Object that handles conversion of filenames to metadata rows. |
def clear_surroundings(self):
"""
clears the cells immediately around the grid of the agent
(just to make it find to see on the screen)
"""
cells_to_clear = self.grd.eight_neighbors(self.current_y, self.current_x)
for cell in cells_to_clear:
self.grd.set_tile(... | clears the cells immediately around the grid of the agent
(just to make it find to see on the screen) |
def _is_zero(x):
""" Returns True if x is numerically 0 or an array with 0's. """
if x is None:
return True
if isinstance(x, numbers.Number):
return x == 0.0
if isinstance(x, np.ndarray):
return np.all(x == 0)
return False | Returns True if x is numerically 0 or an array with 0's. |
def params(self):
""" Return a *copy* (we hope) of the parameters.
DANGER: Altering properties directly doesn't call model._cache
"""
params = odict([])
for key,model in self.models.items():
params.update(model.params)
return params | Return a *copy* (we hope) of the parameters.
DANGER: Altering properties directly doesn't call model._cache |
def format_row(self, row):
"""
The render method expects rows as lists, here we switch our row format
from dict to list respecting the order of the headers
"""
res = []
headers = getattr(self, 'headers', [])
for column in headers:
column_name = column[... | The render method expects rows as lists, here we switch our row format
from dict to list respecting the order of the headers |
def _load_next(self):
"""Load the next days data (or file) without incrementing the date.
Repeated calls will not advance date/file and will produce the same data
Uses info stored in object to either increment the date,
or the file. Looks for self._load_by_date flag.
... | Load the next days data (or file) without incrementing the date.
Repeated calls will not advance date/file and will produce the same data
Uses info stored in object to either increment the date,
or the file. Looks for self._load_by_date flag. |
def pbkdf1(hash_algorithm, password, salt, iterations, key_length):
"""
An implementation of PBKDF1 - should only be used for interop with legacy
systems, not new architectures
:param hash_algorithm:
The string name of the hash algorithm to use: "md2", "md5", "sha1"
:param password:
... | An implementation of PBKDF1 - should only be used for interop with legacy
systems, not new architectures
:param hash_algorithm:
The string name of the hash algorithm to use: "md2", "md5", "sha1"
:param password:
A byte string of the password to use an input to the KDF
:param salt:
... |
def insert(self, path, simfile):
"""
Insert a file into the filesystem. Returns whether the operation was successful.
"""
if self.state is not None:
simfile.set_state(self.state)
mountpoint, chunks = self.get_mountpoint(path)
if mountpoint is None:
... | Insert a file into the filesystem. Returns whether the operation was successful. |
def ntp_authentication_key_encryption_type_sha1_type_sha1(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ntp = ET.SubElement(config, "ntp", xmlns="urn:brocade.com:mgmt:brocade-ntp")
authentication_key = ET.SubElement(ntp, "authentication-key")
k... | Auto Generated Code |
def setContentLen(self, content, len):
"""Replace the content of a node. NOTE: @content is supposed
to be a piece of XML CDATA, so it allows entity references,
but XML special chars need to be escaped first by using
xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars(). """
... | Replace the content of a node. NOTE: @content is supposed
to be a piece of XML CDATA, so it allows entity references,
but XML special chars need to be escaped first by using
xmlEncodeEntitiesReentrant() resp. xmlEncodeSpecialChars(). |
def GetCBVs(campaign, model='nPLD', clobber=False, **kwargs):
'''
Computes the CBVs for a given campaign.
:param int campaign: The campaign number
:param str model: The name of the :py:obj:`everest` model. Default `nPLD`
:param bool clobber: Overwrite existing files? Default `False`
'''
#... | Computes the CBVs for a given campaign.
:param int campaign: The campaign number
:param str model: The name of the :py:obj:`everest` model. Default `nPLD`
:param bool clobber: Overwrite existing files? Default `False` |
def search(cls, element, pattern):
"""
Helper method that returns a list of elements that match the
given path pattern of form {type}.{group}.{label}.
The input may be a Layout, an Overlay type or a single
Element.
"""
if isinstance(element, Layout):
... | Helper method that returns a list of elements that match the
given path pattern of form {type}.{group}.{label}.
The input may be a Layout, an Overlay type or a single
Element. |
def to_python(self, value):
"""
Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted.
"""
if isinstance(value, dict):
return value
if self.blank and not value:
return Non... | Convert the input JSON value into python structures, raises
django.core.exceptions.ValidationError if the data can't be converted. |
def visit_wavedrom(self, node):
"""
Visit the wavedrom node
"""
format = determine_format(self.builder.supported_image_types)
if format is None:
raise SphinxError(__("Cannot determine a suitable output format"))
# Create random filename
bname = "wavedrom-{}".format(uuid4())
outp... | Visit the wavedrom node |
def _gotitem(self,
key: Union[str, List[str]],
ndim: int,
subset: Optional[Union[Series, ABCDataFrame]] = None,
) -> Union[Series, ABCDataFrame]:
"""
Sub-classes to define. Return a sliced object.
Parameters
----------
... | Sub-classes to define. Return a sliced object.
Parameters
----------
key : string / list of selections
ndim : 1,2
requested ndim of result
subset : object, default None
subset to act on |
def reduce_by_device(parallelism, data, reduce_fn):
"""Reduces data per device.
This can be useful, for example, if we want to all-reduce n tensors on k<n
devices (like during eval when we have only one device). We call
reduce_by_device() to first sum the tensors per device, then call our usual
all-reduce o... | Reduces data per device.
This can be useful, for example, if we want to all-reduce n tensors on k<n
devices (like during eval when we have only one device). We call
reduce_by_device() to first sum the tensors per device, then call our usual
all-reduce operation to create one sum per device, followed by
expa... |
def connect(self):
"""
This method connects to RabbitMQ, returning the connection handle.
When the connection is established, the on_connection_open method
will be invoked by pika.
:rtype: pika.SelectConnection
"""
self._logger.info('Connecting to %s' % self._url... | This method connects to RabbitMQ, returning the connection handle.
When the connection is established, the on_connection_open method
will be invoked by pika.
:rtype: pika.SelectConnection |
def cached_property(method):
"""
:param method: a method without arguments except self
:returns: a cached property
"""
name = method.__name__
def newmethod(self):
try:
val = self.__dict__[name]
except KeyError:
val = method(self)
self.__dict__... | :param method: a method without arguments except self
:returns: a cached property |
def get_deployment_by_slot(self, service_name, deployment_slot):
'''
Returns configuration information, status, and system properties for
a deployment.
service_name:
Name of the hosted service.
deployment_slot:
The environment to which the hosted service ... | Returns configuration information, status, and system properties for
a deployment.
service_name:
Name of the hosted service.
deployment_slot:
The environment to which the hosted service is deployed. Valid
values are: staging, production |
def get_value(self, field, quick):
# type: (Field, bool) -> Any
""" Ask user the question represented by this instance.
Args:
field (Field):
The field we're asking the user to provide the value for.
quick (bool):
Enable quick mode. In quic... | Ask user the question represented by this instance.
Args:
field (Field):
The field we're asking the user to provide the value for.
quick (bool):
Enable quick mode. In quick mode, the form will reduce the
number of question asked by using d... |
def get_fetch_request(self, method, fetch_url, *args, **kwargs):
"""This is handy if you want to modify the request right before passing it
to requests, or you want to do something extra special customized
:param method: string, the http method (eg, GET, POST)
:param fetch_url: string, ... | This is handy if you want to modify the request right before passing it
to requests, or you want to do something extra special customized
:param method: string, the http method (eg, GET, POST)
:param fetch_url: string, the full url with query params
:param *args: any other positional ar... |
def component_title(component):
"""
Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc.
"""
title = u''
label_text = u''
title_text = u''
if component.get('label'):
label_text = component.get('label')
if component.get... | Label, title and caption
Title is the label text plus the title text
Title may contain italic tag, etc. |
def background_thread(timeout_fn, timeout_event, handle_exit_code, is_alive,
quit):
""" handles the timeout logic """
# if there's a timeout event, loop
if timeout_event:
while not quit.is_set():
timed_out = event_wait(timeout_event, 0.1)
if timed_out:
... | handles the timeout logic |
def check_write_permissions(file):
"""
Check if we can write to the given file
Otherwise since we might detach the process to run in the background
we might never find out that writing failed and get an ugly
exit message on startup. For example:
ERROR: Child exited immediately with non-zero exi... | Check if we can write to the given file
Otherwise since we might detach the process to run in the background
we might never find out that writing failed and get an ugly
exit message on startup. For example:
ERROR: Child exited immediately with non-zero exit code 127
So we catch this error upfront ... |
def workspace_backup_list(ctx):
"""
List backups
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
for b in backup_manager.list():
print(b) | List backups |
def connect(self, pattern, presenter, **kwargs):
""" Shortcut for self.route_map().connect() method. It is possible to pass presenter class instead of
its name - in that case such class will be saved in presenter collection and it will be available in
route matching.
:param pattern: same as pattern in :meth:`.... | Shortcut for self.route_map().connect() method. It is possible to pass presenter class instead of
its name - in that case such class will be saved in presenter collection and it will be available in
route matching.
:param pattern: same as pattern in :meth:`.WWebRouteMap.connect` method
:param presenter: presen... |
def getquery(query):
'Performs a query and get the results.'
try:
conn = connection.cursor()
conn.execute(query)
data = conn.fetchall()
conn.close()
except: data = list()
return data | Performs a query and get the results. |
def record(self):
# type: () -> bytes
'''
A method to generate the string representing this UDF Partition Volume
Descriptor.
Parameters:
None.
Returns:
A string representing this UDF Partition Volume Descriptor.
'''
if not self._initiali... | A method to generate the string representing this UDF Partition Volume
Descriptor.
Parameters:
None.
Returns:
A string representing this UDF Partition Volume Descriptor. |
def getElementsByType(self, type):
"""
retrieves all Elements that are of type type
@type type: class
@param type: type of the element
"""
foundElements=[]
for element in self.getAllElementsOfHirarchy():
if isinstance(element, type):
... | retrieves all Elements that are of type type
@type type: class
@param type: type of the element |
def up(self):
"""
Move this object up one position.
"""
self.swap(self.get_ordering_queryset().filter(order__lt=self.order).order_by('-order')) | Move this object up one position. |
def read_cyc(this, fn, conv=1.0):
""" Read the lattice information from a cyc.dat file (i.e., tblmd input file)
"""
f = paropen(fn, "r")
f.readline()
f.readline()
f.readline()
f.readline()
cell = np.array( [ [ 0.0, 0.0, 0.0 ], [ 0.0, 0.0, 0.0 ], [ 0.0, 0.0, 0.0 ] ] )
l = f.readline()... | Read the lattice information from a cyc.dat file (i.e., tblmd input file) |
def send_update(url_id, dataset):
"""
Send request to Seeder's API with data changed by user.
Args:
url_id (str): ID used as identification in Seeder.
dataset (dict): WA-KAT dataset sent from frontend.
"""
data = _convert_to_seeder_format(dataset)
if not data:
return
... | Send request to Seeder's API with data changed by user.
Args:
url_id (str): ID used as identification in Seeder.
dataset (dict): WA-KAT dataset sent from frontend. |
def decode_from_sha(sha):
"""convert coerced sha back into numeric list"""
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec") | convert coerced sha back into numeric list |
def highlightNextMatch(self):
"""
Select and highlight the next match in the set of matches.
"""
# If this method was called on an empty input field (ie.
# if the user hit <ctrl>+s again) then pick the default
# selection.
if self.qteText.toPlainText() == '':
... | Select and highlight the next match in the set of matches. |
def verify(self, signed):
'''
Recover the message (digest) from the signature using the public key
:param str signed: The signature created with the private key
:rtype: str
:return: The message (digest) recovered from the signature, or an empty
string if the decrypti... | Recover the message (digest) from the signature using the public key
:param str signed: The signature created with the private key
:rtype: str
:return: The message (digest) recovered from the signature, or an empty
string if the decryption failed |
def _WriteFileChunk(self, chunk):
"""Yields binary chunks, respecting archive file headers and footers.
Args:
chunk: the StreamedFileChunk to be written
"""
if chunk.chunk_index == 0:
# Make sure size of the original file is passed. It's required
# when output_writer is StreamingTarWr... | Yields binary chunks, respecting archive file headers and footers.
Args:
chunk: the StreamedFileChunk to be written |
def __write_srgb(self, outfile):
"""
Write colour reference information: gamma, iccp etc.
This method should be called only from ``write_idat`` method
or chunk order will be ruined.
"""
if self.rendering_intent is not None and self.icc_profile is not None:
ra... | Write colour reference information: gamma, iccp etc.
This method should be called only from ``write_idat`` method
or chunk order will be ruined. |
def read(*paths):
"""Build a file path from *paths* and return the contents."""
filename = os.path.join(*paths)
with codecs.open(filename, mode='r', encoding='utf-8') as handle:
return handle.read() | Build a file path from *paths* and return the contents. |
def get_cognitive_process_id(self):
"""Gets the grade ``Id`` associated with the cognitive process.
return: (osid.id.Id) - the grade ``Id``
raise: IllegalState - ``has_cognitive_process()`` is ``false``
*compliance: mandatory -- This method must be implemented.*
"""
# ... | Gets the grade ``Id`` associated with the cognitive process.
return: (osid.id.Id) - the grade ``Id``
raise: IllegalState - ``has_cognitive_process()`` is ``false``
*compliance: mandatory -- This method must be implemented.* |
def get_instance(
self,
name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Gets the details of a specific Redis instance.
Example:
>>> from google.cloud import redis_... | Gets the details of a specific Redis instance.
Example:
>>> from google.cloud import redis_v1beta1
>>>
>>> client = redis_v1beta1.CloudRedisClient()
>>>
>>> name = client.instance_path('[PROJECT]', '[LOCATION]', '[INSTANCE]')
>>>
... |
def __sweeten(self, dumper: 'Dumper', class_: Type, node: Node) -> None:
"""Applies the user's yatiml_sweeten() function(s), if any.
Sweetening is done for the base classes first, then for the \
derived classes, down the hierarchy to the class we're \
constructing.
Args:
... | Applies the user's yatiml_sweeten() function(s), if any.
Sweetening is done for the base classes first, then for the \
derived classes, down the hierarchy to the class we're \
constructing.
Args:
dumper: The dumper that is dumping this object.
class_: The type o... |
def copyFuncVersionedLib(dest, source, env):
"""Install a versioned library into a destination by copying,
(including copying permission/mode bits) and then creating
required symlinks."""
if os.path.isdir(source):
raise SCons.Errors.UserError("cannot install directory `%s' as a version library"... | Install a versioned library into a destination by copying,
(including copying permission/mode bits) and then creating
required symlinks. |
def wait_for_connection(self, timeout=10):
"""
Busy loop until connection is established.
Will abort after timeout (seconds). Return value is a boolean, whether
connection could be established.
"""
start_time = datetime.datetime.now()
while True:
if ... | Busy loop until connection is established.
Will abort after timeout (seconds). Return value is a boolean, whether
connection could be established. |
def plot_predict(self, h=5, past_values=20, intervals=True, **kwargs):
""" Plots forecasts with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How many pas... | Plots forecasts with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
past_values : int (default : 20)
How many past observations to show on the forecast graph?
intervals : boolean
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.