text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def download_file(image_name, output_path, width=DEFAULT_WIDTH):
"""Download a given Wikimedia Commons file."""
image_name = clean_up_filename(image_name)
logging.info("Downloading %s with width %s", image_name, width)
try:
contents, output_file_name = get_thumbnail_of_file(image_name, width)
... | 0.001646 |
def send_data(socket, data, scan_parameters={}, name='ReadoutData'):
'''Sends the data of every read out (raw data and meta data) via ZeroMQ to a specified socket
'''
if not scan_parameters:
scan_parameters = {}
data_meta_data = dict(
name=name,
dtype=str(data[0].dtype),
... | 0.004027 |
def url_to_tile(url):
"""
Extracts tile name, date and AWS index from tile url on AWS.
:param url: class input parameter 'metafiles'
:type url: str
:return: Name of tile, date and AWS index which uniquely identifies tile on AWS
:rtype: (str, str, int)
"""
... | 0.006397 |
def map_exp_ids(self, exp, positions=False):
"""Maps ids to words or word-position strings.
Args:
exp: list of tuples [(id, weight), (id,weight)]
positions: if True, also return word positions
Returns:
list of tuples (word, weight), or (word_positions, weigh... | 0.002625 |
def validate_parameters(cls, parameters, schema=None):
"""Validate parameters format against schema specification
Raises:
- ValidationError if the instance is invalid
- SchemaError if the schema itself is invalid
"""
if schema is None:
schema = cls.get_par... | 0.005208 |
def _all_equal(iterable):
"""True if all values in `iterable` are equal, else False."""
iterator = iter(iterable)
first = next(iterator)
return all(first == rest for rest in iterator) | 0.005025 |
def build_projection_kwargs(cls, source, mapping):
"""Handle mapping a dictionary of metadata to keyword arguments."""
return cls._map_arg_names(source, cls._default_attr_mapping + mapping) | 0.009756 |
def select_with_correspondence(
self,
selector,
result_selector=KeyedElement):
'''Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input va... | 0.003043 |
def html(self, url, timeout=None):
"""High level method to get http request response in text.
smartly handle the encoding problem.
"""
response = self.get_response(url, timeout=timeout)
if response:
domain = self.get_domain(url)
if domain in self.domain_en... | 0.002686 |
def write_review(review, out):
"""
Write the fields of a single review to out.
"""
out.write('# Review\n\n')
write_value('Reviewer', review.reviewer, out)
write_value('ReviewDate', review.review_date_iso_format, out)
if review.has_comment:
write_text_value('ReviewComment', review.com... | 0.00303 |
def make_serviceitem_servicedllsignatureexists(dll_sig_exists, condition='is', negate=False):
"""
Create a node for ServiceItem/serviceDLLSignatureExists
:return: A IndicatorItem represented as an Element node
"""
document = 'ServiceItem'
search = 'ServiceItem/serviceDLLSignatureExists'
... | 0.007286 |
def get_archiver_index(config, archiver):
"""
Get the contents of the archiver index file.
:param config: The configuration
:type config: :class:`wily.config.WilyConfig`
:param archiver: The name of the archiver type (e.g. 'git')
:type archiver: ``str``
:return: The index data
:... | 0.003984 |
def trigger(self, only_manual=True):
"""Trigger a quick-action automation."""
if not self.is_quick_action and only_manual:
raise AbodeException((ERROR.TRIGGER_NON_QUICKACTION))
url = CONST.AUTOMATION_APPLY_URL
url = url.replace(
'$AUTOMATIONID$', self.automation_... | 0.004577 |
def apply_gates_to_fd(stilde_dict, gates):
"""Applies the given dictionary of gates to the given dictionary of
strain in the frequency domain.
Gates are applied by IFFT-ing the strain data to the time domain, applying
the gate, then FFT-ing back to the frequency domain.
Parameters
----------
... | 0.001773 |
def matrix_to_euler(rotmat):
'''Inverse of euler_to_matrix().'''
if not isinstance(rotmat, np.matrixlib.defmatrix.matrix):
# As this calculation relies on np.matrix algebra - convert array to
# matrix
rotmat = np.matrix(rotmat)
def cvec(x, y, z):
return np.matrix([[x, y, z]]... | 0.001136 |
def can_into(self, val: str) -> bool:
"""Determine if there is a leaf node with name `val`"""
return val in self.paths or (self.param and self.param_name == val) | 0.011299 |
def when_available(self, key: Hashable, **when_kwargs) -> StateWatcher:
"""
Block until ``key in state``, and then return a copy of the state.
.. include:: /api/state/get_when_equality.rst
"""
return self.when(lambda snapshot: key in snapshot, **when_kwargs) | 0.006689 |
def slice_list(in_list, lens):
"""Slice a list into several sub lists by a list of given length.
Args:
in_list (list): The list to be sliced.
lens(int or list): The expected length of each out list.
Returns:
list: A list of sliced list.
"""
if not isinstance(lens, list):
... | 0.001397 |
def create_or_update(model, *, defaults=None, save=True, **kwargs):
"""
Create or update a django model instance.
:param model:
:param defaults:
:param kwargs:
:return: object, created, updated
"""
obj, created = model._default_manager.get_or_create(defaults=defaults, **kwargs)
up... | 0.003236 |
def _append_number(self, value, _file): # pylint: disable=no-self-use
"""Call this function to write number contents.
Keyword arguments:
* value - dict, content to be dumped
* _file - FileIO, output file
"""
_text = value
_labs = ' {text}'.format(text=_... | 0.005682 |
def unix_time(self, end_datetime=None, start_datetime=None):
"""
Get a timestamp between January 1, 1970 and now, unless passed
explicit start_datetime or end_datetime values.
:example 1061306726
"""
start_datetime = self._parse_start_datetime(start_datetime)
end_... | 0.004505 |
def to_bucket(self, timestamp, steps=0):
'''
Calculate the bucket from a timestamp.
'''
dt = datetime.utcfromtimestamp( timestamp )
if steps!=0:
if self._step == 'daily':
dt = dt + timedelta(days=steps)
elif self._step == 'weekly':
dt = dt + timedelta(weeks=steps)
... | 0.019737 |
def get_token(filename=TOKEN_PATH, envvar=TOKEN_ENVVAR):
"""
Returns pipeline_token for API
Tries local file first, then env variable
"""
if os.path.isfile(filename):
with open(filename) as token_file:
token = token_file.readline().strip()
else:
token = os.environ.g... | 0.003724 |
def get_boundargs(cls, *args, **kargs):
"""Return an inspect.BoundArguments object for the application
of this Struct's signature to its arguments. Add missing values
for default fields as keyword arguments.
"""
boundargs = cls._signature.bind(*args, **kargs)
# Include de... | 0.005076 |
def plot_compare(self, other_plotter):
"""
plot two band structure for comparison. One is in red the other in blue.
The two band structures need to be defined on the same symmetry lines!
and the distance between symmetry lines is
the one of the band structure used to build the Ph... | 0.003656 |
def ParseObjs(self, objs, type_names):
"""Parse one or more objects by testing if it is a known RDF class."""
for obj in objs:
for type_name in self._RDFTypes(type_names):
if isinstance(obj, self._GetClass(type_name)):
yield obj | 0.011538 |
def calc_padding(fmt, align):
"""Calculate how many padding bytes needed for ``fmt`` to be aligned to
``align``.
Args:
fmt (str): :mod:`struct` format.
align (int): alignment (2, 4, 8, etc.)
Returns:
str: padding format (e.g., various number of 'x').
>>> calc_padding('b', ... | 0.002037 |
def has_unsaved_changes(self):
"""
True when any of the visible buffers in this tab has unsaved changes.
"""
for w in self.windows():
if w.editor_buffer.has_unsaved_changes:
return True
return False | 0.007519 |
def set_check(self, name, state):
'''set a status value'''
if self.child.is_alive():
self.parent_pipe.send(CheckItem(name, state)) | 0.012658 |
def get_single_group_membership_memberships(self, group_id, membership_id):
"""
Get a single group membership.
Returns the group membership with the given membership id or user id.
"""
path = {}
data = {}
params = {}
# REQUIRED - PATH - group_i... | 0.004837 |
def get_lanczos_eig(self, compute_m=True, feed_dict=None):
"""Computes the min eigen value and corresponding vector of matrix M or H
using the Lanczos algorithm.
Args:
compute_m: boolean to determine whether we should compute eig val/vec
for M or for H. True for M; False for H.
feed_dict... | 0.006711 |
def mode(self, **kwargs):
"""Returns a new QueryCompiler with modes calculated for each label along given axis.
Returns:
A new QueryCompiler with modes calculated.
"""
axis = kwargs.get("axis", 0)
def mode_builder(df, **kwargs):
result = df.mode(**kwargs... | 0.003529 |
def _num_required_args(func):
""" Number of args for func
>>> def foo(a, b, c=None):
... return a + b + c
>>> _num_required_args(foo)
2
>>> def bar(*args):
... return sum(args)
>>> print(_num_required_args(bar))
None
borrowed from: https:/... | 0.001656 |
def checked_run(cmd):
"""Prepare and run a subprocess cmd, checking for successful completion."""
completed_process = run(cmd)
if completed_process.returncode > 0:
print("Command failed! Hanging around in case someone needs a "
"docker connection. (Ctrl-C to quit now)")
time.s... | 0.002597 |
def update_port(self, context, port_id, **kwargs):
"""Update a port.
:param context: neutron api request context.
:param port_id: neutron port id.
:param kwargs: optional kwargs.
:raises IronicException: If the client is unable to update the
downstream port for any r... | 0.001675 |
def compute_theta(self):
"""Compute theta parameter using Kendall's tau.
On Clayton copula this is :math:`τ = θ/(θ + 2) \\implies θ = 2τ/(1-τ)` with
:math:`θ ∈ (0, ∞)`.
On the corner case of :math:`τ = 1`, a big enough number is returned instead of infinity.
"""
if self... | 0.009029 |
def dehtml(text):
'''Remove HTML tag in input text and format the texts
accordingly. '''
# added by BoPeng to handle html output from kernel
#
# Do not understand why, but I cannot define the class outside of the
# function.
try:
# python 2
from HTMLParser import HTMLParser
... | 0.001091 |
def get_catalog_admin_url_template(mode='change'):
"""
Get template of catalog admin url.
URL template will contain a placeholder '{catalog_id}' for catalog id.
Arguments:
mode e.g. change/add.
Returns:
A string containing template for catalog url.
Example:
>>> get_cat... | 0.002035 |
def process_prop(prop_type: PT, value, build_context):
"""Return a cachable representation of the prop `value` given its type."""
if prop_type in (PT.Target, PT.TargetList):
return hashify_targets(value, build_context)
elif prop_type in (PT.File, PT.FileList):
return hashify_files(value)
... | 0.003003 |
def identity_abs(aseq, bseq):
"""Compute absolute identity (# matching sites) between sequence strings."""
assert len(aseq) == len(bseq)
return sum(a == b
for a, b in zip(aseq, bseq)
if not (a in '-.' and b in '-.')) | 0.007752 |
def alterar(self, id_groupl3, name):
"""Change Group L3 from by the identifier.
:param id_groupl3: Identifier of the Group L3. Integer value and greater than zero.
:param name: Group L3 name. String with a minimum 2 and maximum of 80 characters
:return: None
:raise InvalidPara... | 0.005405 |
def get_journey_legs_to_target(self, target, fastest_path=True, min_boardings=False, all_leg_sections=True,
ignore_walk=False, diff_threshold=None, diff_path=None):
"""
Returns a dataframe of aggregated sections from source nodes to target. The returned... | 0.006145 |
def resize(self, nrows, front=False):
"""
Resize the table to the given size, removing or adding rows as
necessary. Note if expanding the table at the end, it is more
efficient to use the append function than resizing and then
writing.
New added rows are zerod, except f... | 0.001398 |
def pointing_vector(self, s, time):
"""
s is the spin vector in roche coordinates
time is the current time
"""
t = time - self._t0
longitude = self._longitude + self._dlongdt * t
# define the basis vectors in the spin (primed) coordinates in terms of
# th... | 0.007003 |
def getCredentials(self, request):
"""
Derive credentials from an HTTP request.
Override SessionWrapper.getCredentials to add the Host: header to the
credentials. This will make web-based virtual hosting work.
@type request: L{nevow.inevow.IRequest}
@param request: The... | 0.00311 |
def validate_redis(self, db_data, user_data, oper):
"""Validate data in Redis.
Args:
db_data (str): The data store in Redis.
user_data (str): The user provided data.
oper (str): The comparison operator.
Returns:
bool: True if the data passed vali... | 0.001198 |
def count(self, strg, case_sensitive=False, *args, **kwargs):
"""Get the count of a word or phrase `s` within this WordList.
:param strg: The string to count.
:param case_sensitive: A boolean, whether or not the search is case-sensitive.
"""
if not case_sensitive:
return [word.lower() for wo... | 0.006803 |
def tag(version=__version__):
"""Deploy a version tag."""
build = local("git tag {0}".format(version))
if build.succeeded:
local("git push --tags") | 0.005988 |
def load_data(self, topology, mol_file, ligand_name, offset=0):
"""
This function loads all relevant data - except trajectories since those are dealt with one at a time.
Therefore, this process only needs to be done once, and every time a trajectory needs to be loaded, it
can be loaded s... | 0.010753 |
def bad_request(cls, errors=None):
"""Shortcut API for HTTP 400 `Bad Request` response.
Args:
errors (list): Response key/value data.
Returns:
WSResponse Instance.
"""
if cls.expose_status: # pragma: no cover
cls.response.content_type = 'app... | 0.004545 |
def put(self, ndef_message, timeout=1.0):
"""Send an NDEF message to the server. Temporarily connects to
the default SNEP server if the client is not yet connected.
.. deprecated:: 0.13
Use :meth:`put_records` or :meth:`put_octets`.
"""
if not self.socket:
... | 0.001748 |
def _cache_contents(self, style_urls, asset_url_path):
"""
Fetches the given URLs and caches their contents
and their assets in the given directory.
"""
files = {}
asset_urls = []
for style_url in style_urls:
if not self.quiet:
print('... | 0.000789 |
def validate(self):
"""Check self.data. Raise InvalidConfig on error
:return: None
"""
if (self.data.get('content-type') or self.data.get('body')) and \
self.data.get('method', '').lower() not in CONTENT_TYPE_METHODS:
raise InvalidConfig(
extr... | 0.008007 |
def foreach_loop(self, context):
"""Run step once for each item in foreach_items.
On each iteration, the invoked step can use context['i'] to get the
current iterator value.
Args:
context: (pypyr.context.Context) The pypyr context. This arg will
mutate.... | 0.001721 |
def sbo_version_source(self, slackbuilds):
"""Create sbo name with version
"""
sbo_versions, sources = [], []
for sbo in slackbuilds:
status(0.02)
sbo_ver = "{0}-{1}".format(sbo, SBoGrep(sbo).version())
sbo_versions.append(sbo_ver)
sources.... | 0.005155 |
def _normalize_helper(number, replacements, remove_non_matches):
"""Normalizes a string of characters representing a phone number by
replacing all characters found in the accompanying map with the values
therein, and stripping all other characters if remove_non_matches is true.
Arguments:
number --... | 0.000855 |
def _addappt(self, iden, appt):
'''
Updates the data structures to add an appointment
'''
if appt.nexttime:
heapq.heappush(self.apptheap, appt)
self.appts[iden] = appt
if self.apptheap and self.apptheap[0] is appt:
self._wake_event.set() | 0.006472 |
def add(self, start, end):
"""
Add the start and end offsets of a matching read.
@param start: The C{int} start offset of the read match in the subject.
@param end: The C{int} end offset of the read match in the subject.
This is Python-style: the end offset is not included i... | 0.004796 |
def select_font(self, font):
'''Select font type
Choices are:
<Bit map fonts>
'brougham'
'lettergothicbold'
'brusselsbit'
'helsinkibit'
'sandiego'
<Outline fonts>
'lettergothic'
'brusselsoutline'
'helsinkioutline'
... | 0.012584 |
def assertTimeZoneNotEqual(self, dt, tz, msg=None):
'''Fail if ``dt``'s ``tzinfo`` attribute equals ``tz`` as
determined by the '!=' operator.
Parameters
----------
dt : datetime
tz : timezone
msg : str
If not provided, the :mod:`marbles.mixins` or
... | 0.002413 |
def get_community_by_id(self, community_id, token=None):
"""
Get a community based on its id.
:param community_id: The id of the target community.
:type community_id: int | long
:param token: (optional) A valid token for the user in question.
:type token: None | string
... | 0.003273 |
def make_next_param(login_url, current_url):
'''
Reduces the scheme and host from a given URL so it can be passed to
the given `login` URL more efficiently.
:param login_url: The login URL being redirected to.
:type login_url: str
:param current_url: The URL to reduce.
:type current_url: st... | 0.003436 |
def get_throttled_by_consumed_write_percent(
table_name, lookback_window_start=15, lookback_period=5):
""" Returns the number of throttled write events in percent of consumption
:type table_name: str
:param table_name: Name of the DynamoDB table
:type lookback_window_start: int
:param lookb... | 0.00067 |
def York_Regression(x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai):
"""
input: x_segment, y_segment, x_mean, y_mean, n, lab_dc_field, steps_Arai
output: x_err, y_err, x_tag, y_tag, b, b_sigma, specimen_b_beta, y_intercept,
x_intercept, x_prime, y_prime, delta_x_prime, delta_... | 0.011817 |
def from_spcm(filepath, name=None, *, delimiter=",", parent=None, verbose=True) -> Data:
"""Create a ``Data`` object from a Becker & Hickl spcm file (ASCII-exported, ``.asc``).
If provided, setup parameters are stored in the ``attrs`` dictionary of the ``Data`` object.
See the `spcm`__ software hompage fo... | 0.001833 |
def Matsumoto_1974(mp, rhop, dp, rhog, D, Vterminal=1):
r'''Calculates saltation velocity of the gas for pneumatic conveying,
according to [1]_. Also described in [2]_.
.. math::
\mu = 0.448 \left(\frac{\rho_p}{\rho_f}\right)^{0.50}\left(\frac{Fr_p}
{10}\right)^{-1.75}\left(\frac{Fr_s}{10}\... | 0.000966 |
def ccmod_xstep(k):
"""Do the X step of the ccmod stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
YU = mp_D_Y - mp_D_U[k]
b = mp_ZSf[k] + mp_drho * sl.rfftn(YU, None, mp_cri.axisN)
Xf = sl.solvedbi... | 0.002387 |
def _wordBeforeCursor(self):
"""Get word, which is located before cursor
"""
cursor = self._qpart.textCursor()
textBeforeCursor = cursor.block().text()[:cursor.positionInBlock()]
match = _wordAtEndRegExp.search(textBeforeCursor)
if match:
return match.group(0)... | 0.005618 |
def draw_commands(self, surf):
"""Draw the list of available commands."""
past_abilities = {act.ability for act in self._past_actions if act.ability}
for y, cmd in enumerate(sorted(self._abilities(
lambda c: c.name != "Smart"), key=lambda c: c.name), start=2):
if self._queued_action and cmd ==... | 0.011335 |
def find_invalid_filenames(filenames, repository_root):
"""Find files that does not exist, are not in the repo or are directories.
Args:
filenames: list of filenames to check
repository_root: the absolute path of the repository's root.
Returns: A list of errors.
"""
errors = []
for... | 0.001059 |
def standard_block(self, bytes_):
"""Adds a standard block of bytes. For TAP files, it's just the
Low + Hi byte plus the content (here, the bytes plus the checksum)
"""
self.out(self.LH(len(bytes_) + 1)) # + 1 for CHECKSUM byte
checksum = 0
for i in bytes_:
... | 0.005013 |
def detectFileEncoding(self, fileName):
'''
Detect content encoding of specific file.
It will return None if it can't determine the encoding.
'''
try:
import chardet
except ImportError:
return
with open(fileName, 'rb') as inputFile:
raw = inputFile.read(2048)
result = chardet.detect(raw)
i... | 0.032103 |
def true_num_reactions(model, custom_spont_id=None):
"""Return the number of reactions associated with a gene.
Args:
model (Model):
custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``
Returns:
int: Number of reactions a... | 0.004754 |
def redo(self):
"""Redo the last action.
This will call `redo()` on all controllers involved in this action.
"""
controllers = self.forward()
if controllers is None:
ups = ()
else:
ups = tuple([controller.redo() for
contr... | 0.004338 |
def smart_search_pool(self, auth, query_str, search_options=None, extra_query=None):
""" Perform a smart search on pool list.
* `auth` [BaseAuth]
AAA options.
* `query_str` [string]
Search string
* `search_options` [options_dict]
... | 0.002833 |
def resource_from_rdf(graph_or_distrib, dataset=None):
'''
Map a Resource domain model to a DCAT/RDF graph
'''
if isinstance(graph_or_distrib, RdfResource):
distrib = graph_or_distrib
else:
node = graph_or_distrib.value(predicate=RDF.type,
object... | 0.000526 |
def from_twodim_list(cls, datalist, tsformat=None):
"""Creates a new TimeSeries instance from the data stored inside a two dimensional list.
:param list datalist: List containing multiple iterables with at least two values.
The first item will always be used as timestamp in the predefine... | 0.00816 |
def get_content(self, zipbundle):
"""Get content."""
for content, filename in self.get_zip_content(zipbundle):
with io.BytesIO(content) as b:
encoding = self._analyze_file(b)
if encoding is None:
encoding = self.default_encoding
... | 0.004684 |
def op_list_venvs(self):
"""Prints out and returns a list of known virtual environments.
:rtype: list
:return: list of virtual environments
"""
self.logger.info('Listing known virtual environments ...')
venvs = self.get_venvs()
for venv in venvs:
self... | 0.006186 |
def draw_line(self, img, pixmapper, pt1, pt2, colour, linewidth):
'''draw a line on the image'''
pix1 = pixmapper(pt1)
pix2 = pixmapper(pt2)
clipped = cv.ClipLine((img.width, img.height), pix1, pix2)
if clipped is None:
if len(self._pix_points) == 0:
s... | 0.003026 |
def do_GET(self):
"""
Handle GET request
"""
consumer_key = os.environ.get('XERO_CONSUMER_KEY')
consumer_secret = os.environ.get('XERO_CONSUMER_SECRET')
private_key_path = os.environ.get('XERO_RSA_CERT_KEY_PATH')
if consumer_key is None or consumer_secret... | 0.002909 |
def validate_lang(ctx, param, lang):
"""Validation callback for the <lang> option.
Ensures <lang> is a supported language unless the <nocheck> flag is set
"""
if ctx.params['nocheck']:
return lang
try:
if lang not in tts_langs():
raise click.UsageError(
"... | 0.001225 |
def circle(rad=0.5):
"""Draw a circle"""
_ctx = _state["ctx"]
_ctx.arc(0, 0, rad, 0, 2 * math.pi)
_ctx.set_line_width(0)
_ctx.stroke_preserve()
# _ctx.set_source_rgb(0.3, 0.4, 0.6)
_ctx.fill() | 0.004545 |
def group(self, labels):
""" group as list """
unique_labels, groupxs = self.group_indicies(labels)
groups = [self.take(idxs) for idxs in groupxs]
return unique_labels, groups | 0.009662 |
def _eval_firstorder(self, rvecs, data, sigma):
"""The first-order Barnes approximation"""
if not self.blocksize:
dist_between_points = self._distance_matrix(rvecs, self.x)
gaussian_weights = self._weight(dist_between_points, sigma=sigma)
return gaussian_weights.dot(d... | 0.002356 |
def flush(self, file=str()):
""" Flushes the updated file content to the given *file*.
.. note:: Overwrites an existing file.
:param str file: name and location of the file.
Default is the original file.
"""
if file:
Path(file).write_bytes(self._cache)
... | 0.005263 |
def get_merged_rect(self, grid, key, rect):
"""Returns cell rect for normal or merged cells and None for merged"""
row, col, tab = key
# Check if cell is merged:
cell_attributes = grid.code_array.cell_attributes
merge_area = cell_attributes[(row, col, tab)]["merge_area"]
... | 0.002134 |
def parse_multipart_upload_result(data):
"""
Parser for complete multipart upload response.
:param data: Response data for complete multipart upload.
:return: :class:`MultipartUploadResult <MultipartUploadResult>`.
"""
root = S3Element.fromstring('CompleteMultipartUploadResult', data)
retu... | 0.002016 |
def get_productivity_stats(self):
"""Return the user's productivity stats.
:return: A JSON-encoded representation of the user's productivity
stats.
:rtype: A JSON-encoded object.
>>> from pytodoist import todoist
>>> user = todoist.login('john.doe@gmail.com', 'passw... | 0.003273 |
def com_google_fonts_check_metadata_nameid_full_name(ttFont, font_metadata):
"""METADATA.pb font.full_name value matches
fullname declared on the name table?
"""
from fontbakery.utils import get_name_entry_strings
full_fontnames = get_name_entry_strings(ttFont, NameID.FULL_FONT_NAME)
if len(full_fontnam... | 0.00703 |
def _expand(dat, counts, start, end):
"""
expand the same counts from start to end
"""
for pos in range(start, end):
for s in counts:
dat[s][pos] += counts[s]
return dat | 0.004785 |
def getNamedItem(self, name: str) -> Optional[Attr]:
"""Get ``Attr`` object which has ``name``.
If does not have ``name`` attr, return None.
"""
return self._dict.get(name, None) | 0.009479 |
def bcc(
self,
bcc_emails,
global_substitutions=None,
is_multiple=False,
p=0):
"""Adds Bcc objects to the Personalization object
:param bcc_emails: An Bcc or list of Bcc objects
:type bcc_emails: Bcc, list(Bcc), tuple
:param gl... | 0.001509 |
def _send_packet(self, data):
" Send to server. "
data = json.dumps(data)
ensure_future(self.pipe.write_message(data)) | 0.014085 |
def build_nodal_plane_dist(npd):
"""
Returns the nodal plane distribution as a Node instance
:param npd:
Nodal plane distribution as instance of :class:
`openquake.hazardlib.pmf.PMF`
:returns:
Instance of :class:`openquake.baselib.node.Node`
"""
npds = []
for prob, n... | 0.001742 |
def comments_between_tokens(token1, token2):
"""Find all comments between two tokens"""
if token2 is None:
buf = token1.end_mark.buffer[token1.end_mark.pointer:]
elif (token1.end_mark.line == token2.start_mark.line and
not isinstance(token1, yaml.StreamStartToken) and
not isinsta... | 0.000939 |
def _create_all_recommendations(cores, ip_views=False, config=None):
"""Calculate all recommendations in multiple processes."""
global _reco, _store
_reco = GraphRecommender(_store)
_reco.load_profile('Profiles')
if ip_views:
_reco.load_profile('Profiles_IP')
manager = Manager()
re... | 0.000683 |
def parsed(self):
"""Get the JSON dictionary object which represents the content.
This property is cached and only parses the content once.
"""
if not self._parsed:
self._parsed = json.loads(self.content)
return self._parsed | 0.007168 |
def verify_day(self, now):
'''Verify the day'''
return self.day == "*" or str(now.day) in self.day.split(" ") | 0.016 |
def sort_like(l, col1, col2):
'''
Sorts the list :py:obj:`l` by comparing :py:obj:`col2` to :py:obj:`col1`.
Specifically, finds the indices :py:obj:`i` such that ``col2[i] = col1``
and returns ``l[i]``. This is useful when comparing the CDPP values of
catalogs generated by different pipelines. The
... | 0.002075 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.