Search is not available for this dataset
text stringlengths 75 104k |
|---|
def partition(iterable, chunk_size, pad_none=False):
"""adapted from Toolz. Breaks an iterable into n iterables up to the
certain chunk size, padding with Nones if availble.
Example:
>>> from searchtweets.utils import partition
>>> iter_ = range(10)
>>> list(partition(iter_, 3))
... |
def merge_dicts(*dicts):
"""
Helpful function to merge / combine dictionaries and return a new
dictionary.
Args:
dicts (list or Iterable): iterable set of dictionaries for merging.
Returns:
dict: dict with all keys from the passed list. Later dictionaries in
the sequence wi... |
def write_ndjson(filename, data_iterable, append=False, **kwargs):
"""
Generator that writes newline-delimited json to a file and returns items
from an iterable.
"""
write_mode = "ab" if append else "wb"
logger.info("writing to file {}".format(filename))
with codecs.open(filename, write_mode... |
def write_result_stream(result_stream, filename_prefix=None,
results_per_file=None, **kwargs):
"""
Wraps a ``ResultStream`` object to save it to a file. This function will still
return all data from the result stream as a generator that wraps the
``write_ndjson`` method.
Arg... |
def read_config(filename):
"""Reads and flattens a configuration file into a single
dictionary for ease of use. Works with both ``.config`` and
``.yaml`` files. Files should look like this::
search_rules:
from-date: 2017-06-01
to-date: 2017-09-01 01:01
pt-rule: k... |
def _load_yaml_credentials(filename=None, yaml_key=None):
"""Loads and parses credentials in a YAML file. Catches common exceptions
and returns an empty dict on error, which will be handled downstream.
Returns:
dict: parsed credentials or {}
"""
try:
with open(os.path.expanduser(fil... |
def load_credentials(filename=None, account_type=None,
yaml_key=None, env_overwrite=True):
"""
Handles credential management. Supports both YAML files and environment
variables. A YAML file is preferred for simplicity and configureability.
A YAML credential file should look somethin... |
def _generate_bearer_token(consumer_key, consumer_secret):
"""
Return the bearer token for a given pair of consumer key and secret values.
"""
data = [('grant_type', 'client_credentials')]
resp = requests.post(OAUTH_ENDPOINT,
data=data,
auth=(consume... |
def email(value, whitelist=None):
"""
Validate an email address.
This validator is based on `Django's email validator`_. Returns
``True`` on success and :class:`~validators.utils.ValidationFailure`
when validation fails.
Examples::
>>> email('someone@example.com')
True
... |
def fi_business_id(business_id):
"""
Validate a Finnish Business ID.
Each company in Finland has a distinct business id. For more
information see `Finnish Trade Register`_
.. _Finnish Trade Register:
http://en.wikipedia.org/wiki/Finnish_Trade_Register
Examples::
>>> fi_busine... |
def fi_ssn(ssn, allow_temporal_ssn=True):
"""
Validate a Finnish Social Security Number.
This validator is based on `django-localflavor-fi`_.
.. _django-localflavor-fi:
https://github.com/django/django-localflavor-fi/
Examples::
>>> fi_ssn('010101-0101')
True
>>>... |
def modcheck(value):
"""Check if the value string passes the mod97-test.
"""
# move country code and check numbers to end
rearranged = value[4:] + value[:4]
# convert letters to numbers
converted = [char_value(char) for char in rearranged]
# interpret as integer
integerized = int(''.join... |
def func_args_as_dict(func, args, kwargs):
"""
Return given function's positional and key value arguments as an ordered
dictionary.
"""
if six.PY2:
_getargspec = inspect.getargspec
else:
_getargspec = inspect.getfullargspec
arg_names = list(
OrderedDict.fromkeys(
... |
def validator(func, *args, **kwargs):
"""
A decorator that makes given function validator.
Whenever the given function is called and returns ``False`` value
this decorator returns :class:`ValidationFailure` object.
Example::
>>> @validator
... def even(value):
... retu... |
def length(value, min=None, max=None):
"""
Return whether or not the length of given string is within a specified
range.
Examples::
>>> length('something', min=2)
True
>>> length('something', min=9, max=9)
True
>>> length('something', max=5)
Validation... |
def url(value, public=False):
"""
Return whether or not given value is a valid URL.
If the value is valid URL this function returns ``True``, otherwise
:class:`~validators.utils.ValidationFailure`.
This validator is based on the wonderful `URL validator of dperini`_.
.. _URL validator of dper... |
def between(value, min=None, max=None):
"""
Validate that a number is between minimum and/or maximum value.
This will work with any comparable type, such as floats, decimals and dates
not just integers.
This validator is originally based on `WTForms NumberRange validator`_.
.. _WTForms Number... |
def ipv4(value):
"""
Return whether or not given value is a valid IP version 4 address.
This validator is based on `WTForms IPAddress validator`_
.. _WTForms IPAddress validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
Examples::
>>> ipv4('123.0.0.7')
... |
def ipv6(value):
"""
Return whether or not given value is a valid IP version 6 address
(including IPv4-mapped IPv6 addresses).
This validator is based on `WTForms IPAddress validator`_.
.. _WTForms IPAddress validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
... |
def get_version(module_name_or_file=None):
"""Return the current version as defined by the given module/file."""
if module_name_or_file is None:
parts = base_module.split('.')
module_name_or_file = parts[0] if len(parts) > 1 else \
find_packages(exclude=['test', 'test.*'])[0]
i... |
def post_report(coverage, args):
"""Post coverage report to coveralls.io."""
response = requests.post(URL, files={'json_file': json.dumps(coverage)},
verify=(not args.skip_ssl_verify))
try:
result = response.json()
except ValueError:
result = {'error': 'Failu... |
def is_source_file(args, filepath):
"""Returns true if it is a C++ source file."""
if args.extension:
return os.path.splitext(filepath)[1] in args.extension
else:
return os.path.splitext(filepath)[1] in _CPP_EXTENSIONS |
def exclude_paths(args):
"""Returns the absolute paths for excluded path."""
results = []
if args.exclude:
for excl_path in args.exclude:
results.append(os.path.abspath(os.path.join(args.root, excl_path)))
return results |
def create_exclude_rules(args):
"""Creates the exlude rules
"""
global _cached_exclude_rules
if _cached_exclude_rules is not None:
return _cached_exclude_rules
rules = []
for excl_path in args.exclude:
abspath = os.path.abspath(os.path.join(args.root, excl_path))
rules.ap... |
def is_excluded_path(args, filepath):
"""Returns true if the filepath is under the one of the exclude path."""
# Try regular expressions first.
for regexp_exclude_path in args.regexp:
if re.match(regexp_exclude_path, filepath):
return True
abspath = os.path.abspath(filepath)
if a... |
def filter_dirs(root, dirs, excl_paths):
"""Filter directory paths based on the exclusion rules defined in
'excl_paths'.
"""
filtered_dirs = []
for dirpath in dirs:
abspath = os.path.abspath(os.path.join(root, dirpath))
if os.path.basename(abspath) in _SKIP_DIRS:
continue... |
def parse_gcov_file(args, fobj, filename):
"""Parses the content of .gcov file
"""
coverage = []
ignoring = False
for line in fobj:
report_fields = line.decode('utf-8', 'replace').split(':', 2)
if len(report_fields) == 1:
continue
line_num = report_fields[1].strip... |
def parse_lcov_file_info(args, filepath, line_iter, line_coverage_re, file_end_string):
""" Parse the file content in lcov info file
"""
coverage = []
lines_covered = []
for line in line_iter:
if line != "end_of_record":
line_coverage_match = line_coverage_re.match(line)
... |
def combine_reports(original, new):
"""Combines two gcov reports for a file into one by adding the number of hits on each line
"""
if original is None:
return new
report = {}
report['name'] = original['name']
report['source_digest'] = original['source_digest']
coverage = []
for o... |
def collect_non_report_files(args, discovered_files):
"""Collects the source files that have no coverage reports.
"""
excl_paths = exclude_paths(args)
abs_root = os.path.abspath(args.root)
non_report_files = []
for root, dirs, files in os.walk(args.root, followlinks=args.follow_symlinks):
... |
def collect(args):
"""Collect coverage reports."""
excl_paths = exclude_paths(args)
report = {}
if args.repo_token:
report['repo_token'] = args.repo_token
report['service_name'] = args.service_name
report['service_job_id'] = args.service_job_id
if os.getenv('COVERALLS_PARALLEL', F... |
def parse_yaml_config(args):
"""Parse yaml config"""
try:
import yaml
except ImportError:
yaml = None
yml = {}
try:
with open(args.coveralls_yaml, 'r') as fp:
if not yaml:
raise SystemExit('PyYAML is required for parsing configuration')
... |
def run():
"""Run cpp coverage."""
import json
import os
import sys
from . import coverage, report
args = coverage.create_args(sys.argv[1:])
if args.verbose:
print('encodings: {}'.format(args.encodings))
yml = parse_yaml_config(args)
if not args.repo_token:
# try ... |
def gitrepo(cwd):
"""Return hash of Git data that can be used to display more information to
users.
Example:
"git": {
"head": {
"id": "5e837ce92220be64821128a70f6093f836dd2c05",
"author_name": "Wil Gieseler",
"author_email": "wil@example.c... |
def git(self, *arguments):
"""
Return (exit code, output) from git.
"""
process = subprocess.Popen(['git'] + list(arguments),
stdout=subprocess.PIPE,
cwd=self.cwd)
out = process.communicate()[0].decode('UTF-8')... |
def _verify(function):
"""decorator to ensure pin is properly set up"""
# @functools.wraps
def wrapped(pin, *args, **kwargs):
pin = int(pin)
if pin not in _open:
ppath = gpiopath(pin)
if not os.path.exists(ppath):
log.debug("Creating Pin {0}".f... |
def cleanup(pin=None, assert_exists=False):
"""Cleanup the pin by closing and unexporting it.
Args:
pin (int, optional): either the pin to clean up or None (default).
If None, clean up all pins.
assert_exists: if True, raise a ValueError if the pin was not
setup. ... |
def setup(pin, mode, pullup=None, initial=False):
'''Setup pin with mode IN or OUT.
Args:
pin (int):
mode (str): use either gpio.OUT or gpio.IN
pullup (None): rpio compatibility. If anything but None, raises
value Error
pullup (bool, optional): Initial pin va... |
def read(pin):
'''read the pin value
Returns:
bool: 0 or 1
'''
f = _open[pin].value
out = int(_read(f))
log.debug("Read {0}: {1}".format(pin, out))
return out |
def set(pin, value):
'''set the pin value to 0 or 1'''
if value is LOW:
value = 0
value = int(bool(value))
log.debug("Write {0}: {1}".format(pin, value))
f = _open[pin].value
_write(f, value) |
def tqdm(self, desc, total, leave, initial=0):
"""
Extension point. Override to provide custom options to tqdm initializer.
:param desc: Description string
:param total: Total number of updates
:param leave: Leave progress bar when done
:param initial: Initial counter sta... |
def build_tqdm_outer(self, desc, total):
"""
Extension point. Override to provide custom options to outer progress bars (Epoch loop)
:param desc: Description
:param total: Number of epochs
:return: new progress bar
"""
return self.tqdm(desc=desc, total=total, leav... |
def build_tqdm_inner(self, desc, total):
"""
Extension point. Override to provide custom options to inner progress bars (Batch loop)
:param desc: Description
:param total: Number of batches
:return: new progress bar
"""
return self.tqdm(desc=desc, total=total, lea... |
def tqdm(self, desc, total, leave, initial=0):
"""
Extension point. Override to provide custom options to tqdm_notebook initializer.
:param desc: Description string
:param total: Total number of updates
:param leave: Leave progress bar when done
:return: new progress bar
... |
def end(self):
"""Close the V interface.
Args::
No argument
Returns::
None
C library equivalent : Vend
"""
# Note: Vend is just a macro; use 'Vfinish' instead
# Note also the the same C function is ... |
def attach(self, num_name, write=0):
"""Open an existing vgroup given its name or its reference
number, or create a new vgroup, returning a VG instance for
that vgroup.
Args::
num_name reference number or name of the vgroup to open,
or -1 to creat... |
def create(self, name):
"""Create a new vgroup, and assign it a name.
Args::
name name to assign to the new vgroup
Returns::
VG instance for the new vgroup
A create(name) call is equivalent to an attach(-1, 1) call,
followed by a call to the setname(nam... |
def find(self, name):
"""Find a vgroup given its name, returning its reference
number if found.
Args::
name name of the vgroup to find
Returns::
vgroup reference number
An exception is raised if the vgroup is not found.
C library equivalent: ... |
def findclass(self, name):
"""Find a vgroup given its class name, returning its reference
number if found.
Args::
name class name of the vgroup to find
Returns::
vgroup reference number
An exception is raised if the vgroup is not found.
C lib... |
def delete(self, num_name):
"""Delete from the HDF file the vgroup identified by its
reference number or its name.
Args::
num_name either the reference number or the name of
the vgroup to delete
Returns::
None
C library equivalent... |
def getid(self, ref):
"""Obtain the reference number of the vgroup following the
vgroup with the given reference number .
Args::
ref reference number of the vgroup after which to search;
set to -1 to start the search at the start of
the HDF file
... |
def insert(self, inst):
"""Insert a vdata or a vgroup in the vgroup.
Args::
inst vdata or vgroup instance to add
Returns::
index of the inserted vdata or vgroup (0 based)
C library equivalent : Vinsert
"""
... |
def add(self, tag, ref):
"""Add to the vgroup an object identified by its tag and
reference number.
Args::
tag tag of the object to add
ref reference number of the object to add
Returns::
total number of objects in the vgroup after the additi... |
def delete(self, tag, ref):
"""Delete from the vgroup the member identified by its tag
and reference number.
Args::
tag tag of the member to delete
ref reference number of the member to delete
Returns::
None
Only the link of the member wit... |
def tagref(self, index):
"""Get the tag and reference number of a vgroup member,
given the index number of that member.
Args::
index member index (0 based)
Returns::
2-element tuple:
- member tag
- member reference number
C libra... |
def tagrefs(self):
"""Get the tags and reference numbers of all the vgroup
members.
Args::
no argument
Returns::
list of (tag,ref) tuples, one for each vgroup member
C library equivalent : Vgettagrefs
... |
def inqtagref(self, tag, ref):
"""Determines if an object identified by its tag and reference
number belongs to the vgroup.
Args::
tag tag of the object to check
ref reference number of the object to check
Returns::
False (0) if the object does... |
def nrefs(self, tag):
"""Determine the number of tags of a given type in a vgroup.
Args::
tag tag type to look for in the vgroup
Returns::
number of members identified by this tag type
C library equivalent : Vnrefs
... |
def attrinfo(self):
"""Return info about all the vgroup attributes.
Args::
no argument
Returns::
dictionnary describing each vgroup attribute; for each attribute,
a (name,data) pair is added to the dictionary, where 'data' is
a tuple holding:
... |
def findattr(self, name):
"""Search the vgroup for a given attribute.
Args::
name attribute name
Returns::
if found, VGAttr instance describing the attribute
None otherwise
C library equivalent : Vfindattr
... |
def get(self):
"""Retrieve the attribute value.
Args::
no argument
Returns::
attribute value(s); a list is returned if the attribute
is made up of more than one value, except in the case of a
string-valued attribute (data type HC.CHAR8) where the
... |
def info(self):
"""Retrieve info about the attribute.
Args::
no argument
Returns::
4-element tuple with the following components:
-attribute name
-attribute data type (one of HC.xxx constants)
-attribute order (number of values)
... |
def info(self):
"""Retrieve info about the attribute : name, data type and
number of values.
Args::
no argument
Returns::
3-element tuple holding:
- attribute name
- attribute data type (see constants SDC.xxx)
- number of values in t... |
def index(self):
"""Retrieve the attribute index number.
Args::
no argument
Returns::
attribute index number (starting at 0)
C library equivalent : SDfindattr
"""
self._index = _C.SDfindattr(self._obj._id, sel... |
def get(self):
"""Retrieve the attribute value.
Args::
no argument
Returns::
attribute value(s); a list is returned if the attribute
is made up of more than one value, except in the case of a
string-valued attribute (data type SDC.CHAR8) where the
... |
def set(self, data_type, values):
"""Update/Create a new attribute and set its value(s).
Args::
data_type : attribute data type (see constants SDC.xxx)
values : attribute value(s); specify a list to create
a multi-valued attribute; a string valued
... |
def end(self):
"""End access to the SD interface and close the HDF file.
Args::
no argument
Returns::
None
The instance should not be used afterwards.
The 'end()' method is implicitly called when the
SD instance is deleted.
C library ... |
def info(self):
"""Retrieve information about the SD interface.
Args::
no argument
Returns::
2-element tuple holding:
number of datasets inside the file
number of file attributes
C library equivalent : SDfileinfo
... |
def nametoindex(self, sds_name):
"""Return the index number of a dataset given the dataset name.
Args::
sds_name : dataset name
Returns::
index number of the dataset
C library equivalent : SDnametoindex
"""
... |
def reftoindex(self, sds_ref):
"""Returns the index number of a dataset given the dataset
reference number.
Args::
sds_ref : dataset reference number
Returns::
dataset index number
C library equivalent : SDreftoindex
... |
def setfillmode(self, fill_mode):
"""Set the fill mode for all the datasets in the file.
Args::
fill_mode : fill mode; one of :
SDC.FILL write the fill value to all the datasets
of the file by default
SDC.NOF... |
def create(self, name, data_type, dim_sizes):
"""Create a dataset.
Args::
name dataset name
data_type type of the data, set to one of the SDC.xxx
constants;
dim_sizes lengths of the dataset dimensions; a one-
... |
def select(self, name_or_index):
"""Locate a dataset.
Args::
name_or_index dataset name or index number
Returns::
SDS instance for the dataset
C library equivalent : SDselect
"""
if isi... |
def attributes(self, full=0):
"""Return a dictionnary describing every global
attribute attached to the SD interface.
Args::
full true to get complete info about each attribute
false to report only each attribute value
Returns::
Empty dict... |
def datasets(self):
"""Return a dictionnary describing all the file datasets.
Args::
no argument
Returns::
Empty dictionnary if no dataset is defined.
Otherwise, dictionnary whose keys are the file dataset names,
and values are tuples describing the co... |
def endaccess(self):
"""Terminates access to the SDS.
Args::
no argument
Returns::
None.
The SDS instance should not be used afterwards.
The 'endaccess()' method is implicitly called when
the SDS instance is deleted.
C library equivalent ... |
def dim(self, dim_index):
"""Get an SDim instance given a dimension index number.
Args::
dim_index index number of the dimension (numbering starts at 0)
C library equivalent : SDgetdimid
"""
id = _C.SDgetdimid(self._id, dim... |
def get(self, start=None, count=None, stride=None):
"""Read data from the dataset.
Args::
start : indices where to start reading in the data array;
default to 0 on all dimensions
count : number of values to read along each dimension;
defa... |
def set(self, data, start=None, count=None, stride=None):
"""Write data to the dataset.
Args::
data : array of data to write; can be given as a numpy
array, or as Python sequence (whose elements can be
imbricated sequences)
start : indic... |
def info(self):
"""Retrieves information about the dataset.
Args::
no argument
Returns::
5-element tuple holding:
- dataset name
- dataset rank (number of dimensions)
- dataset shape, that is a list giving the length of each
data... |
def checkempty(self):
"""Determine whether the dataset is empty.
Args::
no argument
Returns::
True(1) if dataset is empty, False(0) if not
C library equivalent : SDcheckempty
"""
status, emptySDS = _C.SDch... |
def ref(self):
"""Get the reference number of the dataset.
Args::
no argument
Returns::
dataset reference number
C library equivalent : SDidtoref
"""
sds_ref = _C.SDidtoref(self._id)
_checkErr('idtore... |
def getcal(self):
"""Retrieve the SDS calibration coefficients.
Args::
no argument
Returns::
5-element tuple holding:
- cal: calibration factor (attribute 'scale_factor')
- cal_error : calibration factor error
(attribute 'scale... |
def getdatastrs(self):
"""Retrieve the dataset standard string attributes.
Args::
no argument
Returns::
4-element tuple holding:
- dataset label string (attribute 'long_name')
- dataset unit (attribute 'units')
- dataset output format (attri... |
def getrange(self):
"""Retrieve the dataset min and max values.
Args::
no argument
Returns::
(min, max) tuple (attribute 'valid_range')
Note that those are the values as stored
by the 'setrange' method. 'getrange' does *NOT* compute the
min ... |
def setcal(self, cal, cal_error, offset, offset_err, data_type):
"""Set the dataset calibration coefficients.
Args::
cal the calibraton factor (attribute 'scale_factor')
cal_error calibration factor error
(attribute 'scale_factor_err')
offs... |
def setdatastrs(self, label, unit, format, coord_sys):
"""Set the dataset standard string type attributes.
Args::
label dataset label (attribute 'long_name')
unit dataset unit (attribute 'units')
format dataset format (attribute 'format')
... |
def setfillvalue(self, fill_val):
"""Set the dataset fill value.
Args::
fill_val dataset fill value (attribute '_FillValue')
Returns::
None
The fill value is part of the so-called "standard" SDS
attributes. Calling 'setfillvalue' is equivalent to settin... |
def setrange(self, min, max):
"""Set the dataset min and max values.
Args::
min dataset minimum value (attribute 'valid_range')
max dataset maximum value (attribute 'valid_range')
Returns::
None
The data range is part of the so-called "st... |
def getcompress(self):
"""Retrieves info about dataset compression type and mode.
Args::
no argument
Returns::
tuple holding:
- compression type (one of the SDC.COMP_xxx constants)
- optional values, depending on the compression type
COM... |
def setcompress(self, comp_type, value=0, v2=0):
"""Compresses the dataset using a specified compression method.
Args::
comp_type compression type, identified by one of the
SDC.COMP_xxx constants
value,v2 auxiliary value(s) needed by some compression t... |
def setexternalfile(self, filename, offset=0):
"""Store the dataset data in an external file.
Args::
filename external file name
offset offset in bytes where to start writing in
the external file
Returns::
None
C library ... |
def dimensions(self, full=0):
"""Return a dictionnary describing every dataset dimension.
Args::
full true to get complete info about each dimension
false to report only each dimension length
Returns::
Dictionnary where each key is a dimension nam... |
def info(self):
"""Return info about the dimension instance.
Args::
no argument
Returns::
4-element tuple holding:
- dimension name; 'fakeDimx' is returned if the dimension
has not been named yet, where 'x' is the dimension
index number
... |
def setname(self, dim_name):
"""Set the dimension name.
Args::
dim_name dimension name; setting 2 dimensions to the same
name make the dimensions "shared"; in order to be
shared, the dimesions must be deined similarly.
Returns::
... |
def getscale(self):
"""Obtain the scale values along a dimension.
Args::
no argument
Returns::
list with the scale values; the list length is equal to the
dimension length; the element type is equal to the dimension
data type, as set when the 'setdimsc... |
def setscale(self, data_type, scale):
"""Initialize the scale values along the dimension.
Args::
data_type data type code (one of the SDC.xxx constants)
scale sequence holding the scale values; the number of
values must match the current length of t... |
def getstrs(self):
"""Retrieve the dimension standard string attributes.
Args::
no argument
Returns::
3-element tuple holding:
-dimension label (attribute 'long_name')
-dimension unit (attribute 'units')
-dimension format (attribute ... |
def setstrs(self, label, unit, format):
"""Set the dimension standard string attributes.
Args::
label dimension label (attribute 'long_name')
unit dimension unit (attribute 'units')
format dimension format (attribute 'format')
Returns::
None
... |
def attach(self, num_name, write=0):
"""Locate an existing vdata or create a new vdata in the HDF file,
returning a VD instance.
Args::
num_name Name or reference number of the vdata. An existing vdata
can be specified either through its reference number or
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.