text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _expectation(p, mean, none1, none2, none3, nghp=None):
"""
Compute the expectation:
<m(X)>_p(X)
- m(x) :: Linear, Identity or Constant mean function
:return: NxQ
"""
return mean(p.mu) | 0.004545 |
def is_valid_regex(string):
"""
Checks whether the re module can compile the given regular expression.
Parameters
----------
string: str
Returns
-------
boolean
"""
try:
re.compile(string)
is_valid = True
except re.error:
is_valid = False
return ... | 0.003049 |
def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
"""Test if a matrix is positive semidefinite"""
if atol is None:
atol = ATOL_DEFAULT
if rtol is None:
rtol = RTOL_DEFAULT
if not is_hermitian_matrix(mat, rtol=rtol, atol=atol):
return False
# Chec... | 0.002141 |
def format_value(column_dict, value, key=None):
"""
Format a value coming from the database (for example converts datetimes to
strings)
:param column_dict: The column datas collected during inspection
:param value: A value coming from the database
:param key: The exportation key
"""
for... | 0.001168 |
def reload(self, d=None):
"""Reload model from given dict or database."""
if d:
self.clear()
self.update(d)
elif self.id:
new_dict = self.by_id(self._id)
self.clear()
self.update(new_dict)
else:
# should I raise an e... | 0.005013 |
def unstash(self):
"""
Pops the last stash if EPAB made a stash before
"""
if not self.stashed:
LOGGER.error('no stash')
else:
LOGGER.info('popping stash')
self.repo.git.stash('pop')
self.stashed = False | 0.006873 |
def execute(self, input_data):
# Spin up SWF class
swf = SWF()
# Get the raw_bytes
raw_bytes = input_data['sample']['raw_bytes']
# Parse it
swf.parse(StringIO(raw_bytes))
# Header info
head = swf.header
output = {'versio... | 0.016653 |
def int_to_bytes(i, minlen=1, order='big'): # pragma: no cover
"""convert integer to bytes"""
blen = max(minlen, PGPObject.int_byte_len(i), 1)
if six.PY2:
r = iter(_ * 8 for _ in (range(blen) if order == 'little' else range(blen - 1, -1, -1)))
return bytes(bytearray((i ... | 0.007792 |
def dumped(text, level, indent=2):
"""Put curly brackets round an indented text"""
return indented("{\n%s\n}" % indented(text, level + 1, indent) or "None", level, indent) + "\n" | 0.010753 |
def getObject(self, url_or_requests_response, params=None):
'Take a url or some xml response from JottaCloud and wrap it up with the corresponding JFS* class'
if isinstance(url_or_requests_response, requests.models.Response):
# this is a raw xml response that we need to parse
url... | 0.009519 |
def _check_copy_conditions(self, src, dst):
# type: (SyncCopy, blobxfer.models.azure.StorageEntity,
# blobxfer.models.azure.StorageEntity) -> UploadAction
"""Check for synccopy conditions
:param SyncCopy self: this
:param blobxfer.models.azure.StorageEntity src: src
... | 0.001966 |
def splitext(path):
"""splitext for paths with directories that may contain dots.
From https://stackoverflow.com/questions/5930036/separating-file-extensions-using-python-os-path-module"""
li = []
path_without_extensions = os.path.join(os.path.dirname(path),
os.path.basename(path).split(os.extse... | 0.007055 |
def add_custom_func(self, func, dim, *args, **kwargs):
""" adds a user defined function to extract features
Parameters
----------
func : function
a user-defined function, which accepts mdtraj.Trajectory object as
first parameter and as many optional and named arg... | 0.005632 |
def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields):
"""
Changes a given `changed_fields` on object, saves it and returns changed object.
"""
from chamber.models import SmartModel
change(obj, **changed_fields)
if update_only_changed_fields and not isin... | 0.006319 |
def save_data(self, session, exp_id, content):
'''save data will obtain the current subid from the session, and save it
depending on the database type. Currently we just support flat files'''
subid = session.get('subid')
# We only attempt save if there is a subject id, set at start
data_file = ... | 0.005738 |
def should_bypass_proxies(url):
"""
Returns whether we should bypass proxies or not.
"""
get_proxy = lambda k: os.environ.get(k) or os.environ.get(k.upper())
# First check whether no_proxy is defined. If it is, check that the URL
# we're getting isn't in the no_proxy list.
no_proxy = get_pr... | 0.00243 |
def setTextEdit( self, textEdit ):
"""
Sets the text edit that this find widget will use to search.
:param textEdit | <QTextEdit>
"""
if ( self._textEdit ):
self._textEdit.removeAction(self._findAction)
self._textEdit = text... | 0.025 |
def prepare(self, node):
'''Gather analysis result required by this analysis'''
if isinstance(node, ast.Module):
self.ctx.module = node
elif isinstance(node, ast.FunctionDef):
self.ctx.function = node
for D in self.deps:
d = D()
d.attach(s... | 0.004608 |
def from_points(lons, lats):
"""
Compute the BoundingBox from a set of latitudes and longitudes
:param lons: longitudes
:param lats: latitudes
:return: BoundingBox
"""
north, west = max(lats), min(lons)
south, east = min(lats), max(lons)
return Bo... | 0.005305 |
def is_pathlike(value, **kwargs):
"""Indicate whether ``value`` is a path-like object.
:param value: The value to evaluate.
:returns: ``True`` if ``value`` is valid, ``False`` if it is not.
:rtype: :class:`bool <python:bool>`
:raises SyntaxError: if ``kwargs`` contains duplicate keyword parameter... | 0.003478 |
def create_document_dictionary(self, document, document_key=None,
owner_document=None):
"""
Given document generates a dictionary representation of the document.
Includes the widget for each for each field in the document.
"""
... | 0.004658 |
def calc_columns_rows(n):
"""
Calculate the number of columns and rows required to divide an image
into ``n`` parts.
Return a tuple of integers in the format (num_columns, num_rows)
"""
num_columns = int(ceil(sqrt(n)))
num_rows = int(ceil(n / float(num_columns)))
return (num_columns, nu... | 0.003058 |
def reassemble_options(payload):
'''
Reassemble partial options to options, returns a list of dhcp_option
DHCP options are basically `|tag|length|value|` structure. When an
option is longer than 255 bytes, it can be splitted into multiple
structures with the same tag. The splitted structures mu... | 0.004577 |
def QA_indicator_DMA(DataFrame, M1=10, M2=50, M3=10):
"""
平均线差 DMA
"""
CLOSE = DataFrame.close
DDD = MA(CLOSE, M1) - MA(CLOSE, M2)
AMA = MA(DDD, M3)
return pd.DataFrame({
'DDD': DDD, 'AMA': AMA
}) | 0.004237 |
def json_validate(schema, resp):
"""
Validate an RPC response.
The response must either take the
form of the given schema, or it must
take the form of {'error': ...}
Returns the resp on success
Returns {'error': ...} on validation error
"""
# is this an error?
try:
json_... | 0.004566 |
def domain_relationship(self):
"""
Returns a domain relationship equivalent with this resource
relationship.
"""
if self.__domain_relationship is None:
ent = self.relator.get_entity()
self.__domain_relationship = \
self.descriptor.make_... | 0.007916 |
def wrap_objective(f, *args, **kwds):
"""Decorator for creating Objective factories.
Changes f from the closure: (args) => () => TF Tensor
into an Obejective factory: (args) => Objective
while perserving function name, arg info, docs... for interactive python.
"""
objective_func = f(*args, **kwds)
objec... | 0.013208 |
def _parseIsComment(self):
"""
Detect whether the element is HTML comment or not.
Result is saved to the :attr:`_iscomment` property.
"""
self._iscomment = (
self._element.startswith("<!--") and self._element.endswith("-->")
) | 0.006969 |
async def connect(self):
"""Create connection pool asynchronously.
"""
self.pool = await aiomysql.create_pool(
loop=self.loop,
db=self.database,
connect_timeout=self.timeout,
**self.connect_params) | 0.007435 |
def new(
name: str,
arity: Arity,
class_name: str=None,
*,
associative: bool=False,
commutative: bool=False,
one_identity: bool=False,
infix: bool=False
) -> Type['Operation']:
"""Utility method to create a new o... | 0.009183 |
def get_explorer_pid(self):
"""
Tries to find the process ID for "explorer.exe".
@rtype: int or None
@return: Returns the process ID, or C{None} on error.
"""
try:
exp = win32.SHGetFolderPath(win32.CSIDL_WINDOWS)
except Exception:
exp = N... | 0.0033 |
def getChemicalPotential(self, solution):
"""Call solver in order to calculate chemical potential.
"""
if isinstance(solution, Solution):
solution = solution.getSolution()
self.mu = self.solver.chemicalPotential(solution)
return self.mu | 0.00692 |
def get_hosts_retriever(s=None):
"""
Given the function name, looks up the method for dynamically retrieving host data.
"""
s = s or env.hosts_retriever
# #assert s, 'No hosts retriever specified.'
if not s:
return env_hosts_retriever
# module_name = '.'.join(s.split('.')[:-1])
# ... | 0.004 |
def longest_increasing_subsequence(xs):
'''Return a longest increasing subsequence of xs.
(Note that there may be more than one such subsequence.)
>>> longest_increasing_subsequence(range(3))
[0, 1, 2]
>>> longest_increasing_subsequence([3, 1, 2, 0])
[1, 2]
'''
# Patience sort xs, stack... | 0.001035 |
def format(self, full_info: bool = False):
"""
:param full_info: If True, adds more info about the chat. Please, note that this additional info requires
to make up to THREE synchronous api calls.
"""
chat = self.api_object
if full_info:
self.__format_full(... | 0.007937 |
def use(plugin):
"""
Register plugin in grappa.
`plugin` argument can be a function or a object that implement `register`
method, which should accept one argument: `grappa.Engine` instance.
Arguments:
plugin (function|module): grappa plugin object to register.
Raises:
ValueErr... | 0.001117 |
def update_record(self, common_name, **fields):
"""Update fields in an existing record"""
record = self.get_record(common_name)
if fields is not None:
for field, value in fields:
record[field] = value
self.save()
return record | 0.00678 |
def parse_authorization_header(value, charset='utf-8'):
'''Parse an HTTP basic/digest authorisation header.
:param value: the authorisation header to parse.
:return: either `None` if the header was invalid or
not given, otherwise an :class:`Auth` object.
'''
if not value:
return
... | 0.001094 |
def solvemdbi_cg(ah, rho, b, axisM, axisK, tol=1e-5, mit=1000, isn=None):
r"""
Solve a multiple diagonal block linear system with a scaled
identity term using Conjugate Gradient (CG) via
:func:`scipy.sparse.linalg.cg`.
The solution is obtained by independently solving a set of linear
systems of... | 0.002655 |
def _populate_reporting_tab(self):
"""Populate trees about layers."""
self.tree.clear()
self.add_layer.setEnabled(False)
self.remove_layer.setEnabled(False)
self.move_up.setEnabled(False)
self.move_down.setEnabled(False)
self.tree.setColumnCount(1)
self.tr... | 0.000762 |
def helical_turbulent_fd_Srinivasan(Re, Di, Dc):
r'''Calculates Darcy friction factor for a fluid flowing inside a curved
pipe such as a helical coil under turbulent conditions, using the method of
Srinivasan [1]_, as shown in [2]_ and [3]_.
.. math::
f_d = \frac{0.336}{{\left[Re\sqrt{\fr... | 0.004553 |
def deregisterevent(self, event_name):
"""
Remove callback of registered event
@param event_name: Event name in at-spi format.
@type event_name: string
@return: 1 if registration was successful, 0 if not.
@rtype: integer
"""
if event_name in self._pollE... | 0.004474 |
def topics(self):
"""获取问题所属话题.
:return: 问题所属话题
:rtype: Topic.Iterable
"""
from .topic import Topic
for topic in self.soup.find_all('a', class_='zm-item-tag'):
yield Topic(Zhihu_URL + topic['href'], topic.text.replace('\n', ''),
sessio... | 0.008929 |
def _codes_to_ints(self, codes):
"""
Transform combination(s) of uint64 in one uint64 (each), in a strictly
monotonic way (i.e. respecting the lexicographic order of integer
combinations): see BaseMultiIndexCodesEngine documentation.
Parameters
----------
codes :... | 0.001818 |
def keywords_special_characters(keywords):
"""
Confirms that the keywords don't contain special characters
Args:
keywords (str)
Raises:
django.forms.ValidationError
"""
invalid_chars = '!\"#$%&\'()*+-./:;<=>?@[\\]^_{|}~\t\n'
if any(char in invalid_chars for char in keywords... | 0.002611 |
def get_es(**overrides):
"""Return a elasticsearch Elasticsearch object using settings
from ``settings.py``.
:arg overrides: Allows you to override defaults to create the
ElasticSearch object. You can override any of the arguments
isted in :py:func:`elasticutils.get_es`.
For example, i... | 0.001353 |
def validate_txn_obj(obj_name, obj, key, validation_fun):
"""Validate value of `key` in `obj` using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
key (str): key to be validated in `obj`.
validation_fun ... | 0.001119 |
def prune(self):
"""Removes the node and all descendents without looping back past the
root. Note this does not remove the associated data objects.
:returns:
list of :class:`BaseDataNode` subclassers associated with the
removed ``Node`` objects.
"""
targ... | 0.002594 |
def file_object_supports_binary(fp):
# type: (BinaryIO) -> bool
'''
A function to check whether a file-like object supports binary mode.
Parameters:
fp - The file-like object to check for binary mode support.
Returns:
True if the file-like object supports binary mode, False otherwise.
... | 0.003236 |
def check_cmake_exists(cmake_command):
"""
Check whether CMake is installed. If not, print
informative error message and quits.
"""
from subprocess import Popen, PIPE
p = Popen(
'{0} --version'.format(cmake_command),
shell=True,
stdin=PIPE,
stdout=PIPE)
if no... | 0.001299 |
def decompress_messages(self, partitions_offmsgs):
""" Decompress pre-defined compressed fields for each message. """
for pomsg in partitions_offmsgs:
if pomsg['message']:
pomsg['message'] = self.decompress_fun(pomsg['message'])
yield pomsg | 0.006734 |
def update_log_entry(self, log_entry_form):
"""Updates an existing log entry.
arg: log_entry_form (osid.logging.LogEntryForm): the form
containing the elements to be updated
raise: IllegalState - ``log_entry_form`` already used in an
update transaction
... | 0.004215 |
def absent(name, auth=None, **kwargs):
'''
Ensure a network does not exists
name
Name of the network
'''
ret = {'name': name,
'changes': {},
'result': True,
'comment': ''}
kwargs = __utils__['args.clean_kwargs'](**kwargs)
__salt__['neutronng.setup... | 0.001256 |
def logsignalrate(self, s0, s1, slide, step):
"""Calculate the normalized log rate density of signals via lookup"""
td = numpy.array(s0['end_time'] - s1['end_time'] - slide*step, ndmin=1)
pd = numpy.array((s0['coa_phase'] - s1['coa_phase']) % \
(2. * numpy.pi), ndmin=1)
... | 0.001907 |
def SNNL(x, y, temp, cos_distance):
"""Soft Nearest Neighbor Loss
:param x: a matrix.
:param y: a list of labels for each element of x.
:param temp: Temperature.
:cos_distance: Boolean for using cosine or Euclidean distance.
:returns: A tensor for the Soft Nearest Neighbor Loss of the points
... | 0.001709 |
def load_data(filename):
"""Loads data from a file.
Parameters
----------
filename : :obj:`str`
The file to load the collection from.
Returns
-------
:obj:`numpy.ndarray` of float
The data read from the file.
Raises
-----... | 0.005319 |
def compare_operands(self, p_operand1, p_operand2):
"""
Returns True if conditional constructed from both operands and
self.operator is valid. Returns False otherwise.
"""
if self.operator == '<':
return p_operand1 < p_operand2
elif self.operator == '<=':
... | 0.002869 |
def entropy_calc(item, POP):
"""
Calculate reference and response likelihood.
:param item : TOP or P
:type item : dict
:param POP: population
:type POP : dict
:return: reference or response likelihood as float
"""
try:
result = 0
for i in item.keys():
lik... | 0.001969 |
def _ResolveRelativeImport(name, package):
"""Resolves a relative import into an absolute path.
This is mostly an adapted version of the logic found in the backported
version of import_module in Python 2.7.
https://github.com/python/cpython/blob/2.7/Lib/importlib/__init__.py
Args:
name: relative name im... | 0.006417 |
def run(self, args):
"""
Give the user with user_full_name the auth_role permissions on the remote project with project_name.
:param args Namespace arguments parsed from the command line
"""
email = args.email # email of person to give permissions, will be None i... | 0.008762 |
def pv_present(name, **kwargs):
'''
Set a Physical Device to be used as an LVM Physical Volume
name
The device name to initialize.
kwargs
Any supported options to pvcreate. See
:mod:`linux_lvm <salt.modules.linux_lvm>` for more details.
'''
ret = {'changes': {},
... | 0.002849 |
def find_module_defining_flag(self, flagname, default=None):
"""Return the name of the module defining this flag, or default.
Args:
flagname: str, name of the flag to lookup.
default: Value to return if flagname is not defined. Defaults
to None.
Returns:
The name of the module ... | 0.004808 |
def nullity_sort(df, sort=None):
"""
Sorts a DataFrame according to its nullity, in either ascending or descending order.
:param df: The DataFrame object being sorted.
:param sort: The sorting method: either "ascending", "descending", or None (default).
:return: The nullity-sorted DataFrame.
""... | 0.00713 |
def _set_fcoe_fsb(self, v, load=False):
"""
Setter method for fcoe_fsb, mapped from YANG variable /fcoe_fsb (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_fsb is considered as a private
method. Backends looking to populate this variable should
d... | 0.00494 |
def _set_redist_connected(self, v, load=False):
"""
Setter method for redist_connected, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v6/redist_connected (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_redist_connected is consider... | 0.005482 |
def available_providers(request):
"Adds the list of enabled providers to the context."
if APPENGINE:
# Note: AppEngine inequality queries are limited to one property.
# See https://developers.google.com/appengine/docs/python/datastore/queries#Python_Restrictions_on_queries
# Users have a... | 0.004418 |
def Write(packer_type, buf, head, n):
""" Write encodes `n` at buf[head] using `packer_type`. """
packer_type.pack_into(buf, head, n) | 0.007092 |
def to_hmtk(self, use_centroid=True):
'''
Convert the content of the GCMT catalogue to a HMTK
catalogue.
'''
self._preallocate_data_dict()
for iloc, gcmt in enumerate(self.catalogue.gcmts):
self.catalogue.data['eventID'][iloc] = iloc
if use_centro... | 0.000471 |
def remove_completer(self):
"""
Removes current completer.
:return: Method success.
:rtype: bool
"""
if self.__completer:
LOGGER.debug("> Removing '{0}' completer.".format(self.__completer))
# Signals / Slots.
self.__completer.activat... | 0.006536 |
def _get_unique_index(self, dropna=False):
"""
Returns an index containing unique values.
Parameters
----------
dropna : bool
If True, NaN values are dropped.
Returns
-------
uniques : index
"""
if self.is_unique and not dropn... | 0.002994 |
def _read_socket(socket):
"""
The stdout and stderr data from the container multiplexed into one stream of response from the Docker API.
It follows the protocol described here https://docs.docker.com/engine/api/v1.30/#operation/ContainerAttach.
The stream starts with a 8 byte header that contains the fr... | 0.005338 |
def as_dict(self, default=None):
"""
Returns a ``SettingDict`` object for this queryset.
"""
settings = SettingDict(queryset=self, default=default)
return settings | 0.009852 |
def _collapse_to_cwl_record_single(data, want_attrs, input_files):
"""Convert a single sample into a CWL record.
"""
out = {}
for key in want_attrs:
key_parts = key.split("__")
out[key] = _to_cwl(tz.get_in(key_parts, data), input_files)
return out | 0.003534 |
def adapt_package(package):
"""Adapts ``.epub.Package`` to a ``BinderItem`` and cascades
the adaptation downward to ``DocumentItem``
and ``ResourceItem``.
The results of this process provide the same interface as
``.models.Binder``, ``.models.Document`` and ``.models.Resource``.
"""
navigati... | 0.001988 |
def update_metadata(self, key, value):
"""Set *key* in the metadata to *value*.
Returns the previous value of *key*, or None if the key was
not previously set.
"""
old_value = self.contents['metadata'].get(key)
self.contents['metadata'][key] = value
self._log('Up... | 0.005222 |
def get_logw(ns_run, simulate=False):
r"""Calculates the log posterior weights of the samples (using logarithms
to avoid overflow errors with very large or small values).
Uses the trapezium rule such that the weight of point i is
.. math:: w_i = \mathcal{L}_i (X_{i-1} - X_{i+1}) / 2
Parameters
... | 0.000517 |
def granule_paths(self, band_id):
"""Return the path of all granules of a given band."""
band_id = str(band_id).zfill(2)
try:
assert isinstance(band_id, str)
assert band_id in BAND_IDS
except AssertionError:
raise AttributeError(
"band ... | 0.004202 |
def change_term_title(title):
"""
only works on unix systems only tested on Ubuntu GNOME changes text on
terminal title for identifying debugging tasks.
The title will remain until python exists
Args:
title (str):
References:
http://stackoverflow.com/questions/5343265/setting-... | 0.004188 |
def _process_observations(base_env, policies, batch_builder_pool,
active_episodes, unfiltered_obs, rewards, dones,
infos, off_policy_actions, horizon, preprocessors,
obs_filters, unroll_length, pack, callbacks,
soft_... | 0.000124 |
def use_with(data, fn, *attrs):
"""Apply a function on the attributes of the data
:param data: an object
:param fn: a function
:param attrs: some attributes of the object
:returns: an object
Let's create some data first::
>>> from collections import namedtuple
>>> Person = nam... | 0.001534 |
def _image_data(self):
"""Returns the data in image format, with scaling and conversion to uint8 types.
Returns
-------
:obj:`numpy.ndarray` of uint8
A 3D matrix representing the image. The first dimension is rows, the
second is columns, and the third is simply t... | 0.012793 |
def num_rows(self):
"""
Returns the number of rows.
Returns
-------
out : int
Number of rows in the SFrame.
"""
if self._is_vertex_frame():
return self.__graph__.summary()['num_vertices']
elif self._is_edge_frame():
ret... | 0.00554 |
def RLS_SDR(anchors, W, r, print_out=False):
""" Range least squares (RLS) using SDR.
Algorithm cited by A.Beck, P.Stoica in "Approximate and Exact solutions of Source Localization Problems".
:param anchors: anchor points
:param r2: squared distances from anchors to point x.
:return: estimated po... | 0.001892 |
def make_statement(self, action, mention):
"""Makes an INDRA statement from a Geneways action and action mention.
Parameters
----------
action : GenewaysAction
The mechanism that the Geneways mention maps to. Note that
several text mentions can correspond to the ... | 0.000616 |
def uses_base_tear_down(cls):
"""Checks whether the tearDown method is the BasePlug implementation."""
this_tear_down = getattr(cls, 'tearDown')
base_tear_down = getattr(BasePlug, 'tearDown')
return this_tear_down.__code__ is base_tear_down.__code__ | 0.003774 |
def _variance_scale_term(self):
"""Helper to `_covariance` and `_variance` which computes a shared scale."""
# Expand back the last dim so the shape of _variance_scale_term matches the
# shape of self.concentration.
c0 = self.total_concentration[..., tf.newaxis]
return tf.sqrt((1. + c0 / self.total_... | 0.005618 |
def statsd_middleware_factory(app, handler):
"""Send the application stats to statsd."""
@coroutine
def middleware(request):
"""Send stats to statsd."""
timer = Timer()
timer.start()
statsd = yield from app.ps.metrics.client()
pipe = statsd.pipe()
pipe.incr('... | 0.001156 |
def get_tag(self, tagtype):
''' Get the first tag of a particular type'''
for tag in self.__tags:
if tag.tagtype == tagtype:
return tag
return None | 0.01005 |
def example_repl(self, text, example, start_index, continue_flag):
""" REPL for interactive tutorials """
if start_index:
start_index = start_index + 1
cmd = ' '.join(text.split()[:start_index])
example_cli = CommandLineInterface(
application=self.crea... | 0.001846 |
def get_localzone():
"""Returns the zoneinfo-based tzinfo object that matches the Windows-configured timezone."""
global _cache_tz
if _cache_tz is None:
_cache_tz = pytz.timezone(get_localzone_name())
utils.assert_tz_offset(_cache_tz)
return _cache_tz | 0.007143 |
def get_group(name: str) -> _Group:
"""
Get a configuration variable group named |name|
"""
global _groups
if name in _groups:
return _groups[name]
group = _Group(name)
_groups[name] = group
return group | 0.004065 |
def _linux_disks():
'''
Return list of disk devices and work out if they are SSD or HDD.
'''
ret = {'disks': [], 'SSDs': []}
for entry in glob.glob('/sys/block/*/queue/rotational'):
try:
with salt.utils.files.fopen(entry) as entry_fp:
device = entry.split('/')[3]... | 0.002132 |
def mofval(value, indent=MOF_INDENT, maxline=MAX_MOF_LINE, line_pos=0,
end_space=0):
"""
Low level function that returns the MOF representation of a non-string
value (i.e. a value that cannot not be split into multiple parts, for
example a numeric or boolean value).
If the MOF representa... | 0.000549 |
def getResourceTypes(self):
""" Get the list of resource types supported by the HydroShare server
:return: A set of strings representing the HydroShare resource types
:raises: HydroShareHTTPException to signal an HTTP error
"""
url = "{url_base}/resource/types".format(url_base=... | 0.003466 |
def run_command(self, cmd, history=True, new_prompt=True):
"""Run command in interpreter"""
if not cmd:
cmd = ''
else:
if history:
self.add_to_history(cmd)
if not self.multithreaded:
if 'input' not in cmd:
self.... | 0.002237 |
def create_connection(self, from_obj, to_obj):
"""
Creates and returns a connection between the given objects. If a
connection already exists, that connection will be returned instead.
"""
self._validate_ctypes(from_obj, to_obj)
return Connection.objects.get_or_create(rel... | 0.006912 |
def return_train_dataset(self):
"""Returns train data set
Returns:
X (numpy.ndarray): Features
y (numpy.ndarray): Labels
"""
X, y = self.return_main_dataset()
if self.test_dataset['method'] == 'split_from_main':
X, X_test, y, y_test = train_... | 0.003617 |
def transform(self, image_feature, bigdl_type="float"):
"""
transform ImageFeature
"""
callBigDlFunc(bigdl_type, "transformImageFeature", self.value, image_feature)
return image_feature | 0.013333 |
def list_handler(HandlerResult="nparray"):
"""Wraps a function to handle list inputs."""
def decorate(func):
def wrapper(*args, **kwargs):
"""Run through the wrapped function once for each array element.
:param HandlerResult: output type. Defaults to numpy arrays.
""... | 0.008477 |
def copymode(src, dst):
"""Copy mode bits from src to dst"""
if hasattr(os, 'chmod'):
st = os.stat(src)
mode = stat.S_IMODE(st.st_mode)
os.chmod(dst, mode) | 0.005348 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.