text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s"):
"""
A context manager for convenience in writing a file or directory in an atomic way. Set up
a temporary name, then rename it after the operation is done, optionally making a backup of
the previous file or director... | 0.011628 |
def get_context_data(self, **kwargs):
"""Add context data to view"""
context = super().get_context_data(**kwargs)
context.update({
'title': self.get_title(),
'ajax_url': self.get_ajax_url(),
'download_url': self.get_download_url(),
'create_url': se... | 0.005348 |
def is_instance_of(self, some_class):
"""Asserts that val is an instance of the given class."""
try:
if not isinstance(self.val, some_class):
if hasattr(self.val, '__name__'):
t = self.val.__name__
elif hasattr(self.val, '__class__'):
... | 0.004608 |
def sort_topologically(dag):
"""Sort the dag breath first topologically.
Only the nodes inside the dag are returned, i.e. the nodes that are also keys.
Returns:
a topological ordering of the DAG.
Raises:
an error if this is not possible (graph is not valid).
"""
dag = copy.de... | 0.002913 |
def _activity_or_list(value):
"""Tries to convert value to :class:`tincan.ActivityList`
:setter type: :class:`tincan.ActivityList`
:rtype: :class:`tincan.ActivityList`
"""
result = value
if value is not None and not isinstance(value, ActivityList):
try:
... | 0.004115 |
def next(self):
"""Return the next transaction object.
StopIteration will be propagated from self.csvreader.next()
"""
try:
return self.dict_to_xn(self.csvreader.next())
except MetadataException:
# row was metadata; proceed to next row
return ... | 0.006061 |
def create_ticket(self, ticket=None, **kwargs):
"""
Create a new ``Ticket``. Additional arguments are passed to the
``create()`` function. Return the newly created ``Ticket``.
"""
if not ticket:
ticket = self.create_ticket_str()
if 'service' in kwargs:
... | 0.003049 |
def _convert_listlike(arg, unit='ns', box=True, errors='raise', name=None):
"""Convert a list of objects to a timedelta index object."""
if isinstance(arg, (list, tuple)) or not hasattr(arg, 'dtype'):
# This is needed only to ensure that in the case where we end up
# returning arg (errors == "... | 0.000757 |
def load_grouped_actions(spec, default_group=None, key_prefix="actions", pop_keys=False, expr_parser=None):
"""Instanciates actions from a dict. Will look for a key name key_prefix and
for key starting with key_prefix followed by a dot and a group name. A group
name can be any string and will can be used la... | 0.005643 |
def cdf(arr, pos=None):
'''
Return the cumulative density function of a given array or
its intensity at a given position (0-1)
'''
r = (arr.min(), arr.max())
hist, bin_edges = np.histogram(arr, bins=2 * int(r[1] - r[0]), range=r)
hist = np.asfarray(hist) / hist.sum()
cdf = np.c... | 0.002342 |
def not_user_filter(config, message, fasnick=None, *args, **kw):
""" Everything except a particular user
Use this rule to exclude messages that are associated with one or more
users. Specify several users by separating them with a comma ','.
"""
fasnick = kw.get('fasnick', fasnick)
if not fasn... | 0.001724 |
def generate_vector_color_map(self):
"""Generate color stops array for use with match expression in mapbox template"""
vector_stops = []
# if join data specified as filename or URL, parse JSON to list of Python dicts
if type(self.data) == str:
self.data = geojson_to_dict_lis... | 0.008951 |
def create_mssql_pyodbc(self, **kwargs):
"""
:rtype: Engine
"""
return self._ce(
self._ccs(self.DialectAndDriver.mssql_pyodbc), **kwargs
) | 0.010526 |
def vcs_rbridge_config_input_vcs_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
vcs_rbridge_config = ET.Element("vcs_rbridge_config")
config = vcs_rbridge_config
input = ET.SubElement(vcs_rbridge_config, "input")
vcs_id = ET.SubElemen... | 0.004237 |
def get_slide_context(self):
"""Return the context dict for rendering this slide."""
return {
'title': self.title,
'level': self.level,
'content': self.content,
'classes': self.classes,
'slide_classes': self._filter_classes(exclude='content-')... | 0.003752 |
def interpolate_data(self, data, times, resampled_times):
""" Interpolates data feature
:param data: Array in a shape of t x nobs, where nobs = h x w x n
:type data: numpy.ndarray
:param times: Array of reference times in second relative to the first timestamp
:type times: numpy... | 0.006329 |
def check(self, value, major):
"""Check whether the value in the set of allowed values.
Raise a ValueError if it is not.
"""
if self._case_insensitive:
value = value.lower()
values = self._valid_values_lower
caseflag = " (case-insensitive)"
e... | 0.003552 |
def phon(self, cls='current', previousdelimiter="", strict=False,correctionhandling=CorrectionHandling.CURRENT):
"""Get the phonetic representation associated with this element (of the specified class)
The phonetic content will be constructed from child-elements whereever possible, as they are more spe... | 0.00955 |
def set(context="notebook", style="darkgrid", palette="deep",
font="sans-serif", font_scale=1, color_codes=False, rc=None):
"""Set aesthetic parameters in one step.
Each set of parameters can be set directly or temporarily, see the
referenced functions below for more information.
Parameters
... | 0.000803 |
def _parse_config_file_impl(filename):
"""
Format for the file is:
credentials:
email: ...
api_token: ...
:param filename: The filename to parse
:return: A tuple with:
- email
- api_token
"""
api_key = None
email = ... | 0.003707 |
def stop(self):
"""
Stops the service.
"""
if self.log_file != PIPE and not (self.log_file == DEVNULL and _HAS_NATIVE_DEVNULL):
try:
self.log_file.close()
except Exception:
pass
if self.process is None:
return
... | 0.003165 |
def show_keyword_version_message(sender, keyword_version, inasafe_version):
"""Show a message indicating that the keywords version is mismatch
.. versionadded: 3.2
:param sender: Sender of the message signal. Default to Any object.
:type sender: object
:param keyword_version: The version of the l... | 0.000668 |
def zk_client(host, scheme, credential):
""" returns a connected (and possibly authenticated) ZK client """
if not re.match(r".*:\d+$", host):
host = "%s:%d" % (host, DEFAULT_ZK_PORT)
client = KazooClient(hosts=host)
client.start()
if scheme != "":
client.add_auth(scheme, credenti... | 0.002924 |
def construct_formset(self):
"""
Returns an instance of the inline formset
"""
if not self.inline_model or not self.parent_model:
msg = "Parent and Inline models are required in {}".format(self.__class__.__name__)
raise NotModelException(msg)
return inlin... | 0.006818 |
def update(self, other):
""" Merge two XmlCtsWorkMetadata Objects.
- Original (left Object) keeps his parent.
- Added document overwrite text if it already exists
:param other: XmlCtsWorkMetadata object
:type other: CtsWorkMetadata
:return: XmlCtsWorkMetadata Object
... | 0.003619 |
def zero_year_special_case(from_date, to_date, start, end):
"""strptime does not resolve a 0000 year, we must handle this."""
if start == 'pos' and end == 'pos':
# always interval from earlier to later
if from_date.startswith('0000') and not to_date.startswith('0000'):
return True
... | 0.000465 |
def combine_tax_scales(node):
"""
Combine all the MarginalRateTaxScales in the node into a single MarginalRateTaxScale.
"""
combined_tax_scales = None
for child_name in node:
child = node[child_name]
if not isinstance(child, AbstractTaxScale):
log.info('Skipping {} w... | 0.007622 |
def huji_sample(orient_file, meths='FS-FD:SO-POM:SO-SUN', location_name='unknown',
samp_con="1", ignore_dip=True, data_model_num=3,
samp_file="samples.txt", site_file="sites.txt",
dir_path=".", input_dir_path=""):
"""
Convert HUJI sample file to MagIC file(s)
... | 0.000897 |
def is_cached(self):
"""Returns true if this rule is already cached."""
# TODO: cache by target+hash, not per file.
try:
for item in self.rule.output_files:
log.info(item)
self.cachemgr.in_cache(item, self._metahash())
except cache.CacheMiss:
... | 0.004024 |
def display(self, *amplExpressions):
"""
Writes on the current OutputHandler the outcome of the AMPL statement.
.. code-block:: ampl
display e1, e2, .., en;
where e1, ..., en are the strings passed to the procedure.
Args:
amplExpressions: Expressions t... | 0.003899 |
def to_py(o, keyword_fn: Callable[[kw.Keyword], Any] = _kw_name):
"""Recursively convert Lisp collections into Python collections."""
if isinstance(o, ISeq):
return _to_py_list(o, keyword_fn=keyword_fn)
elif not isinstance(
o, (IPersistentList, IPersistentMap, IPersistentSet, IPersistentVect... | 0.002315 |
def _year_month_delta_from_elements(elements):
"""
Return a tuple of (years, months) from a dict of date elements.
Accepts a dict containing any of the following:
- years
- months
Example:
>>> _year_month_delta_from_elements({'years': 2, 'months': 14})
(3, 2)
"""
return di... | 0.002232 |
def metastability(alpha, T, right_eigenvectors, square_map, pi):
"""Return the metastability PCCA+ objective function.
Parameters
----------
alpha : ndarray
Parameters of objective function (e.g. flattened A)
T : csr sparse matrix
Transition matrix
right_eigenvectors : ndarray
... | 0.000757 |
def update_subtask(self, subtask_id, revision, title=None, completed=None):
'''
Updates the subtask with the given ID
See https://developer.wunderlist.com/documentation/endpoints/subtask for detailed parameter information
Returns:
Subtask with given ID with properties and revis... | 0.00883 |
def capture_pywarnings(handler):
"""Log python system warnings."""
logger = logging.getLogger('py.warnings')
# Check for previously installed handlers.
for h in logger.handlers:
if isinstance(h, handler.__class__):
return
logger.addHandler(handler)
... | 0.005602 |
def close(self):
"""Close this metrics repository."""
for reporter in self._reporters:
reporter.close()
self._metrics.clear() | 0.012346 |
def _parse_date(self, date_string):
"""Parse the date_string and return a datetime object as UTC."""
date = datetime.strptime(date_string, self._DATE_FORMAT)
self.date = self._TZ.localize(date).astimezone(pytz.UTC) | 0.008403 |
def format_context(
context: Context, formatter: typing.Union[str, Formatter] = "full"
) -> str:
"""Output the a context dictionary as a string."""
if not context:
return ""
if callable(formatter):
formatter_func = formatter
else:
if formatter in CONTEXT_FORMATTERS:
... | 0.002041 |
def _dryrun_cell(args, cell_body):
"""Implements the BigQuery cell magic used to dry run BQ queries.
The supported syntax is:
%%bq dryrun [-q|--sql <query identifier>]
[<YAML or JSON cell_body or inline SQL>]
Args:
args: the argument following '%bq dryrun'.
cell_body: optional contents of the cel... | 0.010025 |
def teardown_app_request(self, f):
"""Like :meth:`Flask.teardown_request` but for a blueprint. Such a
function is executed when tearing down each request, even if outside of
the blueprint.
"""
self.record_once(lambda s: s.app.teardown_request_funcs
.setdefault(None, ... | 0.008547 |
def base64_process(**kwargs):
"""
Process base64 file io
"""
str_fileToSave = ""
str_fileToRead = ""
str_action = "encode"
data = None
for k,v in kwargs.items():
if k == 'action': str_action = v
if k == 'payloadBytes'... | 0.012848 |
def django_include(context, template_name, **kwargs):
'''
Mako tag to include a Django template withing the current DMP (Mako) template.
Since this is a Django template, it is search for using the Django search
algorithm (instead of the DMP app-based concept).
See https://docs.djangoproject.com/en/2... | 0.004228 |
def create_server(initialize=True):
"""Create a server"""
with provider() as p:
host_string = p.create_server()
if initialize:
env.host_string = host_string
initialize_server() | 0.004464 |
def validate(self,
asset,
amount,
portfolio,
algo_datetime,
algo_current_data):
"""
Fail if we would hold negative shares of asset after completing this
order.
"""
if portfolio.positions[asset].a... | 0.01737 |
def _put(self, *args, **kwargs):
"""
A wrapper for putting things. It will also json encode your 'data' parameter
:returns: The response of your put
:rtype: dict
:raises: This will raise a
:class:`NewRelicAPIServerException<newrelic_api.exceptions.NewRelicAPIServerE... | 0.005857 |
def K2findCampaigns_main(args=None):
"""Exposes K2findCampaigns to the command line."""
parser = argparse.ArgumentParser(
description="Check if a celestial coordinate is "
"(or was) observable by any past or future "
"observing ... | 0.000685 |
def paragraph_sub(match):
"""Captures paragraphs."""
text = re.sub(r' \n', r'\n<br/>\n', match.group(0).strip())
return '<p>{}</p>'.format(text) | 0.006369 |
def print_pack(document_loader, # type: Loader
processobj, # type: CommentedMap
uri, # type: Text
metadata # type: Dict[Text, Any]
): # type (...) -> Text
"""Return a CWL serialization of the CWL document in JSON."""
packed... | 0.003984 |
def explain_template_loading_attempts(app, template, attempts):
"""
This should help developers understand what failed. Mostly the same as
:func:`flask.debughelpers.explain_template_loading_attempts`, except here we've
extended it to support showing what :class:`UnchainedJinjaLoader` is doing.
"""
... | 0.00172 |
def intersect_leaderboards(self, destination, keys, aggregate='SUM'):
'''
Intersect leaderboards given by keys with this leaderboard into a named destination leaderboard.
@param destination [String] Destination leaderboard name.
@param keys [Array] Leaderboards to be merged with the cur... | 0.007407 |
def point(self, x, y, char):
"""Create a point on ASCII canvas.
Args:
x (int): x coordinate. Should be >= 0 and < number of columns in
the canvas.
y (int): y coordinate. Should be >= 0 an < number of lines in the
canvas.
char (str): ch... | 0.003515 |
def to_fits(self):
"""
Converts a `~regions.ShapeList` to a `~astropy.table.Table` object.
"""
max_length_coord = 1
coord_x = []
coord_y = []
shapes = []
radius = []
rotangle_deg = []
components = []
reg_reverse_mapping = {value: ... | 0.002415 |
def isoncurve(self, p):
"""
verifies if a point is on the curve
"""
return p.iszero() or p.y ** 2 == p.x ** 3 + self.a * p.x + self.b | 0.012121 |
def load_vpatt(filename1, filename2):
"""Loads a VectorPatternUniform pattern that is saved between two files.
"""
with open(filename1) as f:
lines = f.readlines()
lst = lines[0].split(',')
patt1 = np.zeros([int(lst[0]), int(lst[1])],
dtype=np.complex128)
... | 0.004753 |
def divisions(self):
"""
Recursively get all the text divisions directly part of this element. If an element contains parts or text without tag. Those will be returned in order and wrapped with a TextDivision.
"""
from .placeholder_division import PlaceholderDivision
pl... | 0.005222 |
def get_tow_guide(session, vehicle_index):
"""Get tow guide information."""
profile = get_profile(session)
_validate_vehicle(vehicle_index, profile)
return session.post(TOW_URL, {
'vin': profile['vehicles'][vehicle_index]['vin']
}).json() | 0.003759 |
def _fix_outputs(self, op, outputs):
"""A workaround to handle dropout or similar operator that have more than one out
in ONNX.
"""
if op == 'Dropout':
assert len(outputs) == 2, "ONNX have two outputs for dropout layer."
outputs = outputs[:-1]
return outpu... | 0.012422 |
def run_filters(actions,
prepare=None, finalize=None,
input_stream=None, output_stream=None,
doc=None,
**kwargs):
"""
Receive a Pandoc document from the input stream (default is stdin),
walk through it applying the functions in *actions* to eac... | 0.001188 |
def get_object(brain_object_uid, default=_marker):
"""Get the full content object
:param brain_object_uid: A catalog brain or content object or uid
:type brain_object_uid: PortalObject/ATContentType/DexterityContentType
/CatalogBrain/basestring
:returns: The full object
"""
if is_uid(brain_... | 0.001524 |
def get_art(cache_dir, size, client):
"""Get the album art."""
song = client.currentsong()
if len(song) < 2:
print("album: Nothing currently playing.")
return
file_name = f"{song['artist']}_{song['album']}_{size}.jpg".replace("/", "")
file_name = cache_dir / file_name
if file_... | 0.001244 |
def get_filtered_path(path_to_image, filename_key, storage):
"""
Return the 'filtered path'
"""
containing_folder, filename = os.path.split(path_to_image)
filtered_filename = get_filtered_filename(filename, filename_key)
path_to_return = os.path.join(*[
containing_folder,
VERSAT... | 0.001908 |
def redirect_to_ssl(self):
"""Redirect incoming requests to HTTPS."""
# Should we redirect?
criteria = [
request.is_secure,
current_app.debug,
current_app.testing,
request.headers.get('X-Forwarded-Proto', 'http') == 'https'
]
if no... | 0.00315 |
def fromseconds(cls, seconds):
"""Return a |Period| instance based on a given number of seconds."""
try:
seconds = int(seconds)
except TypeError:
seconds = int(seconds.flatten()[0])
return cls(datetime.timedelta(0, int(seconds))) | 0.007018 |
def save_pickle(obj, outfile, protocol=2):
"""Save the object as a pickle file
Args:
outfile (str): Filename
protocol (int): Pickle protocol to use. Default is 2 to remain compatible with Python 2
Returns:
str: Path to pickle file
"""
with open(outfile, 'wb') as f:
... | 0.005277 |
def components(self):
"""
Returns full :class:`dict` of :class:`Component` instances, after
a successful :meth:`build`
:return: dict of named :class:`Component` instances
:rtype: :class:`dict`
For more information read about the :ref:`parts_assembly-build-cycle` .
... | 0.004598 |
def get_grid_mapping_variables(ds):
'''
Returns a list of grid mapping variables
:param netCDF4.Dataset ds: An open netCDF4 Dataset
'''
grid_mapping_variables = []
for ncvar in ds.get_variables_by_attributes(grid_mapping=lambda x: x is not None):
if ncvar.grid_mapping in ds.variables:
... | 0.004831 |
def _expectation(p, constant_mean, none, kern, feat, nghp=None):
"""
Compute the expectation:
expectation[n] = <m(x_n)^T K_{x_n, Z}>_p(x_n)
- m(x_i) = c :: Constant function
- K_{.,.} :: Kernel function
:return: NxQxM
"""
with params_as_tensors_for(constant_mean):
c =... | 0.002188 |
def last_time_non_ok_or_up(self):
"""Get the last time the service was in a non-OK state
:return: the nearest last time the service was not ok
:rtype: int
"""
non_ok_times = [x for x in [self.last_time_warning,
self.last_time_critical,
... | 0.003231 |
def recent(self):
"""
Retrieve a selection of conversations with the most recent activity, and store them in the cache.
Each conversation is only retrieved once, so subsequent calls will retrieve older conversations.
Returns:
:class:`SkypeChat` list: collection of recent co... | 0.005564 |
def build_variable_font(
self,
designspace,
output_path=None,
output_dir=None,
master_bin_dir=None,
ttf=True,
):
"""Build OpenType variable font from masters in a designspace."""
assert not (output_path and output_dir), "mutually exclusive args"
... | 0.003712 |
def generateVariant(self, referenceName, position, randomNumberGenerator):
"""
Generate a random variant for the specified position using the
specified random number generator. This generator should be seeded
with a value that is unique to this position so that the same variant
w... | 0.00102 |
def generate_safemode_windows():
"""Produce batch file to run QML in safe-mode
Usage:
$ python -c "import compat;compat.generate_safemode_windows()"
$ run.bat
"""
try:
import pyblish
import pyblish_qml
import PyQt5
except ImportError:
return sys.st... | 0.000738 |
def wraps(__fn, **kw):
"""Like ``functools.wraps``, with support for annotations."""
kw['assigned'] = kw.get('assigned', WRAPPER_ASSIGNMENTS)
return functools.wraps(__fn, **kw) | 0.01 |
def get_sorted_attachments(self):
"""Returns a sorted list of analysis info dictionaries
"""
inf = float("inf")
order = self.get_attachments_order()
attachments = self.get_attachments()
def att_cmp(att1, att2):
_n1 = att1.get('UID')
_n2 = att2.get... | 0.003431 |
def unregister(self, model):
"""
Unregister a permission handler from the model
Parameters
----------
model : django model class
A django model class
Raises
------
KeyError
Raise when the model have not registered in registry yet.... | 0.003509 |
def generator(self, output, target):
"Evaluate the `output` with the critic then uses `self.loss_funcG` to combine it with `target`."
fake_pred = self.gan_model.critic(output)
return self.loss_funcG(fake_pred, target, output) | 0.012048 |
def calc_conf_intervals(self,
conf_percentage,
interval_type='all',
init_vals=None,
epsilon=abc.EPSILON,
**fit_kwargs):
"""
Calculates percentile, bias-corrected an... | 0.001506 |
def get(self, node, path):
"""
Return instance at `path`.
An example module tree:
>>> from anytree import Node
>>> top = Node("top", parent=None)
>>> sub0 = Node("sub0", parent=top)
>>> sub0sub0 = Node("sub0sub0", parent=sub0)
>>> sub0sub1 = Node("sub0su... | 0.002248 |
def GeneralGuinier(q, G, Rg, s):
"""Generalized Guinier scattering
Inputs:
-------
``q``: independent variable
``G``: factor
``Rg``: radius of gyration
``s``: dimensionality parameter (can be 1, 2, 3)
Formula:
--------
``G/q**(3-s)*exp(-(q^2*Rg^2)/s)``
"... | 0.002639 |
def FileTransfer(*args, **kwargs):
"""Factory function selects the proper SCP class and creates object based on device_type."""
if len(args) >= 1:
device_type = args[0].device_type
else:
device_type = kwargs["ssh_conn"].device_type
if device_type not in scp_platforms:
raise Value... | 0.003578 |
def comment_sync(self, comment):
"""Update comments to host and notify subscribers"""
self.host.update(key="comment", value=comment)
self.host.emit("commented", comment=comment) | 0.00995 |
def plot(X, marker='.', kind='plot', title=None, fig='current', ax=None,
**kwargs):
'''General plotting function that aims to cover most common cases.
X : numpy array of 1d, 2d, or 3d points, with one point per row.
marker : passed to the underlying plotting function
kind : one of {plot, scatter} that ... | 0.022388 |
def root_parent(self, category=None):
""" Returns the topmost parent of the current category. """
return next(filter(lambda c: c.is_root, self.hierarchy())) | 0.011628 |
def image_query_record(self, imagename=None):
"""Query the image record from database, if imagename is None, all
of the image records will be returned, otherwise only the specified
image record will be returned."""
if imagename:
with get_image_conn() as conn:
... | 0.003698 |
def _magic_parser(stream, magic):
"""
Parse the section with the SCF cycle
Returns:
dict where the key are the name of columns and
the values are list of numbers. Note if no section was found.
.. warning::
The parser is very fragile and should be replaced by YAML.
"""
... | 0.004471 |
def download_parsed(self, days=60):
"""Downloaded OFX response parsed by :py:meth:`OfxParser.parse`
:param days: Number of days to look back at
:type days: integer
:rtype: :py:class:`ofxparser.Ofx`
"""
if IS_PYTHON_2:
return OfxParser.parse(
s... | 0.004107 |
def urisplit(uristring):
"""Split a well-formed URI reference string into a tuple with five
components corresponding to a URI's general structure::
<scheme>://<authority>/<path>?<query>#<fragment>
"""
if isinstance(uristring, bytes):
result = SplitResultBytes
else:
result = S... | 0.002545 |
def spin_thread(self, interval=1):
"""call Client.spin() in a background thread on some regular interval
This helps ensure that messages don't pile up too much in the zmq queue
while you are working on other things, or just leaving an idle terminal.
It also helps limit ... | 0.008803 |
def cp(hdfs_src, hdfs_dst):
"""Copy a file
:param hdfs_src: Source (str)
:param hdfs_dst: Destination (str)
:raises: IOError: If unsuccessful
"""
cmd = "hadoop fs -cp %s %s" % (hdfs_src, hdfs_dst)
rcode, stdout, stderr = _checked_hadoop_fs_command(cmd) | 0.003559 |
def replace_tax_rate_by_id(cls, tax_rate_id, tax_rate, **kwargs):
"""Replace TaxRate
Replace all attributes of TaxRate
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.replace_tax_rate_by_id(ta... | 0.004965 |
def gen_locale(locale, **kwargs):
'''
Generate a locale. Options:
.. versionadded:: 2014.7.0
:param locale: Any locale listed in /usr/share/i18n/locales or
/usr/share/i18n/SUPPORTED for Debian and Gentoo based distributions,
which require the charmap to be specified as part of the loca... | 0.001092 |
def enumerate_joint_ask(X, e, P):
"""Return a probability distribution over the values of the variable X,
given the {var:val} observations e, in the JointProbDist P. [Section 13.3]
>>> P = JointProbDist(['X', 'Y'])
>>> P[0,0] = 0.25; P[0,1] = 0.5; P[1,1] = P[2,1] = 0.125
>>> enumerate_joint_ask('X',... | 0.004208 |
def get_dict(self, only_attributes=None, exclude_attributes=None, df_format=False):
"""Get a dictionary of this object's attributes. Optional format for storage in a Pandas DataFrame.
Args:
only_attributes (str, list): Attributes that should be returned. If not provided, all are returned.
... | 0.005324 |
def rewrite_subject_group(root, subjects, subject_group_type, overwrite=True):
"add or rewrite subject tags inside subj-group tags"
parent_tag_name = 'subj-group'
tag_name = 'subject'
wrap_tag_name = 'article-categories'
tag_attribute = 'subj-group-type'
# the parent tag where it should be found... | 0.000905 |
def squash(self, a, b):
"""
Returns a generator that squashes two iterables into one.
```
['this', 'that'], [[' and', ' or']] => ['this and', 'this or', 'that and', 'that or']
```
"""
return ((''.join(x) if isinstance(x, tuple) else x) for x in itertools.product... | 0.012232 |
def set_checked(self, checked):
""" Properly check the correct radio button.
"""
if not checked:
self.widget.clearCheck()
else:
#: Checked is a reference to the radio declaration
#: so we need to get the ID of it
rb = checked.proxy.widget
... | 0.004914 |
def get_file_range(ase, offsets, timeout=None):
# type: (blobxfer.models.azure.StorageEntity,
# blobxfer.models.download.Offsets, int) -> bytes
"""Retrieve file range
:param blobxfer.models.azure.StorageEntity ase: Azure StorageEntity
:param blobxfer.models.download.Offsets offsets: download ... | 0.001232 |
def parse_args():
"""Define and parse command line arguments"""
parser = argparse.ArgumentParser(
description='''Convert a set of files to a single h5features file, input files
can be npz (numpy) or mat (MATLAB) files.''')
parser.add_argument('file', nargs='+', type=str,
... | 0.002051 |
def main(argv=None):
""" Invoke the cosmic ray evaluation.
:param argv: the command line arguments
"""
signal.signal(
signal.SIGINT,
lambda *args: sys.exit(_SIGNAL_EXIT_CODE_BASE + signal.SIGINT))
if hasattr(signal, 'SIGINFO'):
signal.signal(
getattr(signal, 'SI... | 0.000805 |
def load():
"""Loads the libdmtx shared library.
"""
if 'Windows' == platform.system():
# Possible scenarios here
# 1. Run from source, DLLs are in pylibdmtx directory
# cdll.LoadLibrary() imports DLLs in repo root directory
# 2. Wheel install into CPython installat... | 0.000935 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.