code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def connect(self, addr=None, userinfo=None):
"""Initiate a connection request to the device."""
if _debug: ProxyClientService._debug("connect addr=%r", addr)
# if the address was provided, use it
if addr:
self.address = addr
else:
addr = self.address
... | Initiate a connection request to the device. |
def help(ctx, topic, **kw):
"""Show help for any command.
"""
# The help command implementation is taken from
# https://www.burgundywall.com/post/having-click-help-subcommand
if topic is None:
click.echo(ctx.parent.get_help())
else:
click.echo(main.commands[topic].get_help(ctx)) | Show help for any command. |
def OnHelpSize(self, event):
"""Help window size event handler stores size in config"""
size = event.GetSize()
config["help_window_size"] = repr((size.width, size.height))
event.Skip() | Help window size event handler stores size in config |
def query_by_expired(cls):
"""Query to select all expired sessions."""
lifetime = current_app.permanent_session_lifetime
expired_moment = datetime.utcnow() - lifetime
return cls.query.filter(cls.created < expired_moment) | Query to select all expired sessions. |
def edit(self, name=None, description=None, **kwargs):
# type: (AnyStr, AnyStr, **Any) -> None
"""
Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`... | Edit the details of a part (model or instance).
For an instance you can edit the Part instance name and the part instance description. To alter the values
of properties use :func:`Part.update()`.
In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as
... |
def notescan_main(options):
'''Main function for this program when run as script.'''
filenames = get_filenames(options)
outputs = []
do_global = options.global_palette and len(filenames) > 1
if do_global:
filenames, palette = get_global_palette(filenames, options)
do_postprocess = ... | Main function for this program when run as script. |
def _adjusted_rand_index(reference_indices, estimated_indices):
"""Compute the Rand index, adjusted for change.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices
Returns
-------
ari ... | Compute the Rand index, adjusted for change.
Parameters
----------
reference_indices : np.ndarray
Array of reference indices
estimated_indices : np.ndarray
Array of estimated indices
Returns
-------
ari : float
Adjusted Rand index
.. note:: Based on sklearn.met... |
def index():
"""Query Elasticsearch using "collection" param in query string."""
collection_names = request.values.getlist('collection')
# Validation of collection names.
collections = Collection.query
if collection_names:
collections = collections.filter(
Collection.name.in_(co... | Query Elasticsearch using "collection" param in query string. |
def thellier_interpreter_BS_pars_calc(self, Grade_As):
'''
calcualte sample or site bootstrap paleointensities
and statistics
Grade_As={}
'''
thellier_interpreter_pars = {}
thellier_interpreter_pars['fail_criteria'] = []
thellier_interpreter_pars['pass_or_... | calcualte sample or site bootstrap paleointensities
and statistics
Grade_As={} |
def _extract_member(self, member, targetpath, pwd):
"""Extract the ZipInfo object 'member' to a physical
file on the path targetpath.
"""
# build the destination pathname, replacing
# forward slashes to platform specific separators.
arcname = member.filename.replace('/... | Extract the ZipInfo object 'member' to a physical
file on the path targetpath. |
def add_event_handler(self, full_usage_id, handler_function,
event_kind = HID_EVT_ALL, aux_data = None):
"""Add event handler for usage value/button changes,
returns True if the handler function was updated"""
report_id = self.find_input_usage(full_usage_id)
if report_id... | Add event handler for usage value/button changes,
returns True if the handler function was updated |
def get_canonical_user_id(self, headers=None):
"""
Convenience method that returns the "CanonicalUserID" of the
user who's credentials are associated with the connection.
The only way to get this value is to do a GET request on the
service which returns all buckets associated wit... | Convenience method that returns the "CanonicalUserID" of the
user who's credentials are associated with the connection.
The only way to get this value is to do a GET request on the
service which returns all buckets associated with the account.
As part of that response, the canonical user... |
def __updateNavButtons(self):
"""
Updates the navigation buttons that might be on the device screen.
"""
navButtons = None
for v in self.views:
if v.getId() == 'com.android.systemui:id/nav_buttons':
navButtons = v
break
if navB... | Updates the navigation buttons that might be on the device screen. |
def get_input_grads(self, merge_multi_context=True):
"""Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
will be collected fro... | Get the gradients with respect to the inputs of the module.
Parameters
----------
merge_multi_context : bool
Defaults to ``True``. In the case when data-parallelism is used, the outputs
will be collected from multiple devices. A `True` value indicate that we
... |
def _detect(self):
""" Detect shadowing
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
"""
results = []
for c in self.contracts:
shadowing = self.detect_shadowing(c)
if shadowing:
... | Detect shadowing
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'} |
def compute_exports(exports):
"""Compute a dictionary of exports given one of the parameters
to the Export() function or the exports argument to SConscript()."""
loc, glob = get_calling_namespaces()
retval = {}
try:
for export in exports:
if SCons.Util.is_Dict(export):
... | Compute a dictionary of exports given one of the parameters
to the Export() function or the exports argument to SConscript(). |
def _print_returns_summary(self, ret):
'''
Display returns summary
'''
return_counter = 0
not_return_counter = 0
not_return_minions = []
not_response_minions = []
not_connected_minions = []
failed_minions = []
for each_minion in ret:
... | Display returns summary |
def append_records(self, dataset_key, stream_id, body):
"""Append records to a stream.
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param stream_id: Stream unique identifier.
:type stream_id: str
:param body: Object body
... | Append records to a stream.
:param dataset_key: Dataset identifier, in the form of owner/id
:type dataset_key: str
:param stream_id: Stream unique identifier.
:type stream_id: str
:param body: Object body
:type body: obj
:raises RestApiException: If a server erro... |
def revisions(self, path, max_revisions):
"""
Get the list of revisions.
:param path: the path to target.
:type path: ``str``
:param max_revisions: the maximum number of revisions.
:type max_revisions: ``int``
:return: A list of revisions.
:rtype: ``l... | Get the list of revisions.
:param path: the path to target.
:type path: ``str``
:param max_revisions: the maximum number of revisions.
:type max_revisions: ``int``
:return: A list of revisions.
:rtype: ``list`` of :class:`Revision` |
def clear_calendars(self):
"""
Deregisters all current registered calendars
"""
self._calendars.clear()
self._calendar_factories.clear()
self._aliases.clear() | Deregisters all current registered calendars |
def setup(self):
"""Setup the simulation and initialize its population."""
super().setup()
self._start_time = self.clock.time
self.initialize_simulants() | Setup the simulation and initialize its population. |
def _cstor_args_from_fields(self, fields, is_struct=False):
"""Returns a string representing the properly formatted arguments for a constructor."""
if is_struct:
args = [(fmt_var(f.name),
fmt_type(f.data_type, tag=True, has_default=f.has_default)) for f in fields]
els... | Returns a string representing the properly formatted arguments for a constructor. |
def send_email(self, msg, tag=None):
"""
Send an e-mail before completing the shutdown.
Returns 0 if success.
"""
try:
return self._send_email(msg, tag)
except:
self.exceptions.append(straceback())
return -2 | Send an e-mail before completing the shutdown.
Returns 0 if success. |
def fast_sync_inspect_snapshot( snapshot_path ):
"""
Inspect a snapshot
Return useful information
Return {'status': True, 'signatures': ..., 'payload_size': ..., 'sig_append_offset': ..., 'hash': ...} on success
Return {'error': ...} on error
"""
with open(snapshot_path, 'r') as f:
i... | Inspect a snapshot
Return useful information
Return {'status': True, 'signatures': ..., 'payload_size': ..., 'sig_append_offset': ..., 'hash': ...} on success
Return {'error': ...} on error |
def apply(self, points):
"""Applies the rigid transformation to a set of 3D objects.
Parameters
----------
points : :obj:`BagOfPoints`
A set of objects to transform. Could be any subclass of BagOfPoints.
Returns
-------
:obj:`BagOfPoints`
... | Applies the rigid transformation to a set of 3D objects.
Parameters
----------
points : :obj:`BagOfPoints`
A set of objects to transform. Could be any subclass of BagOfPoints.
Returns
-------
:obj:`BagOfPoints`
A transformed set of objects of the... |
def key_from_password(password):
"""This method just hashes self.password."""
if isinstance(password, unicode):
password = password.encode('utf-8')
if not isinstance(password, bytes):
raise TypeError("password must be byte string, not %s" % type(password))
sha = SHA256.new()
sha... | This method just hashes self.password. |
def get_user(user_or_username):
"""Return Plone User
:param user_or_username: Plone user or user id
:returns: Plone MemberData
"""
user = None
if isinstance(user_or_username, MemberData):
user = user_or_username
if isinstance(user_or_username, basestring):
user = get_member_... | Return Plone User
:param user_or_username: Plone user or user id
:returns: Plone MemberData |
def delta_encode(data, axis=-1, out=None):
"""Encode Delta."""
if isinstance(data, (bytes, bytearray)):
data = numpy.frombuffer(data, dtype='u1')
diff = numpy.diff(data, axis=0)
return numpy.insert(diff, 0, data[0]).tobytes()
dtype = data.dtype
if dtype.kind == 'f':
data... | Encode Delta. |
def exception(self, timeout=None):
"""Wait for the async function to complete and return its exception.
If the function did not raise an exception this returns ``None``.
"""
if not self._done.wait(timeout):
raise Timeout('timeout waiting for future')
if self._state =... | Wait for the async function to complete and return its exception.
If the function did not raise an exception this returns ``None``. |
async def reprompt_dialog(self):
"""
Calls reprompt on the currently active dialog, if there is one. Used with Prompts that have a reprompt behavior.
:return:
"""
# Check for a dialog on the stack
if self.active_dialog != None:
# Look up dialog
dia... | Calls reprompt on the currently active dialog, if there is one. Used with Prompts that have a reprompt behavior.
:return: |
def submit(self, job):
"""
Submits a given job
:param job: The job to submit
:type job: pyqueue.job.JobInterface
"""
script = self._printer.generate(job)
stdin, stdout, stderr = self._ssh.exec_command('sbatch')
stdin.write(script)
stdin.flush()
... | Submits a given job
:param job: The job to submit
:type job: pyqueue.job.JobInterface |
def allow_unregister(self, plugin_override=True):
""" Returns True if students can unregister from course """
vals = self._hook_manager.call_hook('course_allow_unregister', course=self, default=self._allow_unregister)
return vals[0] if len(vals) and plugin_override else self._allow_unregister | Returns True if students can unregister from course |
def delete(self, alert_condition_id):
"""
This API endpoint allows you to delete an alert condition
:type alert_condition_id: integer
:param alert_condition_id: Alert Condition ID
:rtype: dict
:return: The JSON response of the API
::
{
... | This API endpoint allows you to delete an alert condition
:type alert_condition_id: integer
:param alert_condition_id: Alert Condition ID
:rtype: dict
:return: The JSON response of the API
::
{
"condition": {
"id": "integer",
... |
def get_choices(field):
"""
Find choices of a field, whether it has choices or has a queryset.
Args:
field (BoundField): Django form boundfield
Returns:
list: List of choices
"""
empty_label = getattr(field.field, "empty_label", False)
needs_empty_value = False
choices = []
# Data is the choices
if ha... | Find choices of a field, whether it has choices or has a queryset.
Args:
field (BoundField): Django form boundfield
Returns:
list: List of choices |
def load_locations(self, location_file=None):
"""Load locations into this resolver from the given
*location_file*, which should contain one JSON object per line
representing a location. If *location_file* is not specified,
an internal location database is used."""
if location_fi... | Load locations into this resolver from the given
*location_file*, which should contain one JSON object per line
representing a location. If *location_file* is not specified,
an internal location database is used. |
def get_root_books(self):
"""Gets the root books in the book hierarchy.
A node with no parents is an orphan. While all book ``Ids`` are
known to the hierarchy, an orphan does not appear in the
hierarchy unless explicitly added as a root node or child of
another node.
re... | Gets the root books in the book hierarchy.
A node with no parents is an orphan. While all book ``Ids`` are
known to the hierarchy, an orphan does not appear in the
hierarchy unless explicitly added as a root node or child of
another node.
return: (osid.commenting.BookList) - th... |
def unset_logging(self):
""" Mute newly added handlers to the root level, right after calling executor.status
"""
if self.logger_flag is True:
return
root_logger = logging.getLogger()
for hndlr in root_logger.handlers:
if hndlr not in self.prior_loghandl... | Mute newly added handlers to the root level, right after calling executor.status |
async def remove(gc: GroupControl, slaves):
"""Remove speakers from group."""
click.echo("Removing from existing group: %s" % slaves)
click.echo(await gc.remove(slaves)) | Remove speakers from group. |
def import_file(args):
"""
Given a dataset and a local path, upload and import the file(s).
Command arguments (args):
* create_dataset
* template_id
* full_path
* vault (optional, overrides the vault in full_path)
* path (optional, overrides the path in full_path)
... | Given a dataset and a local path, upload and import the file(s).
Command arguments (args):
* create_dataset
* template_id
* full_path
* vault (optional, overrides the vault in full_path)
* path (optional, overrides the path in full_path)
* commit_mode
* capa... |
def _update_scale_factor(self, accept_rate):
'''Private function.
Updates the covariance scaling factor ``covar_scale_factor``
according to its limits
'''
if accept_rate > self.force_acceptance_max and self.covar_scale_factor < self.covar_scale_factor_max:
self.covar... | Private function.
Updates the covariance scaling factor ``covar_scale_factor``
according to its limits |
def anim_to_html(anim):
"""
adapted from: http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
This function converts and animation object from matplotlib into HTML which can then
be embedded in an IPython notebook.
This requires ffmpeg to be installed in order to build the in... | adapted from: http://jakevdp.github.io/blog/2013/05/12/embedding-matplotlib-animations/
This function converts and animation object from matplotlib into HTML which can then
be embedded in an IPython notebook.
This requires ffmpeg to be installed in order to build the intermediate mp4 file
To get thes... |
def set_extent_location(self, new_location):
# type: (int) -> None
'''
A method to set the location of this UDF File Set Descriptor.
Parameters:
new_location - The new extent this UDF File Set Descriptor should be located at.
Returns:
Nothing.
'''
... | A method to set the location of this UDF File Set Descriptor.
Parameters:
new_location - The new extent this UDF File Set Descriptor should be located at.
Returns:
Nothing. |
def _create_message(response, service_instance):
''' Create message from response.
response:
response from Service Bus cloud server.
service_instance:
the Service Bus client.
'''
respbody = response.body
custom_properties = {}
broker_properties = None
message_type = None... | Create message from response.
response:
response from Service Bus cloud server.
service_instance:
the Service Bus client. |
def mount(self, volume):
"""Mounts the given volume on the provided mountpoint. The default implementation simply calls mount.
:param Volume volume: The volume to be mounted
:param mountpoint: The file system path to mount the filesystem on.
:raises UnsupportedFilesystemError: when the ... | Mounts the given volume on the provided mountpoint. The default implementation simply calls mount.
:param Volume volume: The volume to be mounted
:param mountpoint: The file system path to mount the filesystem on.
:raises UnsupportedFilesystemError: when the volume system type can not be mounte... |
def rmdir(self, directory, missing_okay=False):
"""Forcefully remove the specified directory and all its children."""
# Build a script to walk an entire directory structure and delete every
# file and subfolder. This is tricky because MicroPython has no os.walk
# or similar function to ... | Forcefully remove the specified directory and all its children. |
def jacobian(expr, symbols):
"""
Derive a symbolic expr w.r.t. each symbol in symbols. This returns a symbolic jacobian vector.
:param expr: A sympy Expr.
:param symbols: The symbols w.r.t. which to derive.
"""
jac = []
for symbol in symbols:
# Differentiate to every param
f... | Derive a symbolic expr w.r.t. each symbol in symbols. This returns a symbolic jacobian vector.
:param expr: A sympy Expr.
:param symbols: The symbols w.r.t. which to derive. |
def alphanumeric_hash(s: str, size=5):
"""Short alphanumeric string derived from hash of given string"""
import hashlib
import base64
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | Short alphanumeric string derived from hash of given string |
def _estimate_friedrich_coefficients(x, m, r):
"""
Coefficients of polynomial :math:`h(x)`, which has been fitted to
the deterministic dynamics of Langevin model
.. math::
\dot{x}(t) = h(x(t)) + \mathcal{N}(0,R)
As described by
Friedrich et al. (2000): Physics Letters A 271, p. 217... | Coefficients of polynomial :math:`h(x)`, which has been fitted to
the deterministic dynamics of Langevin model
.. math::
\dot{x}(t) = h(x(t)) + \mathcal{N}(0,R)
As described by
Friedrich et al. (2000): Physics Letters A 271, p. 217-222
*Extracting model equations from experimental ... |
def _M2_dense(X, Y, weights=None, diag_only=False):
""" 2nd moment matrix using dense matrix computations.
This function is encapsulated such that we can make easy modifications of the basic algorithms
"""
if weights is not None:
if diag_only:
return np.sum(weights[:, None] * X * Y... | 2nd moment matrix using dense matrix computations.
This function is encapsulated such that we can make easy modifications of the basic algorithms |
def _iterate_through_pages(get_function, resource, **kwargs):
"""
Iterate through all pages and return the collected data
:rtype: list
"""
request_data = True
data = []
page = 1
while request_data:
temp_response = get_function(page=page, **kw... | Iterate through all pages and return the collected data
:rtype: list |
def get_grade_system_admin_session_for_gradebook(self, gradebook_id, proxy):
"""Gets the ``OsidSession`` associated with the grade system admin service for the given gradebook.
arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook
arg: proxy (osid.proxy.Proxy): a proxy
retur... | Gets the ``OsidSession`` associated with the grade system admin service for the given gradebook.
arg: gradebook_id (osid.id.Id): the ``Id`` of the gradebook
arg: proxy (osid.proxy.Proxy): a proxy
return: (osid.grading.GradeSystemAdminSession) - ``a
GradeSystemAdminSession`... |
def url_fix_host (urlparts):
"""Unquote and fix hostname. Returns is_idn."""
if not urlparts[1]:
urlparts[2] = urllib.unquote(urlparts[2])
return False
userpass, netloc = urllib.splituser(urlparts[1])
if userpass:
userpass = urllib.unquote(userpass)
netloc, is_idn = idna_enco... | Unquote and fix hostname. Returns is_idn. |
def find(name):
"""Locate a filename into the shader library."""
if op.exists(name):
return name
path = op.dirname(__file__) or '.'
paths = [path] + config['include_path']
for path in paths:
filename = op.abspath(op.join(path, name))
if op.exists(filename):
re... | Locate a filename into the shader library. |
def cli(env, identifier, a_record, aaaa_record, ptr, ttl):
"""Sync DNS records."""
items = ['id',
'globalIdentifier',
'fullyQualifiedDomainName',
'hostname',
'domain',
'primaryBackendIpAddress',
'primaryIpAddress',
'''pr... | Sync DNS records. |
def select(self, sql_string, cols, *args, **kwargs):
"""
Execute a SELECT statement
:sql_string: An SQL string template
:columns: A list of columns to be returned by the query
:*args: Arguments to be passed for query parameters.
:returns: Psycopg... | Execute a SELECT statement
:sql_string: An SQL string template
:columns: A list of columns to be returned by the query
:*args: Arguments to be passed for query parameters.
:returns: Psycopg2 result |
def get_audiences(self):
"""
Gets the audiences
:returns: The valid audiences for the SAML Response
:rtype: list
"""
audience_nodes = self.__query_assertion('/saml:Conditions/saml:AudienceRestriction/saml:Audience')
return [OneLogin_Saml2_XML.element_text(node) f... | Gets the audiences
:returns: The valid audiences for the SAML Response
:rtype: list |
def tag_(name, repository, tag='latest', force=False):
'''
.. versionchanged:: 2018.3.0
The repository and tag must now be passed separately using the
``repository`` and ``tag`` arguments, rather than together in the (now
deprecated) ``image`` argument.
Tag an image into a repositor... | .. versionchanged:: 2018.3.0
The repository and tag must now be passed separately using the
``repository`` and ``tag`` arguments, rather than together in the (now
deprecated) ``image`` argument.
Tag an image into a repository and return ``True``. If the tag was
unsuccessful, an error wi... |
def _run_soft_delete(self):
"""
Perform the actual delete query on this model instance.
"""
query = self.new_query().where(self.get_key_name(), self.get_key())
time = self.fresh_timestamp()
setattr(self, self.get_deleted_at_column(), time)
query.update({self.get... | Perform the actual delete query on this model instance. |
def get(self, deviceId):
"""
lists all known active measurements.
"""
measurementsByName = self.measurements.get(deviceId)
if measurementsByName is None:
return []
else:
return list(measurementsByName.values()) | lists all known active measurements. |
def parse_transcripts(transcript_lines):
"""Parse and massage the transcript information
There could be multiple lines with information about the same transcript.
This is why it is necessary to parse the transcripts first and then return a dictionary
where all information has been merged.
Args:
... | Parse and massage the transcript information
There could be multiple lines with information about the same transcript.
This is why it is necessary to parse the transcripts first and then return a dictionary
where all information has been merged.
Args:
transcript_lines(): This could be an itera... |
def SetWeight(self, path_segment_index, weight):
"""Sets a weight for a specific path segment index.
Args:
path_segment_index: an integer containing the path segment index.
weight: an integer containing the weight.
Raises:
ValueError: if the path segment weights do not contain
... | Sets a weight for a specific path segment index.
Args:
path_segment_index: an integer containing the path segment index.
weight: an integer containing the weight.
Raises:
ValueError: if the path segment weights do not contain
the path segment index. |
def remove(self, *nonterminals):
# type: (Iterable[Type[Nonterminal]]) -> None
"""
Remove nonterminals from the set.
Removes also rules using this nonterminal.
Set start symbol to None if deleting nonterminal is start symbol at the same time.
:param nonterminals: Nontermi... | Remove nonterminals from the set.
Removes also rules using this nonterminal.
Set start symbol to None if deleting nonterminal is start symbol at the same time.
:param nonterminals: Nonterminals to remove. |
def auth_list():
'''
List all available authorization
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_list
'''
auths = {}
## read auth_attr file (name:res1:res2:short_desc:long_desc:attr)
with salt.utils.files.fopen('/etc/security/auth_attr', 'r') as auth_attr:
f... | List all available authorization
CLI Example:
.. code-block:: bash
salt '*' rbac.auth_list |
def firstvalue(self, *fieldspecs, **kwargs):
"""
Return the [first] [v]alue or the value given by the keyword
argument `default` if not value exists. `default` defaults to `None`.
"""
default = kwargs.get('default', None)
values = [val for val in self.itervalues(*fieldspe... | Return the [first] [v]alue or the value given by the keyword
argument `default` if not value exists. `default` defaults to `None`. |
def get_security_error(node):
""" return a SecurityError if the specified securityData element has one, else return None """
assert node.name() == 'securityData' and not node.isArray()
if node.hasElement('securityError'):
secid = XmlHelper.get_child_value(node, 'security')
... | return a SecurityError if the specified securityData element has one, else return None |
def authenticateRequest(self, service_request, username, password, **kwargs):
"""
Processes an authentication request. If no authenticator is supplied,
then authentication succeeds.
@return: Returns a C{bool} based on the result of authorization. A
value of C{False} will sto... | Processes an authentication request. If no authenticator is supplied,
then authentication succeeds.
@return: Returns a C{bool} based on the result of authorization. A
value of C{False} will stop processing the request and return an
error to the client.
@rtype: C{bool} |
def update_templates(self, body):
"""Update enrollment and verification SMS templates.
Useful to send custom messages on sms enrollment and verification
Args:
body (dict): Attributes to modify.
See: https://auth0.com/docs/api/management/v2#!/Guardian/put_templates
... | Update enrollment and verification SMS templates.
Useful to send custom messages on sms enrollment and verification
Args:
body (dict): Attributes to modify.
See: https://auth0.com/docs/api/management/v2#!/Guardian/put_templates |
async def remove_pump_async(self, partition_id, reason):
"""
Stops a single partiton pump.
:param partition_id: The partition ID.
:type partition_id: str
:param reason: A reason for closing.
:type reason: str
"""
if partition_id in self.partition_pumps:
... | Stops a single partiton pump.
:param partition_id: The partition ID.
:type partition_id: str
:param reason: A reason for closing.
:type reason: str |
def _SID_call_prep(align_bams, items, ref_file, assoc_files, region=None, out_file=None):
"""Preparation work for SomaticIndelDetector.
"""
base_config = items[0]["config"]
for x in align_bams:
bam.index(x, base_config)
params = ["-R", ref_file, "-T", "SomaticIndelDetector", "-U", "ALLOW_N_... | Preparation work for SomaticIndelDetector. |
def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
Checks for a modify confirmation and performs
the action by calling `process_action`.
"""
queryset = self.get_selected(request)
if request.POST.get('modify'):
response =... | Method for handling POST requests.
Checks for a modify confirmation and performs
the action by calling `process_action`. |
def bgzip_and_index(in_file, config=None, remove_orig=True, prep_cmd="", tabix_args=None, out_dir=None):
"""bgzip and tabix index an input file, handling VCF and BED.
"""
if config is None:
config = {}
out_file = in_file if in_file.endswith(".gz") else in_file + ".gz"
if out_dir:
rem... | bgzip and tabix index an input file, handling VCF and BED. |
def set_root(self, index):
"""Set the given index as root index of list
:param index: the new root index
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None
"""
if not index.isValid():
self.setModel(None) # so we will not... | Set the given index as root index of list
:param index: the new root index
:type index: QtCore.QModelIndex
:returns: None
:rtype: None
:raises: None |
def html_scientific_notation_rate(rate):
"""Helper for convert decimal rate using scientific notation.
For example we want to show the very detail value of fatality rate
because it might be a very small number.
:param rate: Rate value
:type rate: float
:return: Rate value with html tag to sho... | Helper for convert decimal rate using scientific notation.
For example we want to show the very detail value of fatality rate
because it might be a very small number.
:param rate: Rate value
:type rate: float
:return: Rate value with html tag to show the exponent
:rtype: str |
def _collapse_language_array(language_array):
"""
Convert the Ideone language list into a Python dictionary.
"""
language_dict = {}
for language in language_array.item:
key = language.key[0]
value = language.value[0]
language_dict[key] = value
... | Convert the Ideone language list into a Python dictionary. |
def histogram_stretch(self, use_bands, **kwargs):
''' entry point for contrast stretching '''
data = self._read(self[use_bands,...], **kwargs)
data = np.rollaxis(data.astype(np.float32), 0, 3)
return self._histogram_stretch(data, **kwargs) | entry point for contrast stretching |
def login_student(request):
"""
Log in student
POST parameters (JSON):
student:
profile id of the student
"""
if not get_config('proso_user', 'allow_login_students', default=False):
return render_json(request, {
'error': _('Log in as student is not allowed.')... | Log in student
POST parameters (JSON):
student:
profile id of the student |
def to_root(df, path, key='my_ttree', mode='w', store_index=True, *args, **kwargs):
"""
Write DataFrame to a ROOT file.
Parameters
----------
path: string
File path to new ROOT file (will be overwritten)
key: string
Name of tree that the DataFrame will be saved as
mode: stri... | Write DataFrame to a ROOT file.
Parameters
----------
path: string
File path to new ROOT file (will be overwritten)
key: string
Name of tree that the DataFrame will be saved as
mode: string, {'w', 'a'}
Mode that the file should be opened in (default: 'w')
store_index: bo... |
def pprint_args(self, pos_args, keyword_args, infix_operator=None, extra_params={}):
"""
Method to define the positional arguments and keyword order
for pretty printing.
"""
if infix_operator and not (len(pos_args)==2 and keyword_args==[]):
raise Exception('Infix form... | Method to define the positional arguments and keyword order
for pretty printing. |
def cli(ctx, oldversion):
"""Upgrade the current bubble, should mimic init as much as possible(experimental)"""
# print ctx.bubble
path = ctx.home
bubble_file_name = path + '/.bubble'
config_file = path + '/config/config.yaml'
if file_exists(bubble_file_name):
pass
else:
wit... | Upgrade the current bubble, should mimic init as much as possible(experimental) |
def deleteItemAtIndex(self, itemIndex):
""" Removes the item at the itemIndex.
The item's finalize method is called before removing so it can close its resources.
"""
if not itemIndex.isValid():
logger.debug("No valid item selected for deletion (ignored).")
re... | Removes the item at the itemIndex.
The item's finalize method is called before removing so it can close its resources. |
def match(self, fpath):
"""Does `fpath` match one of our filename patterns?"""
for pat in self.pats:
if fnmatch.fnmatch(fpath, pat):
return True
return False | Does `fpath` match one of our filename patterns? |
def fit(self, X, y=None):
"""Fit FeatureSetSelector for feature selection
Parameters
----------
X: array-like of shape (n_samples, n_features)
The training input samples.
y: array-like, shape (n_samples,)
The target values (integers that correspond to cla... | Fit FeatureSetSelector for feature selection
Parameters
----------
X: array-like of shape (n_samples, n_features)
The training input samples.
y: array-like, shape (n_samples,)
The target values (integers that correspond to classes in classification, real numbers ... |
def all_keys(self, uppercase_keys=False):
"""Return all keys regardless where they are set."""
d = {}
for k in self._override.keys():
d[k.upper() if uppercase_keys else k.lower()] = {}
for k in self._args.keys():
d[k.upper() if uppercase_keys else k.lower()] = {... | Return all keys regardless where they are set. |
def delete_brand_by_id(cls, brand_id, **kwargs):
"""Delete Brand
Delete an instance of Brand by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_brand_by_id(brand_id, async=True)... | Delete Brand
Delete an instance of Brand by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_brand_by_id(brand_id, async=True)
>>> result = thread.get()
:param async boo... |
def update_mim_version(self, new_genes, new_panel, old_version):
"""Set the correct version for each gene
Loop over the genes in the new panel
Args:
new_genes(set(str)): Set with the new gene symbols
new_panel(dict)
"""
LOG.info('Updating versions for ne... | Set the correct version for each gene
Loop over the genes in the new panel
Args:
new_genes(set(str)): Set with the new gene symbols
new_panel(dict) |
def get_player_summaries(self, steamids=None, **kwargs):
"""Returns a dictionary containing a player summaries
:param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice
that api will convert if ``32-bit`` are given
:return: dictionary of player s... | Returns a dictionary containing a player summaries
:param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice
that api will convert if ``32-bit`` are given
:return: dictionary of player summaries, see :doc:`responses </responses>` |
def save_bank(self, bank_form, *args, **kwargs):
"""Pass through to provider BankAdminSession.update_bank"""
# Implemented from kitosid template for -
# osid.resource.BinAdminSession.update_bin
if bank_form.is_for_update():
return self.update_bank(bank_form, *args, **kwargs)
... | Pass through to provider BankAdminSession.update_bank |
def get_feature_names(self, always_signed=True):
# type: (bool) -> FeatureNames
"""
Return feature names.
This is a best-effort function which tries to reconstruct feature
names based on what it has seen so far.
HashingVectorizer uses a signed hash function. If always_si... | Return feature names.
This is a best-effort function which tries to reconstruct feature
names based on what it has seen so far.
HashingVectorizer uses a signed hash function. If always_signed is True,
each term in feature names is prepended with its sign. If it is False,
signs a... |
def convert_to_record(func):
"""Wrap mongodb record to a dict record with default value None
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
result = func(self, *args, **kwargs)
if result is not None:
if isinstance(result, dict):
return _record(... | Wrap mongodb record to a dict record with default value None |
def _flush_events(self):
"""! @brief Send all pending events to event sink."""
if self._sink is not None:
for event in self._pending_events:
self._sink.receive(event)
self._pending_events = [] | ! @brief Send all pending events to event sink. |
def check_args(arguments, data_frame):
"""
check arguments against a command_line_dataframe.
checks that:
all arguments are valid
all required arguments are present
default values are used where needed
"""
stripped_args = [a[0] for a in arguments]
df = data_frame.df
# first make ... | check arguments against a command_line_dataframe.
checks that:
all arguments are valid
all required arguments are present
default values are used where needed |
def _getPWMFrequency(self, device, message):
"""
Get the PWM frequency stored on the hardware device.
:Parameters:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol.
message : `bool`
... | Get the PWM frequency stored on the hardware device.
:Parameters:
device : `int`
The device is the integer number of the hardware devices ID and
is only used with the Pololu Protocol.
message : `bool`
If set to `True` a text message will be returned, if s... |
def finish(self):
"""
Respond to nsqd that you’ve processed this message successfully
(or would like to silently discard it).
"""
if self._has_responded:
raise NSQException('already responded')
self._has_responded = True
self.on_finish.send(self) | Respond to nsqd that you’ve processed this message successfully
(or would like to silently discard it). |
def translate_opcodes(code_obj, target):
"""
Very crude inter-python version opcode translator. Raises SyntaxError when
the opcode doesn't exist in the destination opmap. Used to transcribe
python code objects between python versions.
Arguments:
code_obj(pwnypack.bytecode.CodeObject): The c... | Very crude inter-python version opcode translator. Raises SyntaxError when
the opcode doesn't exist in the destination opmap. Used to transcribe
python code objects between python versions.
Arguments:
code_obj(pwnypack.bytecode.CodeObject): The code object representation
to translate.
... |
def add_kb(self, issuer, kb):
"""
Add a key bundle and bind it to an identifier
:param issuer: Owner of the keys in the key bundle
:param kb: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance
"""
try:
self.issuer_keys[issuer].append(kb)
exce... | Add a key bundle and bind it to an identifier
:param issuer: Owner of the keys in the key bundle
:param kb: A :py:class:`oidcmsg.key_bundle.KeyBundle` instance |
def save(unique_keys, data, table_name='swdata'):
"""
Save the given data to the table specified by `table_name`
(which defaults to 'swdata'). The data must be a mapping
or an iterable of mappings. Unique keys is a list of keys that exist
for all rows and for which a unique index will be created.
... | Save the given data to the table specified by `table_name`
(which defaults to 'swdata'). The data must be a mapping
or an iterable of mappings. Unique keys is a list of keys that exist
for all rows and for which a unique index will be created. |
def best_kmers(dt, response, sequence, k=6, consider_shift=True, n_cores=1,
seq_align="start", trim_seq_len=None):
"""
Find best k-mers for CONCISE initialization.
Args:
dt (pd.DataFrame): Table containing response variable and sequence.
response (str): Name of the column use... | Find best k-mers for CONCISE initialization.
Args:
dt (pd.DataFrame): Table containing response variable and sequence.
response (str): Name of the column used as the reponse variable.
sequence (str): Name of the column storing the DNA/RNA sequences.
k (int): Desired k-mer length.
... |
def get_json(self, path, **kwargs):
"""Perform an HTTP GET request with JSON headers of the specified path against Device Cloud
Make an HTTP GET request against Device Cloud with this accounts
credentials and base url. This method uses the
`requests <http://docs.python-requests.org/en/... | Perform an HTTP GET request with JSON headers of the specified path against Device Cloud
Make an HTTP GET request against Device Cloud with this accounts
credentials and base url. This method uses the
`requests <http://docs.python-requests.org/en/latest/>`_ library
`request method <htt... |
def import_modules(names, src, dst):
"""Import modules in package."""
for name in names:
module = importlib.import_module(src + '.' + name)
setattr(sys.modules[dst], name, module) | Import modules in package. |
def synteny(args):
"""
%prog synteny mstmap.out novo.final.fasta reference.fasta
Plot MSTmap against reference genome.
"""
from jcvi.assembly.geneticmap import bed as geneticmap_bed
from jcvi.apps.align import blat
from jcvi.formats.blast import bed as blast_bed, best
p = OptionParser(... | %prog synteny mstmap.out novo.final.fasta reference.fasta
Plot MSTmap against reference genome. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.