index int64 0 731k | package stringlengths 2 98 ⌀ | name stringlengths 1 76 | docstring stringlengths 0 281k ⌀ | code stringlengths 4 8.19k | signature stringlengths 2 42.8k ⌀ | embed_func_code listlengths 768 768 |
|---|---|---|---|---|---|---|
320 | dateutil.relativedelta | normalized |
Return a version of this object represented entirely using integer
values for the relative attributes.
>>> relativedelta(days=1.5, hours=2).normalized()
relativedelta(days=+1, hours=+14)
:return:
Returns a :class:`dateutil.relativedelta.relativedelta` object.
| def normalized(self):
"""
Return a version of this object represented entirely using integer
values for the relative attributes.
>>> relativedelta(days=1.5, hours=2).normalized()
relativedelta(days=+1, hours=+14)
:return:
Returns a :class:`dateutil.relativedelta.relativedelta` object.
"""
# Cascade remainders down (rounding each to roughly nearest microsecond)
days = int(self.days)
hours_f = round(self.hours + 24 * (self.days - days), 11)
hours = int(hours_f)
minutes_f = round(self.minutes + 60 * (hours_f - hours), 10)
minutes = int(minutes_f)
seconds_f = round(self.seconds + 60 * (minutes_f - minutes), 8)
seconds = int(seconds_f)
microseconds = round(self.microseconds + 1e6 * (seconds_f - seconds))
# Constructor carries overflow back up with call to _fix()
return self.__class__(years=self.years, months=self.months,
days=days, hours=hours, minutes=minutes,
seconds=seconds, microseconds=microseconds,
leapdays=self.leapdays, year=self.year,
month=self.month, day=self.day,
weekday=self.weekday, hour=self.hour,
minute=self.minute, second=self.second,
microsecond=self.microsecond)
| (self) | [
-0.024740224704146385,
0.013915219344198704,
-0.012740197591483593,
-0.004237480461597443,
0.0031572929583489895,
-0.055993955582380295,
-0.027497362345457077,
0.012814215384423733,
-0.053921476006507874,
-0.0015370119363069534,
-0.021501975134015083,
0.028681635856628418,
0.0579183995723724... |
323 | datetime | timedelta | Difference between two datetime values.
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
All arguments are optional and default to 0.
Arguments may be integers or floats, and may be positive or negative. | class timedelta:
"""Represent the difference between two datetime objects.
Supported operators:
- add, subtract timedelta
- unary plus, minus, abs
- compare to timedelta
- multiply, divide by int
In addition, datetime supports subtraction of two datetime objects
returning a timedelta, and addition or subtraction of a datetime
and a timedelta giving a datetime.
Representation: (days, seconds, microseconds). Why? Because I
felt like it.
"""
__slots__ = '_days', '_seconds', '_microseconds', '_hashcode'
def __new__(cls, days=0, seconds=0, microseconds=0,
milliseconds=0, minutes=0, hours=0, weeks=0):
# Doing this efficiently and accurately in C is going to be difficult
# and error-prone, due to ubiquitous overflow possibilities, and that
# C double doesn't have enough bits of precision to represent
# microseconds over 10K years faithfully. The code here tries to make
# explicit where go-fast assumptions can be relied on, in order to
# guide the C implementation; it's way more convoluted than speed-
# ignoring auto-overflow-to-long idiomatic Python could be.
# XXX Check that all inputs are ints or floats.
# Final values, all integer.
# s and us fit in 32-bit signed ints; d isn't bounded.
d = s = us = 0
# Normalize everything to days, seconds, microseconds.
days += weeks*7
seconds += minutes*60 + hours*3600
microseconds += milliseconds*1000
# Get rid of all fractions, and normalize s and us.
# Take a deep breath <wink>.
if isinstance(days, float):
dayfrac, days = _math.modf(days)
daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.))
assert daysecondswhole == int(daysecondswhole) # can't overflow
s = int(daysecondswhole)
assert days == int(days)
d = int(days)
else:
daysecondsfrac = 0.0
d = days
assert isinstance(daysecondsfrac, float)
assert abs(daysecondsfrac) <= 1.0
assert isinstance(d, int)
assert abs(s) <= 24 * 3600
# days isn't referenced again before redefinition
if isinstance(seconds, float):
secondsfrac, seconds = _math.modf(seconds)
assert seconds == int(seconds)
seconds = int(seconds)
secondsfrac += daysecondsfrac
assert abs(secondsfrac) <= 2.0
else:
secondsfrac = daysecondsfrac
# daysecondsfrac isn't referenced again
assert isinstance(secondsfrac, float)
assert abs(secondsfrac) <= 2.0
assert isinstance(seconds, int)
days, seconds = divmod(seconds, 24*3600)
d += days
s += int(seconds) # can't overflow
assert isinstance(s, int)
assert abs(s) <= 2 * 24 * 3600
# seconds isn't referenced again before redefinition
usdouble = secondsfrac * 1e6
assert abs(usdouble) < 2.1e6 # exact value not critical
# secondsfrac isn't referenced again
if isinstance(microseconds, float):
microseconds = round(microseconds + usdouble)
seconds, microseconds = divmod(microseconds, 1000000)
days, seconds = divmod(seconds, 24*3600)
d += days
s += seconds
else:
microseconds = int(microseconds)
seconds, microseconds = divmod(microseconds, 1000000)
days, seconds = divmod(seconds, 24*3600)
d += days
s += seconds
microseconds = round(microseconds + usdouble)
assert isinstance(s, int)
assert isinstance(microseconds, int)
assert abs(s) <= 3 * 24 * 3600
assert abs(microseconds) < 3.1e6
# Just a little bit of carrying possible for microseconds and seconds.
seconds, us = divmod(microseconds, 1000000)
s += seconds
days, s = divmod(s, 24*3600)
d += days
assert isinstance(d, int)
assert isinstance(s, int) and 0 <= s < 24*3600
assert isinstance(us, int) and 0 <= us < 1000000
if abs(d) > 999999999:
raise OverflowError("timedelta # of days is too large: %d" % d)
self = object.__new__(cls)
self._days = d
self._seconds = s
self._microseconds = us
self._hashcode = -1
return self
def __repr__(self):
args = []
if self._days:
args.append("days=%d" % self._days)
if self._seconds:
args.append("seconds=%d" % self._seconds)
if self._microseconds:
args.append("microseconds=%d" % self._microseconds)
if not args:
args.append('0')
return "%s.%s(%s)" % (self.__class__.__module__,
self.__class__.__qualname__,
', '.join(args))
def __str__(self):
mm, ss = divmod(self._seconds, 60)
hh, mm = divmod(mm, 60)
s = "%d:%02d:%02d" % (hh, mm, ss)
if self._days:
def plural(n):
return n, abs(n) != 1 and "s" or ""
s = ("%d day%s, " % plural(self._days)) + s
if self._microseconds:
s = s + ".%06d" % self._microseconds
return s
def total_seconds(self):
"""Total seconds in the duration."""
return ((self.days * 86400 + self.seconds) * 10**6 +
self.microseconds) / 10**6
# Read-only field accessors
@property
def days(self):
"""days"""
return self._days
@property
def seconds(self):
"""seconds"""
return self._seconds
@property
def microseconds(self):
"""microseconds"""
return self._microseconds
def __add__(self, other):
if isinstance(other, timedelta):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(self._days + other._days,
self._seconds + other._seconds,
self._microseconds + other._microseconds)
return NotImplemented
__radd__ = __add__
def __sub__(self, other):
if isinstance(other, timedelta):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(self._days - other._days,
self._seconds - other._seconds,
self._microseconds - other._microseconds)
return NotImplemented
def __rsub__(self, other):
if isinstance(other, timedelta):
return -self + other
return NotImplemented
def __neg__(self):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(-self._days,
-self._seconds,
-self._microseconds)
def __pos__(self):
return self
def __abs__(self):
if self._days < 0:
return -self
else:
return self
def __mul__(self, other):
if isinstance(other, int):
# for CPython compatibility, we cannot use
# our __class__ here, but need a real timedelta
return timedelta(self._days * other,
self._seconds * other,
self._microseconds * other)
if isinstance(other, float):
usec = self._to_microseconds()
a, b = other.as_integer_ratio()
return timedelta(0, 0, _divide_and_round(usec * a, b))
return NotImplemented
__rmul__ = __mul__
def _to_microseconds(self):
return ((self._days * (24*3600) + self._seconds) * 1000000 +
self._microseconds)
def __floordiv__(self, other):
if not isinstance(other, (int, timedelta)):
return NotImplemented
usec = self._to_microseconds()
if isinstance(other, timedelta):
| null | [
0.010722691193223,
-0.014322451315820217,
-0.005908421706408262,
0.03873298689723015,
0.008299143984913826,
-0.04265005141496658,
-0.02818535827100277,
0.04017726704478264,
-0.03698234260082245,
-0.015022709034383297,
-0.004765032324939966,
0.07707207649946213,
0.05899668484926224,
0.02958... |
324 | maya.core | to_iso8601 | null | def to_iso8601(dt):
return to_utc_offset_naive(dt).isoformat() + 'Z'
| (dt) | [
-0.01898876018822193,
0.005848986096680164,
0.03444833308458328,
0.0037594474852085114,
0.000010280579772370402,
-0.046619731932878494,
-0.05398799106478691,
0.018282921984791756,
0.02818186953663826,
-0.028646688908338547,
0.0006299818633124232,
-0.021485017612576485,
-0.032003723084926605,... |
325 | maya.core | to_utc_offset_aware | null | def to_utc_offset_aware(dt):
if dt.tzinfo is not None:
return dt
return pytz.utc.localize(dt)
| (dt) | [
-0.007755299564450979,
-0.0005706666852347553,
0.06165196746587753,
0.040178485214710236,
-0.00910404697060585,
-0.03171331807971001,
0.0034850044175982475,
0.04986817017197609,
-0.02603437937796116,
-0.011686189100146294,
-0.034535039216279984,
-0.03993003070354462,
0.025927899405360222,
... |
326 | maya.core | to_utc_offset_naive | null | def to_utc_offset_naive(dt):
if dt.tzinfo is None:
return dt
return dt.astimezone(pytz.utc).replace(tzinfo=None)
| (dt) | [
-0.009943503886461258,
0.003035788657143712,
0.06656648218631744,
0.021509701386094093,
-0.021203191950917244,
-0.05625336617231369,
-0.010646671056747437,
0.031173739582300186,
-0.0101508479565382,
0.0037209258880466223,
-0.034310948103666306,
-0.024286309257149696,
-0.005125006195157766,
... |
327 | maya.core | utc_offset |
Returns the time offset from UTC accounting for DST
Keyword Arguments:
time_struct {time.struct_time} -- the struct time for which to
return the UTC offset.
If None, use current local time.
| def utc_offset(time_struct=None):
"""
Returns the time offset from UTC accounting for DST
Keyword Arguments:
time_struct {time.struct_time} -- the struct time for which to
return the UTC offset.
If None, use current local time.
"""
if time_struct:
ts = time_struct
else:
ts = time.localtime()
if ts[-1]:
offset = time.altzone
else:
offset = time.timezone
return offset
| (time_struct=None) | [
0.009898938238620758,
-0.0279756560921669,
0.007872706279158592,
0.04436764121055603,
-0.016792679205536842,
-0.07919150590896606,
0.004211829509586096,
-0.0114652831107378,
-0.04334769770503044,
0.0240780059248209,
-0.04403980076313019,
-0.05085158348083496,
-0.05372928828001022,
-0.01648... |
328 | maya.core | validate_arguments_type_of_function |
Decorator to validate the <type> of arguments in
the calling function are of the `param_type` class.
if `param_type` is None, uses `param_type` as the class where it is used.
Note: Use this decorator on the functions of the class.
| def validate_arguments_type_of_function(param_type=None):
"""
Decorator to validate the <type> of arguments in
the calling function are of the `param_type` class.
if `param_type` is None, uses `param_type` as the class where it is used.
Note: Use this decorator on the functions of the class.
"""
def inner(function):
def wrapper(self, *args, **kwargs):
type_ = param_type or type(self)
for arg in args + tuple(kwargs.values()):
if not isinstance(arg, type_):
raise TypeError(
(
'Invalid Type: {}.{}() accepts only the '
'arguments of type "<{}>"'
).format(
type(self).__name__,
function.__name__,
type_.__name__,
)
)
return function(self, *args, **kwargs)
return wrapper
return inner
| (param_type=None) | [
0.015413850545883179,
0.037124425172805786,
0.04186570644378662,
0.007407081313431263,
0.027060912922024727,
0.03165227174758911,
-0.04295263811945915,
-0.006446644198149443,
-0.037255603820085526,
0.022357111796736717,
-0.022413332015275955,
-0.013286832720041275,
0.038642384111881256,
-0... |
329 | maya.core | validate_class_type_arguments |
Decorator to validate all the arguments to function
are of the type of calling class for passed operator
| def validate_class_type_arguments(operator):
"""
Decorator to validate all the arguments to function
are of the type of calling class for passed operator
"""
def inner(function):
def wrapper(self, *args, **kwargs):
for arg in args + tuple(kwargs.values()):
if not isinstance(arg, self.__class__):
raise TypeError(
'unorderable types: {}() {} {}()'.format(
type(self).__name__, operator, type(arg).__name__
)
)
return function(self, *args, **kwargs)
return wrapper
return inner
| (operator) | [
0.0011837715283036232,
-0.01777656190097332,
0.031662002205848694,
-0.009230309166014194,
0.009265844710171223,
0.014027582481503487,
-0.035784102976322174,
-0.021108001470565796,
0.007959919981658459,
0.0022664894349873066,
0.02928113378584385,
-0.02176540717482567,
0.027770882472395897,
... |
330 | maya.core | when | "Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
Examples:
'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015'
Keyword Arguments:
string -- string to be parsed
timezone -- timezone referenced from (default: 'UTC')
prefer_dates_from -- what dates are prefered when `string` is ambigous.
options are 'past', 'future', and 'current_period'
(default: 'current_period'). see: [1]
Reference:
[1] dateparser.readthedocs.io/en/latest/usage.html#handling-incomplete-dates
| def when(string, timezone='UTC', prefer_dates_from='current_period'):
""""Returns a MayaDT instance for the human moment specified.
Powered by dateparser. Useful for scraping websites.
Examples:
'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015'
Keyword Arguments:
string -- string to be parsed
timezone -- timezone referenced from (default: 'UTC')
prefer_dates_from -- what dates are prefered when `string` is ambigous.
options are 'past', 'future', and 'current_period'
(default: 'current_period'). see: [1]
Reference:
[1] dateparser.readthedocs.io/en/latest/usage.html#handling-incomplete-dates
"""
settings = {
'TIMEZONE': timezone,
'RETURN_AS_TIMEZONE_AWARE': True,
'TO_TIMEZONE': 'UTC',
'PREFER_DATES_FROM': prefer_dates_from,
}
dt = dateparser.parse(string, settings=settings)
if dt is None:
raise ValueError('invalid datetime input specified.')
return MayaDT.from_datetime(dt)
| (string, timezone='UTC', prefer_dates_from='current_period') | [
0.053708482533693314,
0.02761838585138321,
0.0005833428585901856,
-0.03740672022104263,
-0.0033931678626686335,
-0.05661951005458832,
0.042209915816783905,
0.09060577303171158,
-0.02987443283200264,
-0.004880521446466446,
-0.04930555075407028,
0.06611674278974533,
-0.04108189418911934,
0.0... |
331 | funcsigs | BoundArguments | Result of `Signature.bind` call. Holds the mapping of arguments
to the function's parameters.
Has the following public attributes:
* arguments : OrderedDict
An ordered mutable mapping of parameters' names to arguments' values.
Does not contain arguments' default values.
* signature : Signature
The Signature object that created this instance.
* args : tuple
Tuple of positional arguments values.
* kwargs : dict
Dict of keyword arguments values.
| class BoundArguments(object):
'''Result of `Signature.bind` call. Holds the mapping of arguments
to the function's parameters.
Has the following public attributes:
* arguments : OrderedDict
An ordered mutable mapping of parameters' names to arguments' values.
Does not contain arguments' default values.
* signature : Signature
The Signature object that created this instance.
* args : tuple
Tuple of positional arguments values.
* kwargs : dict
Dict of keyword arguments values.
'''
def __init__(self, signature, arguments):
self.arguments = arguments
self._signature = signature
@property
def signature(self):
return self._signature
@property
def args(self):
args = []
for param_name, param in self._signature.parameters.items():
if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
param._partial_kwarg):
# Keyword arguments mapped by 'functools.partial'
# (Parameter._partial_kwarg is True) are mapped
# in 'BoundArguments.kwargs', along with VAR_KEYWORD &
# KEYWORD_ONLY
break
try:
arg = self.arguments[param_name]
except KeyError:
# We're done here. Other arguments
# will be mapped in 'BoundArguments.kwargs'
break
else:
if param.kind == _VAR_POSITIONAL:
# *args
args.extend(arg)
else:
# plain argument
args.append(arg)
return tuple(args)
@property
def kwargs(self):
kwargs = {}
kwargs_started = False
for param_name, param in self._signature.parameters.items():
if not kwargs_started:
if (param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY) or
param._partial_kwarg):
kwargs_started = True
else:
if param_name not in self.arguments:
kwargs_started = True
continue
if not kwargs_started:
continue
try:
arg = self.arguments[param_name]
except KeyError:
pass
else:
if param.kind == _VAR_KEYWORD:
# **kwargs
kwargs.update(arg)
else:
# plain keyword argument
kwargs[param_name] = arg
return kwargs
def __hash__(self):
msg = "unhashable type: '{0}'".format(self.__class__.__name__)
raise TypeError(msg)
def __eq__(self, other):
return (issubclass(other.__class__, BoundArguments) and
self.signature == other.signature and
self.arguments == other.arguments)
def __ne__(self, other):
return not self.__eq__(other)
| (signature, arguments) | [
0.0030886500608175993,
-0.04545272886753082,
-0.0029456571210175753,
0.006925630383193493,
0.004077685531228781,
0.02751186490058899,
0.0039466083981096745,
0.019408924505114555,
0.05330781266093254,
-0.050104767084121704,
-0.03161099925637245,
0.018970413133502007,
-0.02718774788081646,
-... |
332 | funcsigs | __eq__ | null | def __eq__(self, other):
return (issubclass(other.__class__, BoundArguments) and
self.signature == other.signature and
self.arguments == other.arguments)
| (self, other) | [
0.024079112336039543,
-0.03263141214847565,
0.013187034986913204,
0.02560310624539852,
-0.04909055307507515,
-0.014567594043910503,
-0.01225470844656229,
0.041775379329919815,
0.02890210784971714,
0.004065479151904583,
0.020708395168185234,
-0.051457226276397705,
0.035392530262470245,
0.04... |
333 | funcsigs | __hash__ | null | def __hash__(self):
msg = "unhashable type: '{0}'".format(self.__class__.__name__)
raise TypeError(msg)
| (self) | [
0.016549335792660713,
-0.022529490292072296,
0.01724489964544773,
0.04373571276664734,
-0.018186455592513084,
-0.049402013421058655,
-0.02129104733467102,
-0.017126144841313362,
-0.008431593887507915,
-0.0010693237418308854,
0.013521087355911732,
-0.026414470747113228,
0.013851904310286045,
... |
334 | funcsigs | __init__ | null | def __init__(self, signature, arguments):
self.arguments = arguments
self._signature = signature
| (self, signature, arguments) | [
-0.026450391858816147,
-0.02891956828534603,
0.0366290844976902,
0.007602933328598738,
-0.019486958160996437,
-0.012372530065476894,
-0.033538173884153366,
0.0837743803858757,
0.03373357653617859,
0.015028228051960468,
-0.00002756521280389279,
0.06611710041761398,
-0.044942572712898254,
0.... |
337 | funcsigs | Parameter | Represents a parameter in a function signature.
Has the following public attributes:
* name : str
The name of the parameter as a string.
* default : object
The default value for the parameter if specified. If the
parameter has no default value, this attribute is not set.
* annotation
The annotation for the parameter if specified. If the
parameter has no annotation, this attribute is not set.
* kind : str
Describes how argument values are bound to the parameter.
Possible values: `Parameter.POSITIONAL_ONLY`,
`Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
`Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
| class Parameter(object):
'''Represents a parameter in a function signature.
Has the following public attributes:
* name : str
The name of the parameter as a string.
* default : object
The default value for the parameter if specified. If the
parameter has no default value, this attribute is not set.
* annotation
The annotation for the parameter if specified. If the
parameter has no annotation, this attribute is not set.
* kind : str
Describes how argument values are bound to the parameter.
Possible values: `Parameter.POSITIONAL_ONLY`,
`Parameter.POSITIONAL_OR_KEYWORD`, `Parameter.VAR_POSITIONAL`,
`Parameter.KEYWORD_ONLY`, `Parameter.VAR_KEYWORD`.
'''
__slots__ = ('_name', '_kind', '_default', '_annotation', '_partial_kwarg')
POSITIONAL_ONLY = _POSITIONAL_ONLY
POSITIONAL_OR_KEYWORD = _POSITIONAL_OR_KEYWORD
VAR_POSITIONAL = _VAR_POSITIONAL
KEYWORD_ONLY = _KEYWORD_ONLY
VAR_KEYWORD = _VAR_KEYWORD
empty = _empty
def __init__(self, name, kind, default=_empty, annotation=_empty,
_partial_kwarg=False):
if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
_VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
raise ValueError("invalid value for 'Parameter.kind' attribute")
self._kind = kind
if default is not _empty:
if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
msg = '{0} parameters cannot have default values'.format(kind)
raise ValueError(msg)
self._default = default
self._annotation = annotation
if name is None:
if kind != _POSITIONAL_ONLY:
raise ValueError("None is not a valid name for a "
"non-positional-only parameter")
self._name = name
else:
name = str(name)
if kind != _POSITIONAL_ONLY and not re.match(r'[a-z_]\w*$', name, re.I):
msg = '{0!r} is not a valid parameter name'.format(name)
raise ValueError(msg)
self._name = name
self._partial_kwarg = _partial_kwarg
@property
def name(self):
return self._name
@property
def default(self):
return self._default
@property
def annotation(self):
return self._annotation
@property
def kind(self):
return self._kind
def replace(self, name=_void, kind=_void, annotation=_void,
default=_void, _partial_kwarg=_void):
'''Creates a customized copy of the Parameter.'''
if name is _void:
name = self._name
if kind is _void:
kind = self._kind
if annotation is _void:
annotation = self._annotation
if default is _void:
default = self._default
if _partial_kwarg is _void:
_partial_kwarg = self._partial_kwarg
return type(self)(name, kind, default=default, annotation=annotation,
_partial_kwarg=_partial_kwarg)
def __str__(self):
kind = self.kind
formatted = self._name
if kind == _POSITIONAL_ONLY:
if formatted is None:
formatted = ''
formatted = '<{0}>'.format(formatted)
# Add annotation and default value
if self._annotation is not _empty:
formatted = '{0}:{1}'.format(formatted,
formatannotation(self._annotation))
if self._default is not _empty:
formatted = '{0}={1}'.format(formatted, repr(self._default))
if kind == _VAR_POSITIONAL:
formatted = '*' + formatted
elif kind == _VAR_KEYWORD:
formatted = '**' + formatted
return formatted
def __repr__(self):
return '<{0} at {1:#x} {2!r}>'.format(self.__class__.__name__,
id(self), self.name)
def __hash__(self):
msg = "unhashable type: '{0}'".format(self.__class__.__name__)
raise TypeError(msg)
def __eq__(self, other):
return (issubclass(other.__class__, Parameter) and
self._name == other._name and
self._kind == other._kind and
self._default == other._default and
self._annotation == other._annotation)
def __ne__(self, other):
return not self.__eq__(other)
| (name, kind, default=<class 'funcsigs._empty'>, annotation=<class 'funcsigs._empty'>, _partial_kwarg=False) | [
0.06280073523521423,
-0.02982255630195141,
0.0019393914844840765,
0.010908315889537334,
-0.00012958190927747637,
-0.03899722918868065,
-0.02101798728108406,
-0.012301074340939522,
0.06837176531553268,
-0.039425771683454514,
-0.02863432839512825,
-0.002559071406722069,
-0.01506711170077324,
... |
338 | funcsigs | __eq__ | null | def __eq__(self, other):
return (issubclass(other.__class__, Parameter) and
self._name == other._name and
self._kind == other._kind and
self._default == other._default and
self._annotation == other._annotation)
| (self, other) | [
0.08598125725984573,
-0.02758358232676983,
0.026642829179763794,
0.025879576802253723,
-0.05104915425181389,
-0.055522166192531586,
-0.01660517416894436,
-0.005311703309416771,
0.0383756160736084,
0.02658957988023758,
-0.0012447225162759423,
-0.07355622202157974,
0.03127559274435043,
0.047... |
340 | funcsigs | __init__ | null | def __init__(self, name, kind, default=_empty, annotation=_empty,
_partial_kwarg=False):
if kind not in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD,
_VAR_POSITIONAL, _KEYWORD_ONLY, _VAR_KEYWORD):
raise ValueError("invalid value for 'Parameter.kind' attribute")
self._kind = kind
if default is not _empty:
if kind in (_VAR_POSITIONAL, _VAR_KEYWORD):
msg = '{0} parameters cannot have default values'.format(kind)
raise ValueError(msg)
self._default = default
self._annotation = annotation
if name is None:
if kind != _POSITIONAL_ONLY:
raise ValueError("None is not a valid name for a "
"non-positional-only parameter")
self._name = name
else:
name = str(name)
if kind != _POSITIONAL_ONLY and not re.match(r'[a-z_]\w*$', name, re.I):
msg = '{0!r} is not a valid parameter name'.format(name)
raise ValueError(msg)
self._name = name
self._partial_kwarg = _partial_kwarg
| (self, name, kind, default=<class 'funcsigs._empty'>, annotation=<class 'funcsigs._empty'>, _partial_kwarg=False) | [
0.04558732360601425,
-0.018777722492814064,
0.04158972203731537,
0.0019667097367346287,
0.001963271526619792,
-0.024187320843338966,
0.0007294934475794435,
0.004900728818029165,
0.04852134361863136,
-0.008146488107740879,
-0.02908346615731716,
0.01542193815112114,
-0.04037943854928017,
-0.... |
342 | funcsigs | __repr__ | null | def __repr__(self):
return '<{0} at {1:#x} {2!r}>'.format(self.__class__.__name__,
id(self), self.name)
| (self) | [
0.03509392961859703,
-0.030647877603769302,
0.07598705589771271,
0.02762526646256447,
0.0381692610681057,
-0.0669543668627739,
0.012661579996347427,
0.0011554460506886244,
0.03228219598531723,
-0.028697239235043526,
-0.02077166922390461,
0.012459486722946167,
0.020560789853334427,
0.064880... |
343 | funcsigs | __str__ | null | def __str__(self):
kind = self.kind
formatted = self._name
if kind == _POSITIONAL_ONLY:
if formatted is None:
formatted = ''
formatted = '<{0}>'.format(formatted)
# Add annotation and default value
if self._annotation is not _empty:
formatted = '{0}:{1}'.format(formatted,
formatannotation(self._annotation))
if self._default is not _empty:
formatted = '{0}={1}'.format(formatted, repr(self._default))
if kind == _VAR_POSITIONAL:
formatted = '*' + formatted
elif kind == _VAR_KEYWORD:
formatted = '**' + formatted
return formatted
| (self) | [
0.033840883523225784,
-0.03498060256242752,
0.051936112344264984,
-0.02242616005241871,
0.0640697330236435,
-0.05898483470082283,
0.018621252849698067,
-0.061895500868558884,
0.06073824688792229,
-0.0581081286072731,
-0.03287650644779205,
-0.0022191640455275774,
-0.03717236965894699,
0.000... |
344 | funcsigs | replace | Creates a customized copy of the Parameter. | def replace(self, name=_void, kind=_void, annotation=_void,
default=_void, _partial_kwarg=_void):
'''Creates a customized copy of the Parameter.'''
if name is _void:
name = self._name
if kind is _void:
kind = self._kind
if annotation is _void:
annotation = self._annotation
if default is _void:
default = self._default
if _partial_kwarg is _void:
_partial_kwarg = self._partial_kwarg
return type(self)(name, kind, default=default, annotation=annotation,
_partial_kwarg=_partial_kwarg)
| (self, name=<class 'funcsigs._void'>, kind=<class 'funcsigs._void'>, annotation=<class 'funcsigs._void'>, default=<class 'funcsigs._void'>, _partial_kwarg=<class 'funcsigs._void'>) | [
0.04757272079586983,
-0.06937403231859207,
0.024385297670960426,
-0.020808786153793335,
-0.07009276002645493,
-0.03713410347700119,
0.0034695572685450315,
-0.005321984179317951,
0.06352156400680542,
-0.01759163849055767,
-0.016530664637684822,
-0.01829325035214424,
-0.06471943110227585,
-0... |
345 | funcsigs | Signature | A Signature object represents the overall signature of a function.
It stores a Parameter object for each parameter accepted by the
function, as well as information specific to the function itself.
A Signature object has the following public attributes and methods:
* parameters : OrderedDict
An ordered mapping of parameters' names to the corresponding
Parameter objects (keyword-only arguments are in the same order
as listed in `code.co_varnames`).
* return_annotation : object
The annotation for the return type of the function if specified.
If the function has no annotation for its return type, this
attribute is not set.
* bind(*args, **kwargs) -> BoundArguments
Creates a mapping from positional and keyword arguments to
parameters.
* bind_partial(*args, **kwargs) -> BoundArguments
Creates a partial mapping from positional and keyword arguments
to parameters (simulating 'functools.partial' behavior.)
| class Signature(object):
'''A Signature object represents the overall signature of a function.
It stores a Parameter object for each parameter accepted by the
function, as well as information specific to the function itself.
A Signature object has the following public attributes and methods:
* parameters : OrderedDict
An ordered mapping of parameters' names to the corresponding
Parameter objects (keyword-only arguments are in the same order
as listed in `code.co_varnames`).
* return_annotation : object
The annotation for the return type of the function if specified.
If the function has no annotation for its return type, this
attribute is not set.
* bind(*args, **kwargs) -> BoundArguments
Creates a mapping from positional and keyword arguments to
parameters.
* bind_partial(*args, **kwargs) -> BoundArguments
Creates a partial mapping from positional and keyword arguments
to parameters (simulating 'functools.partial' behavior.)
'''
__slots__ = ('_return_annotation', '_parameters')
_parameter_cls = Parameter
_bound_arguments_cls = BoundArguments
empty = _empty
def __init__(self, parameters=None, return_annotation=_empty,
__validate_parameters__=True):
'''Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
'''
if parameters is None:
params = OrderedDict()
else:
if __validate_parameters__:
params = OrderedDict()
top_kind = _POSITIONAL_ONLY
for idx, param in enumerate(parameters):
kind = param.kind
if kind < top_kind:
msg = 'wrong parameter order: {0} before {1}'
msg = msg.format(top_kind, param.kind)
raise ValueError(msg)
else:
top_kind = kind
name = param.name
if name is None:
name = str(idx)
param = param.replace(name=name)
if name in params:
msg = 'duplicate parameter name: {0!r}'.format(name)
raise ValueError(msg)
params[name] = param
else:
params = OrderedDict(((param.name, param)
for param in parameters))
self._parameters = params
self._return_annotation = return_annotation
@classmethod
def from_function(cls, func):
'''Constructs Signature for the given python function'''
if not isinstance(func, types.FunctionType):
raise TypeError('{0!r} is not a Python function'.format(func))
Parameter = cls._parameter_cls
# Parameter information.
func_code = func.__code__
pos_count = func_code.co_argcount
arg_names = func_code.co_varnames
positional = tuple(arg_names[:pos_count])
keyword_only_count = getattr(func_code, 'co_kwonlyargcount', 0)
keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
annotations = getattr(func, '__annotations__', {})
defaults = func.__defaults__
kwdefaults = getattr(func, '__kwdefaults__', None)
if defaults:
pos_default_count = len(defaults)
else:
pos_default_count = 0
parameters = []
# Non-keyword-only parameters w/o defaults.
non_default_count = pos_count - pos_default_count
for name in positional[:non_default_count]:
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD))
# ... w/ defaults.
for offset, name in enumerate(positional[non_default_count:]):
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD,
default=defaults[offset]))
# *args
if func_code.co_flags & 0x04:
name = arg_names[pos_count + keyword_only_count]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_POSITIONAL))
# Keyword-only parameters.
for name in keyword_only:
default = _empty
if kwdefaults is not None:
default = kwdefaults.get(name, _empty)
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_KEYWORD_ONLY,
default=default))
# **kwargs
if func_code.co_flags & 0x08:
index = pos_count + keyword_only_count
if func_code.co_flags & 0x04:
index += 1
name = arg_names[index]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_KEYWORD))
return cls(parameters,
return_annotation=annotations.get('return', _empty),
__validate_parameters__=False)
@property
def parameters(self):
try:
return types.MappingProxyType(self._parameters)
except AttributeError:
return OrderedDict(self._parameters.items())
@property
def return_annotation(self):
return self._return_annotation
def replace(self, parameters=_void, return_annotation=_void):
'''Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
'''
if parameters is _void:
parameters = self.parameters.values()
if return_annotation is _void:
return_annotation = self._return_annotation
return type(self)(parameters,
return_annotation=return_annotation)
def __hash__(self):
msg = "unhashable type: '{0}'".format(self.__class__.__name__)
raise TypeError(msg)
def __eq__(self, other):
if (not issubclass(type(other), Signature) or
self.return_annotation != other.return_annotation or
len(self.parameters) != len(other.parameters)):
return False
other_positions = dict((param, idx)
for idx, param in enumerate(other.parameters.keys()))
for idx, (param_name, param) in enumerate(self.parameters.items()):
if param.kind == _KEYWORD_ONLY:
try:
other_param = other.parameters[param_name]
except KeyError:
return False
else:
if param != other_param:
return False
else:
try:
other_idx = other_positions[param_name]
except KeyError:
return False
else:
if (idx != other_idx or
param != other.parameters[param_name]):
return False
return True
def __ne__(self, other):
return not self.__eq__(other)
def _bind(self, args, kwargs, partial=False):
'''Private method. Don't use directly.'''
arguments = OrderedDict()
parameters = iter(self.parameters.values())
parameters_ex = ()
arg_vals = iter(args)
if partial:
# Support for binding arguments to 'functools.partial' objects.
# See 'functools.partial' case in 'signature()' implementation
# for details.
for p | (parameters=None, return_annotation=<class 'funcsigs._empty'>, __validate_parameters__=True) | [
0.015471220016479492,
-0.06291218847036362,
0.005069752223789692,
0.03125063329935074,
-0.01787511445581913,
-0.016056783497333527,
-0.04092784970998764,
0.011844831518828869,
0.05198165774345398,
-0.022806180641055107,
-0.033736709505319595,
0.013950807973742485,
-0.017073817551136017,
-0... |
346 | funcsigs | __eq__ | null | def __eq__(self, other):
if (not issubclass(type(other), Signature) or
self.return_annotation != other.return_annotation or
len(self.parameters) != len(other.parameters)):
return False
other_positions = dict((param, idx)
for idx, param in enumerate(other.parameters.keys()))
for idx, (param_name, param) in enumerate(self.parameters.items()):
if param.kind == _KEYWORD_ONLY:
try:
other_param = other.parameters[param_name]
except KeyError:
return False
else:
if param != other_param:
return False
else:
try:
other_idx = other_positions[param_name]
except KeyError:
return False
else:
if (idx != other_idx or
param != other.parameters[param_name]):
return False
return True
| (self, other) | [
0.0481070950627327,
-0.06133561208844185,
0.00032925736741162837,
0.05254144221544266,
-0.05071553587913513,
-0.04438075050711632,
-0.03830680996179581,
0.007559819146990776,
0.05347302928566933,
0.02589808776974678,
0.01065734215080738,
-0.06159645691514015,
0.049560368061065674,
0.019134... |
348 | funcsigs | __init__ | Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
| def __init__(self, parameters=None, return_annotation=_empty,
__validate_parameters__=True):
'''Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
'''
if parameters is None:
params = OrderedDict()
else:
if __validate_parameters__:
params = OrderedDict()
top_kind = _POSITIONAL_ONLY
for idx, param in enumerate(parameters):
kind = param.kind
if kind < top_kind:
msg = 'wrong parameter order: {0} before {1}'
msg = msg.format(top_kind, param.kind)
raise ValueError(msg)
else:
top_kind = kind
name = param.name
if name is None:
name = str(idx)
param = param.replace(name=name)
if name in params:
msg = 'duplicate parameter name: {0!r}'.format(name)
raise ValueError(msg)
params[name] = param
else:
params = OrderedDict(((param.name, param)
for param in parameters))
self._parameters = params
self._return_annotation = return_annotation
| (self, parameters=None, return_annotation=<class 'funcsigs._empty'>, __validate_parameters__=True) | [
-0.017261182889342308,
-0.009848241694271564,
0.011266602203249931,
0.013050703331828117,
-0.014585031196475029,
-0.050240304321050644,
-0.04938393458724022,
0.020267395302653313,
0.01010693609714508,
0.03093632310628891,
-0.004915200173854828,
0.058982402086257935,
-0.021248651668429375,
... |
350 | funcsigs | __str__ | null | def __str__(self):
result = []
render_kw_only_separator = True
for idx, param in enumerate(self.parameters.values()):
formatted = str(param)
kind = param.kind
if kind == _VAR_POSITIONAL:
# OK, we have an '*args'-like parameter, so we won't need
# a '*' to separate keyword-only arguments
render_kw_only_separator = False
elif kind == _KEYWORD_ONLY and render_kw_only_separator:
# We have a keyword-only parameter to render and we haven't
# rendered an '*args'-like parameter before, so add a '*'
# separator to the parameters list ("foo(arg1, *, arg2)" case)
result.append('*')
# This condition should be only triggered once, so
# reset the flag
render_kw_only_separator = False
result.append(formatted)
rendered = '({0})'.format(', '.join(result))
if self.return_annotation is not _empty:
anno = formatannotation(self.return_annotation)
rendered += ' -> {0}'.format(anno)
return rendered
| (self) | [
0.0026252586394548416,
-0.06640689820051193,
0.04708649218082428,
-0.0025458468589931726,
0.039388224482536316,
-0.032325249165296555,
-0.01596643030643463,
-0.0762726441025734,
0.08580204844474792,
-0.006021278444677591,
0.010267470963299274,
-0.008623180910944939,
-0.03193286061286926,
-... |
351 | funcsigs | _bind | Private method. Don't use directly. | def _bind(self, args, kwargs, partial=False):
'''Private method. Don't use directly.'''
arguments = OrderedDict()
parameters = iter(self.parameters.values())
parameters_ex = ()
arg_vals = iter(args)
if partial:
# Support for binding arguments to 'functools.partial' objects.
# See 'functools.partial' case in 'signature()' implementation
# for details.
for param_name, param in self.parameters.items():
if (param._partial_kwarg and param_name not in kwargs):
# Simulating 'functools.partial' behavior
kwargs[param_name] = param.default
while True:
# Let's iterate through the positional arguments and corresponding
# parameters
try:
arg_val = next(arg_vals)
except StopIteration:
# No more positional arguments
try:
param = next(parameters)
except StopIteration:
# No more parameters. That's it. Just need to check that
# we have no `kwargs` after this while loop
break
else:
if param.kind == _VAR_POSITIONAL:
# That's OK, just empty *args. Let's start parsing
# kwargs
break
elif param.name in kwargs:
if param.kind == _POSITIONAL_ONLY:
msg = '{arg!r} parameter is positional only, ' \
'but was passed as a keyword'
msg = msg.format(arg=param.name)
raise TypeError(msg)
parameters_ex = (param,)
break
elif (param.kind == _VAR_KEYWORD or
param.default is not _empty):
# That's fine too - we have a default value for this
# parameter. So, lets start parsing `kwargs`, starting
# with the current parameter
parameters_ex = (param,)
break
else:
if partial:
parameters_ex = (param,)
break
else:
msg = '{arg!r} parameter lacking default value'
msg = msg.format(arg=param.name)
raise TypeError(msg)
else:
# We have a positional argument to process
try:
param = next(parameters)
except StopIteration:
raise TypeError('too many positional arguments')
else:
if param.kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
# Looks like we have no parameter for this positional
# argument
raise TypeError('too many positional arguments')
if param.kind == _VAR_POSITIONAL:
# We have an '*args'-like argument, let's fill it with
# all positional arguments we have left and move on to
# the next phase
values = [arg_val]
values.extend(arg_vals)
arguments[param.name] = tuple(values)
break
if param.name in kwargs:
raise TypeError('multiple values for argument '
'{arg!r}'.format(arg=param.name))
arguments[param.name] = arg_val
# Now, we iterate through the remaining parameters to process
# keyword arguments
kwargs_param = None
for param in itertools.chain(parameters_ex, parameters):
if param.kind == _POSITIONAL_ONLY:
# This should never happen in case of a properly built
# Signature object (but let's have this check here
# to ensure correct behaviour just in case)
raise TypeError('{arg!r} parameter is positional only, '
'but was passed as a keyword'. \
format(arg=param.name))
if param.kind == _VAR_KEYWORD:
# Memorize that we have a '**kwargs'-like parameter
kwargs_param = param
continue
param_name = param.name
try:
arg_val = kwargs.pop(param_name)
except KeyError:
# We have no value for this parameter. It's fine though,
# if it has a default value, or it is an '*args'-like
# parameter, left alone by the processing of positional
# arguments.
if (not partial and param.kind != _VAR_POSITIONAL and
param.default is _empty):
raise TypeError('{arg!r} parameter lacking default value'. \
format(arg=param_name))
else:
arguments[param_name] = arg_val
if kwargs:
if kwargs_param is not None:
# Process our '**kwargs'-like parameter
arguments[kwargs_param.name] = kwargs
else:
raise TypeError('too many keyword arguments %r' % kwargs)
return self._bound_arguments_cls(self, arguments)
| (self, args, kwargs, partial=False) | [
0.0077104936353862286,
-0.022315075621008873,
-0.0066118743270635605,
0.012215840630233288,
0.0037494164425879717,
0.01511861477047205,
-0.013959521427750587,
0.028926949948072433,
0.04209022596478462,
-0.03969140350818634,
-0.038098908960819244,
0.029068056493997574,
-0.05112107843160629,
... |
352 | funcsigs | bind | Get a BoundArguments object, that maps the passed `args`
and `kwargs` to the function's signature. Raises `TypeError`
if the passed arguments can not be bound.
| def bind(*args, **kwargs):
'''Get a BoundArguments object, that maps the passed `args`
and `kwargs` to the function's signature. Raises `TypeError`
if the passed arguments can not be bound.
'''
return args[0]._bind(args[1:], kwargs)
| (*args, **kwargs) | [
-0.022356372326612473,
-0.05672409012913704,
0.04533761367201805,
-0.03773505985736847,
-0.008084224537014961,
0.052662450820207596,
0.02397061511874199,
0.034853722900152206,
0.022807667031884193,
-0.05155157297849655,
-0.03960965946316719,
0.013165612705051899,
-0.024595482274889946,
0.0... |
353 | funcsigs | bind_partial | Get a BoundArguments object, that partially maps the
passed `args` and `kwargs` to the function's signature.
Raises `TypeError` if the passed arguments can not be bound.
| def bind_partial(self, *args, **kwargs):
'''Get a BoundArguments object, that partially maps the
passed `args` and `kwargs` to the function's signature.
Raises `TypeError` if the passed arguments can not be bound.
'''
return self._bind(args, kwargs, partial=True)
| (self, *args, **kwargs) | [
-0.0041367169469594955,
-0.05384458228945732,
0.07129950821399689,
-0.016185324639081955,
-0.0111994044855237,
0.03699502721428871,
0.028755227103829384,
0.005259179510176182,
0.027023186907172203,
-0.05952836573123932,
-0.029747366905212402,
-0.01320049911737442,
-0.03171483054757118,
0.0... |
354 | funcsigs | replace | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
| def replace(self, parameters=_void, return_annotation=_void):
'''Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
'''
if parameters is _void:
parameters = self.parameters.values()
if return_annotation is _void:
return_annotation = self._return_annotation
return type(self)(parameters,
return_annotation=return_annotation)
| (self, parameters=<class 'funcsigs._void'>, return_annotation=<class 'funcsigs._void'>) | [
0.006087445188313723,
-0.07051147520542145,
0.019857075065374374,
0.010297213681042194,
-0.07304934412240982,
-0.05175185948610306,
-0.05343233793973923,
0.037176284939050674,
0.07188329845666885,
0.01557871513068676,
0.011600441299378872,
0.004038291051983833,
-0.04334947094321251,
0.0049... |
355 | builtins | method-wrapper | null | method-wrapper
| () | [
0.05038778483867645,
-0.04559765383601189,
0.039710547775030136,
0.07101093977689743,
-0.02811916172504425,
-0.042855214327573776,
-0.020879117771983147,
0.04354996606707573,
0.08439405262470245,
0.006846961099654436,
0.024809950962662697,
0.0015643341466784477,
0.04673119634389877,
-0.032... |
356 | funcsigs | _ParameterKind | null | class _ParameterKind(int):
def __new__(self, *args, **kwargs):
obj = int.__new__(self, *args)
obj._name = kwargs['name']
return obj
def __str__(self):
return self._name
def __repr__(self):
return '<_ParameterKind: {0!r}>'.format(self._name)
| (*args, **kwargs) | [
0.03781355172395706,
-0.04076885059475899,
0.0321165956556797,
-0.025671914219856262,
0.01473197527229786,
-0.025120019912719727,
-0.01166095957159996,
-0.0057192109525203705,
0.00842971634119749,
-0.05668472498655319,
-0.03991430625319481,
0.024443507194519043,
-0.03455560654401779,
-0.01... |
357 | funcsigs | __new__ | null | def __new__(self, *args, **kwargs):
obj = int.__new__(self, *args)
obj._name = kwargs['name']
return obj
| (self, *args, **kwargs) | [
0.01509977038949728,
-0.040910039097070694,
0.018472222611308098,
-0.01666736789047718,
-0.02433588169515133,
-0.004372324328869581,
-0.001447908696718514,
0.01570138894021511,
-0.02911493368446827,
-0.04809556528925896,
-0.02599668689072132,
0.06558486074209213,
-0.01654026471078396,
0.02... |
358 | funcsigs | __repr__ | null | def __repr__(self):
return '<_ParameterKind: {0!r}>'.format(self._name)
| (self) | [
0.05004360154271126,
-0.05394721403717995,
0.05134480819106102,
0.000725333287846297,
0.031984999775886536,
-0.04125168174505234,
0.007952290587127209,
-0.005815854296088219,
0.06319631636142731,
-0.008620476350188255,
-0.0252503901720047,
-0.011139361187815666,
-0.03525559604167938,
0.007... |
359 | funcsigs | __str__ | null | def __str__(self):
return self._name
| (self) | [
0.003390365745872259,
-0.017084578052163124,
0.024779802188277245,
-0.009557923302054405,
0.02697121351957321,
-0.06557375937700272,
0.02420666441321373,
-0.009111212566494942,
0.10296260565519333,
-0.060348089784383774,
-0.05758354067802429,
-0.02398752234876156,
-0.0227232463657856,
0.01... |
360 | builtins | wrapper_descriptor | null | from builtins import wrapper_descriptor
| () | [
0.0167169701308012,
-0.04747917130589485,
0.015567212365567684,
0.05002683401107788,
0.020662538707256317,
0.054758209735155106,
0.025162305682897568,
0.08053261786699295,
-0.036362096667289734,
-0.00826336070895195,
0.009396574459969997,
0.03546876087784767,
-0.019173644483089447,
-0.0059... |
361 | funcsigs | _empty | null | class _empty(object):
pass
| () | [
-0.0019924950320273638,
-0.023942874744534492,
-0.035502638667821884,
-0.02389347366988659,
-0.010127144865691662,
-0.01814652606844902,
0.004536631517112255,
0.02677518129348755,
0.04248460754752159,
-0.03051316924393177,
-0.017356114462018013,
-0.005899267271161079,
0.026412909850478172,
... |
362 | funcsigs | _get_user_defined_method | null | def _get_user_defined_method(cls, method_name, *nested):
try:
if cls is type:
return
meth = getattr(cls, method_name)
for name in nested:
meth = getattr(meth, name, meth)
except AttributeError:
return
else:
if not isinstance(meth, _NonUserDefinedCallables):
# Once '__signature__' will be added to 'C'-level
# callables, this check won't be necessary
return meth
| (cls, method_name, *nested) | [
0.02503032609820366,
-0.0528767928481102,
0.04794854298233986,
0.03698040544986725,
-0.039018403738737106,
-0.038647860288619995,
0.05610053613781929,
0.008619806729257107,
0.05928722769021988,
0.036498699337244034,
0.001880516647361219,
0.013710170984268188,
0.020565256476402283,
-0.05354... |
363 | funcsigs | _void | A private marker - used in Parameter & Signature | class _void(object):
'''A private marker - used in Parameter & Signature'''
| () | [
-0.03135751187801361,
-0.02140055038034916,
-0.01461564190685749,
0.02534184604883194,
-0.039620403200387955,
-0.06340647488832474,
-0.016231918707489967,
0.04079587757587433,
0.02025964856147766,
-0.02625802531838417,
-0.025549283251166344,
-0.017511112615466118,
0.007178173400461674,
-0.... |
364 | funcsigs | formatannotation | null | def formatannotation(annotation, base_module=None):
if isinstance(annotation, type):
if annotation.__module__ in ('builtins', '__builtin__', base_module):
return annotation.__name__
return annotation.__module__+'.'+annotation.__name__
return repr(annotation)
| (annotation, base_module=None) | [
0.006759339477866888,
0.017083950340747833,
0.041678279638290405,
0.05221007019281387,
0.017230704426765442,
-0.08356373757123947,
0.020338447764515877,
0.005917659495025873,
-0.032855741679668427,
-0.010540425777435303,
0.013328761793673038,
-0.022272152826189995,
-0.04202358424663544,
-0... |
368 | funcsigs | signature | Get a signature object for the passed callable. | def signature(obj):
'''Get a signature object for the passed callable.'''
if not callable(obj):
raise TypeError('{0!r} is not a callable object'.format(obj))
if isinstance(obj, types.MethodType):
sig = signature(obj.__func__)
if obj.__self__ is None:
# Unbound method - preserve as-is.
return sig
else:
# Bound method. Eat self - if we can.
params = tuple(sig.parameters.values())
if not params or params[0].kind in (_VAR_KEYWORD, _KEYWORD_ONLY):
raise ValueError('invalid method signature')
kind = params[0].kind
if kind in (_POSITIONAL_OR_KEYWORD, _POSITIONAL_ONLY):
# Drop first parameter:
# '(p1, p2[, ...])' -> '(p2[, ...])'
params = params[1:]
else:
if kind is not _VAR_POSITIONAL:
# Unless we add a new parameter type we never
# get here
raise ValueError('invalid argument type')
# It's a var-positional parameter.
# Do nothing. '(*args[, ...])' -> '(*args[, ...])'
return sig.replace(parameters=params)
try:
sig = obj.__signature__
except AttributeError:
pass
else:
if sig is not None:
return sig
try:
# Was this function wrapped by a decorator?
wrapped = obj.__wrapped__
except AttributeError:
pass
else:
return signature(wrapped)
if isinstance(obj, types.FunctionType):
return Signature.from_function(obj)
if isinstance(obj, functools.partial):
sig = signature(obj.func)
new_params = OrderedDict(sig.parameters.items())
partial_args = obj.args or ()
partial_keywords = obj.keywords or {}
try:
ba = sig.bind_partial(*partial_args, **partial_keywords)
except TypeError as ex:
msg = 'partial object {0!r} has incorrect arguments'.format(obj)
raise ValueError(msg)
for arg_name, arg_value in ba.arguments.items():
param = new_params[arg_name]
if arg_name in partial_keywords:
# We set a new default value, because the following code
# is correct:
#
# >>> def foo(a): print(a)
# >>> print(partial(partial(foo, a=10), a=20)())
# 20
# >>> print(partial(partial(foo, a=10), a=20)(a=30))
# 30
#
# So, with 'partial' objects, passing a keyword argument is
# like setting a new default value for the corresponding
# parameter
#
# We also mark this parameter with '_partial_kwarg'
# flag. Later, in '_bind', the 'default' value of this
# parameter will be added to 'kwargs', to simulate
# the 'functools.partial' real call.
new_params[arg_name] = param.replace(default=arg_value,
_partial_kwarg=True)
elif (param.kind not in (_VAR_KEYWORD, _VAR_POSITIONAL) and
not param._partial_kwarg):
new_params.pop(arg_name)
return sig.replace(parameters=new_params.values())
sig = None
if isinstance(obj, type):
# obj is a class or a metaclass
# First, let's see if it has an overloaded __call__ defined
# in its metaclass
call = _get_user_defined_method(type(obj), '__call__')
if call is not None:
sig = signature(call)
else:
# Now we check if the 'obj' class has a '__new__' method
new = _get_user_defined_method(obj, '__new__')
if new is not None:
sig = signature(new)
else:
# Finally, we should have at least __init__ implemented
init = _get_user_defined_method(obj, '__init__')
if init is not None:
sig = signature(init)
elif not isinstance(obj, _NonUserDefinedCallables):
# An object with __call__
# We also check that the 'obj' is not an instance of
# _WrapperDescriptor or _MethodWrapper to avoid
# infinite recursion (and even potential segfault)
call = _get_user_defined_method(type(obj), '__call__', 'im_func')
if call is not None:
sig = signature(call)
if sig is not None:
# For classes and objects we skip the first parameter of their
# __call__, __new__, or __init__ methods
return sig.replace(parameters=tuple(sig.parameters.values())[1:])
if isinstance(obj, types.BuiltinFunctionType):
# Raise a nicer error message for builtins
msg = 'no signature found for builtin function {0!r}'.format(obj)
raise ValueError(msg)
raise ValueError('callable {0!r} is not supported by signature'.format(obj))
| (obj) | [
0.009364153258502483,
-0.062455836683511734,
0.022085465490818024,
-0.011560031212866306,
-0.012710755690932274,
-0.027385132387280464,
0.0429040789604187,
0.022212151437997818,
0.03878680616617203,
-0.008002285845577717,
-0.04522664099931717,
0.00841929204761982,
-0.003977389540523291,
-0... |
371 | mohawk.receiver | Receiver |
A Hawk authority that will receive and respond to requests.
:param credentials_map:
Callable to look up the credentials dict by sender ID.
The credentials dict must have the keys:
``id``, ``key``, and ``algorithm``.
See :ref:`receiving-request` for an example.
:type credentials_map: callable
:param request_header:
A `Hawk`_ ``Authorization`` header
such as one created by :class:`mohawk.Sender`.
:type request_header: str
:param url: Absolute URL of the request.
:type url: str
:param method: Method of the request. E.G. POST, GET
:type method: str
:param content=EmptyValue: Byte string of request body.
:type content=EmptyValue: str
:param content_type=EmptyValue: content-type header value for request.
:type content_type=EmptyValue: str
:param accept_untrusted_content=False:
When True, allow requests that do not hash their content.
Read :ref:`skipping-content-checks` to learn more.
:type accept_untrusted_content=False: bool
:param localtime_offset_in_seconds=0:
Seconds to add to local time in case it's out of sync.
:type localtime_offset_in_seconds=0: float
:param timestamp_skew_in_seconds=60:
Max seconds until a message expires. Upon expiry,
:class:`mohawk.exc.TokenExpired` is raised.
:type timestamp_skew_in_seconds=60: float
.. _`Hawk`: https://github.com/hueniverse/hawk
| class Receiver(HawkAuthority):
"""
A Hawk authority that will receive and respond to requests.
:param credentials_map:
Callable to look up the credentials dict by sender ID.
The credentials dict must have the keys:
``id``, ``key``, and ``algorithm``.
See :ref:`receiving-request` for an example.
:type credentials_map: callable
:param request_header:
A `Hawk`_ ``Authorization`` header
such as one created by :class:`mohawk.Sender`.
:type request_header: str
:param url: Absolute URL of the request.
:type url: str
:param method: Method of the request. E.G. POST, GET
:type method: str
:param content=EmptyValue: Byte string of request body.
:type content=EmptyValue: str
:param content_type=EmptyValue: content-type header value for request.
:type content_type=EmptyValue: str
:param accept_untrusted_content=False:
When True, allow requests that do not hash their content.
Read :ref:`skipping-content-checks` to learn more.
:type accept_untrusted_content=False: bool
:param localtime_offset_in_seconds=0:
Seconds to add to local time in case it's out of sync.
:type localtime_offset_in_seconds=0: float
:param timestamp_skew_in_seconds=60:
Max seconds until a message expires. Upon expiry,
:class:`mohawk.exc.TokenExpired` is raised.
:type timestamp_skew_in_seconds=60: float
.. _`Hawk`: https://github.com/hueniverse/hawk
"""
#: Value suitable for a ``Server-Authorization`` header.
response_header = None
def __init__(self,
credentials_map,
request_header,
url,
method,
content=EmptyValue,
content_type=EmptyValue,
seen_nonce=None,
localtime_offset_in_seconds=0,
accept_untrusted_content=False,
timestamp_skew_in_seconds=default_ts_skew_in_seconds,
**auth_kw):
self.response_header = None # make into property that can raise exc?
self.credentials_map = credentials_map
self.seen_nonce = seen_nonce
log.debug('accepting request {header}'.format(header=request_header))
if not request_header:
raise MissingAuthorization()
parsed_header = parse_authorization_header(request_header)
try:
credentials = self.credentials_map(parsed_header['id'])
except LookupError:
etype, val, tb = sys.exc_info()
log.debug('Catching {etype}: {val}'.format(etype=etype, val=val))
raise CredentialsLookupError(
'Could not find credentials for ID {0}'
.format(parsed_header['id']))
validate_credentials(credentials)
resource = Resource(url=url,
method=method,
ext=parsed_header.get('ext', None),
app=parsed_header.get('app', None),
dlg=parsed_header.get('dlg', None),
credentials=credentials,
nonce=parsed_header['nonce'],
seen_nonce=self.seen_nonce,
content=content,
timestamp=parsed_header['ts'],
content_type=content_type)
self._authorize(
'header', parsed_header, resource,
timestamp_skew_in_seconds=timestamp_skew_in_seconds,
localtime_offset_in_seconds=localtime_offset_in_seconds,
accept_untrusted_content=accept_untrusted_content,
**auth_kw)
# Now that we verified an incoming request, we can re-use some of its
# properties to build our response header.
self.parsed_header = parsed_header
self.resource = resource
def respond(self,
content=EmptyValue,
content_type=EmptyValue,
always_hash_content=True,
ext=None):
"""
Respond to the request.
This generates the :attr:`mohawk.Receiver.response_header`
attribute.
:param content=EmptyValue: Byte string of response body that will be sent.
:type content=EmptyValue: str
:param content_type=EmptyValue: content-type header value for response.
:type content_type=EmptyValue: str
:param always_hash_content=True:
When True, ``content`` and ``content_type`` must be provided.
Read :ref:`skipping-content-checks` to learn more.
:type always_hash_content=True: bool
:param ext=None:
An external `Hawk`_ string. If not None, this value will be
signed so that the sender can trust it.
:type ext=None: str
.. _`Hawk`: https://github.com/hueniverse/hawk
"""
log.debug('generating response header')
resource = Resource(url=self.resource.url,
credentials=self.resource.credentials,
ext=ext,
app=self.parsed_header.get('app', None),
dlg=self.parsed_header.get('dlg', None),
method=self.resource.method,
content=content,
content_type=content_type,
always_hash_content=always_hash_content,
nonce=self.parsed_header['nonce'],
timestamp=self.parsed_header['ts'])
mac = calculate_mac('response', resource, resource.gen_content_hash())
self.response_header = self._make_header(resource, mac,
additional_keys=['ext'])
return self.response_header
| (credentials_map, request_header, url, method, content=EmptyValue, content_type=EmptyValue, seen_nonce=None, localtime_offset_in_seconds=0, accept_untrusted_content=False, timestamp_skew_in_seconds=60, **auth_kw) | [
0.0047804443165659904,
-0.013868976384401321,
-0.08918879926204681,
-0.00838865339756012,
0.028845887631177902,
-0.03385138139128685,
-0.02771816775202751,
0.08364912122488022,
-0.06742577999830246,
-0.019804345443844795,
0.05749393254518509,
0.04340732470154762,
0.049461398273706436,
0.02... |
372 | mohawk.receiver | __init__ | null | def __init__(self,
credentials_map,
request_header,
url,
method,
content=EmptyValue,
content_type=EmptyValue,
seen_nonce=None,
localtime_offset_in_seconds=0,
accept_untrusted_content=False,
timestamp_skew_in_seconds=default_ts_skew_in_seconds,
**auth_kw):
self.response_header = None # make into property that can raise exc?
self.credentials_map = credentials_map
self.seen_nonce = seen_nonce
log.debug('accepting request {header}'.format(header=request_header))
if not request_header:
raise MissingAuthorization()
parsed_header = parse_authorization_header(request_header)
try:
credentials = self.credentials_map(parsed_header['id'])
except LookupError:
etype, val, tb = sys.exc_info()
log.debug('Catching {etype}: {val}'.format(etype=etype, val=val))
raise CredentialsLookupError(
'Could not find credentials for ID {0}'
.format(parsed_header['id']))
validate_credentials(credentials)
resource = Resource(url=url,
method=method,
ext=parsed_header.get('ext', None),
app=parsed_header.get('app', None),
dlg=parsed_header.get('dlg', None),
credentials=credentials,
nonce=parsed_header['nonce'],
seen_nonce=self.seen_nonce,
content=content,
timestamp=parsed_header['ts'],
content_type=content_type)
self._authorize(
'header', parsed_header, resource,
timestamp_skew_in_seconds=timestamp_skew_in_seconds,
localtime_offset_in_seconds=localtime_offset_in_seconds,
accept_untrusted_content=accept_untrusted_content,
**auth_kw)
# Now that we verified an incoming request, we can re-use some of its
# properties to build our response header.
self.parsed_header = parsed_header
self.resource = resource
| (self, credentials_map, request_header, url, method, content=EmptyValue, content_type=EmptyValue, seen_nonce=None, localtime_offset_in_seconds=0, accept_untrusted_content=False, timestamp_skew_in_seconds=60, **auth_kw) | [
-0.029101397842168808,
-0.039527490735054016,
-0.058661088347435,
0.014932607300579548,
0.013347689062356949,
-0.0074806250631809235,
0.007146455813199282,
0.06771230697631836,
-0.06954547017812729,
0.0011904792627319694,
0.07130224257707596,
0.11655835807323456,
0.017739631235599518,
0.00... |
373 | mohawk.base | _authorize | null | def _authorize(self, mac_type, parsed_header, resource,
their_timestamp=None,
timestamp_skew_in_seconds=default_ts_skew_in_seconds,
localtime_offset_in_seconds=0,
accept_untrusted_content=False):
now = utc_now(offset_in_seconds=localtime_offset_in_seconds)
their_hash = parsed_header.get('hash', '')
their_mac = parsed_header.get('mac', '')
mac = calculate_mac(mac_type, resource, their_hash)
if not strings_match(mac, their_mac):
raise MacMismatch('MACs do not match; ours: {ours}; '
'theirs: {theirs}'
.format(ours=mac, theirs=their_mac))
check_hash = True
if 'hash' not in parsed_header:
# The request did not hash its content.
if not resource.content and not resource.content_type:
# It is acceptable to not receive a hash if there is no content
# to hash.
log.debug('NOT calculating/verifying payload hash '
'(no hash in header, request body is empty)')
check_hash = False
elif accept_untrusted_content:
# Allow the request, even if it has content. Missing content or
# content_type values will be coerced to the empty string for
# hashing purposes.
log.debug('NOT calculating/verifying payload hash '
'(no hash in header, accept_untrusted_content=True)')
check_hash = False
if check_hash:
if not their_hash:
log.info('request unexpectedly did not hash its content')
content_hash = resource.gen_content_hash()
if not strings_match(content_hash, their_hash):
# The hash declared in the header is incorrect.
# Content could have been tampered with.
log.debug('mismatched content: {content}'
.format(content=repr(resource.content)))
log.debug('mismatched content-type: {typ}'
.format(typ=repr(resource.content_type)))
raise MisComputedContentHash(
'Our hash {ours} ({algo}) did not '
'match theirs {theirs}'
.format(ours=content_hash,
theirs=their_hash,
algo=resource.credentials['algorithm']))
if resource.seen_nonce:
if resource.seen_nonce(resource.credentials['id'],
parsed_header['nonce'],
parsed_header['ts']):
raise AlreadyProcessed('Nonce {nonce} with timestamp {ts} '
'has already been processed for {id}'
.format(nonce=parsed_header['nonce'],
ts=parsed_header['ts'],
id=resource.credentials['id']))
else:
log.warning('seen_nonce was None; not checking nonce. '
'You may be vulnerable to replay attacks')
their_ts = int(their_timestamp or parsed_header['ts'])
if math.fabs(their_ts - now) > timestamp_skew_in_seconds:
message = ('token with UTC timestamp {ts} has expired; '
'it was compared to {now}'
.format(ts=their_ts, now=now))
tsm = calculate_ts_mac(now, resource.credentials)
if isinstance(tsm, six.binary_type):
tsm = tsm.decode('ascii')
www_authenticate = ('Hawk ts="{ts}", tsm="{tsm}", error="{error}"'
.format(ts=now, tsm=tsm, error=message))
raise TokenExpired(message,
localtime_in_seconds=now,
www_authenticate=www_authenticate)
log.debug('authorized OK')
| (self, mac_type, parsed_header, resource, their_timestamp=None, timestamp_skew_in_seconds=60, localtime_offset_in_seconds=0, accept_untrusted_content=False) | [
0.006975546479225159,
0.00783290434628725,
-0.05065007880330086,
0.026826683431863785,
0.021063614636659622,
-0.07289065420627594,
-0.011911696754395962,
0.0666811540722847,
-0.050487738102674484,
0.026725221425294876,
0.05142119154334068,
0.054424483329057693,
0.047484446316957474,
-0.007... |
374 | mohawk.base | _make_header | null | def _make_header(self, resource, mac, additional_keys=None):
keys = additional_keys
if not keys:
# These are the default header keys that you'd send with a
# request header. Response headers are odd because they
# exclude a bunch of keys.
keys = ('id', 'ts', 'nonce', 'ext', 'app', 'dlg')
header = u'Hawk mac="{mac}"'.format(mac=prepare_header_val(mac))
if resource.content_hash:
header = u'{header}, hash="{hash}"'.format(
header=header,
hash=prepare_header_val(resource.content_hash))
if 'id' in keys:
header = u'{header}, id="{id}"'.format(
header=header,
id=prepare_header_val(resource.credentials['id']))
if 'ts' in keys:
header = u'{header}, ts="{ts}"'.format(
header=header, ts=prepare_header_val(resource.timestamp))
if 'nonce' in keys:
header = u'{header}, nonce="{nonce}"'.format(
header=header, nonce=prepare_header_val(resource.nonce))
# These are optional so we need to check if they have values first.
if 'ext' in keys and resource.ext:
header = u'{header}, ext="{ext}"'.format(
header=header, ext=prepare_header_val(resource.ext))
if 'app' in keys and resource.app:
header = u'{header}, app="{app}"'.format(
header=header, app=prepare_header_val(resource.app))
if 'dlg' in keys and resource.dlg:
header = u'{header}, dlg="{dlg}"'.format(
header=header, dlg=prepare_header_val(resource.dlg))
log.debug('Hawk header for URL={url} method={method}: {header}'
.format(url=resource.url, method=resource.method,
header=header))
return header
| (self, resource, mac, additional_keys=None) | [
-0.037206750363111496,
-0.00041873459122143686,
-0.05269143357872963,
-0.02340834029018879,
-0.008698800578713417,
-0.03358036279678345,
0.001681737951003015,
0.09972570091485977,
-0.03479520231485367,
-0.027469897642731667,
0.059980474412441254,
0.03862104192376137,
0.04775954410433769,
0... |
375 | mohawk.receiver | respond |
Respond to the request.
This generates the :attr:`mohawk.Receiver.response_header`
attribute.
:param content=EmptyValue: Byte string of response body that will be sent.
:type content=EmptyValue: str
:param content_type=EmptyValue: content-type header value for response.
:type content_type=EmptyValue: str
:param always_hash_content=True:
When True, ``content`` and ``content_type`` must be provided.
Read :ref:`skipping-content-checks` to learn more.
:type always_hash_content=True: bool
:param ext=None:
An external `Hawk`_ string. If not None, this value will be
signed so that the sender can trust it.
:type ext=None: str
.. _`Hawk`: https://github.com/hueniverse/hawk
| def respond(self,
content=EmptyValue,
content_type=EmptyValue,
always_hash_content=True,
ext=None):
"""
Respond to the request.
This generates the :attr:`mohawk.Receiver.response_header`
attribute.
:param content=EmptyValue: Byte string of response body that will be sent.
:type content=EmptyValue: str
:param content_type=EmptyValue: content-type header value for response.
:type content_type=EmptyValue: str
:param always_hash_content=True:
When True, ``content`` and ``content_type`` must be provided.
Read :ref:`skipping-content-checks` to learn more.
:type always_hash_content=True: bool
:param ext=None:
An external `Hawk`_ string. If not None, this value will be
signed so that the sender can trust it.
:type ext=None: str
.. _`Hawk`: https://github.com/hueniverse/hawk
"""
log.debug('generating response header')
resource = Resource(url=self.resource.url,
credentials=self.resource.credentials,
ext=ext,
app=self.parsed_header.get('app', None),
dlg=self.parsed_header.get('dlg', None),
method=self.resource.method,
content=content,
content_type=content_type,
always_hash_content=always_hash_content,
nonce=self.parsed_header['nonce'],
timestamp=self.parsed_header['ts'])
mac = calculate_mac('response', resource, resource.gen_content_hash())
self.response_header = self._make_header(resource, mac,
additional_keys=['ext'])
return self.response_header
| (self, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, ext=None) | [
0.06603545695543289,
-0.031462013721466064,
-0.0351957269012928,
-0.026666756719350815,
0.05161307752132416,
0.005481601692736149,
-0.04151009023189545,
0.0594465509057045,
-0.04571966826915741,
0.002962718717753887,
0.09985849261283875,
0.03316414728760719,
0.07101373374462128,
0.00950815... |
376 | mohawk.sender | Sender |
A Hawk authority that will emit requests and verify responses.
:param credentials: Dict of credentials with keys ``id``, ``key``,
and ``algorithm``. See :ref:`usage` for an example.
:type credentials: dict
:param url: Absolute URL of the request.
:type url: str
:param method: Method of the request. E.G. POST, GET
:type method: str
:param content=EmptyValue: Byte string of request body or a file-like object.
:type content=EmptyValue: str or file-like object
:param content_type=EmptyValue: content-type header value for request.
:type content_type=EmptyValue: str
:param always_hash_content=True:
When True, ``content`` and ``content_type`` must be provided.
Read :ref:`skipping-content-checks` to learn more.
:type always_hash_content=True: bool
:param nonce=None:
A string that when coupled with the timestamp will
uniquely identify this request to prevent replays.
If None, a nonce will be generated for you.
:type nonce=None: str
:param ext=None:
An external `Hawk`_ string. If not None, this value will be signed
so that the receiver can trust it.
:type ext=None: str
:param app=None:
A `Hawk`_ application string. If not None, this value will be signed
so that the receiver can trust it.
:type app=None: str
:param dlg=None:
A `Hawk`_ delegation string. If not None, this value will be signed
so that the receiver can trust it.
:type dlg=None: str
:param seen_nonce=None:
A callable that returns True if a nonce has been seen.
See :ref:`nonce` for details.
:type seen_nonce=None: callable
.. _`Hawk`: https://github.com/hueniverse/hawk
| class Sender(HawkAuthority):
"""
A Hawk authority that will emit requests and verify responses.
:param credentials: Dict of credentials with keys ``id``, ``key``,
and ``algorithm``. See :ref:`usage` for an example.
:type credentials: dict
:param url: Absolute URL of the request.
:type url: str
:param method: Method of the request. E.G. POST, GET
:type method: str
:param content=EmptyValue: Byte string of request body or a file-like object.
:type content=EmptyValue: str or file-like object
:param content_type=EmptyValue: content-type header value for request.
:type content_type=EmptyValue: str
:param always_hash_content=True:
When True, ``content`` and ``content_type`` must be provided.
Read :ref:`skipping-content-checks` to learn more.
:type always_hash_content=True: bool
:param nonce=None:
A string that when coupled with the timestamp will
uniquely identify this request to prevent replays.
If None, a nonce will be generated for you.
:type nonce=None: str
:param ext=None:
An external `Hawk`_ string. If not None, this value will be signed
so that the receiver can trust it.
:type ext=None: str
:param app=None:
A `Hawk`_ application string. If not None, this value will be signed
so that the receiver can trust it.
:type app=None: str
:param dlg=None:
A `Hawk`_ delegation string. If not None, this value will be signed
so that the receiver can trust it.
:type dlg=None: str
:param seen_nonce=None:
A callable that returns True if a nonce has been seen.
See :ref:`nonce` for details.
:type seen_nonce=None: callable
.. _`Hawk`: https://github.com/hueniverse/hawk
"""
#: Value suitable for an ``Authorization`` header.
request_header = None
def __init__(self, credentials,
url,
method,
content=EmptyValue,
content_type=EmptyValue,
always_hash_content=True,
nonce=None,
ext=None,
app=None,
dlg=None,
seen_nonce=None,
# For easier testing:
_timestamp=None):
self.reconfigure(credentials)
self.request_header = None
self.seen_nonce = seen_nonce
log.debug('generating request header')
self.req_resource = Resource(url=url,
credentials=self.credentials,
ext=ext,
app=app,
dlg=dlg,
nonce=nonce,
method=method,
content=content,
always_hash_content=always_hash_content,
timestamp=_timestamp,
content_type=content_type)
mac = calculate_mac('header', self.req_resource,
self.req_resource.gen_content_hash())
self.request_header = self._make_header(self.req_resource, mac)
def accept_response(self,
response_header,
content=EmptyValue,
content_type=EmptyValue,
accept_untrusted_content=False,
localtime_offset_in_seconds=0,
timestamp_skew_in_seconds=default_ts_skew_in_seconds,
**auth_kw):
"""
Accept a response to this request.
:param response_header:
A `Hawk`_ ``Server-Authorization`` header
such as one created by :class:`mohawk.Receiver`.
:type response_header: str
:param content=EmptyValue: Byte string of the response body received.
:type content=EmptyValue: str
:param content_type=EmptyValue:
Content-Type header value of the response received.
:type content_type=EmptyValue: str
:param accept_untrusted_content=False:
When True, allow responses that do not hash their content.
Read :ref:`skipping-content-checks` to learn more.
:type accept_untrusted_content=False: bool
:param localtime_offset_in_seconds=0:
Seconds to add to local time in case it's out of sync.
:type localtime_offset_in_seconds=0: float
:param timestamp_skew_in_seconds=60:
Max seconds until a message expires. Upon expiry,
:class:`mohawk.exc.TokenExpired` is raised.
:type timestamp_skew_in_seconds=60: float
.. _`Hawk`: https://github.com/hueniverse/hawk
"""
log.debug('accepting response {header}'
.format(header=response_header))
parsed_header = parse_authorization_header(response_header)
resource = Resource(ext=parsed_header.get('ext', None),
content=content,
content_type=content_type,
# The following response attributes are
# in reference to the original request,
# not to the reponse header:
timestamp=self.req_resource.timestamp,
nonce=self.req_resource.nonce,
url=self.req_resource.url,
method=self.req_resource.method,
app=self.req_resource.app,
dlg=self.req_resource.dlg,
credentials=self.credentials,
seen_nonce=self.seen_nonce)
self._authorize(
'response', parsed_header, resource,
# Per Node lib, a responder macs the *sender's* timestamp.
# It does not create its own timestamp.
# I suppose a slow response could time out here. Maybe only check
# mac failures, not timeouts?
their_timestamp=resource.timestamp,
timestamp_skew_in_seconds=timestamp_skew_in_seconds,
localtime_offset_in_seconds=localtime_offset_in_seconds,
accept_untrusted_content=accept_untrusted_content,
**auth_kw)
def reconfigure(self, credentials):
validate_credentials(credentials)
self.credentials = credentials
| (credentials, url, method, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, nonce=None, ext=None, app=None, dlg=None, seen_nonce=None, _timestamp=None) | [
0.002098454162478447,
-0.017567094415426254,
-0.07272367924451828,
-0.014673346653580666,
0.01695326901972294,
-0.01691429689526558,
-0.026716014370322227,
0.07514000684022903,
-0.07291854172945023,
-0.013737994246184826,
0.04509180039167404,
0.03591364994645119,
0.05074289068579674,
0.041... |
377 | mohawk.sender | __init__ | null | def __init__(self, credentials,
url,
method,
content=EmptyValue,
content_type=EmptyValue,
always_hash_content=True,
nonce=None,
ext=None,
app=None,
dlg=None,
seen_nonce=None,
# For easier testing:
_timestamp=None):
self.reconfigure(credentials)
self.request_header = None
self.seen_nonce = seen_nonce
log.debug('generating request header')
self.req_resource = Resource(url=url,
credentials=self.credentials,
ext=ext,
app=app,
dlg=dlg,
nonce=nonce,
method=method,
content=content,
always_hash_content=always_hash_content,
timestamp=_timestamp,
content_type=content_type)
mac = calculate_mac('header', self.req_resource,
self.req_resource.gen_content_hash())
self.request_header = self._make_header(self.req_resource, mac)
| (self, credentials, url, method, content=EmptyValue, content_type=EmptyValue, always_hash_content=True, nonce=None, ext=None, app=None, dlg=None, seen_nonce=None, _timestamp=None) | [
-0.004960676655173302,
-0.04577956348657608,
-0.04075005277991295,
-0.012307616882026196,
0.007714058272540569,
0.014868262223899364,
0.010316004045307636,
0.04460478574037552,
-0.04596312344074249,
0.014620457775890827,
0.07246901094913483,
0.10741860419511795,
0.01529962569475174,
0.0299... |
380 | mohawk.sender | accept_response |
Accept a response to this request.
:param response_header:
A `Hawk`_ ``Server-Authorization`` header
such as one created by :class:`mohawk.Receiver`.
:type response_header: str
:param content=EmptyValue: Byte string of the response body received.
:type content=EmptyValue: str
:param content_type=EmptyValue:
Content-Type header value of the response received.
:type content_type=EmptyValue: str
:param accept_untrusted_content=False:
When True, allow responses that do not hash their content.
Read :ref:`skipping-content-checks` to learn more.
:type accept_untrusted_content=False: bool
:param localtime_offset_in_seconds=0:
Seconds to add to local time in case it's out of sync.
:type localtime_offset_in_seconds=0: float
:param timestamp_skew_in_seconds=60:
Max seconds until a message expires. Upon expiry,
:class:`mohawk.exc.TokenExpired` is raised.
:type timestamp_skew_in_seconds=60: float
.. _`Hawk`: https://github.com/hueniverse/hawk
| def accept_response(self,
response_header,
content=EmptyValue,
content_type=EmptyValue,
accept_untrusted_content=False,
localtime_offset_in_seconds=0,
timestamp_skew_in_seconds=default_ts_skew_in_seconds,
**auth_kw):
"""
Accept a response to this request.
:param response_header:
A `Hawk`_ ``Server-Authorization`` header
such as one created by :class:`mohawk.Receiver`.
:type response_header: str
:param content=EmptyValue: Byte string of the response body received.
:type content=EmptyValue: str
:param content_type=EmptyValue:
Content-Type header value of the response received.
:type content_type=EmptyValue: str
:param accept_untrusted_content=False:
When True, allow responses that do not hash their content.
Read :ref:`skipping-content-checks` to learn more.
:type accept_untrusted_content=False: bool
:param localtime_offset_in_seconds=0:
Seconds to add to local time in case it's out of sync.
:type localtime_offset_in_seconds=0: float
:param timestamp_skew_in_seconds=60:
Max seconds until a message expires. Upon expiry,
:class:`mohawk.exc.TokenExpired` is raised.
:type timestamp_skew_in_seconds=60: float
.. _`Hawk`: https://github.com/hueniverse/hawk
"""
log.debug('accepting response {header}'
.format(header=response_header))
parsed_header = parse_authorization_header(response_header)
resource = Resource(ext=parsed_header.get('ext', None),
content=content,
content_type=content_type,
# The following response attributes are
# in reference to the original request,
# not to the reponse header:
timestamp=self.req_resource.timestamp,
nonce=self.req_resource.nonce,
url=self.req_resource.url,
method=self.req_resource.method,
app=self.req_resource.app,
dlg=self.req_resource.dlg,
credentials=self.credentials,
seen_nonce=self.seen_nonce)
self._authorize(
'response', parsed_header, resource,
# Per Node lib, a responder macs the *sender's* timestamp.
# It does not create its own timestamp.
# I suppose a slow response could time out here. Maybe only check
# mac failures, not timeouts?
their_timestamp=resource.timestamp,
timestamp_skew_in_seconds=timestamp_skew_in_seconds,
localtime_offset_in_seconds=localtime_offset_in_seconds,
accept_untrusted_content=accept_untrusted_content,
**auth_kw)
| (self, response_header, content=EmptyValue, content_type=EmptyValue, accept_untrusted_content=False, localtime_offset_in_seconds=0, timestamp_skew_in_seconds=60, **auth_kw) | [
0.02192823961377144,
-0.0278137419372797,
-0.03658503666520119,
-0.004257495980709791,
0.03732547163963318,
0.0252127293497324,
-0.00566242216154933,
0.08383992314338684,
-0.05824748054146767,
0.011799481697380543,
0.07677731662988663,
0.04260343685746193,
0.08619412034749985,
-0.001225750... |
381 | mohawk.sender | reconfigure | null | def reconfigure(self, credentials):
validate_credentials(credentials)
self.credentials = credentials
| (self, credentials) | [
0.0029081963002681732,
-0.018602319061756134,
-0.005149007309228182,
-0.025242384523153305,
-0.03069974109530449,
-0.023299362510442734,
0.018078548833727837,
0.026982655748724937,
0.03233863785862923,
0.049471016973257065,
-0.003298912663012743,
0.017292892560362816,
0.0025998472701758146,
... |
390 | tufup | main | null | def main(args=None):
# show version before anything else
print(f'tufup {__version__}')
# default to --help
if args is None:
args = sys.argv[1:] or ['--help']
# parse command line arguments
options = cli.get_parser().parse_args(args=args)
# exit if version is requested (printed above)
if options.version:
return
# cli debugging
if options.debug:
logging.basicConfig(level=logging.DEBUG, stream=sys.stdout, force=True)
# process command
try:
options.func(options)
except Exception: # noqa
logger.exception(f'Failed to process command: {args}')
| (args=None) | [
-0.0049266330897808075,
0.015371465124189854,
0.007482381537556648,
-0.03970884904265404,
0.053093019872903824,
-0.038599662482738495,
0.0033113814424723387,
-0.01076834462583065,
0.004305026959627867,
-0.04229694604873657,
0.007075680419802666,
0.018809940665960312,
-0.054645881056785583,
... |
394 | bitmath | Bit | Bit based types fundamentally operate on self._bit_value | class Bit(Bitmath):
"""Bit based types fundamentally operate on self._bit_value"""
def _set_prefix_value(self):
self.prefix_value = self._to_prefix_value(self._bit_value)
def _setup(self):
return (2, 0, 'Bit', 'Bits')
def _norm(self, value):
"""Normalize the input value into the fundamental unit for this prefix
type"""
self._bit_value = value * self._unit_value
self._byte_value = self._bit_value / 8.0
| (value=0, bytes=None, bits=None) | [
0.0065962281078100204,
-0.03856256604194641,
0.050777118653059006,
0.03265824913978577,
0.03808283805847168,
-0.027418168261647224,
-0.08288183808326721,
-0.021200185641646385,
-0.017620693892240524,
-0.07026135921478271,
0.023654166609048843,
0.09638796001672745,
0.05568508058786392,
0.05... |
395 | bitmath | __abs__ | null | def __abs__(self):
return (type(self))(abs(self.prefix_value))
| (self) | [
0.036472219973802567,
0.002957490738481283,
0.05265970900654793,
0.019932102411985397,
-0.000315637094900012,
-0.019126087427139282,
0.019596261903643608,
-0.004296652507036924,
0.02668248675763607,
-0.02413010224699974,
-0.011007155291736126,
0.03383587673306465,
0.05853690952062607,
-0.0... |
396 | bitmath | __add__ | Supported operations with result types:
- bm + bm = bm
- bm + num = num
- num + bm = num (see radd)
| def __add__(self, other):
"""Supported operations with result types:
- bm + bm = bm
- bm + num = num
- num + bm = num (see radd)
"""
if isinstance(other, numbers.Number):
# bm + num
return other + self.value
else:
# bm + bm
total_bytes = self._byte_value + other.bytes
return (type(self))(bytes=total_bytes)
| (self, other) | [
-0.03417810797691345,
-0.0723033919930458,
0.008618306368589401,
0.10299544781446457,
-0.004092427436262369,
-0.03486056625843048,
-0.03910285606980324,
-0.00573170417919755,
-0.006778443232178688,
-0.04714476317167282,
0.054227545857429504,
-0.012311866506934166,
0.05175594985485077,
0.03... |
397 | bitmath | __and__ | "Bitwise and, ex: 100 & 2
bitwise and". Each bit of the output is 1 if the corresponding bit
of x AND of y is 1, otherwise it's 0. | def __and__(self, other):
""""Bitwise and, ex: 100 & 2
bitwise and". Each bit of the output is 1 if the corresponding bit
of x AND of y is 1, otherwise it's 0."""
andd = int(self.bits) & other
return type(self)(bits=andd)
| (self, other) | [
-0.014325943775475025,
-0.07052218168973923,
0.035423167049884796,
0.03473883867263794,
-0.011417534202337265,
-0.02611265704035759,
-0.03295597434043884,
-0.007712238002568483,
-0.016459977254271507,
-0.04372519254684448,
0.052981678396463394,
0.02841777354478836,
0.06209409609436989,
0.0... |
398 | bitmath | __div__ | Division: Supported operations with result types:
- bm1 / bm2 = num
- bm / num = bm
- num / bm = num (see rdiv)
| def __div__(self, other):
"""Division: Supported operations with result types:
- bm1 / bm2 = num
- bm / num = bm
- num / bm = num (see rdiv)
"""
if isinstance(other, numbers.Number):
# bm / num
result = self._byte_value / other
return (type(self))(bytes=result)
else:
# bm1 / bm2
return self._byte_value / float(other.bytes)
| (self, other) | [
0.004879444371908903,
-0.06440149247646332,
-0.007283288519829512,
0.07319166511297226,
0.009651253931224346,
-0.02475600503385067,
-0.0027491722721606493,
-0.04918910562992096,
-0.024791883304715157,
0.01714981161057949,
0.08732770383358002,
-0.019894499331712723,
0.06425797939300537,
0.0... |
399 | bitmath | __eq__ | null | def __eq__(self, other):
if isinstance(other, numbers.Number):
return self.prefix_value == other
else:
return self._byte_value == other.bytes
| (self, other) | [
0.028946926817297935,
-0.0262370016425848,
-0.02676490880548954,
0.07151386886835098,
-0.014667029492557049,
-0.021996144205331802,
-0.04459058493375778,
0.04209182411432266,
0.03691833093762398,
-0.06556610763072968,
0.046948570758104324,
-0.05113663524389267,
0.06609401851892471,
0.02187... |
400 | bitmath | __float__ | Return this instances prefix unit as a floating point number | def __float__(self):
"""Return this instances prefix unit as a floating point number"""
return float(self.prefix_value)
| (self) | [
-0.0032867761328816414,
0.0030155477579683065,
0.020246028900146484,
0.05426277592778206,
0.030138392001390457,
-0.01291645411401987,
-0.03933025896549225,
-0.004736887291073799,
0.003677601460367441,
-0.01768323965370655,
0.015615924261510372,
-0.02883991226553917,
0.03693832457065582,
-0... |
401 | bitmath | __ge__ | null | def __ge__(self, other):
if isinstance(other, numbers.Number):
return self.prefix_value >= other
else:
return self._byte_value >= other.bytes
| (self, other) | [
0.021472549065947533,
-0.01993505097925663,
-0.035816699266433716,
0.07156351208686829,
-0.009312341921031475,
-0.018851814791560173,
-0.0412328839302063,
0.007469092030078173,
0.009321077726781368,
-0.10091573745012283,
0.057935696095228195,
-0.04822150617837906,
0.05727177485823631,
-0.0... |
402 | bitmath | __gt__ | null | def __gt__(self, other):
if isinstance(other, numbers.Number):
return self.prefix_value > other
else:
return self._byte_value > other.bytes
| (self, other) | [
0.005987662356346846,
-0.004694327246397734,
-0.04257119074463844,
0.04584589600563049,
0.0043851458467543125,
-0.024299021810293198,
-0.05173340067267418,
0.014300714246928692,
0.00765549810603261,
-0.11231547594070435,
0.05967630818486214,
-0.022330714389681816,
0.05479908362030983,
-0.0... |
403 | bitmath | __init__ | Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
default behavior: initialize with value of 0
only setting value: assert bytes is None and bits is None
only setting bytes: assert value == 0 and bits is None
only setting bits: assert value == 0 and bytes is None
| def __init__(self, value=0, bytes=None, bits=None):
"""Instantiate with `value` by the unit, in plain bytes, or
bits. Don't supply more than one keyword.
default behavior: initialize with value of 0
only setting value: assert bytes is None and bits is None
only setting bytes: assert value == 0 and bits is None
only setting bits: assert value == 0 and bytes is None
"""
_raise = False
if (value == 0) and (bytes is None) and (bits is None):
pass
# Setting by bytes
elif bytes is not None:
if (value == 0) and (bits is None):
pass
else:
_raise = True
# setting by bits
elif bits is not None:
if (value == 0) and (bytes is None):
pass
else:
_raise = True
if _raise:
raise ValueError("Only one parameter of: value, bytes, or bits is allowed")
self._do_setup()
if bytes:
# We were provided with the fundamental base unit, no need
# to normalize
self._byte_value = bytes
self._bit_value = bytes * 8.0
elif bits:
# We were *ALMOST* given the fundamental base
# unit. Translate it into the fundamental unit then
# normalize.
self._byte_value = bits / 8.0
self._bit_value = bits
else:
# We were given a value representative of this *prefix
# unit*. We need to normalize it into the number of bytes
# it represents.
self._norm(value)
# We have the fundamental unit figured out. Set the 'pretty' unit
self._set_prefix_value()
| (self, value=0, bytes=None, bits=None) | [
0.02978331223130226,
0.030348461121320724,
0.034794293344020844,
0.006315531674772501,
0.02450859546661377,
-0.02575192041695118,
-0.044872768223285675,
0.005029819440096617,
-0.01461850106716156,
-0.04517418146133423,
0.03858078643679619,
0.12056495994329453,
0.02452743425965309,
0.018329... |
404 | bitmath | __int__ | Return this instances prefix unit as an integer | def __int__(self):
"""Return this instances prefix unit as an integer"""
return int(self.prefix_value)
| (self) | [
-0.01966407336294651,
0.007813705131411552,
0.022494761273264885,
0.00994090922176838,
0.035140737891197205,
-0.004526589065790176,
-0.000538605498149991,
0.021741027012467384,
0.009471919387578964,
-0.09165401011705399,
-0.020049314945936203,
0.006427672691643238,
0.04217558354139328,
-0.... |
405 | bitmath | __le__ | null | def __le__(self, other):
if isinstance(other, numbers.Number):
return self.prefix_value <= other
else:
return self._byte_value <= other.bytes
| (self, other) | [
-0.004681911785155535,
-0.0062090023420751095,
-0.03236207365989685,
0.07358039915561676,
0.0002767578698694706,
-0.013888212852180004,
-0.03489993140101433,
0.005740811116993427,
-0.008116772398352623,
-0.09430332481861115,
0.05821322649717331,
-0.03983562812209129,
0.07505060732364655,
-... |
406 | bitmath | __long__ | Return this instances prefix unit as a long integer | def __long__(self):
"""Return this instances prefix unit as a long integer"""
return long(self.prefix_value) # pragma: PY3X no cover
| (self) | [
-0.01646570861339569,
0.022419217973947525,
0.02282745949923992,
0.07845025509595871,
0.017554350197315216,
-0.01770744100213051,
-0.006523346062749624,
-0.005285866558551788,
-0.00650633592158556,
-0.11110951006412506,
-0.015504641458392143,
-0.003918685484677553,
0.007144212257117033,
-0... |
407 | bitmath | __lshift__ | Left shift, ex: 100 << 2
A left shift by n bits is equivalent to multiplication by pow(2,
n). A long integer is returned if the result exceeds the range of
plain integers. | def __lshift__(self, other):
"""Left shift, ex: 100 << 2
A left shift by n bits is equivalent to multiplication by pow(2,
n). A long integer is returned if the result exceeds the range of
plain integers."""
shifted = int(self.bits) << other
return type(self)(bits=shifted)
| (self, other) | [
-0.04831855744123459,
0.011972423642873764,
0.028179869055747986,
0.07648056000471115,
0.014626013115048409,
-0.022640390321612358,
-0.021050022915005684,
0.010480338707566261,
-0.02641081064939499,
-0.04195709154009819,
0.012821215204894543,
0.012249398045241833,
0.04045607149600983,
0.03... |
408 | bitmath | __lt__ | null | def __lt__(self, other):
if isinstance(other, numbers.Number):
return self.prefix_value < other
else:
return self._byte_value < other.bytes
| (self, other) | [
-0.0029584176372736692,
-0.0014018717920407653,
-0.027362097054719925,
0.0521099790930748,
0.007289297413080931,
0.0029431681614369154,
-0.013280202634632587,
0.009210743941366673,
0.015057867392897606,
-0.09494821727275848,
0.04754381999373436,
-0.0557350218296051,
0.05420134961605072,
-0... |
409 | bitmath | __mul__ | Multiplication: Supported operations with result types:
- bm1 * bm2 = bm1
- bm * num = bm
- num * bm = num (see rmul)
| def __mul__(self, other):
"""Multiplication: Supported operations with result types:
- bm1 * bm2 = bm1
- bm * num = bm
- num * bm = num (see rmul)
"""
if isinstance(other, numbers.Number):
# bm * num
result = self._byte_value * other
return (type(self))(bytes=result)
else:
# bm1 * bm2
_other = other.value * other.base ** other.power
_self = self.prefix_value * self._base ** self._power
return (type(self))(bytes=_other * _self)
| (self, other) | [
0.029291458427906036,
-0.06039709970355034,
0.04731987789273262,
0.08942399173974991,
-0.03843795508146286,
-0.06512152403593063,
-0.039949771016836166,
-0.022771747782826424,
-0.02965051494538784,
0.005773251876235008,
0.03709621727466583,
0.01043153926730156,
0.07143336534500122,
0.06285... |
410 | bitmath | __ne__ | null | def __ne__(self, other):
if isinstance(other, numbers.Number):
return self.prefix_value != other
else:
return self._byte_value != other.bytes
| (self, other) | [
0.009809257462620735,
0.008262277580797672,
-0.0008525967714376748,
0.06398870795965195,
-0.05808205530047417,
-0.03702203556895256,
-0.07052820920944214,
0.033471014350652695,
0.05196445435285568,
-0.064094178378582,
0.046725817024707794,
-0.0362837053835392,
0.03572116792201996,
-0.03273... |
411 | bitmath | __neg__ | The negative version of this instance | def __neg__(self):
"""The negative version of this instance"""
return (type(self))(-abs(self.prefix_value))
| (self) | [
0.02878359518945217,
-0.0022634295746684074,
0.08594727516174316,
0.0073219952173531055,
-0.020276295021176338,
-0.03755990043282509,
-0.011567238718271255,
-0.004112842958420515,
0.0428055115044117,
-0.05420462042093277,
-0.028850845992565155,
0.017149103805422783,
0.046638838946819305,
-... |
412 | bitmath | __or__ | Bitwise or, ex: 100 | 2
Does a "bitwise or". Each bit of the output is 0 if the corresponding
bit of x AND of y is 0, otherwise it's 1. | def __or__(self, other):
"""Bitwise or, ex: 100 | 2
Does a "bitwise or". Each bit of the output is 0 if the corresponding
bit of x AND of y is 0, otherwise it's 1."""
ord = int(self.bits) | other
return type(self)(bits=ord)
| (self, other) | [
-0.019762661308050156,
-0.04724946245551109,
0.030165893957018852,
0.04540541023015976,
-0.0043752724304795265,
-0.05713079124689102,
-0.05532153323292732,
0.016613857820630074,
0.010820752941071987,
-0.02844361960887909,
0.06499410420656204,
0.04697111248970032,
0.03851631283760071,
0.036... |
413 | bitmath | __pos__ | null | def __pos__(self):
return (type(self))(abs(self.prefix_value))
| (self) | [
0.027723141014575958,
0.008290993981063366,
0.023855963721871376,
0.007546017877757549,
0.018900619819760323,
0.0033168159425258636,
0.021947486326098442,
0.010664033703505993,
0.031707506626844406,
-0.05906234309077263,
-0.01135878637433052,
0.010220397263765335,
0.0493190661072731,
-0.02... |
414 | bitmath | __radd__ | null | def __radd__(self, other):
# num + bm = num
return other + self.value
| (self, other) | [
-0.04449845477938652,
-0.05090188980102539,
0.024401793256402016,
0.12083319574594498,
-0.013105337508022785,
-0.05205957219004631,
-0.05506231263279915,
-0.011658232659101486,
0.018152112141251564,
-0.05173397436738014,
0.006534579675644636,
-0.011323589831590652,
0.05546026676893234,
0.0... |
415 | bitmath | __rdiv__ | null | def __rdiv__(self, other):
# num / bm = num
return other / float(self.value)
| (self, other) | [
-0.005453083198517561,
-0.04038158431649208,
-0.003864235244691372,
0.09785036742687225,
0.002863849513232708,
-0.03021644428372383,
-0.016485659405589104,
-0.04603082314133644,
-0.031245164573192596,
0.02861233986914158,
0.046867746859788895,
-0.017183097079396248,
0.06991802901029587,
0.... |
416 | bitmath | __repr__ | Representation of this object as you would expect to see in an
interpreter | def __repr__(self):
"""Representation of this object as you would expect to see in an
interpreter"""
global _FORMAT_REPR
return self.format(_FORMAT_REPR)
| (self) | [
0.032229337841272354,
-0.0566413477063179,
0.0490640252828598,
0.024566298350691795,
0.04107526317238808,
-0.05156693980097771,
-0.015548941679298878,
-0.01658610813319683,
0.03198933228850365,
-0.004135812632739544,
-0.015180361457169056,
0.004386533051729202,
0.0075601800344884396,
0.064... |
417 | bitmath | __rmul__ | null | def __rmul__(self, other):
# num * bm = bm
return self * other
| (self, other) | [
-0.01758519373834133,
-0.025348346680402756,
0.04591936990618706,
0.08763183653354645,
-0.06392347067594528,
-0.05593749135732651,
-0.03449300304055214,
-0.030660448595881462,
-0.02477792091667652,
0.0011096586240455508,
-0.014189369976520538,
-0.023940104991197586,
0.04460025578737259,
0.... |
418 | bitmath | __rshift__ | Right shift, ex: 100 >> 2
A right shift by n bits is equivalent to division by pow(2, n). | def __rshift__(self, other):
"""Right shift, ex: 100 >> 2
A right shift by n bits is equivalent to division by pow(2, n)."""
shifted = int(self.bits) >> other
return type(self)(bits=shifted)
| (self, other) | [
-0.0568464957177639,
0.00859987735748291,
0.002083591418340802,
0.056306470185518265,
0.004738708026707172,
-0.03126737102866173,
-0.04892614856362343,
0.03448951244354248,
0.0045654503628611565,
-0.021474942564964294,
0.04881814122200012,
0.04766609147191048,
0.06303876638412476,
0.062354... |
419 | bitmath | __rsub__ | null | def __rsub__(self, other):
# num - bm = num
return other - self.value
| (self, other) | [
0.024300577118992805,
-0.03787776827812195,
0.019388575106859207,
0.08274303376674652,
-0.053755298256874084,
-0.0705668032169342,
-0.021291110664606094,
0.010247753001749516,
0.023159056901931763,
-0.051403071731328964,
-0.008267384953796864,
0.0006723736296407878,
0.0410601943731308,
0.0... |
420 | bitmath | __rtruediv__ | null | def __rtruediv__(self, other):
# num / bm = num
return other / float(self.value)
| (self, other) | [
-0.022798890247941017,
-0.042246028780937195,
0.04441070184111595,
0.08484119921922684,
0.018940884619951248,
-0.021995864808559418,
-0.021594353020191193,
-0.06916477531194687,
-0.05191722512245178,
0.03592658042907715,
0.03854513540863991,
-0.001945368479937315,
0.05739873647689819,
0.05... |
421 | bitmath | __str__ | String representation of this object | def __str__(self):
"""String representation of this object"""
global format_string
return self.format(format_string)
| (self) | [
0.0023601041175425053,
-0.018277335911989212,
0.017130693420767784,
-0.001381576992571354,
0.00841016136109829,
-0.0564873144030571,
0.008151520043611526,
-0.0048021115362644196,
0.03483039513230324,
-0.06255677342414856,
-0.044831205159425735,
-0.011906133033335209,
-0.030519703403115273,
... |
422 | bitmath | __sub__ | Subtraction: Supported operations with result types:
- bm - bm = bm
- bm - num = num
- num - bm = num (see rsub)
| def __sub__(self, other):
"""Subtraction: Supported operations with result types:
- bm - bm = bm
- bm - num = num
- num - bm = num (see rsub)
"""
if isinstance(other, numbers.Number):
# bm - num
return self.value - other
else:
# bm - bm
total_bytes = self._byte_value - other.bytes
return (type(self))(bytes=total_bytes)
| (self, other) | [
0.0257546566426754,
-0.07306880503892899,
0.015923382714390755,
0.06289097666740417,
-0.03589601069688797,
-0.0573095865547657,
-0.005786589812487364,
0.003050613682717085,
0.006251705810427666,
-0.051108039915561676,
0.034892819821834564,
0.0010242811404168606,
0.03235748037695885,
-0.000... |
423 | bitmath | __truediv__ | null | def __truediv__(self, other):
# num / bm
return self.__div__(other)
| (self, other) | [
-0.023414313793182373,
-0.03045056201517582,
0.028964752331376076,
0.08901196718215942,
0.00011067522427765653,
-0.034429799765348434,
-0.0170868132263422,
-0.04481339082121849,
-0.060081370174884796,
0.04590640217065811,
0.047511760145425797,
-0.01969124935567379,
0.04730682075023651,
0.0... |
424 | bitmath | __xor__ | Bitwise xor, ex: 100 ^ 2
Does a "bitwise exclusive or". Each bit of the output is the same
as the corresponding bit in x if that bit in y is 0, and it's the
complement of the bit in x if that bit in y is 1. | def __xor__(self, other):
"""Bitwise xor, ex: 100 ^ 2
Does a "bitwise exclusive or". Each bit of the output is the same
as the corresponding bit in x if that bit in y is 0, and it's the
complement of the bit in x if that bit in y is 1."""
xord = int(self.bits) ^ other
return type(self)(bits=xord)
| (self, other) | [
-0.017696572467684746,
-0.06592339277267456,
0.08936037868261337,
0.04511895030736923,
-0.03043883666396141,
-0.06383929401636124,
-0.08511905372142792,
0.006947001907974482,
0.024204816669225693,
-0.006969853769987822,
0.054113488644361496,
0.012659996747970581,
0.031316354870796204,
0.05... |
425 | bitmath | _do_setup | Setup basic parameters for this class.
`base` is the numeric base which when raised to `power` is equivalent
to 1 unit of the corresponding prefix. I.e., base=2, power=10
represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte.
Likewise, for the SI prefix classes `base` will be 10, and the `power`
for the Kilobyte is 3.
| def _do_setup(self):
"""Setup basic parameters for this class.
`base` is the numeric base which when raised to `power` is equivalent
to 1 unit of the corresponding prefix. I.e., base=2, power=10
represents 2^10, which is the NIST Binary Prefix for 1 Kibibyte.
Likewise, for the SI prefix classes `base` will be 10, and the `power`
for the Kilobyte is 3.
"""
(self._base, self._power, self._name_singular, self._name_plural) = self._setup()
self._unit_value = self._base ** self._power
| (self) | [
0.00286993570625782,
0.024792613461613655,
0.04047403112053871,
0.03277852013707161,
0.02090855874121189,
-0.006924144923686981,
-0.0296204574406147,
-0.03007420338690281,
-0.008090268820524216,
0.00560374790802598,
0.0034348478075116873,
0.07818929851055145,
0.09510490298271179,
0.0487140... |
426 | bitmath | _norm | Normalize the input value into the fundamental unit for this prefix
type | def _norm(self, value):
"""Normalize the input value into the fundamental unit for this prefix
type"""
self._bit_value = value * self._unit_value
self._byte_value = self._bit_value / 8.0
| (self, value) | [
-0.02524532750248909,
0.06916005164384842,
0.01740279421210289,
0.008146173320710659,
0.04382797330617905,
-0.01899906061589718,
-0.03428506478667259,
-0.01931137405335903,
0.013611656613647938,
-0.024846261367201805,
0.004632648080587387,
0.02729271538555622,
0.039455585181713104,
0.02540... |
427 | bitmath | _set_prefix_value | null | def _set_prefix_value(self):
self.prefix_value = self._to_prefix_value(self._bit_value)
| (self) | [
-0.03728190064430237,
0.031588438898324966,
0.005899251904338598,
0.011627014726400375,
0.0074598100036382675,
0.0458906926214695,
-0.005234728567302227,
0.03632155805826187,
0.0724373310804367,
-0.06578352302312851,
-0.003766346722841263,
0.015777070075273514,
0.0621822327375412,
0.010983... |
428 | bitmath | _setup | null | def _setup(self):
return (2, 0, 'Bit', 'Bits')
| (self) | [
0.0016102580120787024,
-0.022419745102524757,
0.035354893654584885,
-0.01771283708512783,
0.03238211199641228,
0.008391921408474445,
-0.020101681351661682,
0.01657150126993656,
-0.002101298188790679,
-0.021110305562615395,
0.03213438019156456,
0.08238858729600906,
0.029550887644290924,
0.0... |
429 | bitmath | _to_prefix_value | Return the number of bits/bytes as they would look like if we
converted *to* this unit | def _to_prefix_value(self, value):
"""Return the number of bits/bytes as they would look like if we
converted *to* this unit"""
return value / float(self._unit_value)
| (self, value) | [
-0.032300110906362534,
-0.007817724719643593,
0.018680201843380928,
0.007157313171774149,
0.05996876582503319,
0.03612534701824188,
0.0023650438524782658,
0.0004090046277269721,
0.004785836674273014,
-0.03437568619847298,
0.03492460027337074,
-0.004798701964318752,
0.05485701188445091,
-0.... |
430 | bitmath | best_prefix | Optional parameter, `system`, allows you to prefer NIST or SI in
the results. By default, the current system is used (Bit/Byte default
to NIST).
Logic discussion/notes:
Base-case, does it need converting?
If the instance is less than one Byte, return the instance as a Bit
instance.
Else, begin by recording the unit system the instance is defined
by. This determines which steps (NIST_STEPS/SI_STEPS) we iterate over.
If the instance is not already a ``Byte`` instance, convert it to one.
NIST units step up by powers of 1024, SI units step up by powers of
1000.
Take integer value of the log(base=STEP_POWER) of the instance's byte
value. E.g.:
>>> int(math.log(Gb(100).bytes, 1000))
3
This will return a value >= 0. The following determines the 'best
prefix unit' for representation:
* result == 0, best represented as a Byte
* result >= len(SYSTEM_STEPS), best represented as an Exbi/Exabyte
* 0 < result < len(SYSTEM_STEPS), best represented as SYSTEM_PREFIXES[result-1]
| def best_prefix(self, system=None):
"""Optional parameter, `system`, allows you to prefer NIST or SI in
the results. By default, the current system is used (Bit/Byte default
to NIST).
Logic discussion/notes:
Base-case, does it need converting?
If the instance is less than one Byte, return the instance as a Bit
instance.
Else, begin by recording the unit system the instance is defined
by. This determines which steps (NIST_STEPS/SI_STEPS) we iterate over.
If the instance is not already a ``Byte`` instance, convert it to one.
NIST units step up by powers of 1024, SI units step up by powers of
1000.
Take integer value of the log(base=STEP_POWER) of the instance's byte
value. E.g.:
>>> int(math.log(Gb(100).bytes, 1000))
3
This will return a value >= 0. The following determines the 'best
prefix unit' for representation:
* result == 0, best represented as a Byte
* result >= len(SYSTEM_STEPS), best represented as an Exbi/Exabyte
* 0 < result < len(SYSTEM_STEPS), best represented as SYSTEM_PREFIXES[result-1]
"""
# Use absolute value so we don't return Bit's for *everything*
# less than Byte(1). From github issue #55
if abs(self) < Byte(1):
return Bit.from_other(self)
else:
if type(self) is Byte: # pylint: disable=unidiomatic-typecheck
_inst = self
else:
_inst = Byte.from_other(self)
# Which table to consult? Was a preferred system provided?
if system is None:
# No preference. Use existing system
if self.system == 'NIST':
_STEPS = NIST_PREFIXES
_BASE = 1024
elif self.system == 'SI':
_STEPS = SI_PREFIXES
_BASE = 1000
# Anything else would have raised by now
else:
# Preferred system provided.
if system == NIST:
_STEPS = NIST_PREFIXES
_BASE = 1024
elif system == SI:
_STEPS = SI_PREFIXES
_BASE = 1000
else:
raise ValueError("Invalid value given for 'system' parameter."
" Must be one of NIST or SI")
# Index of the string of the best prefix in the STEPS list
_index = int(math.log(abs(_inst.bytes), _BASE))
# Recall that the log() function returns >= 0. This doesn't
# map to the STEPS list 1:1. That is to say, 0 is handled with
# special care. So if the _index is 1, we actually want item 0
# in the list.
if _index == 0:
# Already a Byte() type, so return it.
return _inst
elif _index >= len(_STEPS):
# This is a really big number. Use the biggest prefix we've got
_best_prefix = _STEPS[-1]
elif 0 < _index < len(_STEPS):
# There is an appropriate prefix unit to represent this
_best_prefix = _STEPS[_index - 1]
_conversion_method = getattr(
self,
'to_%sB' % _best_prefix)
return _conversion_method()
| (self, system=None) | [
0.02592577040195465,
-0.021564073860645294,
-0.02167687565088272,
-0.013573898002505302,
0.024402936920523643,
-0.016722967848181725,
-0.022240888327360153,
-0.016309358179569244,
0.0268469899892807,
-0.07429923117160797,
0.029535450041294098,
0.06301898509263992,
0.0005302304052747786,
-0... |
431 | bitmath | format | Return a representation of this instance formatted with user
supplied syntax | def format(self, fmt):
"""Return a representation of this instance formatted with user
supplied syntax"""
_fmt_params = {
'base': self.base,
'bin': self.bin,
'binary': self.binary,
'bits': self.bits,
'bytes': self.bytes,
'power': self.power,
'system': self.system,
'unit': self.unit,
'unit_plural': self.unit_plural,
'unit_singular': self.unit_singular,
'value': self.value
}
return fmt.format(**_fmt_params)
| (self, fmt) | [
0.06484465301036835,
-0.03965220972895622,
0.06429249048233032,
-0.01414055097848177,
0.005357707384973764,
-0.04900447279214859,
-0.02358771674335003,
-0.07419691234827042,
-0.0012035429244861007,
-0.021413573995232582,
-0.013622897677123547,
0.04627816751599312,
-0.00979226641356945,
0.0... |
432 | bitmath | to_Bit | null | def to_Bit(self):
return Bit(self._bit_value)
| (self) | [
0.02648862451314926,
-0.03728533908724785,
0.042265813797712326,
0.007018717937171459,
-0.0012792317429557443,
-0.04734862968325615,
0.0061061992309987545,
0.0012845618184655905,
-0.03076978586614132,
-0.05464877933263779,
0.003628753824159503,
0.059390462934970856,
0.026829753071069717,
0... |
433 | bitmath | to_Byte | null | def to_Byte(self):
return Byte(self._byte_value / float(NIST_STEPS['Byte']))
| (self) | [
0.0027008068282157183,
-0.04112652689218521,
-0.004552915226668119,
0.02226066030561924,
0.022950228303670883,
-0.033417511731386185,
-0.020633988082408905,
0.006387342233210802,
-0.027847927063703537,
-0.000848146213684231,
0.05742861330509186,
-0.0012807836756110191,
0.019396301358938217,
... |
434 | bitmath | to_EB | null | def to_EB(self):
return EB(bits=self._bit_value)
| (self) | [
0.08646230399608612,
-0.05193176120519638,
0.016237173229455948,
-0.007256172131747007,
-0.013348298147320747,
-0.06049642339348793,
-0.0005429915036074817,
-0.04411480948328972,
-0.04452265053987503,
-0.0434010848402977,
0.00985615886747837,
0.019066570326685905,
0.04323115199804306,
0.01... |
435 | bitmath | to_Eb | null | def to_Eb(self):
return Eb(bits=self._bit_value)
| (self) | [
0.08937109261751175,
-0.05345078557729721,
0.03289543464779854,
-0.006793062202632427,
-0.008430100046098232,
-0.03647027909755707,
0.005577099975198507,
-0.03408132120966911,
-0.0551350899040699,
-0.036504652351140976,
0.012821313925087452,
-0.005589989945292473,
0.02596917562186718,
0.03... |
436 | bitmath | to_EiB | null | def to_EiB(self):
return EiB(bits=self._bit_value)
| (self) | [
0.07907365262508392,
-0.061761267483234406,
0.022190088406205177,
-0.024354135617613792,
0.0353461317718029,
-0.055818717926740646,
0.00421860720962286,
-0.05485691875219345,
-0.037235379219055176,
-0.031773731112480164,
0.0514562726020813,
-0.008286932483315468,
0.02588270977139473,
0.018... |
437 | bitmath | to_Eib | null | def to_Eib(self):
return Eib(bits=self._bit_value)
| (self) | [
0.08763374388217926,
-0.046760816127061844,
0.024664105847477913,
-0.029028676450252533,
0.0018367570592090487,
-0.056927699595689774,
-0.005943519063293934,
-0.05915277451276779,
-0.03892170637845993,
-0.03029525838792324,
0.030483534559607506,
-0.006388533860445023,
0.012075313366949558,
... |
438 | bitmath | to_GB | null | def to_GB(self):
return GB(bits=self._bit_value)
| (self) | [
0.035119909793138504,
-0.048273056745529175,
-0.03976219519972801,
-0.007758169434964657,
-0.010403095744550228,
-0.03273148462176323,
-0.03935851901769638,
-0.015087432228028774,
-0.04416900500655174,
-0.08342660218477249,
0.024842962622642517,
-0.009721890091896057,
0.03024214319884777,
... |
439 | bitmath | to_Gb | null | def to_Gb(self):
return Gb(bits=self._bit_value)
| (self) | [
0.044223181903362274,
-0.037302494049072266,
-0.017855368554592133,
-0.00007826321962056682,
0.01241397950798273,
-0.027751948684453964,
0.000505264091771096,
-0.020831262692809105,
-0.041039664298295975,
-0.057268671691417694,
0.01661829650402069,
-0.027250198647379875,
0.017708303406834602... |
440 | bitmath | to_GiB | null | def to_GiB(self):
return GiB(bits=self._bit_value)
| (self) | [
0.05911073833703995,
-0.04699285700917244,
-0.011369530111551285,
-0.006681064143776894,
0.046524010598659515,
-0.026652125641703606,
-0.004769612569361925,
-0.007258106023073196,
-0.022576767951250076,
-0.042665041983127594,
0.023262005299329758,
-0.025443945080041885,
0.0069921258836984634... |
441 | bitmath | to_Gib | null | def to_Gib(self):
return Gib(bits=self._bit_value)
| (self) | [
0.05779401212930679,
-0.05015212297439575,
-0.000014222675417840946,
-0.03273572400212288,
-0.0006314555648714304,
-0.026462264358997345,
-0.013968663290143013,
-0.013746515847742558,
-0.013488823547959328,
-0.03495720401406288,
-0.012804607860744,
-0.006300115957856178,
0.00662445230409503,... |
442 | bitmath | to_KiB | null | def to_KiB(self):
return KiB(bits=self._bit_value)
| (self) | [
0.028345957398414612,
-0.040464118123054504,
-0.02209368906915188,
-0.009501339867711067,
0.03285953402519226,
-0.012390379793941975,
-0.00824561808258295,
0.011389314197003841,
-0.008465149439871311,
-0.03498460352420807,
0.02639651484787464,
-0.01754498854279518,
0.029979275539517403,
0.... |
443 | bitmath | to_Kib | null | def to_Kib(self):
return Kib(bits=self._bit_value)
| (self) | [
0.029349910095334053,
-0.05153621733188629,
-0.02128216251730919,
-0.03183630481362343,
-0.0024950900115072727,
-0.016700586304068565,
-0.01177126169204712,
-0.0114061264321208,
0.01585729792714119,
-0.019126126542687416,
-0.009380495175719261,
0.010102071799337864,
0.019752072170376778,
0... |
444 | bitmath | to_MB | null | def to_MB(self):
return MB(bits=self._bit_value)
| (self) | [
0.048769235610961914,
0.02069876901805401,
0.0024529662914574146,
0.0024124388583004475,
-0.016304759308695793,
-0.04143166542053223,
-0.0011219654697924852,
-0.01210698764771223,
-0.021159499883651733,
-0.041499923914670944,
0.004620108753442764,
0.049212902784347534,
0.027592670172452927,
... |
445 | bitmath | to_Mb | null | def to_Mb(self):
return Mb(bits=self._bit_value)
| (self) | [
0.060102034360170364,
0.02492077834904194,
0.019825322553515434,
-0.01187780313193798,
-0.0064258393831551075,
-0.05884990841150284,
-0.003043361008167267,
-0.01843407191336155,
-0.03780724108219147,
-0.028920624405145645,
-0.011703897267580032,
0.046432994306087494,
0.02665984258055687,
0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.