repo
stringlengths 1
29
| path
stringlengths 24
332
| code
stringlengths 39
579k
|
---|---|---|
simpleder | simpleder//der.pyfile:/der.py:function:compute_total_length/compute_total_length | def compute_total_length(hyp):
"""Compute total length of a hypothesis/reference.
Args:
hyp: a list of tuples, where each tuple is (speaker, start, end)
of type (string, float, float)
Returns:
a float number for the total length
"""
total_length = 0.0
for element in hyp:
total_length += element[2] - element[1]
return total_length
|
ch2 | ch2//sql/tables/statistic.pyclass:StatisticName/parse | @classmethod
def parse(cls, name, default_owner=None, default_activity_group=None):
"""
This parses the standard, extended format for naming statistics. It is one to three fields, separated by ':'.
These are one of 'name', 'owner:name', or 'owner:name:activity_group'.
Currently this is used only by reftuple which itself is used only in the power pipeline configuration.
"""
parts, owner, activity_group = name.split(':'), None, None
if len(parts) == 1:
name = parts[0]
elif len(parts) == 2:
owner, name = parts
else:
owner, name, activity_group = parts
if not owner:
owner = default_owner
if not owner:
raise Exception(f'Missing owner for {name}')
if not activity_group:
activity_group = default_activity_group
if activity_group == 'None':
activity_group = None
return owner, name, activity_group
|
TSAnalyzer | TSAnalyzer//algorithms/date.pyfile:/algorithms/date.py:function:julday2mjd/julday2mjd | def julday2mjd(*args):
""" julian day to modified julian day
Args:
julday (int) : julian day
hour (int) : hour, optional
minute (int) : minute, optional
seconds (float) : seconds, optional
Returns:
float : modified julian day
"""
julday = args[0]
mjd = julday - 2400001.0
hms = [24, 1440, 86400]
for i, v in enumerate(args[1:]):
mjd += v / hms[i]
return mjd
|
multidict-4.7.5 | multidict-4.7.5//multidict/_multidict_base.pyfile:/multidict/_multidict_base.py:function:_keysview_isdisjoint/_keysview_isdisjoint | def _keysview_isdisjoint(view, other):
"""Return True if two sets have a null intersection."""
for k in other:
if k in view:
return False
return True
|
datafold | datafold//dynfold/dmap.pyclass:DiffusionMaps/from_operator_name | @classmethod
def from_operator_name(cls, name: str, **kwargs) ->'DiffusionMaps':
"""Instantiate new model to approximate operator (to be selected by name).
Parameters
----------
name
"laplace_beltrami", "fokker_plank", "graph_laplacian" or "rbf".
**kwargs
All parameters in :py:class:`DiffusionMaps` but ``alpha``.
Returns
-------
DiffusionMaps
self
"""
if name == 'laplace_beltrami':
eigfunc_interp = cls.laplace_beltrami(**kwargs)
elif name == 'fokker_planck':
eigfunc_interp = cls.fokker_planck(**kwargs)
elif name == 'graph_laplacian':
eigfunc_interp = cls.graph_laplacian(**kwargs)
elif name == 'rbf':
eigfunc_interp = cls.rbf_kernel(**kwargs)
else:
raise ValueError(
f"name='{name}' not known. Choose from {cls._cls_valid_operator_names}"
)
if name not in cls._cls_valid_operator_names:
raise NotImplementedError(
f'This is a bug. name={name} each name has to be listed in VALID_OPERATOR_NAMES'
)
return eigfunc_interp
|
jc | jc//parsers/gshadow.pyfile:/parsers/gshadow.py:function:process/process | def process(proc_data):
"""
Final processing to conform to the schema.
Parameters:
proc_data: (dictionary) raw structured data to process
Returns:
List of dictionaries. Structured data with the following schema:
[
{
"group_name": string,
"password": string,
"administrators": [
string
],
"members": [
string
]
}
]
"""
for entry in proc_data:
if entry['administrators'] == ['']:
entry['administrators'] = []
if entry['members'] == ['']:
entry['members'] = []
return proc_data
|
librecaptcha-0.6.2 | librecaptcha-0.6.2//librecaptcha/recaptcha.pyclass:Solver/on_solved | def on_solved(response, **kwargs):
"""Callback; set this attribute in the parent class."""
raise NotImplementedError
|
pants | pants//contrib/node/tasks/node_resolve.pyclass:NodeResolve/_clear_resolvers | @classmethod
def _clear_resolvers(cls) ->None:
"""Remove all resolvers.
This method is EXCLUSIVELY for use in tests.
"""
cls._resolver_by_type.clear()
|
spike_py-0.99.17 | spike_py-0.99.17//spike/NPKData.pyfile:/spike/NPKData.py:function:ident/ident | def ident(v):
"""a identity function used by default converter"""
return v
|
railgun-0.1.8 | railgun-0.1.8//railgun/cmemsubsets.pyfile:/railgun/cmemsubsets.py:function:concatfunc/concatfunc | def concatfunc(func, lst):
"""
Concatenate returned list of `func(elem)` for `elem` in `lst`
"""
ret = []
for elem in lst:
ret += func(elem)
return ret
|
pytoolbox | pytoolbox//validation.pyfile:/validation.py:function:valid_port/valid_port | def valid_port(port):
"""
Returns True if `port` is a valid port.
**Example usage**
>>> assert(not valid_port(-1))
>>> assert(not valid_port('something not a port'))
>>> assert(valid_port('80'))
>>> valid_port(65535)
True
"""
try:
return 0 <= int(port) < 2 ** 16
except:
return False
|
pyspark-2.4.5 | pyspark-2.4.5//pyspark/streaming/kinesis.pyfile:/pyspark/streaming/kinesis.py:function:utf8_decoder/utf8_decoder | def utf8_decoder(s):
""" Decode the unicode as UTF-8 """
if s is None:
return None
return s.decode('utf-8')
|
Pytzer-0.4.3 | Pytzer-0.4.3//pytzer/parameters.pyfile:/pytzer/parameters.py:function:psi_MgOH_Na_HSO4_HMW84/psi_MgOH_Na_HSO4_HMW84 | def psi_MgOH_Na_HSO4_HMW84(T, P):
"""c-c'-a: magnesium-hydroxide sodium bisulfate [HMW84]."""
psi = 0.0
valid = T == 298.15
return psi, valid
|
kur | kur//sources/text.pyclass:RawText/default_chunk_size | @classmethod
def default_chunk_size(cls):
""" Returns the default chunk size for this source.
"""
return 256
|
qtile-plasma-1.5.5 | qtile-plasma-1.5.5//plasma/enum.pyfile:/plasma/enum.py:function:_is_dunder/_is_dunder | def _is_dunder(name):
"""Returns True if a __dunder__ name, False otherwise."""
return name[:2] == name[-2:] == '__' and name[2:3] != '_' and name[-3:-2
] != '_' and len(name) > 4
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/info.pyfile:/bpy/ops/info.py:function:report_copy/report_copy | def report_copy():
"""Copy selected reports to Clipboard
"""
pass
|
stormpy-1.3.0 | stormpy-1.3.0//setup/helper.pyfile:/setup/helper.py:function:parse_storm_version/parse_storm_version | def parse_storm_version(version_string):
"""
Parses the version of storm.
:param version_string: String containing version information.
:return: Tuple (version, commit)
"""
split = version_string.split('-')
version = split[0]
commit = ''
if len(split) > 1:
commit = split[1]
return version, commit
|
wmcore-1.1.19.2 | wmcore-1.1.19.2//src/python/WMCore/REST/Server.pyfile:/src/python/WMCore/REST/Server.py:function:rxfilter/rxfilter | def rxfilter(rx, select, cursor):
"""Utility function to convert a sequence `cursor` to a generator, but
applying a filtering predicate to select which rows to return.
The assumption is that `cursor` yields uniform sequence objects ("rows"),
and the `select` operator can be invoked with ``select(row)`` for each
retrieved row to return a string. If the value returned matches the
regular expression `rx`, the original row is included in the generator
output, otherwise it's skipped.
:arg re.RegexObject rx: Regular expression to match against, or at least
any object which supports ``rx.match(value)`` on the value returned by
the ``select(row)`` operator.
:arg callable select: An operator which returns the item to filter on,
given a row of values, typically an :func:`operator.itemgetter`.
:arg sequence cursor: Input sequence."""
for row in cursor:
if rx.match(select(row)):
yield row
|
introcs | introcs//strings.pyfile:/strings.py:function:count_str/count_str | def count_str(text, sub, start=None, end=None):
"""
Computes the number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``.
Optional arguments start and end are interpreted as in slice notation.
:param text: The string to search
:type text: ``str``
:param sub: The substring to count
:type sub: ``str``
:param start: The start of the search range
:type start: ``int``
:param end: The end of the search range
:type end: ``int``
:return: The number of non-overlapping occurrences of substring ``sub`` in ``text[start:end]``.
:rtype: ``int``
"""
assert isinstance(text, str), '%s is not a string' % text
return text.count(sub, start, end)
|
alphapy | alphapy//transforms.pyfile:/transforms.py:function:c2min/c2min | def c2min(f, c1, c2):
"""Take the minimum value between two columns in a dataframe.
Parameters
----------
f : pandas.DataFrame
Dataframe containing the two columns ``c1`` and ``c2``.
c1 : str
Name of the first column in the dataframe ``f``.
c2 : str
Name of the second column in the dataframe ``f``.
Returns
-------
min_val : float
The minimum value of the two columns.
"""
min_val = min(f[c1], f[c2])
return min_val
|
firexapp | firexapp//submit/reporting.pyclass:ReportGenerator/pre_run_report | @staticmethod
def pre_run_report(**kwarg):
""" This runs in the context of __main__ """
pass
|
gwpy | gwpy//timeseries/core.pyclass:TimeSeriesBase/find | @classmethod
def find(cls, channel, start, end, frametype=None, pad=None, scaled=None,
dtype=None, nproc=1, verbose=False, **readargs):
"""Find and read data from frames for a channel
Parameters
----------
channel : `str`, `~gwpy.detector.Channel`
the name of the channel to read, or a `Channel` object.
start : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
GPS start time of required data,
any input parseable by `~gwpy.time.to_gps` is fine
end : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
GPS end time of required data,
any input parseable by `~gwpy.time.to_gps` is fine
frametype : `str`, optional
name of frametype in which this channel is stored, will search
for containing frame types if necessary
nproc : `int`, optional, default: `1`
number of parallel processes to use, serial process by
default.
pad : `float`, optional
value with which to fill gaps in the source data,
by default gaps will result in a `ValueError`.
dtype : `numpy.dtype`, `str`, `type`, or `dict`
numeric data type for returned data, e.g. `numpy.float`, or
`dict` of (`channel`, `dtype`) pairs
allow_tape : `bool`, optional, default: `True`
allow reading from frame files on (slow) magnetic tape
verbose : `bool`, optional
print verbose output about read progress, if ``verbose``
is specified as a string, this defines the prefix for the
progress meter
**readargs
any other keyword arguments to be passed to `.read()`
"""
return cls.DictClass.find([channel], start, end, frametype=frametype,
verbose=verbose, pad=pad, scaled=scaled, dtype=dtype, nproc=nproc,
**readargs)[str(channel)]
|
analytics-python-1.2.9 | analytics-python-1.2.9//analytics/utils.pyfile:/analytics/utils.py:function:total_seconds/total_seconds | def total_seconds(delta):
"""Determines total seconds with python < 2.7 compat."""
return (delta.microseconds + (delta.seconds + delta.days * 24 * 3600) *
1000000.0) / 1000000.0
|
Diofant-0.11.0 | Diofant-0.11.0//diofant/parsing/sympy_parser.pyfile:/diofant/parsing/sympy_parser.py:function:eval_expr/eval_expr | def eval_expr(code, local_dict, global_dict):
"""
Evaluate Python code generated by ``stringify_expr``.
Generally, ``parse_expr`` should be used.
"""
expr = eval(code, global_dict, local_dict)
return expr
|
substanced | substanced//interfaces.pyclass:IFolder/is_reorderable | def is_reorderable():
""" Return true if the folder can be reordered, false otherwise."""
|
reudom-1.1.5 | reudom-1.1.5//reudom/case.pyclass:TestCase/setUpClass | @classmethod
def setUpClass(cls):
"""Hook method for setting up class fixture before running tests in the class."""
|
espa_api_client | espa_api_client//search.pyfile:/search.py:function:three_digit/three_digit | def three_digit(number):
""" Add 0s to inputs that their length is less than 3.
:param number:
The number to convert
:type number:
int
:returns:
String
"""
number = str(number)
if len(number) == 1:
return u'00%s' % number
elif len(number) == 2:
return u'0%s' % number
else:
return number
|
fake-bpy-module-2.80-20200428 | fake-bpy-module-2.80-20200428//bpy/ops/object.pyfile:/bpy/ops/object.py:function:select_less/select_less | def select_less():
"""Deselect objects at the boundaries of parent/child relationships
"""
pass
|
gurux_dlms-1.0.69 | gurux_dlms-1.0.69//gurux_dlms/GXStandardObisCodeCollection.pyclass:GXStandardObisCodeCollection/getDescription | @classmethod
def getDescription(cls, str_):
"""Get description."""
if not str_ or str_[0] != '$':
return ''
value = int(str_[1:])
if value == 1:
ret = 'Sum Li Active power+ (QI+QIV)'
elif value == 2:
ret = 'Sum Li Active power- (QII+QIII)'
elif value == 3:
ret = 'Sum Li Reactive power+ (QI+QII)'
elif value == 4:
ret = 'Sum Li Reactive power- (QIII+QIV)'
elif value == 5:
ret = 'Sum Li Reactive power QI'
elif value == 6:
ret = 'Sum Li Reactive power QII'
elif value == 7:
ret = 'Sum Li Reactive power QIII'
elif value == 8:
ret = 'Sum Li Reactive power QIV'
elif value == 9:
ret = 'Sum Li Apparent power+ (QI+QIV)'
elif value == 10:
ret = 'Sum Li Apparent power- (QII+QIII)'
elif value == 11:
ret = 'Current: any phase'
elif value == 12:
ret = 'Voltage: any phase'
elif value == 13:
ret = 'Sum Li Power factor'
elif value == 14:
ret = 'Supply frequency'
elif value == 15:
ret = 'Sum Li Active power (abs(QI+QIV)+abs(QII+QIII))'
elif value == 16:
ret = 'Sum Li Active power (abs(QI+QIV)-abs(QII+QIII))'
elif value == 17:
ret = 'Sum Li Active power QI'
elif value == 18:
ret = 'Sum Li Active power QII'
elif value == 19:
ret = 'Sum Li Active power QIII'
elif value == 20:
ret = 'Sum Li Active power QIV'
elif value == 21:
ret = 'L1 Active power+ (QI+QIV)'
elif value == 22:
ret = 'L1 Active power- (QII+QIII)'
elif value == 23:
ret = 'L1 Reactive power+ (QI+QII)'
elif value == 24:
ret = 'L1 Reactive power- (QIII+QIV)'
elif value == 25:
ret = 'L1 Reactive power QI'
elif value == 26:
ret = 'L1 Reactive power QII'
elif value == 27:
ret = 'L1 Reactive power QIII'
elif value == 28:
ret = 'L1 Reactive power QIV'
elif value == 29:
ret = 'L1 Apparent power+ (QI+QIV)'
elif value == 30:
ret = 'L1 Apparent power- (QII+QIII)'
elif value == 31:
ret = 'L1 Current'
elif value == 32:
ret = 'L1 Voltage'
elif value == 33:
ret = 'L1 Power factor'
elif value == 34:
ret = 'L1 Supply frequency'
elif value == 35:
ret = 'L1 Active power (abs(QI+QIV)+abs(QII+QIII))'
elif value == 36:
ret = 'L1 Active power (abs(QI+QIV)-abs(QII+QIII))'
elif value == 37:
ret = 'L1 Active power QI'
elif value == 38:
ret = 'L1 Active power QII'
elif value == 39:
ret = 'L1 Active power QIII'
elif value == 40:
ret = 'L1 Active power QIV'
elif value == 41:
ret = 'L2 Active power+ (QI+QIV)'
elif value == 42:
ret = 'L2 Active power- (QII+QIII)'
elif value == 43:
ret = 'L2 Reactive power+ (QI+QII)'
elif value == 44:
ret = 'L2 Reactive power- (QIII+QIV)'
elif value == 45:
ret = 'L2 Reactive power QI'
elif value == 46:
ret = 'L2 Reactive power QII'
elif value == 47:
ret = 'L2 Reactive power QIII'
elif value == 48:
ret = 'L2 Reactive power QIV'
elif value == 49:
ret = 'L2 Apparent power+ (QI+QIV)'
elif value == 50:
ret = 'L2 Apparent power- (QII+QIII)'
elif value == 51:
ret = 'L2 Current'
elif value == 52:
ret = 'L2 Voltage'
elif value == 53:
ret = 'L2 Power factor'
elif value == 54:
ret = 'L2 Supply frequency'
elif value == 55:
ret = 'L2 Active power (abs(QI+QIV)+abs(QII+QIII))'
elif value == 56:
ret = 'L2 Active power (abs(QI+QIV)-abs(QI+QIII))'
elif value == 57:
ret = 'L2 Active power QI'
elif value == 58:
ret = 'L2 Active power QII'
elif value == 59:
ret = 'L2 Active power QIII'
elif value == 60:
ret = 'L2 Active power QIV'
elif value == 61:
ret = 'L3 Active power+ (QI+QIV)'
elif value == 62:
ret = 'L3 Active power- (QII+QIII)'
elif value == 63:
ret = 'L3 Reactive power+ (QI+QII)'
elif value == 64:
ret = 'L3 Reactive power- (QIII+QIV)'
elif value == 65:
ret = 'L3 Reactive power QI'
elif value == 66:
ret = 'L3 Reactive power QII'
elif value == 67:
ret = 'L3 Reactive power QIII'
elif value == 68:
ret = 'L3 Reactive power QIV'
elif value == 69:
ret = 'L3 Apparent power+ (QI+QIV)'
elif value == 70:
ret = 'L3 Apparent power- (QII+QIII)'
elif value == 71:
ret = 'L3 Current'
elif value == 72:
ret = 'L3 Voltage'
elif value == 73:
ret = 'L3 Power factor'
elif value == 74:
ret = 'L3 Supply frequency'
elif value == 75:
ret = 'L3 Active power (abs(QI+QIV)+abs(QII+QIII))'
elif value == 76:
ret = 'L3 Active power (abs(QI+QIV)-abs(QI+QIII))'
elif value == 77:
ret = 'L3 Active power QI'
elif value == 78:
ret = 'L3 Active power QII'
elif value == 79:
ret = 'L3 Active power QIII'
elif value == 80:
ret = 'L3 Active power QIV'
elif value == 82:
ret = 'Unitless quantities (pulses or pieces)'
elif value == 84:
ret = 'Sum Li Power factor-'
elif value == 85:
ret = 'L1 Power factor-'
elif value == 86:
ret = 'L2 Power factor-'
elif value == 87:
ret = 'L3 Power factor-'
elif value == 88:
ret = 'Sum Li A2h QI+QII+QIII+QIV'
elif value == 89:
ret = 'Sum Li V2h QI+QII+QIII+QIV'
elif value == 90:
ret = (
'SLi current (algebraic sum of the unsigned value of the currents in all phases)'
)
elif value == 91:
ret = 'Lo Current (neutral)'
elif value == 92:
ret = 'Lo Voltage (neutral)'
else:
ret = ''
return ret
|
isomer | isomer//logger.pyfile:/logger.py:function:setup_root/setup_root | def setup_root(newroot):
"""
Sets up the root component, so the logger knows where to send logging
signals.
:param newroot:
"""
global root
root = newroot
|
jnpr | jnpr//junos/facts/get_software_information.pyfile:/junos/facts/get_software_information.py:function:provides_facts/provides_facts | def provides_facts():
"""
Returns a dictionary keyed on the facts provided by this module. The value
of each key is the doc string describing the fact.
"""
return {'junos_info':
"A two-level dictionary providing Junos software version information for each RE in the system. The first-level key is the name of the RE. The second level key is 'text' for the version as a string and 'object' for the version as a version_info object."
, 'hostname':
'A string containing the hostname of the current Routing Engine.',
'hostname_info':
'A dictionary keyed on Routing Engine name. The value of each key is the hostname of the Routing Engine.'
, 'model':
'An uppercase string containing the model of the chassis in which the current Routing Engine resides.'
, 'model_info':
'A dictionary keyed on Routing Engine name. The value of each key is an uppercase string containing the model of the chassis in which the Routing Engine resides.'
, 'version':
'A string containing the Junos version of the current Routing Engine.',
'version_info':
'The Junos version of the current Routing Engine as a version_info object.'
, 'version_RE0':
'A string containing the Junos version of the RE in slot 0. (Assuming the system contains an RE0.)'
, 'version_RE1':
'A string containing the Junos version of the RE in slot 1. (Assuming the system contains an RE1)'
}
|
pybofh-0.2.1 | pybofh-0.2.1//pybofh/settingsmodule.pyclass:FrozenDict/merge | @classmethod
def merge(cls, a, b):
"""Merges two FrozeDict. Similar to update(), but returns new instance"""
x = {}
x.update(a)
x.update(b)
return cls(x)
|
fake-blender-api-2.79-0.3.1 | fake-blender-api-2.79-0.3.1//bpy/ops/mesh.pyfile:/bpy/ops/mesh.py:function:extrude_edges_indiv/extrude_edges_indiv | def extrude_edges_indiv(mirror: bool=False):
"""Extrude individual edges only
:param mirror: Mirror Editing
:type mirror: bool
"""
pass
|
conda_mirror-0.8.2 | conda_mirror-0.8.2//versioneer.pyfile:/versioneer.py:function:render_git_describe_long/render_git_describe_long | def render_git_describe_long(pieces):
"""TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix)
"""
if pieces['closest-tag']:
rendered = pieces['closest-tag']
rendered += '-%d-g%s' % (pieces['distance'], pieces['short'])
else:
rendered = pieces['short']
if pieces['dirty']:
rendered += '-dirty'
return rendered
|
numdoclint-0.0.12 | numdoclint-0.0.12//numdoclint/helper.pyfile:/numdoclint/helper.py:function:read_file_str/read_file_str | def read_file_str(file_path):
"""
Read the target file string.
Parameters
----------
file_path : str
Path of target file.
Returns
-------
file_str : str
The target string read.
"""
with open(file_path, mode='r', encoding='utf-8') as f:
file_str = f.read()
return file_str
|
aredis-1.1.8 | aredis-1.1.8//aredis/utils.pyfile:/aredis/utils.py:function:pairs_to_dict/pairs_to_dict | def pairs_to_dict(response):
"""Create a dict given a list of key/value pairs"""
it = iter(response)
return dict(zip(it, it))
|
lima-0.5 | lima-0.5//lima/schema.pyfile:/lima/schema.py:function:_make_function/_make_function | def _make_function(name, code, globals_=None):
"""Return a function created by executing a code string in a new namespace.
This is not much more than a wrapper around :func:`exec`.
Args:
name: The name of the function to create. Must match the function name
in ``code``.
code: A String containing the function definition code. The name of the
function must match ``name``.
globals_: A dict of globals to mix into the new function's namespace.
``__builtins__`` must be provided explicitly if required.
.. warning:
All pitfalls of using :func:`exec` apply to this function as well.
"""
namespace = dict(__builtins__={})
if globals_:
namespace.update(globals_)
exec(code, namespace)
return namespace[name]
|
bs_ds | bs_ds//glassboxes.pyfile:/glassboxes.py:function:viz_tree/viz_tree | def viz_tree(tree_object):
"""Takes a Sklearn Decision Tree and returns a png image using graph_viz and pydotplus."""
from sklearn.externals.six import StringIO
from IPython.display import Image
from sklearn.tree import export_graphviz
import pydotplus
dot_data = StringIO()
export_graphviz(tree_object, out_file=dot_data, filled=True, rounded=
True, special_characters=True)
graph = pydotplus.graph_from_dot_data(dot_data.getvalue())
tree_viz = Image(graph.create_png())
return tree_viz
|
qrandom | qrandom//qrandom.pyfile:/qrandom.py:function:start_servers/start_servers | def start_servers():
"""Checks if servers are running, if not starts them."""
import os
try:
os.system("gnome-terminal -e 'qvm -S'")
os.system("gnome-terminal -e 'quilc -S'")
except:
try:
os.system("terminal -e 'qvm -S'")
os.system("terminal -e 'quilc -S'")
except:
exit()
|
tpDcc-libs-python-0.0.6 | tpDcc-libs-python-0.0.6//tpDcc/libs/python/mathlib.pyfile:/tpDcc/libs/python/mathlib.py:function:bounding_box_half_values/bounding_box_half_values | def bounding_box_half_values(bbox_min, bbox_max):
"""
Returns the values half way between max and min XYZ given tuples
:param bbox_min: tuple, contains the minimum X,Y,Z values of the mesh bounding box
:param bbox_max: tuple, contains the maximum X,Y,Z values of the mesh bounding box
:return: tuple(int, int, int)
"""
min_x, min_y, min_z = bbox_min
max_x, max_y, max_z = bbox_max
half_x = (min_x + max_x) * 0.5
half_y = (min_y + max_y) * 0.5
half_z = (min_z + max_z) * 0.5
return half_x, half_y, half_z
|
pya2l-0.0.1 | pya2l-0.0.1//pya2l/parser/grammar/parser.pyclass:A2lParser/p_pa_data | @staticmethod
def p_pa_data(p):
"""pa_data : generic_parameter_list"""
p[0] = p[1]
|
blocklist-0.1.1 | blocklist-0.1.1//blocklist/func.pyclass:Func/countline | @staticmethod
def countline(fpath):
"""Return the number of line in a file"
"""
with open(fpath, 'r') as f:
return sum(1 for nbline in f)
|
cvui | cvui//cvui.pyfile:/cvui.py:function:text/text | def text(theWhere, theX, theY, theText, theFontScale=0.4, theColor=13553358):
"""
Display a piece of text.
Parameters
----------
theWhere: np.ndarray
image/frame where the component should be rendered.
theX: int
position X where the component should be placed.
theY: int
position Y where the component should be placed.
theText: str
the text content.
theFontScale: float
size of the text.
theColor: uint
color of the text in the format `0xRRGGBB`, e.g. `0xff0000` for red.
See Also
----------
printf()
"""
print('This is wrapper function to help code autocompletion.')
|
TotalDepth | TotalDepth//RP66/core/RepCode.pyfile:/RP66/core/RepCode.py:function:lenUVARI/lenUVARI | def lenUVARI(v):
"""Returns the length of a UVARI value when represented in bytes."""
if v > 127:
if v > 16383:
return 4
else:
return 2
return 1
|
python3.6 | python3.6//operator.pyfile:/operator.py:function:contains/contains | def contains(a, b):
"""Same as b in a (note reversed operands)."""
return b in a
|
bubble | bubble//util/examples.pyfile:/util/examples.py:function:get_example_client_pull/get_example_client_pull | def get_example_client_pull():
"""dummy client with pull method"""
example = """
from bubble import Bubble
class MyFancyHelloPuller(Bubble):
def say_hello(self,i=0):
return 'Hello, ' + str(i)
# alias for the bubble client to be found by the bubble machinery
class BubbleClient(Bubble):
def __init__(self,cfg={}):
self.CFG=cfg
self.client=MyFancyHelloPuller()
class BubbleClient(Bubble):
def __init__(self,cfg={}):
self.CFG=cfg
self.client=MyFancyHelloPuller()
def pull(self, amount=42+1, index=0):
self.say('BC: %d,%d'%(amount,index))
for i in range(amount):
hello_pull=self.client.say_hello('Pulling in Hello:' + str(i));
yield {'in': hello_pull}
if __name__ == '__main__':
from bubble.util.cfg import get_config
BCFG = get_config()
HELLO = BCFG.CFG.DEV.SOURCE
puller = BubbleClient(HELLO)
print(puller)
print(puller.pull())
"""
return example
|
yggdrasil | yggdrasil//command_line.pyfile:/command_line.py:function:yggtime_py/yggtime_py | def yggtime_py():
"""Plot timing statistics comparing the different versions of Python."""
from yggdrasil import timing
timing.plot_scalings(compare='python')
|
Products.PloneRSS-1.0.7beta | Products.PloneRSS-1.0.7beta//Products/PloneRSS/setuphandlers.pyfile:/Products/PloneRSS/setuphandlers.py:function:postInstall/postInstall | def postInstall(context):
"""called as at the end of the setup process and the right place for your code"""
|
pylytics-1.2.2 | pylytics-1.2.2//pylytics/library/source.pyclass:Source/select | @classmethod
def select(cls, for_class, since=None):
""" Select data from this data source and yield each record as an
instance of the fact class provided.
"""
raise NotImplementedError('No select method defined for this source')
|
pylj | pylj//sample.pyfile:/sample.py:function:setup_rdfview/setup_rdfview | def setup_rdfview(ax, system):
"""Builds the radial distribution function visualisation pane.
Parameters
----------
ax: Axes object
The axes position that the pane should be placed in.
system: System
The whole system information.
"""
ax.plot([0], color='#34a5daff')
ax.set_xlim([0, system.box_length / 2])
ax.set_yticks([])
ax.set_ylabel('RDF', fontsize=16)
ax.set_xlabel('r/m', fontsize=16)
|
pygeometa | pygeometa//core.pyfile:/core.py:function:get_distribution_language/get_distribution_language | def get_distribution_language(section):
"""derive language of a given distribution construct"""
try:
return section.split('_')[1]
except IndexError:
return 'en'
|
django_elasticsearch_dsl_drf | django_elasticsearch_dsl_drf//versions.pyfile:/versions.py:function:get_elasticsearch_version/get_elasticsearch_version | def get_elasticsearch_version(default=(2, 0, 0)):
"""Get Elasticsearch version.
:param default: Default value. Mainly added for building the docs
when Elasticsearch is not running.
:type default: tuple
:return:
:rtype: list
"""
try:
from elasticsearch_dsl import __version__
return __version__
except ImportError:
return default
|
plone.restapi-6.10.0 | plone.restapi-6.10.0//src/plone/restapi/interfaces.pyclass:IPrimaryFieldTarget/__init__ | def __init__(field, context, request):
"""Adapts field, context and request.
"""
|
psamm | psamm//datasource/sbml.pyfile:/datasource/sbml.py:function:parse_objective_coefficient/parse_objective_coefficient | def parse_objective_coefficient(entry):
"""Return objective value for reaction entry.
Detect objectives that are specified using the non-standardized
kinetic law parameters which are used by many pre-FBC SBML models. The
objective coefficient is returned for the given reaction, or None if
undefined.
Args:
entry: :class:`SBMLReactionEntry`.
"""
for parameter in entry.kinetic_law_reaction_parameters:
pid, name, value, units = parameter
if pid == 'OBJECTIVE_COEFFICIENT' or name == 'OBJECTIVE_COEFFICIENT':
return value
return None
|
plone | plone//resource/interfaces.pyclass:IResourceDirectory/listDirectory | def listDirectory():
"""Lists the contents of this directory.
Raises OSError if the directory cannot be read.
"""
|
pytzer | pytzer//parameters.pyfile:/parameters.py:function:lambd_NH3_Ba_CB89/lambd_NH3_Ba_CB89 | def lambd_NH3_Ba_CB89(T, P):
"""n-c: ammonia barium [CB89]."""
lambd = -0.021
valid = T == 298.15
return lambd, valid
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/brush.pyfile:/bpy/ops/brush.py:function:scale_size/scale_size | def scale_size(scalar: float=1.0):
"""Change brush size by a scalar
:param scalar: Scalar, Factor to scale brush size by
:type scalar: float
"""
pass
|
aiorabbit-1.0.0a1 | aiorabbit-1.0.0a1//aiorabbit/channel0.pyclass:Channel0/_negotiate | @staticmethod
def _negotiate(client: int, server: int) ->int:
"""Return the negotiated value between what the client has requested
and the server has requested for how the two will communicate.
"""
return min(client, server) or (client or server)
|
django-tastypie-ng-0.14.5 | django-tastypie-ng-0.14.5//tastypie/resources.pyfile:/tastypie/resources.py:function:convert_post_to_VERB/convert_post_to_VERB | def convert_post_to_VERB(request, verb):
"""
Force Django to process the VERB.
"""
if request.method == verb:
if not hasattr(request, '_read_started'):
request._read_started = False
if hasattr(request, '_post'):
del request._post
del request._files
try:
request.method = 'POST'
request._load_post_and_files()
request.method = verb
except AttributeError:
request.META['REQUEST_METHOD'] = 'POST'
request._load_post_and_files()
request.META['REQUEST_METHOD'] = verb
setattr(request, verb, request.POST)
return request
|
zillion-0.2.15 | zillion-0.2.15//zillion/sql_utils.pyfile:/zillion/sql_utils.py:function:column_fullname/column_fullname | def column_fullname(column, prefix=None):
"""Get a fully qualified name for a column
Parameters
----------
column : SQLAlchemy column
A SQLAlchemy column object to get the full name for
prefix : str, optional
If specified, a manual prefix to prepend to the output string. This
will automatically be separted with a ".".
Returns
-------
str
A fully qualified column name. The exact format will vary depending on
your SQLAlchemy metadata, but an example would be: schema.table.column
"""
name = '%s.%s' % (column.table.fullname, column.name)
if prefix:
name = prefix + '.' + name
return name
|
rstdoc | rstdoc//retable.pyfile:/retable.py:function:join_rows/join_rows | def join_rows(rows, sep='\n'):
"""Given a list of rows (a list of lists) this function returns a
flattened list where each the individual columns of all rows are joined
together using the line separator.
"""
output = []
for row in rows:
if len(output) <= len(row):
for i in range(len(row) - len(output)):
output.extend([[]])
for i, field in enumerate(row):
field_text = field.strip()
if field_text:
output[i].append(field_text)
return list(map(lambda lines: sep.join(lines), output))
|
hexfarm-0.0.7 | hexfarm-0.0.7//hexfarm/condor/core.pyfile:/hexfarm/condor/core.py:function:extract_job_ids/extract_job_ids | def extract_job_ids(condor_submit_text):
"""Extract Job Ids from Condor Submit Text."""
_, _, count, *_, cluster = condor_submit_text.strip().split()
for process in map(str, range(int(count))):
yield cluster + process
|
virga | virga//gas_properties.pyfile:/gas_properties.py:function:Mg2SiO4/Mg2SiO4 | def Mg2SiO4(mw_atmos, mh=1):
"""Defines properties for Mg2SiO4 as condensible"""
if mh != 1:
raise Exception(
'Alert: No M/H Dependence in Mg2SiO4 Routine. Consult your local theorist to determine next steps.'
)
gas_mw = 140.7
gas_mmr = 7.1625e-05 / 2 * (gas_mw / mw_atmos)
rho_p = 3.214
return gas_mw, gas_mmr, rho_p
|
urlextract-0.14.0 | urlextract-0.14.0//urlextract/urlextract_core.pyclass:URLExtract/_split_markdown | @staticmethod
def _split_markdown(text_url, tld_pos):
"""
Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int tld_pos: position of TLD
:return: URL that has removed enclosure
:rtype: str
"""
left_bracket_pos = text_url.find('[')
if left_bracket_pos > tld_pos - 3:
return text_url
right_bracket_pos = text_url.find(')')
if right_bracket_pos < tld_pos:
return text_url
middle_pos = text_url.rfind('](')
if middle_pos > tld_pos:
return text_url[left_bracket_pos + 1:middle_pos]
return text_url
|
fake-bpy-module-2.78-20200428 | fake-bpy-module-2.78-20200428//bpy/ops/action.pyfile:/bpy/ops/action.py:function:select_border/select_border | def select_border(gesture_mode: int=0, xmin: int=0, xmax: int=0, ymin: int=
0, ymax: int=0, extend: bool=True, axis_range: bool=False):
"""Select all keyframes within the specified region
:param gesture_mode: Gesture Mode
:type gesture_mode: int
:param xmin: X Min
:type xmin: int
:param xmax: X Max
:type xmax: int
:param ymin: Y Min
:type ymin: int
:param ymax: Y Max
:type ymax: int
:param extend: Extend, Extend selection instead of deselecting everything first
:type extend: bool
:param axis_range: Axis Range
:type axis_range: bool
"""
pass
|
qisrc | qisrc//sync.pyfile:/sync.py:function:find_common_url/find_common_url | def find_common_url(repo_a, repo_b):
""" Find Common Url """
for url_a in repo_a.urls:
for url_b in repo_b.urls:
if url_a == url_b:
return url_b
return None
|
export_action | export_action//report.pyfile:/report.py:function:_can_change_or_view/_can_change_or_view | def _can_change_or_view(model, user):
""" Return True iff `user` has either change or view permission
for `model`.
"""
model_name = model._meta.model_name
app_label = model._meta.app_label
can_change = user.has_perm(app_label + '.change_' + model_name)
can_view = user.has_perm(app_label + '.view_' + model_name)
return can_change or can_view
|
z3c.dav-1.0b2 | z3c.dav-1.0b2//src/z3c/dav/interfaces.pyclass:IDAVInputWidget/toFieldValue | def toFieldValue(element):
"""
Convert the ElementTree element to a value which can be legally
assigned to the field.
"""
|
Radicale-2.1.11 | Radicale-2.1.11//radicale/storage.pyclass:BaseCollection/static_init | @classmethod
def static_init():
"""init collection copy"""
pass
|
PyPDT-0.7.5 | PyPDT-0.7.5//pypdt/pid.pyfile:/pypdt/pid.py:function:isQuark/isQuark | def isQuark(pid):
"""Determine if the PID is that of a quark (incl 4th gen)"""
return pid != 0 and abs(pid) <= 8
|
pykitml | pykitml//_functions.pyfile:/_functions.py:function:mse/mse | def mse(output, target):
"""
Returns mean squared error cost of the output.
"""
return 0.5 * (output - target) ** 2
|
pytzer | pytzer//parameters.pyfile:/parameters.py:function:theta_none/theta_none | def theta_none(T, P):
"""i-i': no interaction effect."""
theta = 0
valid = T > 0
return theta, valid
|
atomistic-0.3.3 | atomistic-0.3.3//atomistic/bicrystal.pyclass:GammaSurface/from_grid | @classmethod
def from_grid(cls, base_structure, grid, expansions=0):
"""Generate a gamma surface from a base structure and a grid specification at a
given expansion.
Parameters
----------
base_structure : Bicrystal
grid : list of length two
Number of relative shifts in each boundary vector direction.
expansions : number or (list or ndarray) of numbers, optional
Expansion(s) for all shifts in the grid. By default, 0, meaning a single grid
is added. If a list or ndarray is supplied, multiple grids are added, one for
each expansion value.
"""
gamma_surface = cls(base_structure, None, None)
gamma_surface.add_grid(grid, expansions)
return gamma_surface
|
photovoltaic | photovoltaic//sun.pyfile:/sun.py:function:space_solar_power/space_solar_power | def space_solar_power(x):
"""Return the radiant power density (W/m²) where x is the distance from the sun (m)"""
return 2.8942e+25 / x ** 2
|
geosoup-0.1.21 | geosoup-0.1.21//geosoup/common.pyclass:Timer/display_time | @staticmethod
def display_time(seconds, precision=3):
"""
method to display time in human readable format
:param seconds: Number of seconds
:param precision: Decimal precision
:return: String
"""
intervals = [('weeks', 604800), ('days', 86400), ('hours', 3600), (
'minutes', 60), ('seconds', 1)]
result = list()
dtype = type(seconds).__name__
if dtype != 'int' or dtype != 'long' or dtype != 'float':
try:
seconds = float(seconds)
except (TypeError, ValueError, NameError):
print('Type not coercible to Float')
for name, count in intervals:
if name != 'seconds':
value = seconds // count
if value:
seconds -= value * count
if value == 1:
name = name.rstrip('s')
value = str(int(value))
result.append('{v} {n}'.format(v=value, n=name))
else:
value = '{:.{p}f}'.format(seconds, p=precision)
result.append('{v} {n}'.format(v=value, n=name))
return ' '.join(result)
|
pyatmlab-0.1.2 | pyatmlab-0.1.2//pyatmlab/physics.pyfile:/pyatmlab/physics.py:function:z2g/z2g | def z2g(r_geoid, g0, z):
"""Calculate gravitational acceleration at elevation
Derived from atmlabs equivalent function
https://www.sat.ltu.se/trac/rt/browser/atmlab/trunk/geophysics/pt2z.m
:param r: surface radius at point [m]
:param g0: surface gravitational acceleration at point [m/s^2]
:param z: elevation [m]
:returns: gravitational acceleration at point [m/s^2]
"""
return g0 * (r_geoid / (r_geoid + z)) ** 2
|
rpgrand | rpgrand//config_map.pyfile:/config_map.py:function:_load_defaults/_load_defaults | def _load_defaults(config):
"""Set config defaults."""
config_defaults = config['Config'].get('Defaults', {})
defaults = {}
defaults['type'] = config_defaults.get('Type', 'list')
defaults['source'] = config_defaults.get('Source', None)
defaults['source_loader'] = config_defaults.get('SourceLoader', None)
defaults['source_type'] = config_defaults.get('SourceType', None)
defaults['randomizer'] = config_defaults.get('Randomizer', None)
defaults['use_name_skp'] = config_defaults.get('UseNameForSourceKeyPath',
None)
return defaults
|
ndspy | ndspy//bnbl.pyclass:BNBL/fromFile | @classmethod
def fromFile(cls, filePath, *args, **kwargs):
"""
Load a BNBL from a filesystem file.
"""
with open(filePath, 'rb') as f:
return cls(f.read(), *args, **kwargs)
|
qpageview-0.5.1 | qpageview-0.5.1//qpageview/viewactions.pyclass:ViewActions/names | @staticmethod
def names():
"""Return a tuple of all the names of the actions we support."""
return ('print', 'fit_width', 'fit_height', 'fit_both', 'zoom_natural',
'zoom_originalzoom_in', 'zoom_out', 'zoomer', 'rotate_left',
'rotate_right', 'layout_single', 'layout_double_right',
'layout_double_left', 'layout_raster', 'vertical', 'horizontal',
'continuous', 'reload', 'previous_page', 'next_page', 'pager',
'magnifier')
|
homeassistant | homeassistant//components/rfxtrx.pyfile:/components/rfxtrx.py:function:get_pt2262_cmd/get_pt2262_cmd | def get_pt2262_cmd(device_id, data_bits):
"""Extract and return the data bits from a Lighting4/PT2262 packet."""
try:
data = bytearray.fromhex(device_id)
except ValueError:
return None
mask = 255 & (1 << data_bits) - 1
return hex(data[-1] & mask)
|
cryptotik-0.36 | cryptotik-0.36//cryptotik/livecoin.pyclass:Livecoin/get_market_order_book | @classmethod
def get_market_order_book(cls, pair):
"""return order book for the market"""
return cls.api(cls.url + '/exchange/order_book?currencyPair=' + cls.
format_pair(pair))
|
pdfminer-20191125 | pdfminer-20191125//pdfminer/utils.pyfile:/pdfminer/utils.py:function:q/q | def q(s):
"""Quotes html string."""
return s.replace('&', '&').replace('<', '<').replace('>', '>'
).replace('"', '"')
|
psi | psi//controller/calibration/calibration.pyclass:FlatCalibration/as_attenuation | @classmethod
def as_attenuation(cls, vrms=1, **kwargs):
"""
Allows levels to be specified in dB attenuation
"""
return cls.from_spl(0, vrms, **kwargs)
|
hyperdns-hal-0.9.1 | hyperdns-hal-0.9.1//restnavigator/utils.pyfile:/restnavigator/utils.py:function:slice_process/slice_process | def slice_process(slc):
"""Returns dictionaries for different slice syntaxes."""
if slc.step is None:
if slc.start is not None and slc.stop is not None:
return {slc.start: slc.stop}
if slc.start is not None and slc.stop is None:
return {slc.start: ''}
if slc.start is None and slc.stop is None:
return {None: None}
raise ValueError('Unsupported slice syntax')
|
watson-developer-cloud-2.10.1 | watson-developer-cloud-2.10.1//watson_developer_cloud/language_translator_v3.pyclass:DeleteModelResult/_from_dict | @classmethod
def _from_dict(cls, _dict):
"""Initialize a DeleteModelResult object from a json dictionary."""
args = {}
if 'status' in _dict:
args['status'] = _dict.get('status')
else:
raise ValueError(
"Required property 'status' not present in DeleteModelResult JSON")
return cls(**args)
|
pyphinb-2.9.4 | pyphinb-2.9.4//pyphinb/convert.pyfile:/pyphinb/convert.py:function:reverse_bits/reverse_bits | def reverse_bits(i, n):
"""Reverse the bits of the ``n``-bit decimal number ``i``.
Examples:
>>> reverse_bits(12, 7)
24
>>> reverse_bits(0, 1)
0
>>> reverse_bits(1, 2)
2
"""
return int(bin(i)[2:].zfill(n)[::-1], 2)
|
spacy | spacy//pipeline/functions.pyfile:/pipeline/functions.py:function:merge_noun_chunks/merge_noun_chunks | def merge_noun_chunks(doc):
"""Merge noun chunks into a single token.
doc (Doc): The Doc object.
RETURNS (Doc): The Doc object with merged noun chunks.
DOCS: https://spacy.io/api/pipeline-functions#merge_noun_chunks
"""
if not doc.is_parsed:
return doc
with doc.retokenize() as retokenizer:
for np in doc.noun_chunks:
attrs = {'tag': np.root.tag, 'dep': np.root.dep}
retokenizer.merge(np, attrs=attrs)
return doc
|
pcapng | pcapng//structs.pyfile:/structs.py:function:struct_encode/struct_encode | def struct_encode(schema, obj, outstream, endianness='='):
"""
In the future, this function will be used to encode a structure into
a stream. For the moment, it just raises :py:exc:`NotImplementedError`.
"""
raise NotImplementedError
|
statsmodels | statsmodels//sandbox/bspline.pyfile:/sandbox/bspline.py:function:_zero_triband/_zero_triband | def _zero_triband(a, lower=0):
"""
Explicitly zero out unused elements of a real symmetric banded matrix.
INPUTS:
a -- a real symmetric banded matrix (either upper or lower hald)
lower -- if True, a is assumed to be the lower half
"""
nrow, ncol = a.shape
if lower:
for i in range(nrow):
a[(i), ncol - i:] = 0.0
else:
for i in range(nrow):
a[(i), 0:i] = 0.0
return a
|
pims | pims//display.pyfile:/display.py:function:normalize/normalize | def normalize(arr):
"""This normalizes an array to values between 0 and 1.
Parameters
----------
arr : ndarray
Returns
-------
ndarray of float
normalized array
"""
ptp = arr.max() - arr.min()
if ptp == 0:
ptp = 1
scaled_arr = (arr - arr.min()) / ptp
return scaled_arr
|
test_9112736-1.15.44 | test_9112736-1.15.44//client/protocols/analytics.pyfile:/client/protocols/analytics.py:function:is_correct/is_correct | def is_correct(grading_results):
"""The grading protocol provides grading_results, a dictionary which
provides the count of tests passed, failed or locked for a single
question. Return True if all tests have passed.
"""
if grading_results['locked'] > 0:
return False
return sum(grading_results.values()) == grading_results['passed']
|
webcord-0.2 | webcord-0.2//webcord/colour.pyclass:Colour/green | @classmethod
def green(cls):
"""A factory method that returns a :class:`Colour` with a value of ``0x2ecc71``."""
return cls(3066993)
|
datafaucet | datafaucet//download.pyfile:/download.py:function:write/write | def write(response, file, chunk_size=8192):
"""
Load the data from the http request and save it to disk
:param response: data returned from the server
:param file:
:param chunk_size: size chunk size of the data
:return:
"""
bytes_written = 0
while 1:
chunk = response.read(chunk_size)
bytes_written += len(chunk)
if not chunk:
break
file.write(chunk)
return bytes_written
|
pycalver | pycalver//rewrite.pyfile:/rewrite.py:function:detect_line_sep/detect_line_sep | def detect_line_sep(content):
"""Parse line separator from content.
>>> detect_line_sep('\\r\\n')
'\\r\\n'
>>> detect_line_sep('\\r')
'\\r'
>>> detect_line_sep('\\n')
'\\n'
>>> detect_line_sep('')
'\\n'
"""
if '\r\n' in content:
return '\r\n'
elif '\r' in content:
return '\r'
else:
return '\n'
|
bpy | bpy//ops/anim.pyfile:/ops/anim.py:function:channels_fcurves_enable/channels_fcurves_enable | def channels_fcurves_enable():
"""Clears ‘disabled’ tag from all F-Curves to get broken F-Curves working again
"""
pass
|
repoze | repoze//who/interfaces.pyclass:IChallenger/challenge | def challenge(environ, status, app_headers, forget_headers):
""" args -> WSGI application or None
o 'environ' is the WSGI environment.
o 'status' is the status written into start_response by the
downstream application.
o 'app_headers' is the headers list written into start_response by the
downstream application.
o 'forget_headers' is a list of headers which must be passed
back in the response in order to perform credentials reset
(logout). These come from the 'forget' method of
IIdentifier plugin used to do the request's identification.
Examine the values passed in and return a WSGI application
(a callable which accepts environ and start_response as its
two positional arguments, ala PEP 333) which causes a
challenge to be performed. Return None to forego performing a
challenge.
"""
|
acefile-0.6.12 | acefile-0.6.12//acefile.pyclass:Pic/classinit_pic_quantizers | def classinit_pic_quantizers(cls):
"""
Decorator that adds the PIC quantizer static tables to *cls*.
"""
cls._quantizer = []
cls._quantizer9 = []
cls._quantizer81 = []
for i in range(-255, -20):
cls._quantizer.append(-4)
for i in range(-20, -6):
cls._quantizer.append(-3)
for i in range(-6, -2):
cls._quantizer.append(-2)
for i in range(-2, 0):
cls._quantizer.append(-1)
cls._quantizer.append(0)
for i in range(1, 3):
cls._quantizer.append(1)
for i in range(3, 7):
cls._quantizer.append(2)
for i in range(7, 21):
cls._quantizer.append(3)
for i in range(21, 256):
cls._quantizer.append(4)
for q in cls._quantizer:
cls._quantizer9.append(9 * q)
cls._quantizer81.append(81 * q)
return cls
|
collective.logbook-1.0.0 | collective.logbook-1.0.0//collective/logbook/interfaces.pyclass:ILogBookStorage/get_referenced_errordata | def get_referenced_errordata(err_id):
""" get data for referenced errors
"""
|
dask-gateway-0.7.1 | dask-gateway-0.7.1//dask_gateway/client.pyclass:_IntEnum/from_name | @classmethod
def from_name(cls, name):
"""Create an enum value from a name"""
try:
return cls[name.upper()]
except KeyError:
pass
raise ValueError('%r is not a valid %s' % (name, cls.__name__))
|
uvn_fira | uvn_fira//core/template.pyfile:/core/template.py:function:generate_template/generate_template | def generate_template(filepath, for_level=0):
"""Generate a template file using the Minigame APIs.
Arguments:
filepath (str): The path to where the template file will be written.
for_level (int): The corresponding level for the minigame. Defaults to 0.
"""
template = (
"""#
# This script corresponds to the Advanced Mode script for Level %s in the minigame.
# It is recommended to keep the appropriate template code to start. Remember that the goal is to
# collect all coins and reach the exit.
#
# To access the documentation for the minigame APIs, either go to Settings > Minigame and click
# "Open Documentation", go to Help > Documentation, or visit the following link in your browser:
# https://fira.marquiskurt.net/api/. Go to https://fira.marquiskurt.net/gameplay.html#limitations-1
# to view the limitations of using the official API as called here.
#
# If you want to use a third-party tool or framework instead of the official Fira API and want to
# sideload in a virtual machine file, do not write any code in this file. More information can be
# found at https://fira.marquiskurt.net/implementation.html#obtaining-code-from-third-party-tools.
#
# Import the level information APIs.
from uvn_fira.api import get_level_information, CSPlayer, CSWorld
# Get all of the information for this particular level.
game_player, game_world = get_level_information(%s,
fn_path=renpy.config.savedir + "/minigame/",
exists=renpy.loadable,
load=renpy.exports.file) # type: (CSPlayer, CSWorld)
# WRITE CODE HERE
"""
% (for_level, for_level))
with open(filepath, 'w+') as file_obj:
file_obj.write(template)
|