code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def main():
"""
Get an info report for a tile. Format is same as input tile but with
min/max values for values under 'data'.
"""
arguments = docopt(__doc__, version='tileinfo 0.1')
src_name = arguments['SOURCE']
src_format = arguments['--srcformat']
indent = arguments['--indent']
... | Get an info report for a tile. Format is same as input tile but with
min/max values for values under 'data'. |
def init_app(self, app):
"""Flask application initialization.
The initialization will:
* Set default values for the configuration variables.
* Initialise the Flask mail extension.
* Configure the extension to avoid the email sending in case of debug
or ``MAIL_SUPP... | Flask application initialization.
The initialization will:
* Set default values for the configuration variables.
* Initialise the Flask mail extension.
* Configure the extension to avoid the email sending in case of debug
or ``MAIL_SUPPRESS_SEND`` config variable set. In ... |
def _tarjan_head(ctx, v):
""" Used by @tarjan and @tarjan_iter. This is the head of the
main iteration """
ctx.index[v] = len(ctx.index)
ctx.lowlink[v] = ctx.index[v]
ctx.S.append(v)
ctx.S_set.add(v)
it = iter(ctx.g.get(v, ()))
ctx.T.append((it,False,... | Used by @tarjan and @tarjan_iter. This is the head of the
main iteration |
def htmlABF(ID,group,d,folder,overwrite=False):
"""given an ID and the dict of files, generate a static html for that abf."""
fname=folder+"/swhlab4/%s_index.html"%ID
if overwrite is False and os.path.exists(fname):
return
html=TEMPLATES['abf']
html=html.replace("~ID~",ID)
html=html.repl... | given an ID and the dict of files, generate a static html for that abf. |
def translate_file(
estimator, subtokenizer, input_file, output_file=None,
print_all_translations=True):
"""Translate lines in file, and save to output file if specified.
Args:
estimator: tf.Estimator used to generate the translations.
subtokenizer: Subtokenizer object for encoding and decoding sou... | Translate lines in file, and save to output file if specified.
Args:
estimator: tf.Estimator used to generate the translations.
subtokenizer: Subtokenizer object for encoding and decoding source and
translated lines.
input_file: file containing lines to translate
output_file: file that stores ... |
def info(self):
"""Get coordinates, image info, and unit"."""
return {'coordinates': self._coordinates(),
'imageinfo': self._imageinfo(),
'miscinfo': self._miscinfo(),
'unit': self._unit()
} | Get coordinates, image info, and unit". |
def download_remote_script(url):
"""Download the content of a remote script to a local temp file."""
temp_fh = tempfile.NamedTemporaryFile('wt', encoding='utf8', suffix=".py", delete=False)
downloader = _ScriptDownloader(url)
logger.info(
"Downloading remote script from %r using (%r downloader) ... | Download the content of a remote script to a local temp file. |
def match(self, sentence, start=0, _v=None, _u=None):
""" Returns the first match found in the given sentence, or None.
"""
if sentence.__class__.__name__ == "Sentence":
pass
elif isinstance(sentence, list) or sentence.__class__.__name__ == "Text":
return find(lam... | Returns the first match found in the given sentence, or None. |
def decode(self, encoded):
""" Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``.
"""
encoded = super().decode(encoded)
tokens = [self.itos[index] for index in encode... | Decodes a tensor into a sequence.
Args:
encoded (torch.Tensor): Encoded sequence.
Returns:
str: Sequence decoded from ``encoded``. |
def max_projection(self, axis=2):
"""
Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along.
"""
if axis >= size(self.value_shape):
raise Exc... | Compute maximum projections of images along a dimension.
Parameters
----------
axis : int, optional, default = 2
Which axis to compute projection along. |
def get_storage(self, id_or_uri):
"""
Get storage details of an OS Volume.
Args:
id_or_uri: ID or URI of the OS Volume.
Returns:
dict: Storage details
"""
uri = self.URI + "/{}/storage".format(extract_id_from_uri(id_or_uri))
return self._... | Get storage details of an OS Volume.
Args:
id_or_uri: ID or URI of the OS Volume.
Returns:
dict: Storage details |
def execute(self):
"""
Execute the actions necessary to perform a `molecule converge` and
returns None.
:return: None
"""
self.print_info()
self._config.provisioner.converge()
self._config.state.change_state('converged', True) | Execute the actions necessary to perform a `molecule converge` and
returns None.
:return: None |
def main():
"""
Main entry point for the script. Create a parser, process the command line,
and run it
"""
parser = cli.Cli()
parser.parse(sys.argv[1:])
return parser.run() | Main entry point for the script. Create a parser, process the command line,
and run it |
def state_angle(ket0: State, ket1: State) -> bk.BKTensor:
"""The Fubini-Study angle between states.
Equal to the Burrs angle for pure states.
"""
return fubini_study_angle(ket0.vec, ket1.vec) | The Fubini-Study angle between states.
Equal to the Burrs angle for pure states. |
def _parse_tile_part_bit_stream(self, fptr, sod_marker, tile_length):
"""Parse the tile part bit stream for SOP, EPH marker segments."""
read_buffer = fptr.read(tile_length)
# The tile length could possibly be too large and extend past
# the end of file. We need to be a bit resilient.
... | Parse the tile part bit stream for SOP, EPH marker segments. |
def expectation(pyquil_prog: Program,
pauli_sum: Union[PauliSum, PauliTerm, np.ndarray],
samples: int,
qc: QuantumComputer) -> float:
"""
Compute the expectation value of pauli_sum over the distribution generated from pyquil_prog.
:par... | Compute the expectation value of pauli_sum over the distribution generated from pyquil_prog.
:param pyquil_prog: The state preparation Program to calculate the expectation value of.
:param pauli_sum: PauliSum representing the operator of which to calculate the expectation
value or a numpy m... |
def p_created_1(self, p):
"""created : CREATED DATE"""
try:
if six.PY2:
value = p[2].decode(encoding='utf-8')
else:
value = p[2]
self.builder.set_created_date(self.document, value)
except CardinalityError:
self.more_... | created : CREATED DATE |
def parse_item(lines):
"""
Given the lines that form a subtag entry (after joining wrapped lines
back together), parse the data they contain.
Returns a generator that yields once if there was any data there
(and an empty generator if this was just the header).
"""
info = {}
for line... | Given the lines that form a subtag entry (after joining wrapped lines
back together), parse the data they contain.
Returns a generator that yields once if there was any data there
(and an empty generator if this was just the header). |
def compute_training_sizes(train_perc, class_sizes, stratified=True):
"""Computes the maximum training size that the smallest class can provide """
size_per_class = np.int64(np.around(train_perc * class_sizes))
if stratified:
print("Different classes in training set are stratified to match smalles... | Computes the maximum training size that the smallest class can provide |
def _close_and_clean(self, cleanup):
"""
Closes the project, and cleanup the disk if cleanup is True
:param cleanup: Whether to delete the project directory
"""
tasks = []
for node in self._nodes:
tasks.append(asyncio.async(node.manager.close_node(node.id)))... | Closes the project, and cleanup the disk if cleanup is True
:param cleanup: Whether to delete the project directory |
def section_path_lengths(neurites, neurite_type=NeuriteType.all):
'''Path lengths of a collection of neurites '''
# Calculates and stores the section lengths in one pass,
# then queries the lengths in the path length iterations.
# This avoids repeatedly calculating the lengths of the
# same sections... | Path lengths of a collection of neurites |
def _populate_issue(self, graph: TraceGraph, instance_id: int) -> None:
"""Adds an issue to the trace graph along with relevant information
pertaining to the issue (e.g. instance, fix_info, sources/sinks)
The issue is identified by its corresponding instance's ID in the input
trace graph... | Adds an issue to the trace graph along with relevant information
pertaining to the issue (e.g. instance, fix_info, sources/sinks)
The issue is identified by its corresponding instance's ID in the input
trace graph. |
def duration_to_string(duration):
"""
Converts a duration to a string
Args:
duration (int): The duration in seconds to convert
Returns s (str): The duration as a string
"""
m, s = divmod(duration, 60)
h, m = divmod(m, 60)
return "%d:%02d:%02d" % (h, m, s) | Converts a duration to a string
Args:
duration (int): The duration in seconds to convert
Returns s (str): The duration as a string |
def _delete(self, obj, **kwargs):
""" Delete the object directly.
.. code-block:: python
DBSession.sacrud(Users)._delete(UserObj)
If you no needed commit session
.. code-block:: python
DBSession.sacrud(Users, commit=False)._delete(UserObj)
"""
... | Delete the object directly.
.. code-block:: python
DBSession.sacrud(Users)._delete(UserObj)
If you no needed commit session
.. code-block:: python
DBSession.sacrud(Users, commit=False)._delete(UserObj) |
def check_assets(self):
"""
Throws an exception if assets file is not configured or cannot be found.
:param assets: path to the assets file
"""
if not self.assets_file:
raise ImproperlyConfigured("You must specify the path to the assets.json file via WEBPACK_ASSETS_FI... | Throws an exception if assets file is not configured or cannot be found.
:param assets: path to the assets file |
def waypoint_set_current_send(self, seq):
'''wrapper for waypoint_set_current_send'''
if self.mavlink10():
self.mav.mission_set_current_send(self.target_system, self.target_component, seq)
else:
self.mav.waypoint_set_current_send(self.target_system, self.target_component,... | wrapper for waypoint_set_current_send |
def show(self, xlim=None, ylim=None, units="thz"):
"""
Show the plot using matplotlib.
Args:
xlim: Specifies the x-axis limits. Set to None for automatic
determination.
ylim: Specifies the y-axis limits.
units: units for the frequencies. Accep... | Show the plot using matplotlib.
Args:
xlim: Specifies the x-axis limits. Set to None for automatic
determination.
ylim: Specifies the y-axis limits.
units: units for the frequencies. Accepted values thz, ev, mev, ha, cm-1, cm^-1. |
def color_array_by_hue_mix(value, palette):
"""
Figure out the appropriate color for a binary string value by averaging
the colors corresponding the indices of each one that it contains. Makes
for visualizations that intuitively show patch overlap.
"""
if int(value, 2) > 0:
# Convert bi... | Figure out the appropriate color for a binary string value by averaging
the colors corresponding the indices of each one that it contains. Makes
for visualizations that intuitively show patch overlap. |
def format_obj_name(obj, delim="<>"):
""" Formats the object name in a pretty way
@obj: any python object
@delim: the characters to wrap a parent object name in
-> #str formatted name
..
from vital.debug import format_obj_name
format_obj_name(vital.debug.Ti... | Formats the object name in a pretty way
@obj: any python object
@delim: the characters to wrap a parent object name in
-> #str formatted name
..
from vital.debug import format_obj_name
format_obj_name(vital.debug.Timer)
# -> 'Timer<vital.debug>'
... |
def dump(self, obj, key=None):
"""Write a pickled representation of obj to the open TFile."""
if key is None:
key = '_pickle'
with preserve_current_directory():
self.__file.cd()
if sys.version_info[0] < 3:
pickle.Pickler.dump(self, obj)
... | Write a pickled representation of obj to the open TFile. |
def gradients_X(self, dL_dK, X, X2=None):
"""
Given the derivative of the objective wrt K (dL_dK), compute the derivative wrt X
"""
if use_stationary_cython:
return self._gradients_X_cython(dL_dK, X, X2)
else:
return self._gradients_X_pure(dL_dK, X, X2) | Given the derivative of the objective wrt K (dL_dK), compute the derivative wrt X |
def get(self, action, default=None):
"""
Returns given action value.
:param action: Action name.
:type action: unicode
:param default: Default value if action is not found.
:type default: object
:return: Action.
:rtype: QAction
"""
try:
... | Returns given action value.
:param action: Action name.
:type action: unicode
:param default: Default value if action is not found.
:type default: object
:return: Action.
:rtype: QAction |
def moveGamepadFocusToNeighbor(self, eDirection, ulFrom):
"""
Changes the Gamepad focus from one overlay to one of its neighbors. Returns VROverlayError_NoNeighbor if there is no
neighbor in that direction
"""
fn = self.function_table.moveGamepadFocusToNeighbor
result = ... | Changes the Gamepad focus from one overlay to one of its neighbors. Returns VROverlayError_NoNeighbor if there is no
neighbor in that direction |
def load_all(self, workers=None, limit=None, n_expected=None):
"""Load all instances witih multiple threads.
:param workers: number of workers to use to load instances, which
defaults to what was given in the class initializer
:param limit: return a maximum, which defaul... | Load all instances witih multiple threads.
:param workers: number of workers to use to load instances, which
defaults to what was given in the class initializer
:param limit: return a maximum, which defaults to no limit
:param n_expected: rerun the iteration on the data... |
def get_whoami(self):
"""
A convenience function used in the event that you need to confirm that
the broker thinks you are who you think you are.
:returns dict whoami: Dict structure contains:
* administrator: whether the user is has admin privileges
* name: user... | A convenience function used in the event that you need to confirm that
the broker thinks you are who you think you are.
:returns dict whoami: Dict structure contains:
* administrator: whether the user is has admin privileges
* name: user name
* auth_backend: backend ... |
def return_estimator(self):
"""Returns base learner using its origin and the given hyperparameters
Returns:
est (estimator): Estimator object
"""
estimator = self.base_learner_origin.return_estimator()
estimator = estimator.set_params(**self.hyperparameters)
... | Returns base learner using its origin and the given hyperparameters
Returns:
est (estimator): Estimator object |
def _sideral(date, longitude=0., model='mean', eop_correction=True, terms=106):
"""Get the sideral time at a defined date
Args:
date (Date):
longitude (float): Longitude of the observer (in degrees)
East positive/West negative.
model (str): 'mean' or 'apparent' for GMST and ... | Get the sideral time at a defined date
Args:
date (Date):
longitude (float): Longitude of the observer (in degrees)
East positive/West negative.
model (str): 'mean' or 'apparent' for GMST and GAST respectively
Return:
float: Sideral time in degrees
GMST: Greenwi... |
def num_mode_groups(self):
"""Most devices only provide a single mode group, however devices
such as the Wacom Cintiq 22HD provide two mode groups.
If multiple mode groups are available, a caller should use
:meth:`~libinput.define.TabletPadModeGroup.has_button`,
:meth:`~libinput.define.TabletPadModeGroup.has... | Most devices only provide a single mode group, however devices
such as the Wacom Cintiq 22HD provide two mode groups.
If multiple mode groups are available, a caller should use
:meth:`~libinput.define.TabletPadModeGroup.has_button`,
:meth:`~libinput.define.TabletPadModeGroup.has_ring`
and :meth:`~libinput.de... |
def p_im(p):
""" asm : IM expr
"""
val = p[2].eval()
if val not in (0, 1, 2):
error(p.lineno(1), 'Invalid IM number %i' % val)
p[0] = None
return
p[0] = Asm(p.lineno(1), 'IM %i' % val) | asm : IM expr |
def istoken(docgraph, node_id, namespace=None):
"""returns true, iff the given node ID belongs to a token node.
Parameters
----------
node_id : str
the node to be checked
namespace : str or None
If a namespace is given, only look for tokens in the given namespace.
Otherwise,... | returns true, iff the given node ID belongs to a token node.
Parameters
----------
node_id : str
the node to be checked
namespace : str or None
If a namespace is given, only look for tokens in the given namespace.
Otherwise, look for tokens in the default namespace of the given
... |
def serialize_oaipmh(self, pid, record):
"""Serialize a single record for OAI-PMH."""
root = etree.Element(
'oai_datacite',
nsmap={
None: 'http://schema.datacite.org/oai/oai-1.0/',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
... | Serialize a single record for OAI-PMH. |
def save(self, path):
"""Saves this catalogue's data to `path`.
:param path: file path to save catalogue data to
:type path: `str`
"""
writer = csv.writer(open(path, 'w', newline=''), delimiter=' ')
rows = list(self.items())
rows.sort(key=lambda x: x[0])
... | Saves this catalogue's data to `path`.
:param path: file path to save catalogue data to
:type path: `str` |
def _match(self, **kwargs):
"""Method which indicates if the object matches specified criteria.
Match accepts criteria as kwargs and looks them up on attributes.
Actual matching is performed with fnmatch, so shell-like wildcards
work within match strings. Examples:
obj._match(A... | Method which indicates if the object matches specified criteria.
Match accepts criteria as kwargs and looks them up on attributes.
Actual matching is performed with fnmatch, so shell-like wildcards
work within match strings. Examples:
obj._match(AXTitle='Terminal*')
obj._match(... |
def url(self):
"""
Returns url for accessing pipeline entity.
"""
return self.get_url(server_url=self._session.server_url, pipeline_name=self.data.name) | Returns url for accessing pipeline entity. |
def version(self, id, expand=None):
"""Get a version Resource.
:param id: ID of the version to get
:type id: str
:param expand: extra information to fetch inside each resource
:type expand: Optional[Any]
:rtype: Version
"""
version = Version(self._option... | Get a version Resource.
:param id: ID of the version to get
:type id: str
:param expand: extra information to fetch inside each resource
:type expand: Optional[Any]
:rtype: Version |
def start(self, work):
"""
Hand the main thread to the window and continue work in the provided
function. A state is passed as the first argument that contains a
`running` flag. The function is expected to exit if the flag becomes
false. The flag can also be set to false to stop ... | Hand the main thread to the window and continue work in the provided
function. A state is passed as the first argument that contains a
`running` flag. The function is expected to exit if the flag becomes
false. The flag can also be set to false to stop the window event loop
and continue ... |
def results_class_wise_average_metrics(self):
"""Class-wise averaged metrics
Returns
-------
dict
results in a dictionary format
"""
event_wise_results = self.results_class_wise_metrics()
event_wise_f_measure = []
event_wise_precision = []
... | Class-wise averaged metrics
Returns
-------
dict
results in a dictionary format |
def design_stat_cooling(self, value="Cooling"):
"""Corresponds to IDD Field `design_stat_cooling`
Args:
value (str): value for IDD Field `design_stat_cooling`
Accepted values are:
- Cooling
Default value: Cooling
if `valu... | Corresponds to IDD Field `design_stat_cooling`
Args:
value (str): value for IDD Field `design_stat_cooling`
Accepted values are:
- Cooling
Default value: Cooling
if `value` is None it will not be checked against the
... |
async def unmount(self):
"""Unmount this block device."""
self._data = await self._handler.unmount(
system_id=self.node.system_id, id=self.id) | Unmount this block device. |
def findXdk( self, name ):
"""
Looks up the xdk item based on the current name.
:param name | <str>
:return <XdkItem> || None
"""
for i in range(self.uiContentsTREE.topLevelItemCount()):
item = self.uiContentsTREE.topLevelItem(i)
... | Looks up the xdk item based on the current name.
:param name | <str>
:return <XdkItem> || None |
def return_videos(self, begtime, endtime):
"""It returns the videos and beginning and end time of the video
segment. The MFF video format is not well documented. As far as I can
see, the manual 20150805 says that there might be multiple .mp4 files
but I only see one .mov file (and no way... | It returns the videos and beginning and end time of the video
segment. The MFF video format is not well documented. As far as I can
see, the manual 20150805 says that there might be multiple .mp4 files
but I only see one .mov file (and no way to specify which video file to
read). In addi... |
def add_dhcp_interface(self, interface_id, dynamic_index, zone_ref=None,
vlan_id=None, comment=None):
"""
Add a DHCP interface on a single FW
:param int interface_id: interface id
:param int dynamic_index: index number for dhcp interface
:param bool primary_mgt: whet... | Add a DHCP interface on a single FW
:param int interface_id: interface id
:param int dynamic_index: index number for dhcp interface
:param bool primary_mgt: whether to make this primary mgt
:param str zone_ref: zone reference, can be name, href or Zone
:raises EngineCommandFaile... |
def set_updated(self):
"""
Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status.
"""
# get latest output
output = []
for method in self.methods.values():
data = method["last_output"]... | Mark the module as updated.
We check if the actual content has changed and if so we trigger an
update in py3status. |
def _subtask_result(self, idx, value):
"""Receive a result from a single subtask."""
self._results[idx] = value
if len(self._results) == self._num_tasks:
self.set_result([
self._results[i]
for i in range(self._num_tasks)
]) | Receive a result from a single subtask. |
def get_doc(project, source_code, offset, resource=None, maxfixes=1):
"""Get the pydoc"""
fixer = fixsyntax.FixSyntax(project, source_code, resource, maxfixes)
pyname = fixer.pyname_at(offset)
if pyname is None:
return None
pyobject = pyname.get_object()
return PyDocExtractor().get_doc(p... | Get the pydoc |
def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
logger.debug("Checking usage for service %s", self.service_name)
self.connect()
for lim i... | Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`. |
def unrecognized_arguments_error(self, args, parsed, extras):
"""
This exists because argparser is dumb and naive and doesn't
fail unrecognized arguments early.
"""
# loop variants
kwargs = vars(parsed)
failed = list(extras)
# initial values
runti... | This exists because argparser is dumb and naive and doesn't
fail unrecognized arguments early. |
def remote_file_exists(self):
"""Verify whether the file (scene) exists on AWS Storage."""
url = join(self.base_url, 'index.html')
return super(AWSDownloader, self).remote_file_exists(url) | Verify whether the file (scene) exists on AWS Storage. |
def _posterior(self, x):
"""Internal function to calculate and cache the posterior
"""
yedge = self._nuis_pdf.marginalization_bins()
yc = 0.5 * (yedge[1:] + yedge[:-1])
yw = yedge[1:] - yedge[:-1]
like_array = self.like(x[:, np.newaxis], yc[np.newaxis, :]) * yw
l... | Internal function to calculate and cache the posterior |
def remove_stale_indexes_from_bika_catalog(portal):
"""Removes stale indexes and metadata from bika_catalog. Most of these
indexes and metadata were used for Samples, but they are no longer used.
"""
logger.info("Removing stale indexes and metadata from bika_catalog ...")
cat_id = "bika_catalog"
... | Removes stale indexes and metadata from bika_catalog. Most of these
indexes and metadata were used for Samples, but they are no longer used. |
def get_dataset(self, key, info):
"""Load dataset designated by the given key from file"""
logger.debug('Reading dataset {}'.format(key.name))
# Read data from file and calibrate if necessary
if 'longitude' in key.name:
data = self.geo_data['lon']
elif 'latitude' in ... | Load dataset designated by the given key from file |
def locate(desktop_filename_or_name):
'''Locate a .desktop from the standard locations.
Find the path to the .desktop file of a given .desktop filename or application name.
Standard locations:
- ``~/.local/share/applications/``
- ``/usr/share/applications``
Args:
desktop_filename_or_name (str): Either the ... | Locate a .desktop from the standard locations.
Find the path to the .desktop file of a given .desktop filename or application name.
Standard locations:
- ``~/.local/share/applications/``
- ``/usr/share/applications``
Args:
desktop_filename_or_name (str): Either the filename of a .desktop file or the name of... |
def _get_channel_state_statelessly(self, grpc_channel, channel_id):
"""
We get state of the channel (nonce, amount, unspent_amount)
We do it by securely combine information from the server and blockchain
https://github.com/singnet/wiki/blob/master/multiPartyEscrowContract/MultiPartyEscro... | We get state of the channel (nonce, amount, unspent_amount)
We do it by securely combine information from the server and blockchain
https://github.com/singnet/wiki/blob/master/multiPartyEscrowContract/MultiPartyEscrow_stateless_client.md |
def privileges(
state, host,
user, privileges,
user_hostname='localhost',
database='*', table='*',
present=True,
flush=True,
# Details for speaking to MySQL via `mysql` CLI
mysql_user=None, mysql_password=None,
mysql_host=None, mysql_port=None,
):
'''
Add/remove MySQL privile... | Add/remove MySQL privileges for a user, either global, database or table specific.
+ user: name of the user to manage privileges for
+ privileges: list of privileges the user should have
+ user_hostname: the hostname of the user
+ database: name of the database to grant privileges to (defaults to all)
... |
def create_server(AssociatePublicIpAddress=None, DisableAutomatedBackup=None, Engine=None, EngineModel=None, EngineVersion=None, EngineAttributes=None, BackupRetentionCount=None, ServerName=None, InstanceProfileArn=None, InstanceType=None, KeyPair=None, PreferredMaintenanceWindow=None, PreferredBackupWindow=None, Secur... | Creates and immedately starts a new server. The server is ready to use when it is in the HEALTHY state. By default, you can create a maximum of 10 servers.
This operation is asynchronous.
A LimitExceededException is thrown when you have created the maximum number of servers (10). A ResourceAlreadyExistsExceptio... |
def make_operatorsetid(
domain, # type: Text
version, # type: int
): # type: (...) -> OperatorSetIdProto
"""Construct an OperatorSetIdProto.
Arguments:
domain (string): The domain of the operator set id
version (integer): Version of operator set id
"""
operatorsetid =... | Construct an OperatorSetIdProto.
Arguments:
domain (string): The domain of the operator set id
version (integer): Version of operator set id |
def to_OrderedDict(self, include_null=True):
"""
Convert to OrderedDict.
"""
if include_null:
return OrderedDict(self.items())
else:
items = list()
for c in self.__table__._columns:
try:
items.append((c.name,... | Convert to OrderedDict. |
def entries(self):
"""A list of :class:`PasswordEntry` objects."""
passwords = []
for store in self.stores:
passwords.extend(store.entries)
return natsort(passwords, key=lambda e: e.name) | A list of :class:`PasswordEntry` objects. |
def _fromJSON(cls, jsonobject):
"""Generates a new instance of :class:`maspy.core.Si` from a decoded
JSON object (as generated by :func:`maspy.core.Si._reprJSON()`).
:param jsonobject: decoded JSON object
:returns: a new instance of :class:`Si`
"""
newInstance = cls(Non... | Generates a new instance of :class:`maspy.core.Si` from a decoded
JSON object (as generated by :func:`maspy.core.Si._reprJSON()`).
:param jsonobject: decoded JSON object
:returns: a new instance of :class:`Si` |
def load_script(zap_helper, **options):
"""Load a script from a file."""
with zap_error_handler():
if not os.path.isfile(options['file_path']):
raise ZAPError('No file found at "{0}", cannot load script.'.format(options['file_path']))
if not _is_valid_script_engine(zap_helper.zap, o... | Load a script from a file. |
def pop(self, queue_name):
"""
Pops a task off the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:returns: The data for the task.
:rtype: string
"""
self._only_watch_from(... | Pops a task off the queue.
:param queue_name: The name of the queue. Usually handled by the
``Gator`` instance.
:type queue_name: string
:returns: The data for the task.
:rtype: string |
def font_to_wx_font(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_font = ... | Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings |
def dump_data(data,
filename=None,
file_type='json',
klazz=YapconfError,
open_kwargs=None,
dump_kwargs=None):
"""Dump data given to file or stdout in file_type.
Args:
data (dict): The dictionary to dump.
filename (str, option... | Dump data given to file or stdout in file_type.
Args:
data (dict): The dictionary to dump.
filename (str, optional): Defaults to None. The filename to write
the data to. If none is provided, it will be written to STDOUT.
file_type (str, optional): Defaults to 'json'. Can be any of
... |
def coordinate_reproject(x, y, s_crs, t_crs):
"""
reproject a coordinate from one CRS to another
Parameters
----------
x: int or float
the X coordinate component
y: int or float
the Y coordinate component
s_crs: int, str or :osgeo:class:`osr.SpatialReference`
the... | reproject a coordinate from one CRS to another
Parameters
----------
x: int or float
the X coordinate component
y: int or float
the Y coordinate component
s_crs: int, str or :osgeo:class:`osr.SpatialReference`
the source CRS. See :func:`~spatialist.auxil.crsConvert` for ... |
def rebalance(self):
"""The genetic rebalancing algorithm runs for a fixed number of
generations. Each generation has two phases: exploration and pruning.
In exploration, a large set of possible states are found by randomly
applying assignment changes to the existing states. In pruning, ... | The genetic rebalancing algorithm runs for a fixed number of
generations. Each generation has two phases: exploration and pruning.
In exploration, a large set of possible states are found by randomly
applying assignment changes to the existing states. In pruning, each
state is given a sc... |
def present(name,
user=None,
password=None,
auth='password',
encoding='UTF8',
locale=None,
runas=None,
waldir=None,
checksums=False):
'''
Initialize the PostgreSQL data directory
name
The name of the directory to initialize
user
... | Initialize the PostgreSQL data directory
name
The name of the directory to initialize
user
The database superuser name
password
The password to set for the postgres user
auth
The default authentication method for local connections
encoding
The default enc... |
def is_parent_of_family(self, id_, family_id):
"""Tests if an ``Id`` is a direct parent of a family.
arg: id (osid.id.Id): an ``Id``
arg: family_id (osid.id.Id): the ``Id`` of a family
return: (boolean) - ``true`` if this ``id`` is a parent of
``family_id,`` ``fal... | Tests if an ``Id`` is a direct parent of a family.
arg: id (osid.id.Id): an ``Id``
arg: family_id (osid.id.Id): the ``Id`` of a family
return: (boolean) - ``true`` if this ``id`` is a parent of
``family_id,`` ``false`` otherwise
raise: NotFound - ``family_id`` is... |
def set_static_ip_address(self, context, msg):
"""Process request for setting rules in iptables.
In cases that static ip address is assigned for a VM, it is needed
to update the iptables rule for that address.
"""
args = jsonutils.loads(msg)
macaddr = args.get('mac')
... | Process request for setting rules in iptables.
In cases that static ip address is assigned for a VM, it is needed
to update the iptables rule for that address. |
def set_filetype(self, filetype, bufnr=None):
"""Set filetype for a buffer.
Note: it's a quirk of Vim's Python API that using the buffer.options
dictionary to set filetype does not trigger ``FileType`` autocommands,
hence this implementation executes as a command instead.
Args:... | Set filetype for a buffer.
Note: it's a quirk of Vim's Python API that using the buffer.options
dictionary to set filetype does not trigger ``FileType`` autocommands,
hence this implementation executes as a command instead.
Args:
filetype (str): The filetype to set.
... |
def _check_row_table_name(table_name, row):
"""Checks that a row belongs to a table.
:type table_name: str
:param table_name: The name of the table.
:type row: :class:`~google.cloud.bigtable.row.Row`
:param row: An instance of :class:`~google.cloud.bigtable.row.Row`
subclasses.
... | Checks that a row belongs to a table.
:type table_name: str
:param table_name: The name of the table.
:type row: :class:`~google.cloud.bigtable.row.Row`
:param row: An instance of :class:`~google.cloud.bigtable.row.Row`
subclasses.
:raises: :exc:`~.table.TableMismatchError` if the... |
def maskAt(self, index):
""" Returns the mask at the index.
It the mask is a boolean it is returned since this boolean representes the mask for
all array elements.
"""
if isinstance(self.mask, bool):
return self.mask
else:
return self.mask... | Returns the mask at the index.
It the mask is a boolean it is returned since this boolean representes the mask for
all array elements. |
def froze_it(cls):
"""
Decorator to prevent from creating attributes in the object ouside __init__().
This decorator must be applied to the final class (doesn't work if a
decorated class is inherited).
Yoann's answer at http://stackoverflow.com/questions/3603502
"""
cls._frozen = ... | Decorator to prevent from creating attributes in the object ouside __init__().
This decorator must be applied to the final class (doesn't work if a
decorated class is inherited).
Yoann's answer at http://stackoverflow.com/questions/3603502 |
def getoutputfiles(self, loadmetadata=True, client=None,requiremetadata=False):
"""Iterates over all output files and their output template. Yields (CLAMOutputFile, str:outputtemplate_id) tuples. The last three arguments are passed to its constructor."""
for outputfilename, outputtemplate in self.output... | Iterates over all output files and their output template. Yields (CLAMOutputFile, str:outputtemplate_id) tuples. The last three arguments are passed to its constructor. |
def warning_handler(self, handler):
"""Setter for the warning handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on warni... | Setter for the warning handler function.
If the DLL is open, this function is a no-op, so it should be called
prior to calling ``open()``.
Args:
self (JLink): the ``JLink`` instance
handler (function): function to call on warning messages
Returns:
``None`... |
def yield_for_all_futures(result):
""" Converts result into a Future by collapsing any futures inside result.
If result is a Future we yield until it's done, then if the value inside
the Future is another Future we yield until it's done as well, and so on.
"""
while True:
# This is needed ... | Converts result into a Future by collapsing any futures inside result.
If result is a Future we yield until it's done, then if the value inside
the Future is another Future we yield until it's done as well, and so on. |
def _cpu(self):
"""Record CPU usage."""
value = int(psutil.cpu_percent())
set_metric("cpu", value, category=self.category)
gauge("cpu", value) | Record CPU usage. |
def input_streams(self):
"""Return a list of DataStream objects for all singular input streams.
This function only returns individual streams, not the streams that would
be selected from a selector like 'all outputs' for example.
Returns:
list(DataStream): A list of all of ... | Return a list of DataStream objects for all singular input streams.
This function only returns individual streams, not the streams that would
be selected from a selector like 'all outputs' for example.
Returns:
list(DataStream): A list of all of the individual DataStreams that are ... |
def tag_file(filename, artist, title, year=None, genre=None, artwork_url=None, album=None, track_number=None, url=None):
"""
Attempt to put ID3 tags on a file.
Args:
artist (str):
title (str):
year (int):
genre (str):
artwork_url (str):
album (str):
t... | Attempt to put ID3 tags on a file.
Args:
artist (str):
title (str):
year (int):
genre (str):
artwork_url (str):
album (str):
track_number (str):
filename (str):
url (str): |
def num2hexstring(number, size=1, little_endian=False):
"""
Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_endi... | Converts a number to a big endian hexstring of a suitable size, optionally little endian
:param {number} number
:param {number} size - The required size in hex chars, eg 2 for Uint8, 4 for Uint16. Defaults to 2.
:param {boolean} little_endian - Encode the hex in little endian form
:return {string} |
def deriv(self, p):
"""
Derivative of the power transform
Parameters
----------
p : array-like
Mean parameters
Returns
--------
g'(p) : array
Derivative of power transform of `p`
Notes
-----
g'(`p`) = `pow... | Derivative of the power transform
Parameters
----------
p : array-like
Mean parameters
Returns
--------
g'(p) : array
Derivative of power transform of `p`
Notes
-----
g'(`p`) = `power` * `p`**(`power` - 1) |
def plot(self, numPoints=100):
"""
Specific plotting method for cylinders.
"""
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# generate cylinder
x = np.linspace(- self.radius, self.radius, numPoints)
z = np.linspace(- self.height / 2., self.height / 2., numPoints)
Xc... | Specific plotting method for cylinders. |
def variable(self, var_name, shape, init, dt=tf.float32, train=None):
"""Adds a named variable to this bookkeeper or returns an existing one.
Variables marked train are returned by the training_variables method. If
the requested name already exists and it is compatible (same shape, dt and
train) then i... | Adds a named variable to this bookkeeper or returns an existing one.
Variables marked train are returned by the training_variables method. If
the requested name already exists and it is compatible (same shape, dt and
train) then it is returned. In case of an incompatible type, an exception is
thrown.
... |
def cols_to_numeric(df, col_list,dest = False):
""" Coerces a list of columns to numeric
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return ... | Coerces a list of columns to numeric
Parameters:
df - DataFrame
DataFrame to operate on
col_list - list of strings
names of columns to coerce
dest - bool, default False
Whether to apply the result to the DataFrame or return it.
True is apply, False is return. |
def read_name(self):
"""Reads a domain name from the packet"""
result = ''
off = self.offset
next = -1
first = off
while 1:
len = ord(self.data[off])
off += 1
if len == 0:
break
t = len & 0xC0
if... | Reads a domain name from the packet |
def sync_handler(self, args):
'''Handler for sync command.
XXX Here we emulate sync command with get/put -r -f --sync-check. So
it doesn't provide delete operation.
'''
self.opt.recursive = True
self.opt.sync_check = True
self.opt.force = True
self.validate('cmd|s3,local|s3,lo... | Handler for sync command.
XXX Here we emulate sync command with get/put -r -f --sync-check. So
it doesn't provide delete operation. |
def best_structures(uniprot_id, outname=None, outdir=None, seq_ident_cutoff=0.0, force_rerun=False):
"""Use the PDBe REST service to query for the best PDB structures for a UniProt ID.
More information found here: https://www.ebi.ac.uk/pdbe/api/doc/sifts.html
Link used to retrieve results: https://www.ebi.... | Use the PDBe REST service to query for the best PDB structures for a UniProt ID.
More information found here: https://www.ebi.ac.uk/pdbe/api/doc/sifts.html
Link used to retrieve results: https://www.ebi.ac.uk/pdbe/api/mappings/best_structures/:accession
The list of PDB structures mapping to a UniProt acces... |
def get_intent(self,
name,
language_code=None,
intent_view=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Retrieves... | Retrieves the specified intent.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.IntentsClient()
>>>
>>> name = client.intent_path('[PROJECT]', '[INTENT]')
>>>
>>> response = client.get_intent(name)
Arg... |
def _Open(self, path_spec, mode='rb'):
"""Opens the file system defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the APFS volume could n... | Opens the file system defined by path specification.
Args:
path_spec (PathSpec): path specification.
mode (Optional[str]): file access mode.
Raises:
AccessError: if the access to open the file was denied.
IOError: if the APFS volume could not be retrieved or unlocked.
OSError: if... |
def rename_pickled_ontology(filename, newname):
""" try to rename a cached ontology """
pickledfile = ONTOSPY_LOCAL_CACHE + "/" + filename + ".pickle"
newpickledfile = ONTOSPY_LOCAL_CACHE + "/" + newname + ".pickle"
if os.path.isfile(pickledfile) and not GLOBAL_DISABLE_CACHE:
os.rename(pickledfile, newpickledfile... | try to rename a cached ontology |
def dirname(hdfs_path):
"""
Return the directory component of ``hdfs_path``.
"""
scheme, netloc, path = parse(hdfs_path)
return unparse(scheme, netloc, os.path.dirname(path)) | Return the directory component of ``hdfs_path``. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.