code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def lock_machine(self, session, lock_type):
"""Locks the machine for the given session to enable the caller
to make changes to the machine or start the VM or control
VM execution.
There are two ways to lock a machine for such uses:
If you want to make c... | Locks the machine for the given session to enable the caller
to make changes to the machine or start the VM or control
VM execution.
There are two ways to lock a machine for such uses:
If you want to make changes to the machine settings,
you must obtain... |
def _open(self, archive):
"""Open RAR archive file."""
try:
handle = unrarlib.RAROpenArchiveEx(ctypes.byref(archive))
except unrarlib.UnrarException:
raise BadRarFile("Invalid RAR file.")
return handle | Open RAR archive file. |
def split_transfer_kwargs(kwargs, skip=None):
"""
Takes keyword arguments *kwargs*, splits them into two separate dictionaries depending on their
content, and returns them in a tuple. The first one will contain arguments related to potential
file transfer operations (e.g. ``"cache"`` or ``"retries"``), ... | Takes keyword arguments *kwargs*, splits them into two separate dictionaries depending on their
content, and returns them in a tuple. The first one will contain arguments related to potential
file transfer operations (e.g. ``"cache"`` or ``"retries"``), while the second one will contain
all remaining argume... |
def hrv_parameters(data, sample_rate, signal=False, in_seconds=False):
"""
-----
Brief
-----
Function for extracting HRV parameters from time and frequency domains.
-----------
Description
-----------
ECG signals require specific processing due to their cyclic nature. For example, i... | -----
Brief
-----
Function for extracting HRV parameters from time and frequency domains.
-----------
Description
-----------
ECG signals require specific processing due to their cyclic nature. For example, it is expected that in similar
conditions the RR peak interval to be similar, wh... |
def set_module_options(self, module):
"""
Set universal module options to be interpreted by i3bar
https://i3wm.org/i3status/manpage.html#_universal_module_options
"""
self.i3bar_module_options = {}
self.i3bar_gaps_module_options = {}
self.py3status_module_options ... | Set universal module options to be interpreted by i3bar
https://i3wm.org/i3status/manpage.html#_universal_module_options |
def create_buffer(self, ignore_unsupported=False):
"""
Create this tree's TreeBuffer
"""
bufferdict = OrderedDict()
for branch in self.iterbranches():
# only include activated branches
if not self.GetBranchStatus(branch.GetName()):
continue... | Create this tree's TreeBuffer |
def present(name, mediatype, **kwargs):
'''
Creates new mediatype.
NOTE: This function accepts all standard mediatype properties: keyword argument names differ depending on your
zabbix version, see:
https://www.zabbix.com/documentation/3.0/manual/api/reference/host/object#host_inventory
:param ... | Creates new mediatype.
NOTE: This function accepts all standard mediatype properties: keyword argument names differ depending on your
zabbix version, see:
https://www.zabbix.com/documentation/3.0/manual/api/reference/host/object#host_inventory
:param name: name of the mediatype
:param _connection_u... |
def _get_block(self):
"""Just read a single block from your current location in _fh"""
b = self._fh.read(4) # get block size bytes
#print self._fh.tell()
if not b: raise StopIteration
block_size = struct.unpack('<i',b)[0]
return self._fh.read(block_size) | Just read a single block from your current location in _fh |
def _process_comment(self, comment: praw.models.Comment):
"""
Process a reddit comment. Calls `func_comment(*func_comment_args)`.
:param comment: Comment to process
"""
self._func_comment(comment, *self._func_comment_args) | Process a reddit comment. Calls `func_comment(*func_comment_args)`.
:param comment: Comment to process |
def register_pickle():
"""The fastest serialization method, but restricts
you to python clients."""
import cPickle
registry.register('pickle', cPickle.dumps, cPickle.loads,
content_type='application/x-python-serialize',
content_encoding='binary') | The fastest serialization method, but restricts
you to python clients. |
def revoke_token(access_token):
"""
Instructs the API to delete this access token and associated refresh token
"""
response = requests.post(
get_revoke_token_url(),
data={
'token': access_token,
'client_id': settings.API_CLIENT_ID,
'client_secret': set... | Instructs the API to delete this access token and associated refresh token |
def iter_paths(self, pathnames=None, mapfunc=None):
"""
Special iteration on paths. Yields couples of path and items. If a expanded path
doesn't match with any files a couple with path and `None` is returned.
:param pathnames: Iterable with a set of pathnames. If is `None` uses the all ... | Special iteration on paths. Yields couples of path and items. If a expanded path
doesn't match with any files a couple with path and `None` is returned.
:param pathnames: Iterable with a set of pathnames. If is `None` uses the all \
the stored pathnames.
:param mapfunc: A mapping functi... |
def set_value(self, eid, val, idx='*'):
"""
Set the content of an xml element marked with the matching eid attribute.
"""
if eid in self.__element_ids:
elems = self.__element_ids[eid]
if type(val) in SEQ_TYPES:
idx = 0
if idx == '*':
... | Set the content of an xml element marked with the matching eid attribute. |
def search_users(self, user_name):
"""Searches for users via provisioning API.
If you get back an error 999, then the provisioning API is not enabled.
:param user_name: name of user to be searched for
:returns: list of usernames that contain user_name as substring
:raises: HTTP... | Searches for users via provisioning API.
If you get back an error 999, then the provisioning API is not enabled.
:param user_name: name of user to be searched for
:returns: list of usernames that contain user_name as substring
:raises: HTTPResponseError in case an HTTP error status was... |
def get_ssh_dir(config, username):
"""Get the users ssh dir"""
sshdir = config.get('ssh_config_dir')
if not sshdir:
sshdir = os.path.expanduser('~/.ssh')
if not os.path.isdir(sshdir):
pwentry = getpwnam(username)
sshdir = os.path.join(pwentry.pw_dir, '.ssh')
... | Get the users ssh dir |
def get_tab_tip(self, filename, is_modified=None, is_readonly=None):
"""Return tab menu title"""
text = u"%s — %s"
text = self.__modified_readonly_title(text,
is_modified, is_readonly)
if self.tempfile_path is not None\
and f... | Return tab menu title |
def match(self, url):
'''
Try to find if url matches against any of the schemes within this
endpoint.
Args:
url: The url to match against each scheme
Returns:
True if a matching scheme was found for the url, False otherwise
'''
try:
... | Try to find if url matches against any of the schemes within this
endpoint.
Args:
url: The url to match against each scheme
Returns:
True if a matching scheme was found for the url, False otherwise |
def store_sample(self, sample_bytes, filename, type_tag):
"""Store a sample into the datastore.
Args:
filename: Name of the file.
sample_bytes: Actual bytes of sample.
type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...)
Returns:
m... | Store a sample into the datastore.
Args:
filename: Name of the file.
sample_bytes: Actual bytes of sample.
type_tag: Type of sample ('exe','pcap','pdf','json','swf', or ...)
Returns:
md5 digest of the sample. |
def kill_given_tasks(self, task_ids, scale=False, force=None):
"""Kill a list of given tasks.
:param list[str] task_ids: tasks to kill
:param bool scale: if true, scale down the app by the number of tasks killed
:param bool force: if true, ignore any current running deployments
... | Kill a list of given tasks.
:param list[str] task_ids: tasks to kill
:param bool scale: if true, scale down the app by the number of tasks killed
:param bool force: if true, ignore any current running deployments
:return: True on success
:rtype: bool |
def get_member(thing_obj, member_string):
"""Get a member from an object by (string) name"""
mems = {x[0]: x[1] for x in inspect.getmembers(thing_obj)}
if member_string in mems:
return mems[member_string] | Get a member from an object by (string) name |
def _as_rescale(self, get, targetbitdepth):
"""Helper used by :meth:`asRGB8` and :meth:`asRGBA8`."""
width,height,pixels,meta = get()
maxval = 2**meta['bitdepth'] - 1
targetmaxval = 2**targetbitdepth - 1
factor = float(targetmaxval) / float(maxval)
meta['bitdepth'] = tar... | Helper used by :meth:`asRGB8` and :meth:`asRGBA8`. |
async def handle_client_hello(self, client_addr, _: ClientHello):
""" Handle an ClientHello message. Send available containers to the client """
self._logger.info("New client connected %s", client_addr)
self._registered_clients.add(client_addr)
await self.send_container_update_to_client(... | Handle an ClientHello message. Send available containers to the client |
def confirm_delete_view(self, request, object_id):
"""
Instantiates a class-based view to provide 'delete confirmation'
functionality for the assigned model, or redirect to Wagtail's delete
confirmation view if the assigned model extends 'Page'. The view class
used can be overrid... | Instantiates a class-based view to provide 'delete confirmation'
functionality for the assigned model, or redirect to Wagtail's delete
confirmation view if the assigned model extends 'Page'. The view class
used can be overridden by changing the 'confirm_delete_view_class'
attribute. |
def get_resource_allocation(self):
"""Get the :py:class:`ResourceAllocation` element tance.
Returns:
ResourceAllocation: Resource allocation used to access information about the resource where this PE is running.
.. versionadded:: 1.9
"""
if hasattr(self, 'resourceA... | Get the :py:class:`ResourceAllocation` element tance.
Returns:
ResourceAllocation: Resource allocation used to access information about the resource where this PE is running.
.. versionadded:: 1.9 |
def check_df(
state, index, missing_msg=None, not_instance_msg=None, expand_msg=None
):
"""Check whether a DataFrame was defined and it is the right type
``check_df()`` is a combo of ``check_object()`` and ``is_instance()`` that checks whether the specified object exists
and whether the specified o... | Check whether a DataFrame was defined and it is the right type
``check_df()`` is a combo of ``check_object()`` and ``is_instance()`` that checks whether the specified object exists
and whether the specified object is pandas DataFrame.
You can continue checking the data frame with ``check_keys()`` func... |
def unpack_rsp(cls, rsp_pb):
"""Convert from PLS response to user response"""
if rsp_pb.retType != RET_OK:
return RET_ERROR, rsp_pb.retMsg, None
raw_position_list = rsp_pb.s2c.positionList
position_list = [{
"code": merge_trd_mkt_stock_str(rsp_p... | Convert from PLS response to user response |
def norm_coefs(self):
"""Multiply all coefficients by the same factor, so that their sum
becomes one."""
sum_coefs = self.sum_coefs
self.ar_coefs /= sum_coefs
self.ma_coefs /= sum_coefs | Multiply all coefficients by the same factor, so that their sum
becomes one. |
def apply_shortcuts(self):
"""Apply shortcuts settings to all widgets/plugins"""
toberemoved = []
for index, (qobject, context, name,
add_sc_to_tip) in enumerate(self.shortcut_data):
keyseq = QKeySequence( get_shortcut(context, name) )
try:
... | Apply shortcuts settings to all widgets/plugins |
def to_dict(self):
"""
Encode the token as a dictionary suitable for JSON serialization.
"""
d = {
'id': self.id,
'start': self.start,
'end': self.end,
'form': self.form
}
if self.lnk is not None:
cfrom, cto = se... | Encode the token as a dictionary suitable for JSON serialization. |
def tobinary(series, path, prefix='series', overwrite=False, credentials=None):
"""
Writes out data to binary format.
Parameters
----------
series : Series
The data to write
path : string path or URI to directory to be created
Output files will be written underneath path.
... | Writes out data to binary format.
Parameters
----------
series : Series
The data to write
path : string path or URI to directory to be created
Output files will be written underneath path.
Directory will be created as a result of this call.
prefix : str, optional, default ... |
def build_encryption_materials_cache_key(partition, request):
"""Generates a cache key for an encrypt request.
:param bytes partition: Partition name for which to generate key
:param request: Request for which to generate key
:type request: aws_encryption_sdk.materials_managers.EncryptionMaterialsReque... | Generates a cache key for an encrypt request.
:param bytes partition: Partition name for which to generate key
:param request: Request for which to generate key
:type request: aws_encryption_sdk.materials_managers.EncryptionMaterialsRequest
:returns: cache key
:rtype: bytes |
def mod9710(iban):
"""
Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
@method mod9710
@param {String} iban
@returns {Number}
"""
remainder = iban
block = None
while len(remainder) > 2:
block = remainder[:9]
remainder = str(int(block) % 97) + re... | Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064.
@method mod9710
@param {String} iban
@returns {Number} |
def _evaluate(self,R,phi=0.,t=0.):
"""
NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
... | NAME:
_evaluate
PURPOSE:
evaluate the potential at R,phi,t
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
Phi(R,phi,t)
HISTORY:
2017-10-16 - Written - Bovy (UofT) |
def _drain(writer, ion_event):
"""Drain the writer of its pending write events.
Args:
writer (Coroutine): A writer co-routine.
ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer.
Yields:
DataEvent: Yields each pending data event.
"""
result_event =... | Drain the writer of its pending write events.
Args:
writer (Coroutine): A writer co-routine.
ion_event (amazon.ion.core.IonEvent): The first event to apply to the writer.
Yields:
DataEvent: Yields each pending data event. |
def build_colormap(palette, info):
"""Create the colormap from the `raw_palette` and the valid_range."""
from trollimage.colormap import Colormap
if 'palette_meanings' in palette.attrs:
palette_indices = palette.attrs['palette_meanings']
else:
palette_indices = r... | Create the colormap from the `raw_palette` and the valid_range. |
def nvrtcAddNameExpression(self, prog, name_expression):
"""
Notes the given name expression denoting a __global__ function or
function template instantiation.
"""
code = self._lib.nvrtcAddNameExpression(prog,
c_char_p(encode_str(na... | Notes the given name expression denoting a __global__ function or
function template instantiation. |
def get_post_agg(mconf):
"""
For a metric specified as `postagg` returns the
kind of post aggregation for pydruid.
"""
if mconf.get('type') == 'javascript':
return JavascriptPostAggregator(
name=mconf.get('name', ''),
field_names=mconf.... | For a metric specified as `postagg` returns the
kind of post aggregation for pydruid. |
def stripped_photo_to_jpg(stripped):
"""
Adds the JPG header and footer to a stripped image.
Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225
"""
if len(stripped) < 3 or stripped[0] != 1:
retur... | Adds the JPG header and footer to a stripped image.
Ported from https://github.com/telegramdesktop/tdesktop/blob/bec39d89e19670eb436dc794a8f20b657cb87c71/Telegram/SourceFiles/ui/image/image.cpp#L225 |
def _conj(self, f):
"""Function returning the complex conjugate of a result."""
def f_conj(x, **kwargs):
result = np.asarray(f(x, **kwargs),
dtype=self.scalar_out_dtype)
return result.conj()
if is_real_dtype(self.out_dtype):
re... | Function returning the complex conjugate of a result. |
def simulate_experiment(self, modelparams, expparams, repeat=1):
"""
Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter ... | Produces data according to the given model parameters and experimental
parameters, structured as a NumPy array.
:param np.ndarray modelparams: A shape ``(n_models, n_modelparams)``
array of model parameter vectors describing the hypotheses under
which data should be simulated.
... |
def update_items(portal_type=None, uid=None, endpoint=None, **kw):
""" update items
1. If the uid is given, the user wants to update the object with the data
given in request body
2. If no uid is given, the user wants to update a bunch of objects.
-> each record contains either an UID, path o... | update items
1. If the uid is given, the user wants to update the object with the data
given in request body
2. If no uid is given, the user wants to update a bunch of objects.
-> each record contains either an UID, path or parent_path + id |
def get_pint_to_fortran_safe_units_mapping(inverse=False):
"""Get the mappings from Pint to Fortran safe units.
Fortran can't handle special characters like "^" or "/" in names, but we need
these in Pint. Conversely, Pint stores variables with spaces by default e.g. "Mt
CO2 / yr" but we don't want thes... | Get the mappings from Pint to Fortran safe units.
Fortran can't handle special characters like "^" or "/" in names, but we need
these in Pint. Conversely, Pint stores variables with spaces by default e.g. "Mt
CO2 / yr" but we don't want these in the input files as Fortran is likely to think
the whitesp... |
def simxEraseFile(clientID, fileName_serverSide, operationMode):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
if (sys.version_info[0] == 3) and (type(fileName_serverSide) is str):
fileName_serverSide=fileName_serverSide.encode('utf-8')
return... | Please have a look at the function description/documentation in the V-REP user manual |
def parse_analyzer_arguments(arguments):
"""
Parse string in format `function_1:param1=value:param2 function_2:param` into array of FunctionArguments
"""
rets = []
for argument in arguments:
args = argument.split(argument_splitter)
# The first one is the function name
func... | Parse string in format `function_1:param1=value:param2 function_2:param` into array of FunctionArguments |
def update_resource(self, resource, underlined=None):
"""Update the cache for global names in `resource`"""
try:
pymodule = self.project.get_pymodule(resource)
modname = self._module_name(resource)
self._add_names(pymodule, modname, underlined)
except exceptio... | Update the cache for global names in `resource` |
def trailing_input(self):
"""
Get the `MatchVariable` instance, representing trailing input, if there is any.
"Trailing input" is input at the end that does not match the grammar anymore, but
when this is removed from the end of the input, the input would be a valid string.
"""
... | Get the `MatchVariable` instance, representing trailing input, if there is any.
"Trailing input" is input at the end that does not match the grammar anymore, but
when this is removed from the end of the input, the input would be a valid string. |
def upload_async(self, remote_path, local_path, callback=None):
"""Uploads resource to remote path on WebDAV server asynchronously.
In case resource is directory it will upload all nested files and directories.
:param remote_path: the path for uploading resources on WebDAV server. Can be file a... | Uploads resource to remote path on WebDAV server asynchronously.
In case resource is directory it will upload all nested files and directories.
:param remote_path: the path for uploading resources on WebDAV server. Can be file and directory.
:param local_path: the path to local resource for upl... |
def annual_heating_design_day_996(self):
"""A design day object representing the annual 99.6% heating design day."""
if bool(self._winter_des_day_dict) is True:
return DesignDay.from_ashrae_dict_heating(
self._winter_des_day_dict, self.location, False,
self._s... | A design day object representing the annual 99.6% heating design day. |
def get_request_data():
"""
Get request data based on request.method
If method is GET or DELETE, get data from request.args
If method is POST, PATCH or PUT, get data from request.form or request.json
"""
method = request.method.lower()
if method in ["get", "delete"]:
return request.... | Get request data based on request.method
If method is GET or DELETE, get data from request.args
If method is POST, PATCH or PUT, get data from request.form or request.json |
def xstep_check(self, b):
r"""Check the minimisation of the Augmented Lagrangian with
respect to :math:`\mathbf{x}` by method `xstep` defined in
derived classes. This method should be called at the end of any
`xstep` method.
"""
if self.opt['LinSolveCheck']:
... | r"""Check the minimisation of the Augmented Lagrangian with
respect to :math:`\mathbf{x}` by method `xstep` defined in
derived classes. This method should be called at the end of any
`xstep` method. |
def declare_base(erroName=True):
"""Create a Exception with default message.
:param errorName: boolean, True if you want the Exception name in the
error message body.
"""
if erroName:
class Base(Exception):
def __str__(self):
if len(self.args):
... | Create a Exception with default message.
:param errorName: boolean, True if you want the Exception name in the
error message body. |
def replaceWith(self, el):
"""
Replace value in this element with values from `el`.
This useful when you don't want change all references to object.
Args:
el (obj): :class:`HTMLElement` instance.
"""
self.childs = el.childs
self.params = el.params
... | Replace value in this element with values from `el`.
This useful when you don't want change all references to object.
Args:
el (obj): :class:`HTMLElement` instance. |
async def sysinfo(dev: Device):
"""Print out system information (version, MAC addrs)."""
click.echo(await dev.get_system_info())
click.echo(await dev.get_interface_information()) | Print out system information (version, MAC addrs). |
def _actuator_on_off(self, on_off, service_location_id, actuator_id,
duration=None):
"""
Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : i... | Turn actuator on or off
Parameters
----------
on_off : str
'on' or 'off'
service_location_id : int
actuator_id : int
duration : int, optional
300,900,1800 or 3600 , specifying the time in seconds the actuator
should be turned on. Any o... |
def fleets(self):
"""
:rtype: twilio.rest.preview.deployed_devices.fleet.FleetList
"""
if self._fleets is None:
self._fleets = FleetList(self)
return self._fleets | :rtype: twilio.rest.preview.deployed_devices.fleet.FleetList |
def get_account_details(self, session=None, lightweight=None):
"""
Returns the details relating your account, including your discount
rate and Betfair point balance.
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a ... | Returns the details relating your account, including your discount
rate and Betfair point balance.
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
:rtype: resources.AccountDetails |
def isTemporal(inferenceType):
""" Returns True if the inference type is 'temporal', i.e. requires a
temporal memory in the network.
"""
if InferenceType.__temporalInferenceTypes is None:
InferenceType.__temporalInferenceTypes = \
set([InferenceType.TemporalNextStep... | Returns True if the inference type is 'temporal', i.e. requires a
temporal memory in the network. |
def add_reviewer(self, doc, reviewer):
"""Adds a reviewer to the SPDX Document.
Reviwer is an entity created by an EntityBuilder.
Raises SPDXValueError if not a valid reviewer type.
"""
# Each reviewer marks the start of a new review object.
# FIXME: this state does not m... | Adds a reviewer to the SPDX Document.
Reviwer is an entity created by an EntityBuilder.
Raises SPDXValueError if not a valid reviewer type. |
def many_until(these, term):
"""Consumes as many of these as it can until it term is encountered.
Returns a tuple of the list of these results and the term result
"""
results = []
while True:
stop, result = choice(_tag(True, term),
_tag(False, these))
... | Consumes as many of these as it can until it term is encountered.
Returns a tuple of the list of these results and the term result |
async def fetching_data(self, *_):
"""Get the latest data from met.no."""
try:
with async_timeout.timeout(10):
resp = await self._websession.get(self._api_url, params=self._urlparams)
if resp.status != 200:
_LOGGER.error('%s returned %s', self._ap... | Get the latest data from met.no. |
def delete_old_tickets(**kwargs):
"""
Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created']
"""
sender = kwargs.get('sender', None)
now = datetime.now()
expire = datetime(now.year, now.month, now.day - 2)
sender.objects.filter(created__lt... | Delete tickets if they are over 2 days old
kwargs = ['raw', 'signal', 'instance', 'sender', 'created'] |
def send_status_message(self, object_id, status):
"""Send a message to the `status_queue` to update a job's status.
Returns `True` if the message was sent, else `False`
Args:
object_id (`str`): ID of the job that was executed
status (:obj:`SchedulerStatus`): Status of t... | Send a message to the `status_queue` to update a job's status.
Returns `True` if the message was sent, else `False`
Args:
object_id (`str`): ID of the job that was executed
status (:obj:`SchedulerStatus`): Status of the job
Returns:
`bool` |
def create_class(self, data, options=None, **kwargs):
"""Return instance of class based on Go data
Data keys handled here:
_type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
... | Return instance of class based on Go data
Data keys handled here:
_type
Set the object class
consts, types, vars, funcs
Recurse into :py:meth:`create_class` to create child object
instances
:param data: dictionary data from godo... |
def _update_tokens(self, write_token=True, override=None,
patch_skip=False):
"""Update tokens to the next available values."""
next_token = next(self.tokens)
patch_value = ''
patch_tokens = ''
if self.pfile and write_token:
token = override if... | Update tokens to the next available values. |
def _upsert_persons(cursor, person_ids, lookup_func):
"""Upsert's user info into the database.
The model contains the user info as part of the role values.
"""
person_ids = list(set(person_ids)) # cleanse data
# Check for existing records to update.
cursor.execute("SELECT personid from persons... | Upsert's user info into the database.
The model contains the user info as part of the role values. |
def filter(self, cls, recursive=False):
"""Retrieves all descendants (including self) that are instances
of a given class.
Args:
cls (class): The class to use as a filter.
Kwargs:
recursive (bool): Whether to descend recursively down the tree.
"""
... | Retrieves all descendants (including self) that are instances
of a given class.
Args:
cls (class): The class to use as a filter.
Kwargs:
recursive (bool): Whether to descend recursively down the tree. |
def extract_labels(filename):
"""Extract the labels into a 1D uint8 numpy array [index]."""
with gzip.open(filename) as bytestream:
magic = _read32(bytestream)
if magic != 2049:
raise ValueError(
'Invalid magic number %d in MNIST label file: %s' %
(mag... | Extract the labels into a 1D uint8 numpy array [index]. |
def doDup(self, WHAT={}, **params):
"""This function will perform the command -dup."""
if hasattr(WHAT, '_modified'):
for key, value in WHAT._modified():
if WHAT.__new2old__.has_key(key):
self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), value)
else:
self._addDBParam(key, value)
self.... | This function will perform the command -dup. |
def whoami(*args, **kwargs):
"""
Prints information about the current user.
Assumes the user is already logged-in.
"""
user = client.whoami()
if user:
print_user(user)
else:
print('You are not logged-in.') | Prints information about the current user.
Assumes the user is already logged-in. |
def write(self, pos, size, **kwargs):
"""
Writes some data, loaded from the state, into the file.
:param pos: The address to read the data to write from in memory
:param size: The requested size of the write
:return: The real length of the write
"""
... | Writes some data, loaded from the state, into the file.
:param pos: The address to read the data to write from in memory
:param size: The requested size of the write
:return: The real length of the write |
def update(self):
'''
Updates LaserData.
'''
if self.hasproxy():
irD = IRData()
received = 0
data = self.proxy.getIRData()
irD.received = data.received
self.lock.acquire()
self.ir = irD
self.lock.releas... | Updates LaserData. |
def _vmomentsurfaceMCIntegrand(vz,vR,vT,R,z,df,sigmaR1,gamma,sigmaz1,mvT,n,m,o):
"""Internal function that is the integrand for the vmomentsurface mass integration"""
return vR**n*vT**m*vz**o*df(R,vR*sigmaR1,vT*sigmaR1*gamma,z,vz*sigmaz1,use_physical=False)*numpy.exp(vR**2./2.+(vT-mvT)**2./2.+vz**2./2.) | Internal function that is the integrand for the vmomentsurface mass integration |
def f_get_from_runs(self, name, include_default_run=True, use_indices=False,
fast_access=False, with_links = True,
shortcuts=True, max_depth=None, auto_load=False):
"""Searches for all occurrences of `name` in each run.
Generates an ordered dictionary wit... | Searches for all occurrences of `name` in each run.
Generates an ordered dictionary with the run names or indices as keys and
found items as values.
Example:
>>> traj.f_get_from_runs(self, 'deep.universal_answer', use_indices=True, fast_access=True)
OrderedDict([(0, 42), (1, 4... |
def inspect(self, **kwargs):
"""
Plot the evolution of the structural relaxation with matplotlib.
Args:
what: Either "hist" or "scf". The first option (default) extracts data
from the HIST file and plot the evolution of the structural
parameters, forc... | Plot the evolution of the structural relaxation with matplotlib.
Args:
what: Either "hist" or "scf". The first option (default) extracts data
from the HIST file and plot the evolution of the structural
parameters, forces, pressures and energies.
The s... |
def _handleInvalid(invalidDefault):
'''
_handleInvalid - Common code for raising / returning an invalid value
@param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None
and "val" is not in #possib... | _handleInvalid - Common code for raising / returning an invalid value
@param invalidDefault <None/str/Exception> - The value to return if "val" is not empty string/None
and "val" is not in #possibleValues
If instantiated Excep... |
def verify_signature(public_key, signature, hash, hash_algo):
"""Verify the given signature is correct for the given hash and public key.
Args:
public_key (str): PEM encoded public key
signature (bytes): signature to verify
hash (bytes): hash of data
hash_algo (str): hash algori... | Verify the given signature is correct for the given hash and public key.
Args:
public_key (str): PEM encoded public key
signature (bytes): signature to verify
hash (bytes): hash of data
hash_algo (str): hash algorithm used
Returns:
True if the signature is valid, False ... |
def ParseOptions(cls, options, configuration_object):
"""Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is o... | Parses and validates options.
Args:
options (argparse.Namespace): parser options.
configuration_object (CLITool): object to be configured by the argument
helper.
Raises:
BadConfigObject: when the configuration object is of the wrong type. |
def list_product_versions(page_size=200, page_index=0, sort="", q=""):
"""
List all ProductVersions
"""
content = list_product_versions_raw(page_size, page_index, sort, q)
if content:
return utils.format_json_list(content) | List all ProductVersions |
def ip_v6_network_validator(v: Any) -> IPv6Network:
"""
Assume IPv6Network initialised with a default ``strict`` argument
See more:
https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network
"""
if isinstance(v, IPv6Network):
return v
with change_exception(errors.IPv6Netw... | Assume IPv6Network initialised with a default ``strict`` argument
See more:
https://docs.python.org/library/ipaddress.html#ipaddress.IPv6Network |
def words_to_word_ids(data=None, word_to_id=None, unk_key='UNK'):
"""Convert a list of string (words) to IDs.
Parameters
----------
data : list of string or byte
The context in list format
word_to_id : a dictionary
that maps word to ID.
unk_key : str
Represent the unknow... | Convert a list of string (words) to IDs.
Parameters
----------
data : list of string or byte
The context in list format
word_to_id : a dictionary
that maps word to ID.
unk_key : str
Represent the unknown words.
Returns
--------
list of int
A list of IDs ... |
def nf_io_to_process(ios, def_ios, scatter_ios=None):
"""Convert CWL input/output into a nextflow process definition.
Needs to handle scattered/parallel variables.
"""
scatter_names = {k: v for k, v in scatter_ios} if scatter_ios else {}
var_types = {}
for def_io in def_ios:
var_types[d... | Convert CWL input/output into a nextflow process definition.
Needs to handle scattered/parallel variables. |
def mimeData(self, indexes):
"""
Reimplements the :meth:`QAbstractItemModel.mimeData` method.
:param indexes: Indexes.
:type indexes: QModelIndexList
:return: MimeData.
:rtype: QMimeData
"""
byte_stream = pickle.dumps([self.get_node(index) for index in i... | Reimplements the :meth:`QAbstractItemModel.mimeData` method.
:param indexes: Indexes.
:type indexes: QModelIndexList
:return: MimeData.
:rtype: QMimeData |
def _handle_app_result_build_failure(self,out,err,exit_status,result_paths):
""" Catch the error when files are not produced """
try:
raise ApplicationError, \
'RAxML failed to produce an output file due to the following error: \n\n%s ' \
% err.read()
excep... | Catch the error when files are not produced |
def beta_pdf(x, a, b):
"""Beta distirbution probability density function."""
bc = 1 / beta(a, b)
fc = x ** (a - 1)
sc = (1 - x) ** (b - 1)
return bc * fc * sc | Beta distirbution probability density function. |
def output(self):
""" Generates output from data array
:returns Pythoned file
:rtype str or unicode
"""
if len(self.files) < 1:
raise Exception('Converter#output: No files to convert')
return self.template.render(self.files) | Generates output from data array
:returns Pythoned file
:rtype str or unicode |
def create(self, phone_number, sms_capability, account_sid=values.unset,
friendly_name=values.unset, unique_name=values.unset,
cc_emails=values.unset, sms_url=values.unset,
sms_method=values.unset, sms_fallback_url=values.unset,
sms_fallback_method=values.unse... | Create a new HostedNumberOrderInstance
:param unicode phone_number: An E164 formatted phone number.
:param bool sms_capability: Specify SMS capability to host.
:param unicode account_sid: Account Sid.
:param unicode friendly_name: A human readable description of this resource.
:... |
def _read_function(schema):
"""Add a write method for named schema to a class.
"""
def func(
filename=None,
data=None,
add_node_labels=True,
use_uids=True,
**kwargs):
# Use generic write class to write data.
return _read(
filename=filename,... | Add a write method for named schema to a class. |
def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None):
'''
Compare different libcloud versions
'''
if not HAS_LIBCLOUD:
return False
if not isinstance(reqver, (list, tuple)):
raise RuntimeError(
'\'reqver\' needs to passed as a tuple or list, i.e., (0, 14... | Compare different libcloud versions |
def leaves_are_consistent(self):
"""
Return ``True`` if the sync map fragments
which are the leaves of the sync map tree
(except for HEAD and TAIL leaves)
are all consistent, that is,
their intervals do not overlap in forbidden ways.
:rtype: bool
.. vers... | Return ``True`` if the sync map fragments
which are the leaves of the sync map tree
(except for HEAD and TAIL leaves)
are all consistent, that is,
their intervals do not overlap in forbidden ways.
:rtype: bool
.. versionadded:: 1.7.0 |
def label_tree(n,lookup):
'''label tree will again recursively label the tree
:param n: the root node, usually d3['children'][0]
:param lookup: the node/id lookup
'''
if len(n["children"]) == 0:
leaves = [lookup[n["node_id"]]]
else:
leaves = reduce(lambda ls, c: ls + label_tree(c... | label tree will again recursively label the tree
:param n: the root node, usually d3['children'][0]
:param lookup: the node/id lookup |
def merge_coords(objs, compat='minimal', join='outer', priority_arg=None,
indexes=None):
"""Merge coordinate variables.
See merge_core below for argument descriptions. This works similarly to
merge_core, except everything we don't worry about whether variables are
coordinates or not.
... | Merge coordinate variables.
See merge_core below for argument descriptions. This works similarly to
merge_core, except everything we don't worry about whether variables are
coordinates or not. |
def run(self, parent=None):
"""Start the configeditor
:returns: None
:rtype: None
:raises: None
"""
self.gw = GuerillaMGMTWin(parent=parent)
self.gw.show() | Start the configeditor
:returns: None
:rtype: None
:raises: None |
def _parse_string_el(el):
"""read a string element, maybe encoded in base64"""
value = str(el)
el_type = el.attributes().get('xsi:type')
if el_type and el_type.value == 'xsd:base64Binary':
value = base64.b64decode(value)
if not PY2:
value = value.decode('utf-8', errors='repla... | read a string element, maybe encoded in base64 |
def find(cls, session, resource_id, include=None):
"""Retrieve a single resource.
This should only be called from sub-classes.
Args:
session(Session): The session to find the resource in
resource_id: The ``id`` for the resource to look up
Keyword Args:
... | Retrieve a single resource.
This should only be called from sub-classes.
Args:
session(Session): The session to find the resource in
resource_id: The ``id`` for the resource to look up
Keyword Args:
include: Resource classes to include
Returns:
... |
def compute(self, nodes):
"""Helper function to find edges of the overlapping clusters.
Parameters
----------
nodes:
A dictionary with entires `{node id}:{list of ids in node}`
Returns
-------
edges:
A 1-skeleton of the nerve (intersectin... | Helper function to find edges of the overlapping clusters.
Parameters
----------
nodes:
A dictionary with entires `{node id}:{list of ids in node}`
Returns
-------
edges:
A 1-skeleton of the nerve (intersecting nodes)
simplicies:
... |
def close(self):
"""
Commit and close the connection.
.. seealso:: :py:meth:`sqlite3.Connection.close`
"""
if self.__delayed_connection_path and self.__connection is None:
self.__initialize_connection()
return
try:
self.check_connect... | Commit and close the connection.
.. seealso:: :py:meth:`sqlite3.Connection.close` |
def predict(self, features, batch_size = -1):
"""
Model inference base on the given data.
:param features: it can be a ndarray or list of ndarray for locally inference
or RDD[Sample] for running in distributed fashion
:param batch_size: total batch size of predic... | Model inference base on the given data.
:param features: it can be a ndarray or list of ndarray for locally inference
or RDD[Sample] for running in distributed fashion
:param batch_size: total batch size of prediction.
:return: ndarray or RDD[Sample] depend on the the ty... |
def format_stack_frame_json(self):
"""Convert StackFrame object to json format."""
stack_frame_json = {}
stack_frame_json['function_name'] = get_truncatable_str(
self.func_name)
stack_frame_json['original_function_name'] = get_truncatable_str(
self.original_func_n... | Convert StackFrame object to json format. |
def start(self):
""" Starts the clock from 0.
Uses a separate thread to handle the timing functionalities. """
if not hasattr(self,"thread") or not self.thread.isAlive():
self.thread = threading.Thread(target=self.__run)
self.status = RUNNING
self.reset()
self.thread.start()
else:
print("Clock a... | Starts the clock from 0.
Uses a separate thread to handle the timing functionalities. |
def univprop(self):
'''
.foo
'''
self.ignore(whitespace)
if not self.nextstr('.'):
self._raiseSyntaxError('universal property expected .')
name = self.noms(varset)
if not name:
mesg = 'Expected a univeral property name.'
self.... | .foo |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.