text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def sprinter(self):
"""
Called when parallelize is True.
This function will generate the file names in a directory tree by adding directories to a Queue and
continuously exploring directories in the Queue until Queue is emptied.
Significantly faster than crawler method for larger... | 0.0037 |
def texture_array(self, size, components, data=None, *, alignment=1, dtype='f1') -> 'TextureArray':
'''
Create a :py:class:`TextureArray` object.
Args:
size (tuple): The ``(width, height, layers)`` of the texture.
components (int): The number of component... | 0.004926 |
def add_event_handler(self, action):
"""Add a event handler into actions list
:param action: event handler to add
:type action: alignak.eventhandler.EventHandler
:return: None
"""
if action.uuid in self.actions:
logger.info("Already existing event handler: %s... | 0.004662 |
def load_hdf(cls, filename, path='', ic=None):
"""
Loads stored ObservationTree from file.
You can provide the isochrone to use; or it will default to MIST
TODO: saving and loading must be fixed! save ic type, bands, etc.
"""
store = pd.HDFStore(filename)
try:
... | 0.003836 |
def __select_autocomplete_identities(self, sources):
"""Select the identities used for autocompleting"""
MIN_PRIORITY = 99999999
checked = {}
for source in sources:
uids = api.unique_identities(self.db, source=source)
for uid in uids:
if uid.uu... | 0.001738 |
def clear_last_check(self):
"""Clear the checksum of the file."""
with db.session.begin_nested():
self.last_check = None
self.last_check_at = datetime.utcnow()
return self | 0.009132 |
def initialize(
self, config_file: str = "bmi_config.txt", initialize_indicators=True
):
""" Initialize the executable AnalysisGraph with a config file.
Args:
config_file
Returns:
AnalysisGraph
"""
self.t = 0.0
if not os.path.isfile(c... | 0.002366 |
def collate(self, graph):
"""
:type graph: VariantGraph
"""
# prepare the token index
self.token_index.prepare()
self.vertex_array = [None] * len(self.token_index.token_array)
# Build the variant graph for the first witness
# this is easy: generate a vert... | 0.004202 |
def delete_event_ticket_class(self, id, ticket_class_id, **data):
"""
DELETE /events/:id/ticket_classes/:ticket_class_id/
Deletes the ticket class. Returns ``{"deleted": true}``.
"""
return self.delete("/events/{0}/ticket_classes/{0}/".format(id,ticket_class_id), data=da... | 0.01548 |
def m_b(mbmb, scale, f, alphasMZ=0.1185, loop=3):
r"""Get running b quark mass in the MSbar scheme at the scale `scale`
in the theory with `f` dynamical quark flavours starting from $m_b(m_b)$"""
if scale == mbmb and f == 5:
return mbmb # nothing to do
_sane(scale, f)
alphas_mb = alpha_s(mb... | 0.000734 |
def _get_pwned(prefix):
"""
Fetches a dict of all hash suffixes from Pwned Passwords for a
given SHA-1 prefix.
"""
try:
response = requests.get(
url=API_ENDPOINT.format(prefix),
headers={'User-Agent': USER_AGENT},
timeout=getattr(
settings... | 0.001157 |
def save(self, *args):
""" Save cache to file using pickle.
Parameters
----------
*args:
All but the last argument are inputs to the cached function. The
last is the actual value of the function.
"""
with open(self.file_root + '.pkl', "wb") as f:
... | 0.005181 |
def find_repositories_by_walking_and_following_symlinks(path):
"""Walk a tree and return a sequence of (directory, dotdir) pairs."""
repos = []
# This is for detecting symlink loops and escaping them. This is similar to
# http://stackoverflow.com/questions/36977259/avoiding-infinite-recursion-with-os-w... | 0.002326 |
def filter_image_sep2d(image, fh, fv, impl='numpy', padding=None):
"""Filter an image with a separable filter.
Parameters
----------
image : 2D array-like
The image to be filtered. It must have a real (vs. complex) dtype.
fh, fv : 1D array-like
Horizontal (axis 0) and vertical (axis... | 0.000151 |
def print_location(proc_obj):
"""Show where we are. GUI's and front-end interfaces often
use this to update displays. So it is helpful to make sure
we give at least some place that's located in a file.
"""
i_stack = proc_obj.curindex
if i_stack is None or proc_obj.stack is None:
return F... | 0.002661 |
def count_subgraph_sizes(graph: BELGraph, annotation: str = 'Subgraph') -> Counter[int]:
"""Count the number of nodes in each subgraph induced by an annotation.
:param annotation: The annotation to group by and compare. Defaults to 'Subgraph'
:return: A dictionary from {annotation value: number of nodes}
... | 0.007481 |
def raise_302(instance, location):
"""Abort the current request with a 302 (Found) response code. Sets the
Location header correctly. If the location does not start with a slash,
the path of the current request is prepended.
:param instance: Resource instance (used to access the response)
:type ins... | 0.001792 |
def get_query_batch_request(self, batch_id, job_id=None):
""" Fetch the request sent for the batch. Note should only used for query batches """
if not job_id:
job_id = self.lookup_job_id(batch_id)
url = self.endpoint + "/job/{}/batch/{}/request".format(job_id, batch_id)
resp... | 0.009501 |
def _extract_alphabet(self, grammar):
"""
Extract an alphabet from the given grammar.
"""
alphabet = set([])
for terminal in grammar.Terminals:
alphabet |= set([x for x in terminal])
self.alphabet = list(alphabet) | 0.007326 |
def update_from_item(self, item):
"""
Update from i3status output. returns if item has changed.
"""
if not self.is_time_module:
# correct the output
# Restore the name/instance.
item["name"] = self.name
item["instance"] = self.instance
... | 0.001047 |
def read_namespaced_pod_disruption_budget(self, name, namespace, **kwargs):
"""
read the specified PodDisruptionBudget
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_pod_di... | 0.005416 |
def from_ase_atoms(cls, atoms):
"""Create an instance of the own class from an ase molecule
Args:
molecule (:class:`ase.atoms.Atoms`):
Returns:
Cartesian:
"""
return cls(atoms=atoms.get_chemical_symbols(), coords=atoms.positions) | 0.00678 |
def _get_result_paths(self, data):
"""Gets the results for a run of bwa index.
bwa index outputs 5 files when the index is created. The filename
prefix will be the same as the input fasta, unless overridden with
the -p option, and the 5 extensions are listed below:
.amb
... | 0.001955 |
def save(self):
"""
Write data to user config file.
"""
with open(self._user_config_file, 'w', encoding='utf-8') as f:
self.write(f) | 0.011364 |
def addSignal(self, s):
"""
Adds a L{Signal} to the interface
"""
if s.nargs == -1:
s.nargs = len([a for a in marshal.genCompleteTypes(s.sig)])
self.signals[s.name] = s
self._xml = None | 0.008163 |
def dynamic_presence(self):
"""
Determine presence based on bed heating level and end presence
time reported by the api.
Idea originated from Alex Lee Yuk Cheung SmartThings Code.
"""
# self.heating_stats()
if not self.presence:
if self.heating_leve... | 0.003492 |
def is_valid_python(tkn: str) -> bool:
"""Determine whether tkn is a valid python identifier
:param tkn:
:return:
"""
try:
root = ast.parse(tkn)
except SyntaxError:
return False
return len(root.body) == 1 and isinstance(root.body[0], ast.Expr) and isinstance(root.body[0].val... | 0.006006 |
def treat(request_body):
"""
Treat a notification and guarantee its authenticity.
:param request_body: The request body in plain text.
:type request_body: string
:return: A safe APIResource
:rtype: APIResource
"""
# Python 3+ support
if isinstance(request_body, six.binary_type):
... | 0.002463 |
async def prover_get_credential(wallet_handle: int,
cred_id: str) -> str:
"""
Gets human readable credential by the given id.
:param wallet_handle: wallet handler (created by open_wallet).
:param cred_id: Identifier by which requested credential is stored in the wallet
... | 0.002063 |
def admin_permission_factory(admin_view):
"""Default factory for creating a permission for an admin.
It tries to load a :class:`invenio_access.permissions.Permission`
instance if `invenio_access` is installed.
Otherwise, it loads a :class:`flask_principal.Permission` instance.
:param admin_view: I... | 0.001456 |
def subscribe(self, name, params=[], callback=None):
"""Subscribe to a collection
Arguments:
name - the name of the publication
params - the subscription parameters
Keyword Arguments:
callback - a function callback that returns an error (if exists)"""
self._wait_... | 0.002141 |
def prepare_project(project, project_dir, binaries, ips, urls):
"""
Generates blacklists / whitelists
"""
# Get Various Lists / Project Waivers
lists = get_lists.GetLists()
# Get file name black list and project waivers
file_audit_list, file_audit_project_list = lists.file_audit_list(proje... | 0.002316 |
def get_offsets(self):
"""
returns
-------
a dictionary with these entries
header_start:
byte offset from beginning of the file to the start
of the header
data_start:
byte offset from beginning of the file to the start
of t... | 0.002695 |
def sanitize(s,
normalize_whitespace=True,
normalize_unicode=True,
form='NFKC',
enforce_encoding=True,
encoding='utf-8'):
"""Normalize a string
Args:
s (unicode string): input unicode string
normalize_whitespace (bool): if True, n... | 0.004437 |
def write(self, psd_data_or_future, time_start, time_stop, samples):
"""Write PSD of one frequency hop"""
try:
# Wait for result of future
f_array, pwr_array = psd_data_or_future.result()
except AttributeError:
f_array, pwr_array = psd_data_or_future
... | 0.002561 |
def _position_for_dispense(self, location=None, clearance=0.5):
"""
Position this :any:`Pipette` for an dispense
"""
if location:
if isinstance(location, Placeable):
location = location.bottom(min(location.z_size(), clearance))
self.move_to(locati... | 0.006192 |
def createCircle(self, cx, cy, r, strokewidth=1, stroke='black', fill='none'):
"""
Creates a circle
@type cx: string or int
@param cx: starting x-coordinate
@type cy: string or int
@param cy: starting y-coordinate
@type r: string or int
@param r: ... | 0.010669 |
def date_time_this_decade(
self,
before_now=True,
after_now=False,
tzinfo=None):
"""
Gets a DateTime object for the decade year.
:param before_now: include days in current decade before today
:param after_now: include days in current decad... | 0.001711 |
def floyd_warshall_get_path(self, distance, nextn, i, j):
'''
API:
floyd_warshall_get_path(self, distance, nextn, i, j):
Description:
Finds shortest path between i and j using distance and nextn
dictionaries.
Pre:
(1) distance and nextn are... | 0.010689 |
async def arun_process(path: Union[Path, str], target: Callable, *,
args: Tuple[Any]=(),
kwargs: Dict[str, Any]=None,
callback: Callable[[Set[Tuple[Change, str]]], Awaitable]=None,
watcher_cls: Type[AllWatcher]=PythonWatcher,
... | 0.012821 |
def subscribe(self, topic, qos=0):
# type: (str, int) -> Tuple[int, int]
"""
Subscribe to a certain topic.
:param topic: a string specifying the subscription topic to
subscribe to.
:param qos: the desired quality of service level for the subscription.
... | 0.001723 |
def modify_karma(self, words):
"""
Given a regex object, look through the groups and modify karma
as necessary
"""
# 'user': karma
k = defaultdict(int)
if words:
# For loop through all of the group members
for word_tuple in words:
... | 0.001736 |
def do_map(input_dict, feature_format, positive_class=None):
'''
Maps a new example to a set of features.
'''
# Context of the unseen example(s)
train_context = input_dict['train_ctx']
test_context = input_dict['test_ctx']
# Currently known examples & background knowledge
features = inp... | 0.001642 |
def _verify_time_range(payload_dict):
"""Verifies the issued at and expiration from a JWT payload.
Makes sure the current time (in UTC) falls between the issued at and
expiration for the JWT (with some skew allowed for via
``CLOCK_SKEW_SECS``).
Args:
payload_dict: dict, A dictionary contai... | 0.000447 |
def kerr_lightring_velocity(chi):
"""Return the velocity at the Kerr light ring"""
# If chi > 0.9996, the algorithm cannot solve the function
if chi >= 0.9996:
return brentq(kerr_lightring, 0, 0.8, args=(0.9996))
else:
return brentq(kerr_lightring, 0, 0.8, args=(chi)) | 0.003333 |
def list_calculations(db, job_type, user_name):
"""
Yield a summary of past calculations.
:param db: a :class:`openquake.server.dbapi.Db` instance
:param job_type: 'hazard' or 'risk'
:param user_name: an user name
"""
jobs = db('SELECT *, %s FROM job WHERE user_name=?x '
'AND ... | 0.001247 |
def _from_rest_ignore(model, props):
""" Purge fields that are completely unknown """
fields = model.all_fields
for prop in props.keys():
if prop not in fields:
del props[prop] | 0.004762 |
def deactivate_version(self, service_id, version_number):
"""Deactivate the current version."""
content = self._fetch("/service/%s/version/%d/deactivate" % (service_id, version_number), method="PUT")
return FastlyVersion(self, content) | 0.024896 |
def publish_model(cursor, model, publisher, message):
"""Publishes the ``model`` and return its ident_hash."""
publishers = publisher
if isinstance(publishers, list) and len(publishers) > 1:
raise ValueError("Only one publisher is allowed. '{}' "
"were given: {}"
... | 0.000574 |
def draw(self, **kwargs):
"""
Creates the bar chart of the cross-validated scores generated from the
fit method and places a dashed horizontal line that represents the
average value of the scores.
"""
color = kwargs.pop("color", "b")
width = kwargs.pop("width", 0... | 0.002813 |
def ignore(self, tube):
"""Remove the given tube from the watchlist.
:param tube: Name of tube to remove from the watchlist
If all tubes are :func:`ignore()` d, beanstalk will auto-add "default" to the watchlist
to prevent the list from being empty. See :func:`watch()` for more unforma... | 0.004854 |
def build_menus(self, order_cats=[]):
""" 生成全局内存菜单"""
menus = [{'category': _cat, 'items': []} for _cat in order_cats]
for path in self.routes:
route = self.routes[path]
for menu in menus:
if route['category'] == menu['category']:
menu[... | 0.00551 |
def to_fits(self, filename, wavelengths=None, **kwargs):
"""Write the reddening law to a FITS file.
:math:`R(V)` column is automatically named 'Av/E(B-V)'.
Parameters
----------
filename : str
Output filename.
wavelengths : array-like, `~astropy.units.quant... | 0.001395 |
async def release(self):
"Releases the already acquired lock"
expected_token = self.local.token
if expected_token is None:
raise LockError("Cannot release an unlocked lock")
self.local.token = None
await self.do_release(expected_token) | 0.006969 |
def get_views(self, path, year=None, month=None, day=None, hour=None):
""" Get the number of views for a Telegraph article
:param path: Path to the Telegraph page
:param year: Required if month is passed. If passed, the number of
page views for the requested year will be r... | 0.002137 |
def get_default_database(self):
"""DEPRECATED - Get the database named in the MongoDB connection URI.
>>> uri = 'mongodb://host/my_database'
>>> client = MongoClient(uri)
>>> db = client.get_default_database()
>>> assert db.name == 'my_database'
>>> db = client.get_datab... | 0.002188 |
def _get_field_schema(self):
"""
Get a list of all of the default fields for this query type.
If data is available in the monitor type, a list of field definitions
will be returned ahead of the actual data, providing insight into
the available fields. If no data is available in a... | 0.004934 |
def get_request_data(self, path, action, body=None):
"""Get the default data and status code of the given path + action request.
Args:
path: path of the request.
action: action of the request(get, post, delete...)
body: body sent, used to sent it back for post reques... | 0.003457 |
def later(timeout, actor, method, *args, **kwargs):
'''
Sets a timer that will call the *method* of the *actor* past *timeout*
seconds.
See example in :ref:`sample_inter`
:param int timeout: seconds until the method is called.
:param Proxy actor: actor to which make the call after *time* secon... | 0.00086 |
def from_url(cls, url, **kwargs):
"""
Creates an instance of the KubeConfig class from a single URL (useful
for interacting with kubectl proxy).
"""
doc = {
"clusters": [
{
"name": "self",
"cluster": {
... | 0.002778 |
def guess_depth(self, root_dir):
"""
Try to guess the depth of a directory repository (i.e. whether it has
sub-folders for multiple subjects or visits, depending on where files
and/or derived label files are found in the hierarchy of
sub-directories under the root dir.
P... | 0.000912 |
def delete_all_objects(self, async_=False):
"""
Deletes all objects from this container.
By default the call will block until all objects have been deleted. By
passing True for the 'async_' parameter, this method will not block, and
instead return an object that can be used to f... | 0.002825 |
def abort(*args, **kwargs):
"""
Usage:
return abort("...") => will sys.exit() by default
return abort("...", fatal=True) => Will sys.exit()
# Not fatal, but will log/print message:
return abort("...", fatal=False) => Will return False
return abort("...", fatal=(False, No... | 0.001786 |
def check_inlet(self, helper):
"""
check the Inlets of Raritan PDUs
"""
# walk the data
try:
inlet_values = self.sess.walk_oid(self.oids['oid_inlet_value'])
inlet_units = self.sess.walk_oid(self.oids['oid_inlet_unit'])
inlet_digits = self.sess.... | 0.007474 |
def split_data(data, squeeze=False):
"""
Split 1D or 2D into two parts, using the last axis
Parameters
----------
data:
squeeze : squeeze results to remove unnecessary dimensions
"""
vdata = np.atleast_2d(data)
nr_freqs = int(vdata.shape[1] / 2)
part1 = vdata[:, 0:nr_freqs]
... | 0.002212 |
def _compute_primary_smooths(self):
"""Compute fixed-span smooths with all of the default spans."""
for span in DEFAULT_SPANS:
smooth = smoother.perform_smooth(self.x, self.y, span)
self._primary_smooths.append(smooth) | 0.007752 |
def _set_group_best(self, v, load=False):
"""
Setter method for group_best, mapped from YANG variable /routing_system/route_map/content/match/additional_paths/advertise_set/group_best (empty)
If this variable is read-only (config: false) in the
source YANG file, then _set_group_best is considered as a p... | 0.005414 |
def process_class_docstrings(app, what, name, obj, options, lines):
"""
For those classes for which we use ::
:template: autosummary/class_without_autosummary.rst
the documented attributes/methods have to be listed in the class
docstring. However, if one of those lists is empty, we use 'None',
... | 0.001099 |
def _parse_date_time_time_zone(self, date_time_time_zone):
""" Parses and convert to protocol timezone a dateTimeTimeZone resource
This resource is a dict with a date time and a windows timezone
This is a common structure on Microsoft apis so it's included here.
"""
if date_time_... | 0.004433 |
def get_abs_file_path(self, rel_file_path,
quit_on_error=None, check_relative_to_path=True):
"""
Returns the absolute file path of the given [relative] file path
to either this script or to the config file.
May throw a RuntimeError if quit_on_error is True.
... | 0.002901 |
def update_timestep(self, modelparams, expparams):
r"""
Returns a set of model parameter vectors that is the update of an
input set of model parameter vectors, such that the new models are
conditioned on a particular experiment having been performed.
By default, this is the trivi... | 0.010045 |
def reply_message(self, message_url, body):
"""回复某条站内消息
:param message_url: 该条消息的页面 URL
:param body: 内容(不能超过 1024 个字符)
"""
id = re.findall(r'(\d+)/?$', message_url)[0]
api = 'http://www.shanbay.com/api/v1/message/%s/reply/'
url = api % id
data = {
... | 0.004405 |
def _encrypt(cipher, key, data, iv, padding):
"""
Encrypts plaintext
:param cipher:
A kSecAttrKeyType* value that specifies the cipher to use
:param key:
The encryption key - a byte string 5-16 bytes long
:param data:
The plaintext - a byte string
:param iv:
T... | 0.001992 |
def _load_converted_gssha_data_from_lsm(self, gssha_var, lsm_var, load_type, time_step=None):
"""
This function loads data from LSM and converts to GSSHA format
"""
if 'radiation' in gssha_var:
conversion_factor = self.netcdf_attributes[gssha_var]['conversion_factor'][load_ty... | 0.004925 |
def verify(verified_entity, verification_key):
"""
Метод должен райзить ошибки
:param verified_entity: сущность
:param verification_key: ключ
:return:
"""
verification = get_object_or_none(Verification, verified_entity=verified_entity)
if verification is ... | 0.00821 |
def add_const(features):
"""
Prepend the constant feature 1 as first feature and return the modified
feature set.
Parameters
----------
features : ndarray or DataFrame
"""
content = np.empty((features.shape[0], features.shape[1] + 1), dtype='float64')
content[:, 0] = 1.
if isins... | 0.005034 |
def register_service(
self,
clazz,
service,
properties,
send_event=True,
factory=False,
prototype=False,
):
# type: (Union[List[Any], type, str], object, dict, bool, bool, bool) -> ServiceRegistration
"""
Registers a service
:p... | 0.004344 |
def input(self, _in, out, **kw):
"""Input filtering."""
args = [self.binary or 'cleancss'] + self.rebase_opt
if self.extra_args:
args.extend(self.extra_args)
self.subprocess(args, out, _in) | 0.008584 |
def expand_path(path):
'''
Given a compressed path, return a new path that has all the segments
in it interpolated.
'''
expanded = []
if len(path) < 2:
return expanded
for i in range(len(path)-1):
expanded += bresenham(path[i], path[i + 1])
expanded += [path[:-1]]
ret... | 0.003012 |
def make_url_fetcher(dispatcher=None,
next_fetcher=weasyprint.default_url_fetcher):
"""Return an function suitable as a ``url_fetcher`` in WeasyPrint.
You generally don’t need to call this directly.
If ``dispatcher`` is not provided, :func:`make_flask_url_dispatcher`
is called to ... | 0.000419 |
def connect_inputs(self, datas):
"""
Connects input ``Pipers`` to "datas" input data in the correct order
determined, by the ``Piper.ornament`` attribute and the ``Dagger._cmp``
function.
It is assumed that the input data is in the form of an iterator and
that all inp... | 0.012141 |
def pmdec(self,*args,**kwargs):
"""
NAME:
pmdec
PURPOSE:
return proper motion in declination (in mas/yr)
INPUT:
t - (optional) time at which to get pmdec (can be Quantity)
obs=[X,Y,Z,vx,vy,vz] - (optional) position and velocity of observe... | 0.010899 |
def data_iterator_cache(uri,
batch_size,
shuffle=False,
rng=None,
normalize=True,
with_memory_cache=True,
epoch_begin_callbacks=[],
epoch_end_callbacks=... | 0.002233 |
def lessThan(self, value):
"""
Sets the operator type to Query.Op.LessThan and sets the
value to the inputted value.
:param value <variant>
:return <Query>
:sa lessThan
:usage |>>> from orb import Que... | 0.010292 |
def Jobs(self, crawlId=None):
"""
Create a JobClient for listing and creating jobs.
The JobClient inherits the confId from the Nutch client.
:param crawlId: crawlIds to use for this client. If not provided, will be generated
by nutch.defaultCrawlId()
:return: a JobClie... | 0.006623 |
def make_at_least_n_items_valid(flag_list, n):
"""
tries to make at least min(len(flag_list, n) items True in flag_list
Args:
flag_list (list): list of booleans
n (int): number of items to ensure are True
CommandLine:
python -m utool.util_dev --test-make_at_least_n_items_valid
... | 0.000788 |
def paintEvent(self, event):
"""
Overloads the paint event to handle painting pointers for the popup \
mode.
:param event | <QPaintEvent>
"""
# use the base technique for the dialog mode
if self.currentMode() == XPopupWidget.Mode.Dialog:
... | 0.007273 |
def to_xdr_object(self):
"""Creates an XDR Transaction object that represents this
:class:`Transaction`.
"""
source_account = account_xdr_object(self.source)
memo = self.memo.to_xdr_object()
operations = [o.to_xdr_object() for o in self.operations]
ext = Xdr.null... | 0.003992 |
def select(self, space, key=None, **kwargs) -> _MethodRet:
"""
Select request coroutine.
Examples:
.. code-block:: pycon
>>> await conn.select('tester')
<Response sync=3 rowcount=2 data=[
<TarantoolTuple id=1 name='one'>,... | 0.001259 |
def initialize(self, runtime=None):
"""Initializes this manager.
A manager is initialized once at the time of creation.
arg: runtime (osid.OsidRuntimeManager): the runtime
environment
raise: CONFIGURATION_ERROR - an error with implementation
configurat... | 0.001819 |
def get_default_config(self):
"""
Returns the default collector settings
"""
config = super(HttpdCollector, self).get_default_config()
config.update({
'path': 'httpd',
'urls': ['localhost http://localhost:8080/server-status?auto']
})
... | 0.00597 |
def list_users(self, objectmask=None, objectfilter=None):
"""Lists all users on an account
:param string objectmask: Used to overwrite the default objectmask.
:param dictionary objectfilter: If you want to use an objectfilter.
:returns: A list of dictionaries that describe each user
... | 0.006033 |
def _process_items(cls, vals):
"Processes list of items assigning unique paths to each."
if type(vals) is cls:
return vals.data
elif not isinstance(vals, (list, tuple)):
vals = [vals]
items = []
counts = defaultdict(lambda: 1)
cls._unpack_paths(val... | 0.00495 |
def templates(self) -> List['Template']:
"""Return a list of templates as template objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
Template(_lststr, _type_to_spans, span, 'Template')
for span in self._subspans('Template')] | 0.006431 |
def _get_to_many_relationship_value(self, obj, column):
"""
Get the resulting datas for a One To many or a many to many relationship
:param obj obj: The instance we manage
:param dict column: The column description dictionnary
:returns: The associated value
"""
r... | 0.002483 |
def to_meshcode(lat, lon, level):
"""緯度経度から指定次の地域メッシュコードを算出する。
Args:
lat: 世界測地系の緯度(度単位)
lon: 世界測地系の経度(度単位)
level: 地域メッシュコードの次数
1次(80km四方):1
40倍(40km四方):40000
20倍(20km四方):20000
16倍(16km四方):16000
2次(10km四方):2
... | 0.005994 |
def load(cls, filename, format=None):
""" Return an instance of the class that is saved in the file with the
given filename in the specified format.
"""
if format is None:
# try to derive protocol from file extension
format = format_from_extension(filename)
... | 0.004219 |
def findWhere(self, attrs=None):
"""
Convenience version of a common use case of `find`:
getting the first object
containing specific `key:value` pairs.
"""
return self._wrap(self._clean.where(attrs, True)) | 0.007874 |
def asin(x):
"""
Inverse sine
"""
if isinstance(x, UncertainFunction):
mcpts = np.arcsin(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.arcsin(x) | 0.005 |
def _valid_ip(ip_address):
'''
Check if the IP address is valid and routable
Return either True or False
'''
try:
address = ipaddress.IPv4Address(ip_address)
except ipaddress.AddressValueError:
return False
if address.is_unspecified or \
address.is_loopback or \
... | 0.004425 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.