code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def _set_weight(self, v, load=False):
"""
Setter method for weight, mapped from YANG variable /routing_system/route_map/content/set/weight (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_weight is considered as a private
method. Backends looking to popula... | Setter method for weight, mapped from YANG variable /routing_system/route_map/content/set/weight (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_weight is considered as a private
method. Backends looking to populate this variable should
do so via calling this... |
def replace(self, key, value, expire=0, noreply=None):
"""
The memcached "replace" command.
Args:
key: str, see class docs for details.
value: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from ... | The memcached "replace" command.
Args:
key: str, see class docs for details.
value: str, see class docs for details.
expire: optional int, number of seconds until the item is expired
from the cache, or zero for no expiry (the default).
noreply: optional... |
def list_locked(**kwargs):
'''
Query the package database those packages which are
locked against reinstallation, modification or deletion.
Returns returns a list of package names with version strings
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locked
jail
List l... | Query the package database those packages which are
locked against reinstallation, modification or deletion.
Returns returns a list of package names with version strings
CLI Example:
.. code-block:: bash
salt '*' pkg.list_locked
jail
List locked packages within the specified jai... |
def _options_protobuf(self, retry_id):
"""Convert the current object to protobuf.
The ``retry_id`` value is used when retrying a transaction that
failed (e.g. due to contention). It is intended to be the "first"
transaction that failed (i.e. if multiple retries are needed).
Arg... | Convert the current object to protobuf.
The ``retry_id`` value is used when retrying a transaction that
failed (e.g. due to contention). It is intended to be the "first"
transaction that failed (i.e. if multiple retries are needed).
Args:
retry_id (Union[bytes, NoneType]): ... |
def git_push():
"""
Push new version and corresponding tag to origin
:return:
"""
# get current version
new_version = version.__version__
values = list(map(lambda x: int(x), new_version.split('.')))
# Push to origin new version and corresponding tag:
# * commit new version
# * ... | Push new version and corresponding tag to origin
:return: |
def _save_stdin(self, stdin):
"""
Creates a temporary dir (self.temp_dir) and saves the given input
stream to a file within that dir. Returns the path to the file. The dir
is removed in the __del__ method.
"""
self.temp_dir = TemporaryDirectory()
file_path = os.path.join(self.temp_dir.name, 'dataset')
... | Creates a temporary dir (self.temp_dir) and saves the given input
stream to a file within that dir. Returns the path to the file. The dir
is removed in the __del__ method. |
def pipool(name, ivals):
"""
This entry point provides toolkit programmers a method for
programmatically inserting integer data into the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pipool_c.html
:param name: The kernel pool name to associate with values.
:type name: st... | This entry point provides toolkit programmers a method for
programmatically inserting integer data into the kernel pool.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pipool_c.html
:param name: The kernel pool name to associate with values.
:type name: str
:param ivals: An array of integ... |
def _partial_extraction_fixed(self, idx, extra_idx=0):
"""
Private method for a single extraction on a fixed-type tab file
"""
myarray = np.array([])
with open(self.abspath) as fobj:
contents = fobj.readlines()[idx+extra_idx:]
for line in contents:
... | Private method for a single extraction on a fixed-type tab file |
def get_over_current(self, channel):
'''Reading over current status of power channel
'''
try:
bit = self._ch_map[channel]['GPIOOC']['bit']
except KeyError:
raise ValueError('get_over_current() not supported for channel %s' % channel)
return not self._get_p... | Reading over current status of power channel |
def prepare_destruction(self):
"""Get rid of circular references"""
self._tool = None
self._painter = None
self.relieve_model(self._selection)
self._selection = None
# clear observer class attributes, also see ExtendenController.destroy()
self._Observer__PROP_TO_M... | Get rid of circular references |
def bundle(self, name: str) -> models.Bundle:
"""Fetch a bundle from the store."""
return self.Bundle.filter_by(name=name).first() | Fetch a bundle from the store. |
def descendants(self, node, relations=None, reflexive=False):
"""
Returns all descendants of specified node.
The default implementation is to use networkx, but some
implementations of the Ontology class may use a database or
service backed implementation, for large graphs.
... | Returns all descendants of specified node.
The default implementation is to use networkx, but some
implementations of the Ontology class may use a database or
service backed implementation, for large graphs.
Arguments
---------
node : str
identifier for nod... |
def fetchmany(self, size=None):
"""Fetch many rows from select result set.
:param size: Number of rows to return.
:returns: list of row records (tuples)
"""
self._check_closed()
if not self._executed:
raise ProgrammingError("Require execute() first")
i... | Fetch many rows from select result set.
:param size: Number of rows to return.
:returns: list of row records (tuples) |
def log_listener(log:logging.Logger=None, level=logging.INFO):
"""Progress Monitor listener that logs all updates to the given logger"""
if log is None:
log = logging.getLogger("ProgressMonitor")
def listen(monitor):
name = "{}: ".format(monitor.name) if monitor.name is not None else ""
... | Progress Monitor listener that logs all updates to the given logger |
def _set_ldp_out(self, v, load=False):
"""
Setter method for ldp_out, mapped from YANG variable /mpls_state/ldp/ldp_out (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_out is considered as a private
method. Backends looking to populate this variable s... | Setter method for ldp_out, mapped from YANG variable /mpls_state/ldp/ldp_out (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_ldp_out is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_ldp_out() ... |
def fillScreen(self, color=None):
"""Fill the matrix with the given RGB color"""
md.fill_rect(self.set, 0, 0, self.width, self.height, color) | Fill the matrix with the given RGB color |
def edit(self, id):
""" Edit a prefix.
"""
# find prefix
c.prefix = Prefix.get(int(id))
# we got a HTTP POST - edit object
if request.method == 'POST':
c.prefix.prefix = request.params['prefix_prefix']
c.prefix.description = request.params['prefi... | Edit a prefix. |
def down_ec2(connection, instance_id, region, log=False):
""" shutdown of an existing EC2 instance """
# get the instance_id from the state file, and stop the instance
instance = connection.stop_instances(instance_ids=instance_id)[0]
while instance.state != "stopped":
if log:
log_yel... | shutdown of an existing EC2 instance |
def route(rule=None, **kwargs):
"""
This decorator defines custom route for both class and methods in the view.
It behaves the same way as Flask's @app.route
on class:
It takes the following args
- rule: the root route of the endpoint
- decorators: a list of decorators t... | This decorator defines custom route for both class and methods in the view.
It behaves the same way as Flask's @app.route
on class:
It takes the following args
- rule: the root route of the endpoint
- decorators: a list of decorators to run on each method
on methods:
... |
def register(func_path, factory=mock.MagicMock):
# type: (str, Callable) -> Callable
"""
Kwargs:
func_path: import path to mock (as you would give to `mock.patch`)
factory: function that returns a mock for the patched func
Returns:
(decorator)
Usage:
automock.regis... | Kwargs:
func_path: import path to mock (as you would give to `mock.patch`)
factory: function that returns a mock for the patched func
Returns:
(decorator)
Usage:
automock.register('path.to.func.to.mock') # default MagicMock
automock.register('path.to.func.to.mock', Cu... |
def acquire_account_for(self, host, owner=None):
"""
Acquires an account for the given host and returns it.
The host is passed to each of the match functions that were
passed in when adding the pool. The first pool for which the
match function returns True is chosen to assign an ... | Acquires an account for the given host and returns it.
The host is passed to each of the match functions that were
passed in when adding the pool. The first pool for which the
match function returns True is chosen to assign an account.
:type host: :class:`Host`
:param host: The... |
def get_webassets_env_from_settings(settings, prefix='webassets'):
"""This function will take all webassets.* parameters, and
call the ``Environment()`` constructor with kwargs passed in.
The only two parameters that are not passed as keywords are:
* base_dir
* base_url
which are passed in po... | This function will take all webassets.* parameters, and
call the ``Environment()`` constructor with kwargs passed in.
The only two parameters that are not passed as keywords are:
* base_dir
* base_url
which are passed in positionally.
Read the ``WebAssets`` docs for ``Environment`` for more ... |
def _glimpse_network(self, x_t, l_p):
"""
Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
4x12 matrix
"""
sensor_output = self._refined_glimpse_sensor(x_t, l_p)
sensor_output = T.flatten(sensor_output)
h_g = self._... | Parameters:
x_t - 28x28 image
l_p - 2x1 focus vector
Returns:
4x12 matrix |
def make_name(super_name, default_super_name, sub_name):
"""Helper which makes a `str` name; useful for tf.compat.v1.name_scope."""
name = super_name if super_name is not None else default_super_name
if sub_name is not None:
name += '_' + sub_name
return name | Helper which makes a `str` name; useful for tf.compat.v1.name_scope. |
def _request_internal(self, command, **kwargs):
"""Make request parse response"""
args = dict(kwargs)
if self.ssid:
args['ssid'] = self.ssid
method = getattr(self.api, command)
response = method(**args)
if response and 'status' in response:
if resp... | Make request parse response |
def within_ipv4_network(self, field, values):
"""
This filter adds specified networks to a filter to check
for inclusion.
:param str field: name of field to filter on. Taken from 'Show Filter
Expression' within SMC.
:param list values: network definitions, in... | This filter adds specified networks to a filter to check
for inclusion.
:param str field: name of field to filter on. Taken from 'Show Filter
Expression' within SMC.
:param list values: network definitions, in cidr format, i.e: 1.1.1.0/24. |
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT,
curve=None):
""" Verifies that `sig' is a signature of pubkey `pk' for the
message `s'. """
if isinstance(s, six.text_type):
raise ValueError("Encode `s` to a bytestring yourself to" +
" pre... | Verifies that `sig' is a signature of pubkey `pk' for the
message `s'. |
def factory(feature):
"""
Factory to choose feature extractor
:param feature: name of the feature
:return: Feature extractor function
"""
if feature == 'hog':
return hog
elif feature == 'deep':
return deep
elif feature == 'gray':
return gray
elif feature == '... | Factory to choose feature extractor
:param feature: name of the feature
:return: Feature extractor function |
def clean(self):
""" Run all of the cleaners added by the user. """
if self.cleaners:
yield from asyncio.wait([x() for x in self.cleaners],
loop=self.loop) | Run all of the cleaners added by the user. |
def _pad_block(self, handle):
'''Pad the file with 0s to the end of the next block boundary.'''
extra = handle.tell() % 512
if extra:
handle.write(b'\x00' * (512 - extra)) | Pad the file with 0s to the end of the next block boundary. |
def _load_properties(self):
"""Loads the properties from Flickr."""
self.__loaded = True
method = 'flickr.photos.getInfo'
data = _doget(method, photo_id=self.id)
photo = data.rsp.photo
self.__secret = photo.secret
self.__server = photo.server
... | Loads the properties from Flickr. |
def _get_default_jp2_boxes(self):
"""Create a default set of JP2 boxes."""
# Try to create a reasonable default.
boxes = [JPEG2000SignatureBox(),
FileTypeBox(),
JP2HeaderBox(),
ContiguousCodestreamBox()]
height = self.codestream.segment[... | Create a default set of JP2 boxes. |
def fake2db_initiator(self, number_of_rows, **connection_kwargs):
'''Main handler for the operation
'''
rows = number_of_rows
cursor, conn = self.database_caller_creator(number_of_rows, **connection_kwargs)
self.data_filler_simple_registration(rows, cursor, conn)
self.da... | Main handler for the operation |
def delete_attributes(self, attrs):
"""
Delete just these attributes, not the whole object.
:param attrs: Attributes to save, as a list of string names
:type attrs: list
:return: self
:rtype: :class:`boto.sdb.db.model.Model`
"""
assert(isinstance(attrs, l... | Delete just these attributes, not the whole object.
:param attrs: Attributes to save, as a list of string names
:type attrs: list
:return: self
:rtype: :class:`boto.sdb.db.model.Model` |
def save_results(self, output_dir='.', prefix='', prefix_sep='_',
image_list=None):
""" Write out any images generated by the meta-analysis.
Args:
output_dir (str): folder to write images to
prefix (str): all image files will be prepended with this string
... | Write out any images generated by the meta-analysis.
Args:
output_dir (str): folder to write images to
prefix (str): all image files will be prepended with this string
prefix_sep (str): glue between the prefix and rest of filename
image_list (list): optional list ... |
def login(self, account=None, app_account=None, flush=True):
"""
Log into the connected host using the best method available.
If an account is not given, default to the account that was
used during the last call to login(). If a previous call was not
made, use the account that wa... | Log into the connected host using the best method available.
If an account is not given, default to the account that was
used during the last call to login(). If a previous call was not
made, use the account that was passed to the constructor. If that
also fails, raise a TypeError.
... |
def _require_homogeneous_roots(self, accept_predicate, reject_predicate):
"""Ensures that there is no ambiguity in the context according to the given predicates.
If any targets in the context satisfy the accept_predicate, and no targets satisfy the
reject_predicate, returns the accepted targets.
If no... | Ensures that there is no ambiguity in the context according to the given predicates.
If any targets in the context satisfy the accept_predicate, and no targets satisfy the
reject_predicate, returns the accepted targets.
If no targets satisfy the accept_predicate, returns None.
Otherwise throws TaskEr... |
def create_table(instance,
table_id,
initial_split_keys=None,
column_families=None):
"""
Creates the specified Cloud Bigtable table.
Raises ``google.api_core.exceptions.AlreadyExists`` if the table exists.
:type instance: In... | Creates the specified Cloud Bigtable table.
Raises ``google.api_core.exceptions.AlreadyExists`` if the table exists.
:type instance: Instance
:param instance: The Cloud Bigtable instance that owns the table.
:type table_id: str
:param table_id: The ID of the table to create in C... |
def fetch(self, endpoint=None, page=1, **kwargs):
"""Returns the results of an API call.
This is the main work horse of the class. It builds the API query
string and sends the request to MetaSmoke. If there are multiple
pages of results, and we've configured `max_pages` to b... | Returns the results of an API call.
This is the main work horse of the class. It builds the API query
string and sends the request to MetaSmoke. If there are multiple
pages of results, and we've configured `max_pages` to be greater than
1, it will automatically paginate ... |
def install(self, opener):
# type: (Union[Type[Opener], Opener, Callable[[], Opener]]) -> None
"""Install an opener.
Arguments:
opener (`Opener`): an `Opener` instance, or a callable that
returns an opener instance.
Note:
May be used as a class d... | Install an opener.
Arguments:
opener (`Opener`): an `Opener` instance, or a callable that
returns an opener instance.
Note:
May be used as a class decorator. For example::
registry = Registry()
@registry.install
cl... |
def end_anonymous_session_view(request):
''' End the anonymous session if the user is a superuser. '''
request.session['ANONYMOUS_SESSION'] = False
messages.add_message(request, messages.INFO, MESSAGES['ANONYMOUS_SESSION_ENDED'])
return HttpResponseRedirect(reverse('utilities')) | End the anonymous session if the user is a superuser. |
def get(self, *args, **kwargs):
"""Get the next waiting message from the queue.
:returns: A :class:`Message` instance, or ``None`` if there is
no messages waiting.
"""
if not mqueue.qsize():
return None
message_data, content_type, content_encoding = mque... | Get the next waiting message from the queue.
:returns: A :class:`Message` instance, or ``None`` if there is
no messages waiting. |
def mark_all_as_active(self, recipient=None):
"""Mark current queryset as active(un-deleted).
Optionally, filter by recipient first.
"""
assert_soft_delete()
qset = self.deleted()
if recipient:
qset = qset.filter(recipient=recipient)
return qset.updat... | Mark current queryset as active(un-deleted).
Optionally, filter by recipient first. |
def adj_nodes_aws(aws_nodes):
"""Adjust details specific to AWS."""
for node in aws_nodes:
node.cloud = "aws"
node.cloud_disp = "AWS"
node.private_ips = ip_to_str(node.private_ips)
node.public_ips = ip_to_str(node.public_ips)
node.zone = node.extra['availability']
... | Adjust details specific to AWS. |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return TransType(key)
if key not in TransType._member_map_:
extend_enum(TransType, key, default)
return TransType[key] | Backport support for original codes. |
def main(request, query, hproPk=None, returnMenuOnly=False):
""" Main method called for main page"""
if settings.PIAPI_STANDALONE:
global plugIt, baseURI
# Check if settings are ok
if settings.PIAPI_ORGAMODE and settings.PIAPI_REALUSERS:
return gen404(request, baseURI,
... | Main method called for main page |
def getObjectsAspecting(self, point, aspList):
""" Returns a list of objects aspecting a point
considering a list of possible aspects.
"""
res = []
for obj in self:
if obj.isPlanet() and aspects.isAspecting(obj, point, aspList):
res.append(ob... | Returns a list of objects aspecting a point
considering a list of possible aspects. |
def citedby_url(self):
"""URL to Scopus page listing citing papers."""
cite_link = self.coredata.find('link[@rel="scopus-citedby"]', ns)
try:
return cite_link.get('href')
except AttributeError: # cite_link is None
return None | URL to Scopus page listing citing papers. |
def default_triple(cls, inner_as_primary=True, inner_as_overcontact=False,
starA='starA', starB='starB', starC='starC',
inner='inner', outer='outer',
contact_envelope='contact_envelope'):
"""Load a bundle with a default triple system.
... | Load a bundle with a default triple system.
Set inner_as_primary based on what hierarchical configuration you want.
inner_as_primary = True:
starA - starB -- starC
inner_as_primary = False:
starC -- starA - starB
This is a constructor, so should be called as:
... |
def cast(current: Any, new: str) -> Any:
"""Tries to force a new value into the same type as the current when trying to set the value for a parameter.
:param current: current value for the parameter, type varies
:param new: new value
:return: new value with same type as current, or the current value if... | Tries to force a new value into the same type as the current when trying to set the value for a parameter.
:param current: current value for the parameter, type varies
:param new: new value
:return: new value with same type as current, or the current value if there was an error casting |
def filter_feed(self, updated=False, following=False, folder=False,
filter_folder="", sort="updated", nid=None):
"""Get filtered feed
Only one filter type (updated, following, folder) is possible.
:type nid: str
:param nid: This is the ID of the network to get the ... | Get filtered feed
Only one filter type (updated, following, folder) is possible.
:type nid: str
:param nid: This is the ID of the network to get the feed
from. This is optional and only to override the existing
`network_id` entered when created the class
:type ... |
def parse_numbering(document, xmlcontent):
"""Parse numbering document.
Numbering is defined in file 'numbering.xml'.
"""
numbering = etree.fromstring(xmlcontent)
document.abstruct_numbering = {}
document.numbering = {}
for abstruct_num in numbering.xpath('.//w:abstractNum', namespaces=N... | Parse numbering document.
Numbering is defined in file 'numbering.xml'. |
def cancelOrder(self, orderId):
""" cancel order on IB TWS """
self.ibConn.cancelOrder(orderId)
# update order id for next time
self.requestOrderIds()
return orderId | cancel order on IB TWS |
def operation_file(uploader, cmd, filename=''):
"""File operations"""
if cmd == 'list':
operation_list(uploader)
if cmd == 'do':
for path in filename:
uploader.file_do(path)
elif cmd == 'format':
uploader.file_format()
elif cmd == 'remove':
for path in fil... | File operations |
def add_into(self, other):
"""Return the sum of the two time series accounting for the time stamp.
The other vector will be resized and time shifted wiht sub-sample
precision before adding. This assumes that one can assume zeros
outside of the original vector range.
"""
... | Return the sum of the two time series accounting for the time stamp.
The other vector will be resized and time shifted wiht sub-sample
precision before adding. This assumes that one can assume zeros
outside of the original vector range. |
def map_resnum_a_to_resnum_b(resnums, a_aln, b_aln):
"""Map a residue number in a sequence to the corresponding residue number in an aligned sequence.
Examples:
>>> map_resnum_a_to_resnum_b([1,2,3], '--ABCDEF', 'XXABCDEF')
{1: 3, 2: 4, 3: 5}
>>> map_resnum_a_to_resnum_b(5, '--ABCDEF', 'XXABCDEF')
... | Map a residue number in a sequence to the corresponding residue number in an aligned sequence.
Examples:
>>> map_resnum_a_to_resnum_b([1,2,3], '--ABCDEF', 'XXABCDEF')
{1: 3, 2: 4, 3: 5}
>>> map_resnum_a_to_resnum_b(5, '--ABCDEF', 'XXABCDEF')
{5: 7}
>>> map_resnum_a_to_resnum_b(5, 'ABCDEF', 'ABC... |
def gaussian_pdf(std=10.0, mean=0.0):
"""Gaussian PDF for orientation averaging.
Args:
std: The standard deviation in degrees of the Gaussian PDF
mean: The mean in degrees of the Gaussian PDF. This should be a number
in the interval [0, 180)
Returns:
pdf(x), a function t... | Gaussian PDF for orientation averaging.
Args:
std: The standard deviation in degrees of the Gaussian PDF
mean: The mean in degrees of the Gaussian PDF. This should be a number
in the interval [0, 180)
Returns:
pdf(x), a function that returns the value of the spherical Jacobi... |
def plot_flat(r, c, figsize):
"Shortcut for `enumerate(subplots.flatten())`"
return enumerate(plt.subplots(r, c, figsize=figsize)[1].flatten()) | Shortcut for `enumerate(subplots.flatten())` |
def bellman_ford(graph, weight, source=0):
""" Single source shortest paths by Bellman-Ford
:param graph: directed graph in listlist or listdict format
:param weight: can be negative.
in matrix format or same listdict graph
:returns: distance table, precedence table, bool
:explan... | Single source shortest paths by Bellman-Ford
:param graph: directed graph in listlist or listdict format
:param weight: can be negative.
in matrix format or same listdict graph
:returns: distance table, precedence table, bool
:explanation: bool is True if a negative circuit is
... |
def unhide_dataset(dataset_id,**kwargs):
"""
Hide a particular piece of data so it can only be seen by its owner.
Only an owner can hide (and unhide) data.
Data with no owner cannot be hidden.
The exceptions paramater lists the usernames of those with permission to view the data
... | Hide a particular piece of data so it can only be seen by its owner.
Only an owner can hide (and unhide) data.
Data with no owner cannot be hidden.
The exceptions paramater lists the usernames of those with permission to view the data
read, write and share indicate whether these users c... |
def handle_remove_readonly(func, path, exc):
"""Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion.
:param function func: The caller function
:param str path: The target path ... | Error handler for shutil.rmtree.
Windows source repo folders are read-only by default, so this error handler
attempts to set them as writeable and then proceed with deletion.
:param function func: The caller function
:param str path: The target path for removal
:param Exception exc: The raised exc... |
def TemplateValidator(value):
"""Try to compile a string into a Django template"""
try:
Template(value)
except Exception as e:
raise ValidationError(
_("Cannot compile template (%(exception)s)"),
params={"exception": e}
) | Try to compile a string into a Django template |
def _set_default(path, dest, name):
'''
Set the subvolume as the current default.
'''
subvol_id = __salt__['btrfs.subvolume_show'](path)[name]['subvolume id']
return __salt__['btrfs.subvolume_set_default'](subvol_id, dest) | Set the subvolume as the current default. |
def execute(self, command):
"""Primary method to execute ipmitool commands
:param command: ipmi command to execute, str or list
e.g.
> ipmi = ipmitool('consolename.prod', 'secretpass')
> ipmi.execute('chassis status')
>
"""
if isinstance(command, ... | Primary method to execute ipmitool commands
:param command: ipmi command to execute, str or list
e.g.
> ipmi = ipmitool('consolename.prod', 'secretpass')
> ipmi.execute('chassis status')
> |
def get_sql_for_new_models(apps=None, using=DEFAULT_DB_ALIAS):
"""
Unashamedly copied and tweaked from django.core.management.commands.syncdb
"""
connection = connections[using]
# Get a list of already installed *models* so that references work right.
tables = connection.introspection.table... | Unashamedly copied and tweaked from django.core.management.commands.syncdb |
def read_validate_params(self, request):
"""
Validate the incoming request.
:param request: The incoming :class:`oauth2.web.Request`.
:return: Returns ``True`` if data is valid.
:raises: :class:`oauth2.error.OAuthInvalidError`
"""
self.refresh_token = request.... | Validate the incoming request.
:param request: The incoming :class:`oauth2.web.Request`.
:return: Returns ``True`` if data is valid.
:raises: :class:`oauth2.error.OAuthInvalidError` |
def apply_object(self, config_obj, apply_on=None):
# type: (object, Optional[Tuple[str, ...]]) -> None
"""Apply additional configuration from any Python object
This will look for object attributes that exist in the base_config and apply their values on the current
configuration object
... | Apply additional configuration from any Python object
This will look for object attributes that exist in the base_config and apply their values on the current
configuration object |
def list_as_sub(access_token, subscription_id):
'''List availability sets in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of the list of availability set properties.
... | List availability sets in a subscription.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
Returns:
HTTP response. JSON body of the list of availability set properties. |
def __verify_arguments(self):
"""!
@brief Checks algorithm's arguments and if some of them is incorrect then exception is thrown.
"""
if self.__kmax > len(self.__data):
raise ValueError("K max value '" + str(self.__kmax) + "' is bigger than amount of objects '" +
... | !
@brief Checks algorithm's arguments and if some of them is incorrect then exception is thrown. |
def find_root_thrifts(basedirs, sources, log=None):
"""Finds the root thrift files in the graph formed by sources and their recursive includes.
:basedirs: A set of thrift source file base directories to look for includes in.
:sources: Seed thrift files to examine.
:log: An optional logger.
"""
root_source... | Finds the root thrift files in the graph formed by sources and their recursive includes.
:basedirs: A set of thrift source file base directories to look for includes in.
:sources: Seed thrift files to examine.
:log: An optional logger. |
def parse_player_info(self, player):
"""
Parse a PlayerInfo struct. This arrives before a FileInfo message
"""
if not player.ishltv:
self.player_info[player.name] = {
"user_id": player.userID,
"guid": player.guid,
"bot": player.... | Parse a PlayerInfo struct. This arrives before a FileInfo message |
def DiffPrimitiveArrays(self, oldObj, newObj):
"""Diff two primitive arrays"""
if len(oldObj) != len(newObj):
__Log__.debug('DiffDoArrays: Array lengths do not match %d != %d'
% (len(oldObj), len(newObj)))
return False
match = True
if self._ignoreArrayOrder:
... | Diff two primitive arrays |
def reset( self ):
"""
Resets the colors to the default settings.
"""
dataSet = self.dataSet()
if ( not dataSet ):
dataSet = XScheme()
dataSet.reset() | Resets the colors to the default settings. |
def _get_version():
'''
Get the pkgin version
'''
version_string = __salt__['cmd.run'](
[_check_pkgin(), '-v'],
output_loglevel='trace')
if version_string is None:
# Dunno why it would, but...
return False
version_match = VERSION_MATCH.search(version_string)
... | Get the pkgin version |
def vgdisplay(vgname='', quiet=False):
'''
Return information about the volume group(s)
vgname
volume group name
quiet
if the volume group is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.vgdisplay
salt '*' lvm.vgdisplay n... | Return information about the volume group(s)
vgname
volume group name
quiet
if the volume group is not present, do not show any error
CLI Examples:
.. code-block:: bash
salt '*' lvm.vgdisplay
salt '*' lvm.vgdisplay nova-volumes |
def _process_iq_response(self, stanza):
"""Process IQ stanza of type 'response' or 'error'.
:Parameters:
- `stanza`: the stanza received
:Types:
- `stanza`: `Iq`
If a matching handler is available pass the stanza to it. Otherwise
ignore it if it is "err... | Process IQ stanza of type 'response' or 'error'.
:Parameters:
- `stanza`: the stanza received
:Types:
- `stanza`: `Iq`
If a matching handler is available pass the stanza to it. Otherwise
ignore it if it is "error" or "result" stanza or return
"feature-n... |
def KIC(N, rho, k):
r"""Kullback information criterion
.. math:: KIC(k) = log(\rho_k) + 3 \frac{k+1}{N}
:validation: double checked versus octave.
"""
from numpy import log, array
res = log(rho) + 3. * (k+1.) /float(N)
return res | r"""Kullback information criterion
.. math:: KIC(k) = log(\rho_k) + 3 \frac{k+1}{N}
:validation: double checked versus octave. |
def create(cls, fields=None, **fields_kwargs):
"""
create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also
... | create an instance of cls with the passed in fields and set it into the db
fields -- dict -- field_name keys, with their respective values
**fields_kwargs -- dict -- if you would rather pass in fields as name=val, that works also |
def _ConvertDictToObject(cls, json_dict):
"""Converts a JSON dict into an object.
The dictionary of the JSON serialized objects consists of:
{
'__type__': 'AttributeContainer'
'__container_type__': ...
...
}
Here '__type__' indicates the object base type. In this case
'... | Converts a JSON dict into an object.
The dictionary of the JSON serialized objects consists of:
{
'__type__': 'AttributeContainer'
'__container_type__': ...
...
}
Here '__type__' indicates the object base type. In this case
'AttributeContainer'.
'__container_type__' in... |
def get_diversity(self,X):
"""compute mean diversity of individual outputs"""
# diversity in terms of cosine distances between features
feature_correlations = np.zeros(X.shape[0]-1)
for i in np.arange(1,X.shape[0]-1):
feature_correlations[i] = max(0.0,r2_score(X[0],X[i]))
... | compute mean diversity of individual outputs |
def get_cds_ranges_for_transcript(self, transcript_id):
""" obtain the sequence for a transcript from ensembl
"""
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=cds".format(transcript_id)
r = self.ensembl_re... | obtain the sequence for a transcript from ensembl |
def com_google_fonts_check_metadata_canonical_weight_value(font_metadata):
"""METADATA.pb: Check that font weight has a canonical value."""
first_digit = font_metadata.weight / 100
if (font_metadata.weight % 100) != 0 or \
(first_digit < 1 or first_digit > 9):
yield FAIL, ("METADATA.pb: The weight is decl... | METADATA.pb: Check that font weight has a canonical value. |
def align(args):
"""
%prog align database.fasta read1.fq [read2.fq]
Wrapper for three modes of BWA - mem (default), aln, bwasw (long reads).
"""
valid_modes = ("bwasw", "aln", "mem")
p = OptionParser(align.__doc__)
p.add_option("--mode", default="mem", choices=valid_modes, help="BWA mode")
... | %prog align database.fasta read1.fq [read2.fq]
Wrapper for three modes of BWA - mem (default), aln, bwasw (long reads). |
def tag(self, repository_tag, tags=[]):
"""
Tags image with one or more tags.
Raises exception on failure.
"""
if not isinstance(repository_tag, six.string_types):
raise TypeError('repository_tag must be a string')
if not isinstance(tags, list):
... | Tags image with one or more tags.
Raises exception on failure. |
def show_std_icons():
"""
Show all standard Icons
"""
app = qapplication()
dialog = ShowStdIcons(None)
dialog.show()
sys.exit(app.exec_()) | Show all standard Icons |
def debug(request, message, extra_tags='', fail_silently=False, async=False):
"""Adds a message with the ``DEBUG`` level."""
if ASYNC and async:
messages.debug(_get_user(request), message)
else:
add_message(request, constants.DEBUG, message, extra_tags=extra_tags,
fail_si... | Adds a message with the ``DEBUG`` level. |
def _postrun(cls, span, obj, **kwargs):
""" Trigger to execute just before closing the span
:param opentracing.span.Span span: the SpanContext instance
:param Any obj: Object to use as context
:param dict kwargs: additional data
"""
span.set_tag("response.status_code", ... | Trigger to execute just before closing the span
:param opentracing.span.Span span: the SpanContext instance
:param Any obj: Object to use as context
:param dict kwargs: additional data |
def reports(self):
"""returns a list of reports on the server"""
if self._metrics is None:
self.__init()
self._reports = []
for r in self._metrics:
url = self._url + "/%s" % six.moves.urllib.parse.quote_plus(r['reportname'])
self._reports.append(UsageR... | returns a list of reports on the server |
def get_manifest_selfLink(self, repo_name, digest=None):
''' get a selfLink for the manifest, for use by the client get_manifest
function, along with the parents pull
Parameters
==========
repo_name: reference to the <username>/<repository>:<tag> to obtain
digest: a tag or shas... | get a selfLink for the manifest, for use by the client get_manifest
function, along with the parents pull
Parameters
==========
repo_name: reference to the <username>/<repository>:<tag> to obtain
digest: a tag or shasum version |
def _cond_x(self, word, suffix_len):
"""Return Lovins' condition X.
Parameters
----------
word : str
Word to check
suffix_len : int
Suffix length
Returns
-------
bool
True if condition is met
"""
retur... | Return Lovins' condition X.
Parameters
----------
word : str
Word to check
suffix_len : int
Suffix length
Returns
-------
bool
True if condition is met |
def rings_full_data(self):
""" Returns a generator for iterating over each ring
Yields
------
For each ring, tuple composed by ring ID, list of edges, list of nodes
Notes
-----
Circuit breakers must be closed to find rings, this is done automatically.
... | Returns a generator for iterating over each ring
Yields
------
For each ring, tuple composed by ring ID, list of edges, list of nodes
Notes
-----
Circuit breakers must be closed to find rings, this is done automatically. |
def wait_for_redfish_firmware_update_to_complete(self, redfish_object):
"""Continuously polls for iLO firmware update to complete.
:param redfish_object: redfish instance
"""
p_state = ['Idle']
c_state = ['Idle']
def has_firmware_flash_completed():
"""Checks... | Continuously polls for iLO firmware update to complete.
:param redfish_object: redfish instance |
def subpoint(self):
"""Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
... | Return the latitude and longitude directly beneath this position.
Returns a :class:`~skyfield.toposlib.Topos` whose ``longitude``
and ``latitude`` are those of the point on the Earth's surface
directly beneath this position, and whose ``elevation`` is the
height of this position above t... |
def breakLines(self, width):
"""
Returns a broken line structure. There are two cases
A) For the simple case of a single formatting input fragment the output is
A fragment specifier with
- kind = 0
- fontName, fontSize, leading, textColor
... | Returns a broken line structure. There are two cases
A) For the simple case of a single formatting input fragment the output is
A fragment specifier with
- kind = 0
- fontName, fontSize, leading, textColor
- lines= A list of lines
... |
def Operate(self, values):
"""Takes a list of values and if at least one matches, returns True."""
for val in values:
try:
if self.Operation(val, self.right_operand):
return True
except (TypeError, ValueError):
pass
return False | Takes a list of values and if at least one matches, returns True. |
def read(self):
""" Reads the whole las data (header, vlrs ,points, etc) and returns a LasData
object
"""
vlrs = self.read_vlrs()
self._warn_if_not_at_expected_pos(
self.header.offset_to_point_data, "end of vlrs", "start of points"
)
self.stream.seek(s... | Reads the whole las data (header, vlrs ,points, etc) and returns a LasData
object |
def SaveAvatarToFile(self, Filename, AvatarId=1):
"""Saves user avatar to a file.
:Parameters:
Filename : str
Destination path.
AvatarId : int
Avatar Id.
"""
s = 'USER %s AVATAR %s %s' % (self.Handle, AvatarId, path2unicode(Filename))
... | Saves user avatar to a file.
:Parameters:
Filename : str
Destination path.
AvatarId : int
Avatar Id. |
def optimize(image, fmt='jpeg', quality=80):
"""
Optimize the image if the IMAGE_OPTIMIZATION_CMD is set.
IMAGE_OPTIMIZATION_CMD must accept piped input
"""
from io import BytesIO
if IMAGE_OPTIMIZATION_CMD and is_tool(IMAGE_OPTIMIZATION_CMD):
image_buffer = BytesIO()
image.save... | Optimize the image if the IMAGE_OPTIMIZATION_CMD is set.
IMAGE_OPTIMIZATION_CMD must accept piped input |
async def _on_heartbeat(self, update):
"""Receive a new heartbeat for a service."""
name = update['service']
if name not in self.services:
return
with self._state_lock:
self.services[name].heartbeat() | Receive a new heartbeat for a service. |
def parse_csv(file_path: str,
entrez_id_header,
log_fold_change_header,
adjusted_p_value_header,
entrez_delimiter,
base_mean_header=None,
sep=",") -> List[Gene]:
"""Read a csv file on differential expression values as Gene objects.
... | Read a csv file on differential expression values as Gene objects.
:param str file_path: The path to the differential expression file to be parsed.
:param config.Params params: An object that includes paths, cutoffs and other information.
:return list: A list of Gene objects. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.