index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
21,479 | tfields.triangles_3d | mesh |
Returns:
tfields.Mesh3D
| def mesh(self):
"""
Returns:
tfields.Mesh3D
"""
mp = tfields.TensorFields(np.arange(len(self)).reshape((-1, 3)), *self.fields)
mesh = tfields.Mesh3D(self, maps=[mp])
return mesh.cleaned(stale=False) # stale vertices can not occure here
| (self) |
21,485 | tfields.triangles_3d | norms |
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert np.allclose(m.triangles().norms(),
... [[0.0, 0.0, 1.0],
... [0.0, 0.0, -1.0],
... [0.0, 1.0, 0.0],
... [0.57735027] * 3],
... atol=1e-8)
| def norms(self):
"""
Examples:
>>> import numpy as np
>>> import tfields
>>> m = tfields.Mesh3D([[0,0,0], [1,0,0], [-1,0,0], [0,1,0], [0,0,1]],
... faces=[[0, 1, 3],[0, 2, 3],[1,2,4], [1, 3, 4]]);
>>> assert np.allclose(m.triangles().norms(),
... [[0.0, 0.0, 1.0],
... [0.0, 0.0, -1.0],
... [0.0, 1.0, 0.0],
... [0.57735027] * 3],
... atol=1e-8)
"""
ab, ac = self.edges()
vectors = np.cross(ab, ac)
norms = np.apply_along_axis(np.linalg.norm, 0, vectors.T).reshape(-1, 1)
# cross product may be zero, so replace zero norms by ones to divide vectors by norms
np.place(norms, norms == 0.0, 1.0)
return vectors / norms
| (self) |
21,486 | tfields.triangles_3d | ntriangles |
Returns:
int: number of triangles
| def ntriangles(self):
"""
Returns:
int: number of triangles
"""
return len(self) // 3
| (self) |
21,497 | tfields.core | dim |
Manifold dimension
| def dim(tensor):
"""
Manifold dimension
"""
tensor = np.asarray(tensor)
if rank(tensor) == 0:
return 1
return tensor.shape[1]
| (tensor) |
21,498 | tfields.mask | evalf |
Linking sympy and numpy by retrieving a mask according to the cut_expression
Args:
array (numpy ndarray)
cut_expression (sympy logical expression)
coord_sys (str): coord_sys to evalfuate the expression in.
Returns:
np.array: mask which is True, where cut_expression evalfuates True.
Examples:
>>> import sympy
>>> import numpy as np
>>> import tfields
>>> x, y, z = sympy.symbols('x y z')
>>> a = np.array([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> assert np.array_equal(
... tfields.evalf(a, x > 0),
... np.array([ True, True, True, False, True, False]))
And combination
>>> assert np.array_equal(
... tfields.evalf(a, (x > 0) & (y < 3)),
... np.array([True, False, True, False, True, False]))
Or combination
>>> assert np.array_equal(
... tfields.evalf(a, (x > 0) | (y > 3)),
... np.array([True, True, True, False, True, False]))
If array of other shape than (?, 3) is given, the coords need to be
specified
>>> a0, a1 = sympy.symbols('a0 a1')
>>> assert np.array_equal(
... tfields.evalf([[0., 1.], [-1, 3]], a1 > 2, coords=[a0, a1]),
... np.array([False, True], dtype=bool))
>= is taken care of
>>> assert np.array_equal(
... tfields.evalf(a, x >= 0),
... np.array([ True, True, True, False, True, True]))
| def evalf(array, cut_expression=None, coords=None):
"""
Linking sympy and numpy by retrieving a mask according to the cut_expression
Args:
array (numpy ndarray)
cut_expression (sympy logical expression)
coord_sys (str): coord_sys to evalfuate the expression in.
Returns:
np.array: mask which is True, where cut_expression evalfuates True.
Examples:
>>> import sympy
>>> import numpy as np
>>> import tfields
>>> x, y, z = sympy.symbols('x y z')
>>> a = np.array([[1., 2., 3.], [4., 5., 6.], [1, 2, -6],
... [-5, -5, -5], [1,0,-1], [0,1,-1]])
>>> assert np.array_equal(
... tfields.evalf(a, x > 0),
... np.array([ True, True, True, False, True, False]))
And combination
>>> assert np.array_equal(
... tfields.evalf(a, (x > 0) & (y < 3)),
... np.array([True, False, True, False, True, False]))
Or combination
>>> assert np.array_equal(
... tfields.evalf(a, (x > 0) | (y > 3)),
... np.array([True, True, True, False, True, False]))
If array of other shape than (?, 3) is given, the coords need to be
specified
>>> a0, a1 = sympy.symbols('a0 a1')
>>> assert np.array_equal(
... tfields.evalf([[0., 1.], [-1, 3]], a1 > 2, coords=[a0, a1]),
... np.array([False, True], dtype=bool))
>= is taken care of
>>> assert np.array_equal(
... tfields.evalf(a, x >= 0),
... np.array([ True, True, True, False, True, True]))
"""
if isinstance(array, list):
array = np.array(array)
if cut_expression is None:
return np.full((array.shape[0]), False, dtype=bool)
if len(array.shape) != 2:
raise NotImplementedError("Array shape other than 2")
if coords is None:
if array.shape[1] == 3:
coords = sympy.symbols("x y z")
else:
raise ValueError("coords are None and shape is not (?, 3)")
elif len(coords) != array.shape[1]:
raise ValueError(
"Length of coords is not {0} but {1}".format(array.shape[1], len(coords))
)
pre_mask = sympy.utilities.lambdify(
coords, cut_expression, modules={"&": np.logical_and, "|": np.logical_or}
)
mask = np.array([pre_mask(*vals) for vals in array], dtype=bool)
return mask
| (array, cut_expression=None, coords=None) |
21,504 | tfields.core | rank |
Tensor rank
| def rank(tensor):
"""
Tensor rank
"""
tensor = np.asarray(tensor)
return len(tensor.shape) - 1
| (tensor) |
21,508 | fp2md4roam.convert | convert | null | def convert(path, target_directory):
loglevel(WARN)
filer = FSFiler(target_directory)
logger.info('converting %s %s' % (path, filer.target_directory))
mindmap = RawMap(read(path), path)
Author(filer).visit(mindmap)
| (path, target_directory) |
21,509 | fp2md4roam | converter | null | def converter(): # pragma: no cover
if len(sys.argv) != 3:
print('usage: python3 convert.py path_to_map target_directory')
sys.exit(1)
map_path = sys.argv[1]
target_dir = sys.argv[2]
convert(map_path, target_dir)
| () |
21,513 | numbers | Number | All numbers inherit from this class.
If you just want to check if an argument x is a number, without
caring what kind, use isinstance(x, Number).
| class Number(metaclass=ABCMeta):
"""All numbers inherit from this class.
If you just want to check if an argument x is a number, without
caring what kind, use isinstance(x, Number).
"""
__slots__ = ()
# Concrete numeric types must provide their own hash implementation
__hash__ = None
| () |
21,514 | tempora | _Saved_NS |
Bundle a timedelta with nanoseconds.
>>> _Saved_NS.derive('microseconds', .001)
_Saved_NS(td=datetime.timedelta(0), nanoseconds=1)
| class _Saved_NS:
"""
Bundle a timedelta with nanoseconds.
>>> _Saved_NS.derive('microseconds', .001)
_Saved_NS(td=datetime.timedelta(0), nanoseconds=1)
"""
td = datetime.timedelta()
nanoseconds = 0
multiplier = dict(
seconds=1000000000,
milliseconds=1000000,
microseconds=1000,
)
def __init__(self, **kwargs):
vars(self).update(kwargs)
@classmethod
def derive(cls, unit, value):
if unit == 'nanoseconds':
return _Saved_NS(nanoseconds=value)
try:
raw_td = datetime.timedelta(**{unit: value})
except TypeError:
raise ValueError(f"Invalid unit {unit}")
res = _Saved_NS(td=raw_td)
with contextlib.suppress(KeyError):
res.nanoseconds = int(value * cls.multiplier[unit]) % 1000
return res
def __add__(self, other):
return _Saved_NS(
td=self.td + other.td, nanoseconds=self.nanoseconds + other.nanoseconds
)
def resolve(self):
"""
Resolve any nanoseconds into the microseconds field,
discarding any nanosecond resolution (but honoring partial
microseconds).
"""
addl_micros = round(self.nanoseconds / 1000)
return self.td + datetime.timedelta(microseconds=addl_micros)
def __repr__(self):
return f'_Saved_NS(td={self.td!r}, nanoseconds={self.nanoseconds!r})'
| (**kwargs) |
21,515 | tempora | __add__ | null | def __add__(self, other):
return _Saved_NS(
td=self.td + other.td, nanoseconds=self.nanoseconds + other.nanoseconds
)
| (self, other) |
21,516 | tempora | __init__ | null | def __init__(self, **kwargs):
vars(self).update(kwargs)
| (self, **kwargs) |
21,517 | tempora | __repr__ | null | def __repr__(self):
return f'_Saved_NS(td={self.td!r}, nanoseconds={self.nanoseconds!r})'
| (self) |
21,518 | tempora | resolve |
Resolve any nanoseconds into the microseconds field,
discarding any nanosecond resolution (but honoring partial
microseconds).
| def resolve(self):
"""
Resolve any nanoseconds into the microseconds field,
discarding any nanosecond resolution (but honoring partial
microseconds).
"""
addl_micros = round(self.nanoseconds / 1000)
return self.td + datetime.timedelta(microseconds=addl_micros)
| (self) |
21,519 | tempora | _check_unmatched |
Ensure no words appear in unmatched text.
| def _check_unmatched(matches, text):
"""
Ensure no words appear in unmatched text.
"""
def check_unmatched(unmatched):
found = re.search(r'\w+', unmatched)
if found:
raise ValueError(f"Unexpected {found.group(0)!r}")
pos = 0
for match in matches:
check_unmatched(text[pos : match.start()])
yield match
pos = match.end()
check_unmatched(text[pos:])
| (matches, text) |
21,520 | tempora | _parse_timedelta_composite | null | def _parse_timedelta_composite(raw_value, unit):
if unit != 'seconds':
raise ValueError("Cannot specify units with composite delta")
values = raw_value.split(':')
units = 'hours', 'minutes', 'seconds'
composed = ' '.join(f'{value} {unit}' for value, unit in zip(values, units))
return _parse_timedelta_nanos(composed)
| (raw_value, unit) |
21,521 | tempora | _parse_timedelta_nanos | null | def _parse_timedelta_nanos(str):
parts = re.finditer(r'(?P<value>[\d.:]+)\s?(?P<unit>[^\W\d_]+)?', str)
chk_parts = _check_unmatched(parts, str)
deltas = map(_parse_timedelta_part, chk_parts)
return sum(deltas, _Saved_NS())
| (str) |
21,522 | tempora | _parse_timedelta_part | null | def _parse_timedelta_part(match):
unit = _resolve_unit(match.group('unit'))
if not unit.endswith('s'):
unit += 's'
raw_value = match.group('value')
if ':' in raw_value:
return _parse_timedelta_composite(raw_value, unit)
value = float(raw_value)
if unit == 'months':
unit = 'years'
value = value / 12
if unit == 'years':
unit = 'days'
value = value * days_per_year
return _Saved_NS.derive(unit, value)
| (match) |
21,523 | tempora | _prorated_values |
Given a rate (a string in units per unit time), and return that same
rate for various time periods.
>>> for period, value in _prorated_values('20/hour'):
... print('{period}: {value:0.3f}'.format(**locals()))
minute: 0.333
hour: 20.000
day: 480.000
month: 14609.694
year: 175316.333
| def _prorated_values(rate: str) -> Iterable[Tuple[str, Number]]:
"""
Given a rate (a string in units per unit time), and return that same
rate for various time periods.
>>> for period, value in _prorated_values('20/hour'):
... print('{period}: {value:0.3f}'.format(**locals()))
minute: 0.333
hour: 20.000
day: 480.000
month: 14609.694
year: 175316.333
"""
match = re.match(r'(?P<value>[\d.]+)/(?P<period>\w+)$', rate)
res = cast(re.Match, match).groupdict()
value = float(res['value'])
value_per_second = value / get_period_seconds(res['period'])
for period in ('minute', 'hour', 'day', 'month', 'year'):
period_value = value_per_second * get_period_seconds(period)
yield period, period_value
| (rate: str) -> Iterable[Tuple[str, numbers.Number]] |
21,524 | tempora | _resolve_unit | null | def _resolve_unit(raw_match):
if raw_match is None:
return 'second'
text = raw_match.lower()
return _unit_lookup.get(text, text)
| (raw_match) |
21,525 | tempora | calculate_prorated_values |
>>> monkeypatch = getfixture('monkeypatch')
>>> import builtins
>>> monkeypatch.setattr(builtins, 'input', lambda prompt: '3/hour')
>>> calculate_prorated_values()
per minute: 0.05
per hour: 3.0
per day: 72.0
per month: 2191.454166666667
per year: 26297.45
| def calculate_prorated_values():
"""
>>> monkeypatch = getfixture('monkeypatch')
>>> import builtins
>>> monkeypatch.setattr(builtins, 'input', lambda prompt: '3/hour')
>>> calculate_prorated_values()
per minute: 0.05
per hour: 3.0
per day: 72.0
per month: 2191.454166666667
per year: 26297.45
"""
rate = input("Enter the rate (3/hour, 50/month)> ")
for period, value in _prorated_values(rate):
print(f"per {period}: {value}")
| () |
21,528 | tempora | date_range |
Much like the built-in function range, but works with dates
>>> range_items = date_range(
... datetime.datetime(2005,12,21),
... datetime.datetime(2005,12,25),
... )
>>> my_range = tuple(range_items)
>>> datetime.datetime(2005,12,21) in my_range
True
>>> datetime.datetime(2005,12,22) in my_range
True
>>> datetime.datetime(2005,12,25) in my_range
False
>>> from_now = date_range(stop=datetime.datetime(2099, 12, 31))
>>> next(from_now)
datetime.datetime(...)
| def date_range(start=None, stop=None, step=None):
"""
Much like the built-in function range, but works with dates
>>> range_items = date_range(
... datetime.datetime(2005,12,21),
... datetime.datetime(2005,12,25),
... )
>>> my_range = tuple(range_items)
>>> datetime.datetime(2005,12,21) in my_range
True
>>> datetime.datetime(2005,12,22) in my_range
True
>>> datetime.datetime(2005,12,25) in my_range
False
>>> from_now = date_range(stop=datetime.datetime(2099, 12, 31))
>>> next(from_now)
datetime.datetime(...)
"""
if step is None:
step = datetime.timedelta(days=1)
if start is None:
start = datetime.datetime.now()
while start < stop:
yield start
start += step
| (start=None, stop=None, step=None) |
21,530 | tempora | datetime_mod |
Find the time which is the specified date/time truncated to the time delta
relative to the start date/time.
By default, the start time is midnight of the same day as the specified
date/time.
>>> datetime_mod(datetime.datetime(2004, 1, 2, 3),
... datetime.timedelta(days = 1.5),
... start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 2, 13),
... datetime.timedelta(days = 1.5),
... start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 2, 12, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 2, 13),
... datetime.timedelta(days = 7),
... start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 10, 13),
... datetime.timedelta(days = 7),
... start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 8, 0, 0)
| def datetime_mod(dt, period, start=None):
"""
Find the time which is the specified date/time truncated to the time delta
relative to the start date/time.
By default, the start time is midnight of the same day as the specified
date/time.
>>> datetime_mod(datetime.datetime(2004, 1, 2, 3),
... datetime.timedelta(days = 1.5),
... start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 2, 13),
... datetime.timedelta(days = 1.5),
... start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 2, 12, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 2, 13),
... datetime.timedelta(days = 7),
... start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 1, 0, 0)
>>> datetime_mod(datetime.datetime(2004, 1, 10, 13),
... datetime.timedelta(days = 7),
... start = datetime.datetime(2004, 1, 1))
datetime.datetime(2004, 1, 8, 0, 0)
"""
if start is None:
# use midnight of the same day
start = datetime.datetime.combine(dt.date(), datetime.time())
# calculate the difference between the specified time and the start date.
delta = dt - start
# now aggregate the delta and the period into microseconds
# Use microseconds because that's the highest precision of these time
# pieces. Also, using microseconds ensures perfect precision (no floating
# point errors).
def get_time_delta_microseconds(td):
return (td.days * seconds_per_day + td.seconds) * 1000000 + td.microseconds
delta, period = map(get_time_delta_microseconds, (delta, period))
offset = datetime.timedelta(microseconds=delta % period)
# the result is the original specified time minus the offset
result = dt - offset
return result
| (dt, period, start=None) |
21,531 | tempora | datetime_round |
Find the nearest even period for the specified date/time.
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 11, 13),
... datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 8, 0)
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 31, 13),
... datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 9, 0)
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 30),
... datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 9, 0)
| def datetime_round(dt, period, start=None):
"""
Find the nearest even period for the specified date/time.
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 11, 13),
... datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 8, 0)
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 31, 13),
... datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 9, 0)
>>> datetime_round(datetime.datetime(2004, 11, 13, 8, 30),
... datetime.timedelta(hours = 1))
datetime.datetime(2004, 11, 13, 9, 0)
"""
result = datetime_mod(dt, period, start)
if abs(dt - result) >= period // 2:
result += period
return result
| (dt, period, start=None) |
21,532 | tempora | ensure_datetime |
Given a datetime or date or time object from the ``datetime``
module, always return a datetime using default values.
| def ensure_datetime(ob: AnyDatetime) -> datetime.datetime:
"""
Given a datetime or date or time object from the ``datetime``
module, always return a datetime using default values.
"""
if isinstance(ob, datetime.datetime):
return ob
date = cast(datetime.date, ob)
time = cast(datetime.time, ob)
if isinstance(ob, datetime.date):
time = datetime.time()
if isinstance(ob, datetime.time):
date = datetime.date(1900, 1, 1)
return datetime.datetime.combine(date, time)
| (ob: Union[datetime.datetime, datetime.date, datetime.time]) -> datetime.datetime |
21,534 | tempora | get_date_format_string |
For a given period (e.g. 'month', 'day', or some numeric interval
such as 3600 (in secs)), return the format string that can be
used with strftime to format that time to specify the times
across that interval, but no more detailed.
For example,
>>> get_date_format_string('month')
'%Y-%m'
>>> get_date_format_string(3600)
'%Y-%m-%d %H'
>>> get_date_format_string('hour')
'%Y-%m-%d %H'
>>> get_date_format_string(None)
Traceback (most recent call last):
...
TypeError: period must be a string or integer
>>> get_date_format_string('garbage')
Traceback (most recent call last):
...
ValueError: period not in (second, minute, hour, day, month, year)
| def get_date_format_string(period):
"""
For a given period (e.g. 'month', 'day', or some numeric interval
such as 3600 (in secs)), return the format string that can be
used with strftime to format that time to specify the times
across that interval, but no more detailed.
For example,
>>> get_date_format_string('month')
'%Y-%m'
>>> get_date_format_string(3600)
'%Y-%m-%d %H'
>>> get_date_format_string('hour')
'%Y-%m-%d %H'
>>> get_date_format_string(None)
Traceback (most recent call last):
...
TypeError: period must be a string or integer
>>> get_date_format_string('garbage')
Traceback (most recent call last):
...
ValueError: period not in (second, minute, hour, day, month, year)
"""
# handle the special case of 'month' which doesn't have
# a static interval in seconds
if isinstance(period, str) and period.lower() == 'month':
return '%Y-%m'
file_period_secs = get_period_seconds(period)
format_pieces = ('%Y', '-%m-%d', ' %H', '-%M', '-%S')
seconds_per_second = 1
intervals = (
seconds_per_year,
seconds_per_day,
seconds_per_hour,
seconds_per_minute,
seconds_per_second,
)
mods = list(map(lambda interval: file_period_secs % interval, intervals))
format_pieces = format_pieces[: mods.index(0) + 1]
return ''.join(format_pieces)
| (period) |
21,535 | tempora | get_nearest_year_for_day |
Returns the nearest year to now inferred from a Julian date.
>>> freezer = getfixture('freezer')
>>> freezer.move_to('2019-05-20')
>>> get_nearest_year_for_day(20)
2019
>>> get_nearest_year_for_day(340)
2018
>>> freezer.move_to('2019-12-15')
>>> get_nearest_year_for_day(20)
2020
| def get_nearest_year_for_day(day):
"""
Returns the nearest year to now inferred from a Julian date.
>>> freezer = getfixture('freezer')
>>> freezer.move_to('2019-05-20')
>>> get_nearest_year_for_day(20)
2019
>>> get_nearest_year_for_day(340)
2018
>>> freezer.move_to('2019-12-15')
>>> get_nearest_year_for_day(20)
2020
"""
now = time.gmtime()
result = now.tm_year
# if the day is far greater than today, it must be from last year
if day - now.tm_yday > 365 // 2:
result -= 1
# if the day is far less than today, it must be for next year.
if now.tm_yday - day > 365 // 2:
result += 1
return result
| (day) |
21,536 | tempora | get_period_seconds |
return the number of seconds in the specified period
>>> get_period_seconds('day')
86400
>>> get_period_seconds(86400)
86400
>>> get_period_seconds(datetime.timedelta(hours=24))
86400
>>> get_period_seconds('day + os.system("rm -Rf *")')
Traceback (most recent call last):
...
ValueError: period not in (second, minute, hour, day, month, year)
| def get_period_seconds(period):
"""
return the number of seconds in the specified period
>>> get_period_seconds('day')
86400
>>> get_period_seconds(86400)
86400
>>> get_period_seconds(datetime.timedelta(hours=24))
86400
>>> get_period_seconds('day + os.system("rm -Rf *")')
Traceback (most recent call last):
...
ValueError: period not in (second, minute, hour, day, month, year)
"""
if isinstance(period, str):
try:
name = 'seconds_per_' + period.lower()
result = globals()[name]
except KeyError:
msg = "period not in (second, minute, hour, day, month, year)"
raise ValueError(msg)
elif isinstance(period, numbers.Number):
result = period
elif isinstance(period, datetime.timedelta):
result = period.days * get_period_seconds('day') + period.seconds
else:
raise TypeError('period must be a string or integer')
return result
| (period) |
21,537 | tempora | gregorian_date |
Gregorian Date is defined as a year and a julian day (1-based
index into the days of the year).
>>> gregorian_date(2007, 15)
datetime.date(2007, 1, 15)
| def gregorian_date(year, julian_day):
"""
Gregorian Date is defined as a year and a julian day (1-based
index into the days of the year).
>>> gregorian_date(2007, 15)
datetime.date(2007, 1, 15)
"""
result = datetime.date(year, 1, 1)
result += datetime.timedelta(days=julian_day - 1)
return result
| (year, julian_day) |
21,538 | tempora | infer_datetime | null | def infer_datetime(ob: Union[AnyDatetime, StructDatetime]) -> datetime.datetime:
if isinstance(ob, (time.struct_time, tuple)):
ob = datetime.datetime(*ob[:6]) # type: ignore
return ensure_datetime(ob)
| (ob: Union[datetime.datetime, datetime.date, datetime.time, Tuple[int, ...], time.struct_time]) -> datetime.datetime |
21,540 | tempora | parse_timedelta |
Take a string representing a span of time and parse it to a time delta.
Accepts any string of comma-separated numbers each with a unit indicator.
>>> parse_timedelta('1 day')
datetime.timedelta(days=1)
>>> parse_timedelta('1 day, 30 seconds')
datetime.timedelta(days=1, seconds=30)
>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')
datetime.timedelta(days=47, seconds=28848, microseconds=15400)
Supports weeks, months, years
>>> parse_timedelta('1 week')
datetime.timedelta(days=7)
>>> parse_timedelta('1 year, 1 month')
datetime.timedelta(days=395, seconds=58685)
Note that months and years strict intervals, not aligned
to a calendar:
>>> date = datetime.datetime.fromisoformat('2000-01-01')
>>> later = date + parse_timedelta('1 year')
>>> diff = later.replace(year=date.year) - date
>>> diff.seconds
20940
>>> parse_timedelta('foo')
Traceback (most recent call last):
...
ValueError: Unexpected 'foo'
>>> parse_timedelta('14 seconds foo')
Traceback (most recent call last):
...
ValueError: Unexpected 'foo'
Supports abbreviations:
>>> parse_timedelta('1s')
datetime.timedelta(seconds=1)
>>> parse_timedelta('1sec')
datetime.timedelta(seconds=1)
>>> parse_timedelta('5min1sec')
datetime.timedelta(seconds=301)
>>> parse_timedelta('1 ms')
datetime.timedelta(microseconds=1000)
>>> parse_timedelta('1 µs')
datetime.timedelta(microseconds=1)
>>> parse_timedelta('1 us')
datetime.timedelta(microseconds=1)
And supports the common colon-separated duration:
>>> parse_timedelta('14:00:35.362')
datetime.timedelta(seconds=50435, microseconds=362000)
TODO: Should this be 14 hours or 14 minutes?
>>> parse_timedelta('14:00')
datetime.timedelta(seconds=50400)
>>> parse_timedelta('14:00 minutes')
Traceback (most recent call last):
...
ValueError: Cannot specify units with composite delta
Nanoseconds get rounded to the nearest microsecond:
>>> parse_timedelta('600 ns')
datetime.timedelta(microseconds=1)
>>> parse_timedelta('.002 µs, 499 ns')
datetime.timedelta(microseconds=1)
Expect ValueError for other invalid inputs.
>>> parse_timedelta('13 feet')
Traceback (most recent call last):
...
ValueError: Invalid unit feets
| def parse_timedelta(str):
"""
Take a string representing a span of time and parse it to a time delta.
Accepts any string of comma-separated numbers each with a unit indicator.
>>> parse_timedelta('1 day')
datetime.timedelta(days=1)
>>> parse_timedelta('1 day, 30 seconds')
datetime.timedelta(days=1, seconds=30)
>>> parse_timedelta('47.32 days, 20 minutes, 15.4 milliseconds')
datetime.timedelta(days=47, seconds=28848, microseconds=15400)
Supports weeks, months, years
>>> parse_timedelta('1 week')
datetime.timedelta(days=7)
>>> parse_timedelta('1 year, 1 month')
datetime.timedelta(days=395, seconds=58685)
Note that months and years strict intervals, not aligned
to a calendar:
>>> date = datetime.datetime.fromisoformat('2000-01-01')
>>> later = date + parse_timedelta('1 year')
>>> diff = later.replace(year=date.year) - date
>>> diff.seconds
20940
>>> parse_timedelta('foo')
Traceback (most recent call last):
...
ValueError: Unexpected 'foo'
>>> parse_timedelta('14 seconds foo')
Traceback (most recent call last):
...
ValueError: Unexpected 'foo'
Supports abbreviations:
>>> parse_timedelta('1s')
datetime.timedelta(seconds=1)
>>> parse_timedelta('1sec')
datetime.timedelta(seconds=1)
>>> parse_timedelta('5min1sec')
datetime.timedelta(seconds=301)
>>> parse_timedelta('1 ms')
datetime.timedelta(microseconds=1000)
>>> parse_timedelta('1 µs')
datetime.timedelta(microseconds=1)
>>> parse_timedelta('1 us')
datetime.timedelta(microseconds=1)
And supports the common colon-separated duration:
>>> parse_timedelta('14:00:35.362')
datetime.timedelta(seconds=50435, microseconds=362000)
TODO: Should this be 14 hours or 14 minutes?
>>> parse_timedelta('14:00')
datetime.timedelta(seconds=50400)
>>> parse_timedelta('14:00 minutes')
Traceback (most recent call last):
...
ValueError: Cannot specify units with composite delta
Nanoseconds get rounded to the nearest microsecond:
>>> parse_timedelta('600 ns')
datetime.timedelta(microseconds=1)
>>> parse_timedelta('.002 µs, 499 ns')
datetime.timedelta(microseconds=1)
Expect ValueError for other invalid inputs.
>>> parse_timedelta('13 feet')
Traceback (most recent call last):
...
ValueError: Invalid unit feets
"""
return _parse_timedelta_nanos(str).resolve()
| (str) |
21,542 | tempora | strftime |
Portable strftime.
In the stdlib, strftime has `known portability problems
<https://bugs.python.org/issue13305>`_. This function
aims to smooth over those issues and provide a
consistent experience across the major platforms.
>>> strftime('%Y', datetime.datetime(1890, 1, 1))
'1890'
>>> strftime('%Y', datetime.datetime(900, 1, 1))
'0900'
Supports time.struct_time, tuples, and datetime.datetime objects.
>>> strftime('%Y-%m-%d', (1976, 5, 7))
'1976-05-07'
Also supports date objects
>>> strftime('%Y', datetime.date(1976, 5, 7))
'1976'
Also supports milliseconds using %s.
>>> strftime('%s', datetime.time(microsecond=20000))
'020'
Also supports microseconds (3 digits) using %µ
>>> strftime('%µ', datetime.time(microsecond=123456))
'456'
Historically, %u was used for microseconds, but now
it honors the value rendered by stdlib.
>>> strftime('%u', datetime.date(1976, 5, 7))
'5'
Also supports microseconds (6 digits) using %f
>>> strftime('%f', datetime.time(microsecond=23456))
'023456'
Even supports time values on date objects (discouraged):
>>> strftime('%f', datetime.date(1976, 1, 1))
'000000'
>>> strftime('%µ', datetime.date(1976, 1, 1))
'000'
>>> strftime('%s', datetime.date(1976, 1, 1))
'000'
And vice-versa:
>>> strftime('%Y', datetime.time())
'1900'
| def strftime(fmt: str, t: Union[AnyDatetime, tuple, time.struct_time]) -> str:
"""
Portable strftime.
In the stdlib, strftime has `known portability problems
<https://bugs.python.org/issue13305>`_. This function
aims to smooth over those issues and provide a
consistent experience across the major platforms.
>>> strftime('%Y', datetime.datetime(1890, 1, 1))
'1890'
>>> strftime('%Y', datetime.datetime(900, 1, 1))
'0900'
Supports time.struct_time, tuples, and datetime.datetime objects.
>>> strftime('%Y-%m-%d', (1976, 5, 7))
'1976-05-07'
Also supports date objects
>>> strftime('%Y', datetime.date(1976, 5, 7))
'1976'
Also supports milliseconds using %s.
>>> strftime('%s', datetime.time(microsecond=20000))
'020'
Also supports microseconds (3 digits) using %µ
>>> strftime('%µ', datetime.time(microsecond=123456))
'456'
Historically, %u was used for microseconds, but now
it honors the value rendered by stdlib.
>>> strftime('%u', datetime.date(1976, 5, 7))
'5'
Also supports microseconds (6 digits) using %f
>>> strftime('%f', datetime.time(microsecond=23456))
'023456'
Even supports time values on date objects (discouraged):
>>> strftime('%f', datetime.date(1976, 1, 1))
'000000'
>>> strftime('%µ', datetime.date(1976, 1, 1))
'000'
>>> strftime('%s', datetime.date(1976, 1, 1))
'000'
And vice-versa:
>>> strftime('%Y', datetime.time())
'1900'
"""
t = infer_datetime(t)
subs = (
('%s', '%03d' % (t.microsecond // 1000)),
('%µ', '%03d' % (t.microsecond % 1000)),
) + (('%Y', '%04d' % t.year),) * _needs_year_help()
def doSub(s, sub):
return s.replace(*sub)
def doSubs(s):
return functools.reduce(doSub, subs, s)
fmt = '%%'.join(map(doSubs, fmt.split('%%')))
return t.strftime(fmt)
| (fmt: str, t: Union[datetime.datetime, datetime.date, datetime.time, tuple, time.struct_time]) -> str |
21,546 | cptree.cptree | cptree | call _cptree with work_dir from argument or a temp dir | def cptree(*args, output_dir=None, **kwargs):
"""call _cptree with work_dir from argument or a temp dir"""
if output_dir:
output_dir = Path(output_dir)
if not output_dir.is_dir():
output_dir.mkdir()
kwargs["output_dir"] = output_dir
return _cptree(*args, **kwargs)
else:
with TemporaryDirectory() as temp_dir:
kwargs["output_dir"] = Path(temp_dir)
return _cptree(*args, **kwargs)
| (*args, output_dir=None, **kwargs) |
21,556 | cleanco.classify | countrysources | business countries / type abbreviations sorted by length of type abbreviations | def countrysources():
"business countries / type abbreviations sorted by length of type abbreviations"
countries = []
for country in terms_by_country:
for item in terms_by_country[country]:
countries.append((country, item))
return sorted(countries, key=lambda part: len(part[1]), reverse=True)
| () |
21,557 | cleanco.classify | matches | get types or countries matching with the legal terms in name | def matches(name, sources):
"get types or countries matching with the legal terms in name"
name = strip_tail(name)
parts = name.split()
nparts = [normalized(p) for p in parts]
matches = []
for classifier, term in sources:
nterm = normalized(term)
try:
idx = nparts.index(nterm)
except ValueError:
pass
else:
matches.append(classifier)
return matches
| (name, sources) |
21,559 | cleanco.clean | prepare_default_terms | construct an optimized term structure for basename extraction | def prepare_default_terms():
"construct an optimized term structure for basename extraction"
terms = get_unique_terms()
nterms = normalize_terms(terms)
ntermparts = (t.split() for t in nterms)
# make sure that the result is deterministic, sort terms descending by number of tokens, ascending by names
sntermparts = sorted(ntermparts, key=lambda x: (-len(x), x))
return [(len(tp), tp) for tp in sntermparts]
| () |
21,561 | cleanco.classify | typesources | business types / abbreviations sorted by length of business type | def typesources():
"business types / abbreviations sorted by length of business type"
types = []
for business_type in terms_by_type:
for item in terms_by_type[business_type]:
types.append((business_type, item))
return sorted(types, key=lambda part: len(part[1]), reverse=True)
| () |
21,562 | ldsso.ld_sso | SSO | null | class SSO:
LD_SSO_SERVICE_API = os.environ.get("LD_SSO_SERVICE_API")
LD_KEYCLOAK_CLIENT_ID = os.environ.get("LD_KEYCLOAK_CLIENT_ID")
LD_NAMESPACE = os.environ.get("LD_NAMESPACE")
LD_HOSTNAME = os.environ.get("HOSTNAME", "")
LD_URI_PREFIX = os.environ.get("LD_URI_PREFIX", "")
URI_USERINFO = "userinfo"
URI_JUDGE = "judge"
URI_POLICY = "policies"
def __init__(
self, token, host=None, api_prefix="/api/access-policy/", max_retries=3
):
assert token, "token must be provided"
if not host:
host = self.LD_SSO_SERVICE_API
assert host, f"environment variable $LD_SSO_SERVICE_API not set"
self.sso_url = urljoin(host, api_prefix)
if not self.sso_url.endswith("/"):
self.sso_url = self.sso_url + "/"
self.r = requests.Session()
self.r.mount("http://", HTTPAdapter(max_retries=max_retries))
self.r.mount("https://", HTTPAdapter(max_retries=max_retries))
self.r.headers = {
"Content-Type": "application/vnd.api+json",
"Authorization": token,
}
self.userinfo = self.get_userinfo(token)
def __handle_response(self, response: Response, success_code=200):
status_code = response.status_code
if status_code != success_code:
try:
error_message = response.json()["error_message"]
except:
error_message = response.text
abort(status_code, error_message)
def get_userinfo(self, token=None):
"""获取用户信息"""
url = urljoin(self.sso_url, self.URI_USERINFO)
headers = self.r.headers
if token:
headers = {**headers, "Authorization": token}
response = self.r.get(url, headers=headers)
self.__handle_response(response)
return response.json()
def judge_api(self, ld_project, api_url, method):
"""检测用户是否允许请求服务"""
url = urljoin(self.sso_url, self.URI_JUDGE)
headers = {**self.r.headers, "Ld-Project": quote(ld_project)}
params = {"url": api_url, "method": method}
response = self.r.get(url, params=params, headers=headers)
self.__handle_response(response)
res = response.json()
return res["effect"] == "allow", res
def judge_resource(self, action, resource):
"""检测用户是否允许请求数据"""
url = urljoin(self.sso_url, self.URI_JUDGE)
data = [{"action": action, "resource": resource}]
response = self.r.post(url, json=data)
self.__handle_response(response)
res = response.json()
return res["effect"] == "allow", res
def create_policy(
self,
name: str,
statements: list[dict[str, str]],
description: str = None,
version: str = None,
):
"""
创建policy声明
statements: [
{
"sid": "xxxxx",
"effect": "Allow",
"action": ["x"],
"resource": ["x"],
}
]
"""
url = urljoin(self.sso_url, self.URI_POLICY)
if description is None:
description = name
if version is None:
version = "v1"
assert statements, '"statements" must be provided'
data = {
"name": name,
"description": description,
"statements": {"Version": version, "Statement": statements},
}
response = self.r.post(url, json=data)
self.__handle_response(response)
return response.json()
@classmethod
def decorator_judge_api(
cls,
client_name: str = None,
api_url: str = None,
**sso_kwargs,
):
"""装饰器, 检测用户是否允许请求当前接口.
- 从被装饰函数的Request参数中解析method.
- 从环境变量LD_NAMESPACE中提取ld_project.
Args:
client_name (str, optional): 默认从环境变量LD_KEYCLOAK_CLIENT_ID中提取client_name.
api_url (str, optional): 应与action的apis中一致. 默认先从环境变量LD_URI_PREFIX取, 取不到再从pod的hostname中解析, 本地调试请手动传入该参数.
Returns:
装饰后,Request参数会追加ld_account,ld_roles,ld_userinfo属性
"""
if not api_url:
if cls.LD_URI_PREFIX:
api_url = cls.LD_URI_PREFIX
elif cls.LD_HOSTNAME.startswith("func-"):
api_url = f'/api/{"_".join(cls.LD_HOSTNAME.split("-")[:-2])}'
assert api_url, '"api_url" is required'
ld_namespace = cls.LD_NAMESPACE
assert ld_namespace, "ENV $LD_NAMESPACE is required"
func = None
if client_name and callable(client_name):
func = client_name
client_name = None
if not client_name:
client_name = cls.LD_KEYCLOAK_CLIENT_ID
assert client_name, f"ENV $LD_KEYCLOAK_CLIENT_ID is required"
def decorator(func):
def wrapper(*args, **kwargs):
req = None
for req in (*args, *kwargs.values()):
if isinstance(req, Request):
break
if getattr(req, "request", None) and isinstance(
req.request, Request
):
req = req.request
break
method = getattr(req, "method", None)
assert method, "decorated function must have a Request argument"
token = req.headers.get("Authorization")
assert token, "Authorization is required"
sso = cls(token=token, **sso_kwargs)
api_allowed, res = sso.judge_api(unquote(ld_namespace), api_url, method)
assert api_allowed, f"Deny. Sid: {res['sid']}"
account = sso.userinfo["preferred_username"]
all_roles = (
sso.userinfo["resource_access"]
.get(client_name, {})
.get("roles", [])
)
setattr(req, "ld_account", account)
setattr(req, "ld_roles", all_roles)
setattr(req, "ld_userinfo", sso.userinfo)
return func(*args, **kwargs)
return wrapper
if func and callable(func):
return decorator(func)
return decorator
@classmethod
def decorator_cors(cls, func):
"""装饰器. 修改view返回的Response的headers, 允许所有跨域请求"""
def wrapper(*args, **kwargs):
req = None
for req in (*args, *kwargs.values()):
if isinstance(req, Request):
break
if getattr(req, "request", None) and isinstance(req.request, Request):
req = req.request
break
assert req, "Decorated function must have a Request argument"
response_headers = {
"Access-Control-Allow-Origin": req.headers.get("Origin") or "*",
"Access-Control-Allow-Headers": "Ld-Client,Ld-Project,Content-Type,Content-Length,User-Agent,Authorization,Accept,X-Requested-With",
"Access-Control-Allow-Methods": "GET,POST,PUT,PATCH,DELETE,OPTIONS",
"Access-Control-Allow-Credentials": "true",
}
if req.method == "OPTIONS":
resp = make_response()
else:
try:
view_res = func(*args, **kwargs)
except HTTPException as e:
view_res = e.get_response()
except:
logging.exception("View has not catch error.")
view_res = "", 500
if isinstance(view_res, Response):
resp = view_res
else:
resp = make_response(view_res)
for h, v in response_headers.items():
resp.headers[h] = v
return resp
return wrapper
| (token, host=None, api_prefix='/api/access-policy/', max_retries=3) |
21,563 | ldsso.ld_sso | __handle_response | null | def __handle_response(self, response: Response, success_code=200):
status_code = response.status_code
if status_code != success_code:
try:
error_message = response.json()["error_message"]
except:
error_message = response.text
abort(status_code, error_message)
| (self, response: flask.wrappers.Response, success_code=200) |
21,564 | ldsso.ld_sso | __init__ | null | def __init__(
self, token, host=None, api_prefix="/api/access-policy/", max_retries=3
):
assert token, "token must be provided"
if not host:
host = self.LD_SSO_SERVICE_API
assert host, f"environment variable $LD_SSO_SERVICE_API not set"
self.sso_url = urljoin(host, api_prefix)
if not self.sso_url.endswith("/"):
self.sso_url = self.sso_url + "/"
self.r = requests.Session()
self.r.mount("http://", HTTPAdapter(max_retries=max_retries))
self.r.mount("https://", HTTPAdapter(max_retries=max_retries))
self.r.headers = {
"Content-Type": "application/vnd.api+json",
"Authorization": token,
}
self.userinfo = self.get_userinfo(token)
| (self, token, host=None, api_prefix='/api/access-policy/', max_retries=3) |
21,565 | ldsso.ld_sso | create_policy |
创建policy声明
statements: [
{
"sid": "xxxxx",
"effect": "Allow",
"action": ["x"],
"resource": ["x"],
}
]
| def create_policy(
self,
name: str,
statements: list[dict[str, str]],
description: str = None,
version: str = None,
):
"""
创建policy声明
statements: [
{
"sid": "xxxxx",
"effect": "Allow",
"action": ["x"],
"resource": ["x"],
}
]
"""
url = urljoin(self.sso_url, self.URI_POLICY)
if description is None:
description = name
if version is None:
version = "v1"
assert statements, '"statements" must be provided'
data = {
"name": name,
"description": description,
"statements": {"Version": version, "Statement": statements},
}
response = self.r.post(url, json=data)
self.__handle_response(response)
return response.json()
| (self, name: str, statements: list[dict[str, str]], description: Optional[str] = None, version: Optional[str] = None) |
21,566 | ldsso.ld_sso | get_userinfo | 获取用户信息 | def get_userinfo(self, token=None):
"""获取用户信息"""
url = urljoin(self.sso_url, self.URI_USERINFO)
headers = self.r.headers
if token:
headers = {**headers, "Authorization": token}
response = self.r.get(url, headers=headers)
self.__handle_response(response)
return response.json()
| (self, token=None) |
21,567 | ldsso.ld_sso | judge_api | 检测用户是否允许请求服务 | def judge_api(self, ld_project, api_url, method):
"""检测用户是否允许请求服务"""
url = urljoin(self.sso_url, self.URI_JUDGE)
headers = {**self.r.headers, "Ld-Project": quote(ld_project)}
params = {"url": api_url, "method": method}
response = self.r.get(url, params=params, headers=headers)
self.__handle_response(response)
res = response.json()
return res["effect"] == "allow", res
| (self, ld_project, api_url, method) |
21,568 | ldsso.ld_sso | judge_resource | 检测用户是否允许请求数据 | def judge_resource(self, action, resource):
"""检测用户是否允许请求数据"""
url = urljoin(self.sso_url, self.URI_JUDGE)
data = [{"action": action, "resource": resource}]
response = self.r.post(url, json=data)
self.__handle_response(response)
res = response.json()
return res["effect"] == "allow", res
| (self, action, resource) |
21,570 | delorean.dates | Delorean |
The class `Delorean <Delorean>` object. This method accepts naive
datetime objects, with a string timezone.
| class Delorean(object):
"""
The class `Delorean <Delorean>` object. This method accepts naive
datetime objects, with a string timezone.
"""
_VALID_SHIFT_DIRECTIONS = ('last', 'next')
_VALID_SHIFT_UNITS = ('second', 'minute', 'hour', 'day', 'week',
'month', 'year', 'monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'saturday', 'sunday')
def __init__(self, datetime=None, timezone=None):
# maybe set timezone on the way in here. if here set it if not
# use UTC
is_datetime_instance(datetime)
if datetime:
if is_datetime_naive(datetime):
if timezone:
if isinstance(timezone, tzoffset):
utcoffset = timezone.utcoffset(None)
total_seconds = (
(utcoffset.microseconds + (
utcoffset.seconds + utcoffset.days * 24 * 3600) * 10 ** 6) / 10 ** 6)
self._tzinfo = pytz.FixedOffset(total_seconds / 60)
elif isinstance(timezone, tzinfo):
self._tzinfo = timezone
else:
self._tzinfo = pytz.timezone(timezone)
self._dt = localize(datetime, self._tzinfo)
self._tzinfo = self._dt.tzinfo
else:
# TODO(mlew, 2015-08-09):
# Should we really throw an error here, or should this
# default to UTC?)
raise DeloreanInvalidTimezone('Provide a valid timezone')
else:
self._tzinfo = datetime.tzinfo
self._dt = datetime
else:
if timezone:
if isinstance(timezone, tzoffset):
self._tzinfo = pytz.FixedOffset(timezone.utcoffset(None).total_seconds() / 60)
elif isinstance(timezone, tzinfo):
self._tzinfo = timezone
else:
self._tzinfo = pytz.timezone(timezone)
self._dt = datetime_timezone(self._tzinfo)
self._tzinfo = self._dt.tzinfo
else:
self._tzinfo = pytz.utc
self._dt = datetime_timezone('UTC')
def __repr__(self):
dt = self.datetime.replace(tzinfo=None)
if isinstance(self.timezone, pytz._FixedOffset):
tz = self.timezone
else:
tz = self.timezone.tzname(None)
return 'Delorean(datetime=%r, timezone=%r)' % (dt, tz)
def __eq__(self, other):
if isinstance(other, Delorean):
return self.epoch == other.epoch
return False
def __lt__(self, other):
return self.epoch < other.epoch
def __gt__(self, other):
return self.epoch > other.epoch
def __ge__(self, other):
return self.epoch >= other.epoch
def __le__(self, other):
return self.epoch <= other.epoch
def __ne__(self, other):
return not self == other
def __add__(self, other):
if not isinstance(other, timedelta):
raise TypeError("Delorean objects can only be added with timedelta objects")
dt = self._dt + other
return Delorean(datetime=dt, timezone=self.timezone)
def __sub__(self, other):
if isinstance(other, timedelta):
dt = self._dt - other
return Delorean(datetime=dt, timezone=self.timezone)
elif isinstance(other, Delorean):
return self._dt - other._dt
else:
raise TypeError("Delorean objects can only be subtracted with timedelta or other Delorean objects")
def __getattr__(self, name):
"""
Implement __getattr__ to call `shift_date` function when function
called does not exist
"""
func_parts = name.split('_')
# is the func we are trying to call the right length?
if len(func_parts) != 2:
raise AttributeError
# is the function we are trying to call valid?
if (func_parts[0] not in self._VALID_SHIFT_DIRECTIONS or
func_parts[1] not in self._VALID_SHIFT_UNITS):
return AttributeError
# dispatch our function
func = partial(self._shift_date, func_parts[0], func_parts[1])
# update our partial with self.shift_date attributes
update_wrapper(func, self._shift_date)
return func
def _shift_date(self, direction, unit, *args):
"""
Shift datetime in `direction` in _VALID_SHIFT_DIRECTIONS and by some
unit in _VALID_SHIFTS and shift that amount by some multiple,
defined by by args[0] if it exists
"""
this_module = sys.modules[__name__]
num_shifts = 1
if len(args) > 0:
num_shifts = int(args[0])
if unit in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
'saturday', 'sunday']:
shift_func = move_datetime_namedday
dt = shift_func(self._dt, direction, unit)
if num_shifts > 1:
for n in range(num_shifts - 1):
dt = shift_func(dt, direction, unit)
else:
shift_func = getattr(this_module, 'move_datetime_%s' % unit)
dt = shift_func(self._dt, direction, num_shifts)
return Delorean(datetime=dt.replace(tzinfo=None), timezone=self.timezone)
@property
def timezone(self):
"""
Returns a valid tzinfo object associated with
the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='UTC')
>>> d.timezone
<UTC>
"""
return self._tzinfo
def truncate(self, s):
"""
Truncate the delorian object to the nearest s
(second, minute, hour, day, month, year)
This is a destructive method, modifies the internal datetime
object associated with the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 10), timezone='US/Pacific')
>>> d.truncate('hour')
Delorean(datetime=datetime.datetime(2015, 1, 1, 12, 0), timezone='US/Pacific')
"""
if s == 'second':
self._dt = self._dt.replace(microsecond=0)
elif s == 'minute':
self._dt = self._dt.replace(second=0, microsecond=0)
elif s == 'hour':
self._dt = self._dt.replace(minute=0, second=0, microsecond=0)
elif s == 'day':
self._dt = self._dt.replace(hour=0, minute=0, second=0, microsecond=0)
elif s == 'month':
self._dt = self._dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
elif s == 'year':
self._dt = self._dt.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
else:
raise ValueError("Invalid truncation level")
return self
@property
def naive(self):
"""
Returns a naive datetime object associated with the Delorean
object, this method simply converts the localize datetime to UTC
and removes the tzinfo that is associated with it modifying the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.naive
datetime.datetime(2015, 1, 1, 8, 0)
"""
self.shift('UTC')
return self._dt.replace(tzinfo=None)
@classmethod
def now(cls, timezone=None):
if timezone:
return cls(timezone=timezone)
else:
return cls(timezone=get_localzone())
@classmethod
def utcnow(cls):
return cls()
@property
def midnight(self):
"""
Returns midnight for datetime associated with
the Delorean object modifying the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12), timezone='UTC')
>>> d.midnight
datetime.datetime(2015, 1, 1, 0, 0, tzinfo=<UTC>)
"""
return self._dt.replace(hour=0, minute=0, second=0, microsecond=0)
@property
def start_of_day(self):
"""
Returns the start of the day for datetime assoicated
with the Delorean object, modifying the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12), timezone='UTC')
>>> d.start_of_day
datetime.datetime(2015, 1, 1, 0, 0, tzinfo=<UTC>)
"""
return self.midnight
@property
def end_of_day(self):
"""
Returns the end of the day for the datetime
assocaited with the Delorean object, modifying the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12), timezone='UTC')
>>> d.end_of_day
datetime.datetime(2015, 1, 1, 23, 59, 59, 999999, tzinfo=<UTC>)
"""
return self._dt.replace(hour=23, minute=59, second=59, microsecond=999999)
def shift(self, timezone):
"""
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,
modifying the Delorean object and returning the modified object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.shift('UTC')
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 0), timezone='UTC')
"""
try:
self._tzinfo = pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
raise DeloreanInvalidTimezone('Provide a valid timezone')
self._dt = self._tzinfo.normalize(self._dt.astimezone(self._tzinfo))
self._tzinfo = self._dt.tzinfo
return self
@property
def epoch(self):
"""
Returns the total seconds since epoch associated with
the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.epoch
1420099200.0
"""
epoch_sec = pytz.utc.localize(datetime.utcfromtimestamp(0))
now_sec = pytz.utc.normalize(self._dt)
delta_sec = now_sec - epoch_sec
return get_total_second(delta_sec)
@property
def date(self):
"""
Returns the actual date object associated with
the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='US/Pacific')
>>> d.date
datetime.date(2015, 1, 1)
"""
return self._dt.date()
@property
def datetime(self):
"""
Returns the actual datetime object associated with
the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='UTC')
>>> d.datetime
datetime.datetime(2015, 1, 1, 12, 15, tzinfo=<UTC>)
"""
return self._dt
def replace(self, **kwargs):
"""
Returns a new Delorean object after applying replace on the
existing datetime object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='UTC')
>>> d.replace(hour=8)
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 15), timezone='UTC')
"""
return Delorean(datetime=self._dt.replace(**kwargs), timezone=self.timezone)
def humanize(self):
"""
Humanize relative to now:
.. testsetup::
from datetime import timedelta
from delorean import Delorean
.. doctest::
>>> past = Delorean.utcnow() - timedelta(hours=1)
>>> past.humanize()
'an hour ago'
"""
now = self.now(self.timezone)
return humanize.naturaltime(now - self)
def format_datetime(self, format='medium', locale='en_US'):
"""
Return a date string formatted to the given pattern.
.. testsetup::
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 30), timezone='US/Pacific')
>>> d.format_datetime(locale='en_US')
u'Jan 1, 2015, 12:30:00 PM'
>>> d.format_datetime(format='long', locale='de_DE')
u'1. Januar 2015 12:30:00 -0800'
:param format: one of "full", "long", "medium", "short", or a custom datetime pattern
:param locale: a locale identifier
"""
return format_datetime(self._dt, format=format, locale=locale)
| (datetime=None, timezone=None) |
21,571 | delorean.dates | __add__ | null | def __add__(self, other):
if not isinstance(other, timedelta):
raise TypeError("Delorean objects can only be added with timedelta objects")
dt = self._dt + other
return Delorean(datetime=dt, timezone=self.timezone)
| (self, other) |
21,572 | delorean.dates | __eq__ | null | def __eq__(self, other):
if isinstance(other, Delorean):
return self.epoch == other.epoch
return False
| (self, other) |
21,573 | delorean.dates | __ge__ | null | def __ge__(self, other):
return self.epoch >= other.epoch
| (self, other) |
21,574 | delorean.dates | __getattr__ |
Implement __getattr__ to call `shift_date` function when function
called does not exist
| def __getattr__(self, name):
"""
Implement __getattr__ to call `shift_date` function when function
called does not exist
"""
func_parts = name.split('_')
# is the func we are trying to call the right length?
if len(func_parts) != 2:
raise AttributeError
# is the function we are trying to call valid?
if (func_parts[0] not in self._VALID_SHIFT_DIRECTIONS or
func_parts[1] not in self._VALID_SHIFT_UNITS):
return AttributeError
# dispatch our function
func = partial(self._shift_date, func_parts[0], func_parts[1])
# update our partial with self.shift_date attributes
update_wrapper(func, self._shift_date)
return func
| (self, name) |
21,575 | delorean.dates | __gt__ | null | def __gt__(self, other):
return self.epoch > other.epoch
| (self, other) |
21,576 | delorean.dates | __init__ | null | def __init__(self, datetime=None, timezone=None):
# maybe set timezone on the way in here. if here set it if not
# use UTC
is_datetime_instance(datetime)
if datetime:
if is_datetime_naive(datetime):
if timezone:
if isinstance(timezone, tzoffset):
utcoffset = timezone.utcoffset(None)
total_seconds = (
(utcoffset.microseconds + (
utcoffset.seconds + utcoffset.days * 24 * 3600) * 10 ** 6) / 10 ** 6)
self._tzinfo = pytz.FixedOffset(total_seconds / 60)
elif isinstance(timezone, tzinfo):
self._tzinfo = timezone
else:
self._tzinfo = pytz.timezone(timezone)
self._dt = localize(datetime, self._tzinfo)
self._tzinfo = self._dt.tzinfo
else:
# TODO(mlew, 2015-08-09):
# Should we really throw an error here, or should this
# default to UTC?)
raise DeloreanInvalidTimezone('Provide a valid timezone')
else:
self._tzinfo = datetime.tzinfo
self._dt = datetime
else:
if timezone:
if isinstance(timezone, tzoffset):
self._tzinfo = pytz.FixedOffset(timezone.utcoffset(None).total_seconds() / 60)
elif isinstance(timezone, tzinfo):
self._tzinfo = timezone
else:
self._tzinfo = pytz.timezone(timezone)
self._dt = datetime_timezone(self._tzinfo)
self._tzinfo = self._dt.tzinfo
else:
self._tzinfo = pytz.utc
self._dt = datetime_timezone('UTC')
| (self, datetime=None, timezone=None) |
21,577 | delorean.dates | __le__ | null | def __le__(self, other):
return self.epoch <= other.epoch
| (self, other) |
21,578 | delorean.dates | __lt__ | null | def __lt__(self, other):
return self.epoch < other.epoch
| (self, other) |
21,580 | delorean.dates | __repr__ | null | def __repr__(self):
dt = self.datetime.replace(tzinfo=None)
if isinstance(self.timezone, pytz._FixedOffset):
tz = self.timezone
else:
tz = self.timezone.tzname(None)
return 'Delorean(datetime=%r, timezone=%r)' % (dt, tz)
| (self) |
21,581 | delorean.dates | __sub__ | null | def __sub__(self, other):
if isinstance(other, timedelta):
dt = self._dt - other
return Delorean(datetime=dt, timezone=self.timezone)
elif isinstance(other, Delorean):
return self._dt - other._dt
else:
raise TypeError("Delorean objects can only be subtracted with timedelta or other Delorean objects")
| (self, other) |
21,582 | delorean.dates | _shift_date |
Shift datetime in `direction` in _VALID_SHIFT_DIRECTIONS and by some
unit in _VALID_SHIFTS and shift that amount by some multiple,
defined by by args[0] if it exists
| def _shift_date(self, direction, unit, *args):
"""
Shift datetime in `direction` in _VALID_SHIFT_DIRECTIONS and by some
unit in _VALID_SHIFTS and shift that amount by some multiple,
defined by by args[0] if it exists
"""
this_module = sys.modules[__name__]
num_shifts = 1
if len(args) > 0:
num_shifts = int(args[0])
if unit in ['monday', 'tuesday', 'wednesday', 'thursday', 'friday',
'saturday', 'sunday']:
shift_func = move_datetime_namedday
dt = shift_func(self._dt, direction, unit)
if num_shifts > 1:
for n in range(num_shifts - 1):
dt = shift_func(dt, direction, unit)
else:
shift_func = getattr(this_module, 'move_datetime_%s' % unit)
dt = shift_func(self._dt, direction, num_shifts)
return Delorean(datetime=dt.replace(tzinfo=None), timezone=self.timezone)
| (self, direction, unit, *args) |
21,583 | delorean.dates | format_datetime |
Return a date string formatted to the given pattern.
.. testsetup::
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 30), timezone='US/Pacific')
>>> d.format_datetime(locale='en_US')
u'Jan 1, 2015, 12:30:00 PM'
>>> d.format_datetime(format='long', locale='de_DE')
u'1. Januar 2015 12:30:00 -0800'
:param format: one of "full", "long", "medium", "short", or a custom datetime pattern
:param locale: a locale identifier
| def format_datetime(self, format='medium', locale='en_US'):
"""
Return a date string formatted to the given pattern.
.. testsetup::
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 30), timezone='US/Pacific')
>>> d.format_datetime(locale='en_US')
u'Jan 1, 2015, 12:30:00 PM'
>>> d.format_datetime(format='long', locale='de_DE')
u'1. Januar 2015 12:30:00 -0800'
:param format: one of "full", "long", "medium", "short", or a custom datetime pattern
:param locale: a locale identifier
"""
return format_datetime(self._dt, format=format, locale=locale)
| (self, format='medium', locale='en_US') |
21,584 | delorean.dates | humanize |
Humanize relative to now:
.. testsetup::
from datetime import timedelta
from delorean import Delorean
.. doctest::
>>> past = Delorean.utcnow() - timedelta(hours=1)
>>> past.humanize()
'an hour ago'
| def humanize(self):
"""
Humanize relative to now:
.. testsetup::
from datetime import timedelta
from delorean import Delorean
.. doctest::
>>> past = Delorean.utcnow() - timedelta(hours=1)
>>> past.humanize()
'an hour ago'
"""
now = self.now(self.timezone)
return humanize.naturaltime(now - self)
| (self) |
21,585 | delorean.dates | replace |
Returns a new Delorean object after applying replace on the
existing datetime object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='UTC')
>>> d.replace(hour=8)
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 15), timezone='UTC')
| def replace(self, **kwargs):
"""
Returns a new Delorean object after applying replace on the
existing datetime object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 15), timezone='UTC')
>>> d.replace(hour=8)
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 15), timezone='UTC')
"""
return Delorean(datetime=self._dt.replace(**kwargs), timezone=self.timezone)
| (self, **kwargs) |
21,586 | delorean.dates | shift |
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,
modifying the Delorean object and returning the modified object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.shift('UTC')
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 0), timezone='UTC')
| def shift(self, timezone):
"""
Shifts the timezone from the current timezone to the specified timezone associated with the Delorean object,
modifying the Delorean object and returning the modified object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1), timezone='US/Pacific')
>>> d.shift('UTC')
Delorean(datetime=datetime.datetime(2015, 1, 1, 8, 0), timezone='UTC')
"""
try:
self._tzinfo = pytz.timezone(timezone)
except pytz.UnknownTimeZoneError:
raise DeloreanInvalidTimezone('Provide a valid timezone')
self._dt = self._tzinfo.normalize(self._dt.astimezone(self._tzinfo))
self._tzinfo = self._dt.tzinfo
return self
| (self, timezone) |
21,587 | delorean.dates | truncate |
Truncate the delorian object to the nearest s
(second, minute, hour, day, month, year)
This is a destructive method, modifies the internal datetime
object associated with the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 10), timezone='US/Pacific')
>>> d.truncate('hour')
Delorean(datetime=datetime.datetime(2015, 1, 1, 12, 0), timezone='US/Pacific')
| def truncate(self, s):
"""
Truncate the delorian object to the nearest s
(second, minute, hour, day, month, year)
This is a destructive method, modifies the internal datetime
object associated with the Delorean object.
.. testsetup::
from datetime import datetime
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 10), timezone='US/Pacific')
>>> d.truncate('hour')
Delorean(datetime=datetime.datetime(2015, 1, 1, 12, 0), timezone='US/Pacific')
"""
if s == 'second':
self._dt = self._dt.replace(microsecond=0)
elif s == 'minute':
self._dt = self._dt.replace(second=0, microsecond=0)
elif s == 'hour':
self._dt = self._dt.replace(minute=0, second=0, microsecond=0)
elif s == 'day':
self._dt = self._dt.replace(hour=0, minute=0, second=0, microsecond=0)
elif s == 'month':
self._dt = self._dt.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
elif s == 'year':
self._dt = self._dt.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
else:
raise ValueError("Invalid truncation level")
return self
| (self, s) |
21,588 | delorean.exceptions | DeloreanInvalidDatetime |
Exception that is raised when an improper datetime object is passed
in.
| class DeloreanInvalidDatetime(DeloreanError):
"""
Exception that is raised when an improper datetime object is passed
in.
"""
pass
| (msg) |
21,589 | delorean.exceptions | __init__ | null | def __init__(self, msg):
self.msg = str(msg)
Exception.__init__(self, msg)
| (self, msg) |
21,590 | delorean.exceptions | __str__ | null | def __str__(self):
return self.msg
| (self) |
21,591 | delorean.exceptions | DeloreanInvalidTimezone |
Exception that is raised when an invalid timezone is passed in.
| class DeloreanInvalidTimezone(DeloreanError):
"""
Exception that is raised when an invalid timezone is passed in.
"""
pass
| (msg) |
21,595 | delorean.dates | datetime_timezone |
This method given a timezone returns a localized datetime object.
| def datetime_timezone(tz):
"""
This method given a timezone returns a localized datetime object.
"""
utc_datetime_naive = datetime.utcnow()
# return a localized datetime to UTC
utc_localized_datetime = localize(utc_datetime_naive, 'UTC')
# normalize the datetime to given timezone
normalized_datetime = normalize(utc_localized_datetime, tz)
return normalized_datetime
| (tz) |
21,596 | delorean.interface | epoch | null | def epoch(s):
dt = datetime.utcfromtimestamp(s)
return Delorean(datetime=dt, timezone='UTC')
| (s) |
21,598 | delorean.interface | flux | null | def flux():
print("If you put your mind to it, you can accomplish anything.")
| () |
21,600 | delorean.dates | localize |
Given a naive datetime object this method will return a localized
datetime object
| def localize(dt, tz):
"""
Given a naive datetime object this method will return a localized
datetime object
"""
if not isinstance(tz, tzinfo):
tz = pytz.timezone(tz)
return tz.localize(dt)
| (dt, tz) |
21,601 | delorean.dates | move_datetime_day | null | def move_datetime_day(dt, direction, num_shifts):
delta = relativedelta(days=+num_shifts)
return _move_datetime(dt, direction, delta)
| (dt, direction, num_shifts) |
21,602 | delorean.dates | move_datetime_hour | null | def move_datetime_hour(dt, direction, num_shifts):
delta = relativedelta(hours=+num_shifts)
return _move_datetime(dt, direction, delta)
| (dt, direction, num_shifts) |
21,603 | delorean.dates | move_datetime_minute | null | def move_datetime_minute(dt, direction, num_shifts):
delta = relativedelta(minutes=+num_shifts)
return _move_datetime(dt, direction, delta)
| (dt, direction, num_shifts) |
21,604 | delorean.dates | move_datetime_month |
Move datetime 1 month in the chosen direction.
unit is a no-op, to keep the API the same as the day case
| def move_datetime_month(dt, direction, num_shifts):
"""
Move datetime 1 month in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(months=+num_shifts)
return _move_datetime(dt, direction, delta)
| (dt, direction, num_shifts) |
21,605 | delorean.dates | move_datetime_namedday | null | def move_datetime_namedday(dt, direction, unit):
TOTAL_DAYS = 7
days = {
'monday': 1,
'tuesday': 2,
'wednesday': 3,
'thursday': 4,
'friday': 5,
'saturday': 6,
'sunday': 7,
}
current_day = days[dt.strftime('%A').lower()]
target_day = days[unit.lower()]
if direction == 'next':
if current_day < target_day:
delta_days = target_day - current_day
else:
delta_days = (target_day - current_day) + TOTAL_DAYS
elif direction == 'last':
if current_day <= target_day:
delta_days = (current_day - target_day) + TOTAL_DAYS
else:
delta_days = current_day - target_day
delta = relativedelta(days=+delta_days)
return _move_datetime(dt, direction, delta)
| (dt, direction, unit) |
21,606 | delorean.dates | move_datetime_second | null | def move_datetime_second(dt, direction, num_shifts):
delta = relativedelta(seconds=+num_shifts)
return _move_datetime(dt, direction, delta)
| (dt, direction, num_shifts) |
21,607 | delorean.dates | move_datetime_week |
Move datetime 1 week in the chosen direction.
unit is a no-op, to keep the API the same as the day case
| def move_datetime_week(dt, direction, num_shifts):
"""
Move datetime 1 week in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(weeks=+num_shifts)
return _move_datetime(dt, direction, delta)
| (dt, direction, num_shifts) |
21,608 | delorean.dates | move_datetime_year |
Move datetime 1 year in the chosen direction.
unit is a no-op, to keep the API the same as the day case
| def move_datetime_year(dt, direction, num_shifts):
"""
Move datetime 1 year in the chosen direction.
unit is a no-op, to keep the API the same as the day case
"""
delta = relativedelta(years=+num_shifts)
return _move_datetime(dt, direction, delta)
| (dt, direction, num_shifts) |
21,609 | delorean.dates | normalize |
Given a object with a timezone return a datetime object
normalized to the proper timezone.
This means take the give localized datetime and returns the
datetime normalized to match the specificed timezone.
| def normalize(dt, tz):
"""
Given a object with a timezone return a datetime object
normalized to the proper timezone.
This means take the give localized datetime and returns the
datetime normalized to match the specificed timezone.
"""
if not isinstance(tz, tzinfo):
tz = pytz.timezone(tz)
dt = tz.normalize(dt)
return dt
| (dt, tz) |
21,610 | delorean.interface | now |
Return a Delorean object for the current local date and time, setting the timezone to the local timezone of the
caller.
| def now():
"""
Return a Delorean object for the current local date and time, setting the timezone to the local timezone of the
caller.
"""
return Delorean(timezone=get_localzone())
| () |
21,611 | delorean.interface | parse |
Parses a datetime string and returns a `Delorean` object.
:param datetime_str: The string to be interpreted into a `Delorean` object.
:param timezone: Pass this parameter and the returned Delorean object will be normalized to this timezone. Any
offsets passed as part of datetime_str will be ignored.
:param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the day
(True) or month (False). If yearfirst is set to True, this distinguishes between YDM and YMD.
:param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the
year. If True, the first number is taken to be the year, otherwise the last number is taken to be the year.
.. testsetup::
from delorean import Delorean
from delorean import parse
.. doctest::
>>> parse('2015-01-01 00:01:02')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
If a fixed offset is provided in the datetime_str, it will be parsed and the returned `Delorean` object will store a
`pytz.FixedOffest` as it's timezone.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0800')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone=pytz.FixedOffset(-480))
If the timezone argument is supplied, the returned Delorean object will be in the timezone supplied. Any offsets in
the datetime_str will be ignored.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0500', timezone='US/Pacific')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='US/Pacific')
If an unambiguous timezone is detected in the datetime string, a Delorean object with that datetime and
timezone will be returned.
.. doctest::
>>> parse('2015-01-01 00:01:02 PST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='America/Los_Angeles')
However if the provided timezone is ambiguous, parse will ignore the timezone and return a `Delorean` object in UTC
time.
>>> parse('2015-01-01 00:01:02 EST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
| def parse(datetime_str, timezone=None, dayfirst=True, yearfirst=True):
"""
Parses a datetime string and returns a `Delorean` object.
:param datetime_str: The string to be interpreted into a `Delorean` object.
:param timezone: Pass this parameter and the returned Delorean object will be normalized to this timezone. Any
offsets passed as part of datetime_str will be ignored.
:param dayfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the day
(True) or month (False). If yearfirst is set to True, this distinguishes between YDM and YMD.
:param yearfirst: Whether to interpret the first value in an ambiguous 3-integer date (ex. 01/05/09) as the
year. If True, the first number is taken to be the year, otherwise the last number is taken to be the year.
.. testsetup::
from delorean import Delorean
from delorean import parse
.. doctest::
>>> parse('2015-01-01 00:01:02')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
If a fixed offset is provided in the datetime_str, it will be parsed and the returned `Delorean` object will store a
`pytz.FixedOffest` as it's timezone.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0800')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone=pytz.FixedOffset(-480))
If the timezone argument is supplied, the returned Delorean object will be in the timezone supplied. Any offsets in
the datetime_str will be ignored.
.. doctest::
>>> parse('2015-01-01 00:01:02 -0500', timezone='US/Pacific')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='US/Pacific')
If an unambiguous timezone is detected in the datetime string, a Delorean object with that datetime and
timezone will be returned.
.. doctest::
>>> parse('2015-01-01 00:01:02 PST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='America/Los_Angeles')
However if the provided timezone is ambiguous, parse will ignore the timezone and return a `Delorean` object in UTC
time.
>>> parse('2015-01-01 00:01:02 EST')
Delorean(datetime=datetime.datetime(2015, 1, 1, 0, 1, 2), timezone='UTC')
"""
dt = capture(datetime_str, dayfirst=dayfirst, yearfirst=yearfirst)
if timezone:
dt = dt.replace(tzinfo=None)
do = Delorean(datetime=dt, timezone=timezone)
elif dt.tzinfo is None:
# assuming datetime object passed in is UTC
do = Delorean(datetime=dt, timezone='UTC')
elif isinstance(dt.tzinfo, tzoffset):
utcoffset = dt.tzinfo.utcoffset(None)
total_seconds = (
(utcoffset.microseconds + (utcoffset.seconds + utcoffset.days * 24 * 3600) * 10**6) / 10**6)
tz = pytz.FixedOffset(total_seconds / 60)
dt = dt.replace(tzinfo=None)
do = Delorean(dt, timezone=tz)
elif isinstance(dt.tzinfo, tzlocal):
tz = get_localzone()
dt = dt.replace(tzinfo=None)
do = Delorean(dt, timezone=tz)
else:
dt = pytz.utc.normalize(dt)
# making dt naive so we can pass it to Delorean
dt = dt.replace(tzinfo=None)
# if parse string has tzinfo we return a normalized UTC
# delorean object that represents the time.
do = Delorean(datetime=dt, timezone='UTC')
return do
| (datetime_str, timezone=None, dayfirst=True, yearfirst=True) |
21,612 | delorean.interface | range_daily |
This an alternative way to generating sets of Delorean objects with
DAILY stops
| def range_daily(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
DAILY stops
"""
return stops(start=start, stop=stop, freq=DAILY, timezone=timezone, count=count)
| (start=None, stop=None, timezone='UTC', count=None) |
21,613 | delorean.interface | range_hourly |
This an alternative way to generating sets of Delorean objects with
HOURLY stops
| def range_hourly(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
HOURLY stops
"""
return stops(start=start, stop=stop, freq=HOURLY, timezone=timezone, count=count)
| (start=None, stop=None, timezone='UTC', count=None) |
21,614 | delorean.interface | range_monthly |
This an alternative way to generating sets of Delorean objects with
MONTHLY stops
| def range_monthly(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
MONTHLY stops
"""
return stops(start=start, stop=stop, freq=MONTHLY, timezone=timezone, count=count)
| (start=None, stop=None, timezone='UTC', count=None) |
21,615 | delorean.interface | range_yearly |
This an alternative way to generating sets of Delorean objects with
YEARLY stops
| def range_yearly(start=None, stop=None, timezone='UTC', count=None):
"""
This an alternative way to generating sets of Delorean objects with
YEARLY stops
"""
return stops(start=start, stop=stop, freq=YEARLY, timezone=timezone, count=count)
| (start=None, stop=None, timezone='UTC', count=None) |
21,616 | delorean.interface | stops |
This will create a list of delorean objects the apply to
setting possed in.
| def stops(freq, interval=1, count=None, wkst=None, bysetpos=None,
bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
byweekno=None, byweekday=None, byhour=None, byminute=None,
bysecond=None, timezone='UTC', start=None, stop=None):
"""
This will create a list of delorean objects the apply to
setting possed in.
"""
# check to see if datetimees passed in are naive if so process them
# with given timezone.
if all([(start is None or is_datetime_naive(start)),
(stop is None or is_datetime_naive(stop))]):
pass
else:
raise DeloreanInvalidDatetime('Provide a naive datetime object')
# if no datetimes are passed in create a proper datetime object for
# start default because default in dateutil is datetime.now() :(
if start is None:
start = datetime_timezone(timezone)
for dt in rrule(freq, interval=interval, count=count, wkst=wkst, bysetpos=bysetpos,
bymonth=bymonth, bymonthday=bymonthday, byyearday=byyearday, byeaster=byeaster,
byweekno=byweekno, byweekday=byweekday, byhour=byhour, byminute=byminute,
bysecond=bysecond, until=stop, dtstart=start):
# make the delorean object
# yield it.
# doing this to make sure delorean receives a naive datetime.
dt = dt.replace(tzinfo=None)
d = Delorean(datetime=dt, timezone=timezone)
yield d
| (freq, interval=1, count=None, wkst=None, bysetpos=None, bymonth=None, bymonthday=None, byyearday=None, byeaster=None, byweekno=None, byweekday=None, byhour=None, byminute=None, bysecond=None, timezone='UTC', start=None, stop=None) |
21,617 | delorean.interface | utcnow |
Return a Delorean object for the current UTC date and time, setting the timezone to UTC.
| def utcnow():
"""
Return a Delorean object for the current UTC date and time, setting the timezone to UTC.
"""
return Delorean()
| () |
21,618 | python_usernames.validators | is_safe_username | null | def is_safe_username(
username: str, whitelist=None, blacklist=None, regex=username_regex, max_length=None
) -> bool:
# check for max length
if max_length and len(username) > max_length:
return False
# check against provided regex
if not re.match(regex, username):
return False
# ensure the word is not in the blacklist and is not a reserved word
if whitelist is None:
whitelist = []
if blacklist is None:
blacklist = []
default_words = get_reserved_words()
whitelist = set(
[each_whitelisted_name.lower() for each_whitelisted_name in whitelist]
)
blacklist = set(
[each_blacklisted_name.lower() for each_blacklisted_name in blacklist]
)
default_words = default_words - whitelist
default_words = default_words.union(blacklist)
return False if username.lower() in default_words else True
| (username: str, whitelist=None, blacklist=None, regex=re.compile('\n ^ # beginning of string\n (?!_$) # no only _\n (?![-.]) # no - or . at the beginning\n (?!.*[_.-]{2}) # no __ or _. or ._, re.VERBOSE), max_length=None) -> bool |
21,621 | smartypants | _Attr |
class for instantiation of module attribute :attr:`Attr`.
| class _Attr(object):
"""
class for instantiation of module attribute :attr:`Attr`.
"""
q = 1 << 0
"""
flag for normal quotes (``"``) and (``'``) to curly ones.
.. seealso:: :func:`convert_quotes`
"""
b = 1 << 1
"""
flag for double quotes (````backticks''``) to curly ones.
.. seealso:: :func:`convert_backticks`
"""
B = 1 << 2 | b
"""
flag for double quotes (````backticks''``) and single quotes
(```single'``) to curly ones.
.. seealso:: :func:`convert_backticks` and :func:`convert_single_backticks`
"""
mask_b = b | B
d = 1 << 3
"""
flag for dashes (``--``) to em-dashes.
.. seealso:: :func:`convert_dashes`
"""
D = 1 << 4 | d
"""
flag for old-school typewriter dashes (``--``) to en-dashes and dashes
(``---``) to em-dashes.
.. seealso:: :func:`convert_dashes_oldschool`
"""
i = 1 << 5 | d
"""
flag for inverted old-school typewriter dashes (``--``) to em-dashes and
dashes (``---``) to en-dashes.
.. seealso:: :func:`convert_dashes_oldschool_inverted`
"""
mask_d = d | D | i
e = 1 << 6
"""
flag for dashes (``...``) to ellipses.
.. seealso:: :func:`convert_ellipses`
"""
w = 1 << 7
"""
flag for dashes (``"``) to ASCII double quotes (``"``).
This should be of no interest to most people, but of particular interest
to anyone who writes their posts using Dreamweaver, as Dreamweaver
inexplicably uses this entity to represent a literal double-quote
character. SmartyPants only educates normal quotes, not entities (because
ordinarily, entities are used for the explicit purpose of representing the
specific character they represent). The "w" option must be used in
conjunction with one (or both) of the other quote options ("q" or "b").
Thus, if you wish to apply all SmartyPants transformations (quotes, en-
and em-dashes, and ellipses) and also convert ``"`` entities into
regular quotes so SmartyPants can educate them.
"""
u = 0 << 9 | 1 << 8
"""
Output Unicode characters instead of numeric character references, for
example, from ``“`` to left double quotation mark (``“``) (U+201C).
.. seealso:: :func:`convert_entities`
"""
h = 1 << 9 | 0 << 8
"""
Output HTML named entities instead of numeric character references, for
example, from ``“`` to ``“``.
.. seealso:: :func:`convert_entities`
"""
s = 1 << 9 | 1 << 8
"""
Output ASCII equivalents instead of numeric character references, for
example, from ``—`` to ``--``.
.. seealso:: :func:`convert_entities`
"""
mask_o = u | h | s
set0 = 0
"suppress all transformations. (Do nothing.)"
set1 = q | b | d | e
"equivalent to :attr:`q` | :attr:`b` | :attr:`d` | :attr:`e`"
set2 = q | b | D | e
"""
equivalent to :attr:`q` | :attr:`b` | :attr:`D` | :attr:`e`
For old school en- and em- dash.
"""
set3 = q | b | i | e
"""
equivalent to :attr:`q` | :attr:`b` | :attr:`i` | :attr:`e`
For inverted old school en & em- dash."
"""
@property
def default(self):
"Default value of attributes, same value as :attr:`set1`"
global default_smartypants_attr
return default_smartypants_attr
@default.setter
def default(self, attr):
global default_smartypants_attr
default_smartypants_attr = attr
| () |
21,622 | smartypants | _tags_to_skip_regex |
Convert a list of skipped tags into regular expression
The default *tags* are :attr:`tags_to_skip`.
>>> f = _tags_to_skip_regex
>>> print(f(['foo', 'bar']).pattern)
<(/)?(foo|bar)[^>]*>
| def _tags_to_skip_regex(tags=None):
"""
Convert a list of skipped tags into regular expression
The default *tags* are :attr:`tags_to_skip`.
>>> f = _tags_to_skip_regex
>>> print(f(['foo', 'bar']).pattern)
<(/)?(foo|bar)[^>]*>
"""
if tags is None:
tags = tags_to_skip
if isinstance(tags, (list, tuple)):
tags = '|'.join(tags)
return re.compile('<(/)?(%s)[^>]*>' % tags, re.I)
| (tags=None) |
21,623 | smartypants | _tokenize |
Reference to an array of the tokens comprising the input string. Each token
is either a tag (possibly with nested, tags contained therein, such as
``<a href="<MTFoo>">``, or a run of text between tags. Each element of the
array is a two-element array; the first is either 'tag' or 'text'; the
second is the actual value.
Based on the _tokenize() subroutine from `Brad Choate's MTRegex plugin`__.
__ http://www.bradchoate.com/past/mtregex.php
| def _tokenize(text):
"""
Reference to an array of the tokens comprising the input string. Each token
is either a tag (possibly with nested, tags contained therein, such as
``<a href="<MTFoo>">``, or a run of text between tags. Each element of the
array is a two-element array; the first is either 'tag' or 'text'; the
second is the actual value.
Based on the _tokenize() subroutine from `Brad Choate's MTRegex plugin`__.
__ http://www.bradchoate.com/past/mtregex.php
"""
tokens = []
tag_soup = re.compile(r'([^<]*)(<!--.*?--\s*>|<[^>]*>)', re.S)
token_match = tag_soup.match(text)
previous_end = 0
while token_match:
if token_match.group(1):
tokens.append(['text', token_match.group(1)])
# if -- in text part of comment, then it's not a comment, therefore it
# should be converted.
#
# In HTML4 [1]:
# [...] Authors should avoid putting two or more adjacent hyphens
# inside comments.
#
# In HTML5 [2]:
# [...] the comment may have text, with the additional restriction
# that the text must not [...], nor contain two consecutive U+002D
# HYPHEN-MINUS characters (--)
#
# [1]: http://www.w3.org/TR/REC-html40/intro/sgmltut.html#h-3.2.4
# [2]: http://www.w3.org/TR/html5/syntax.html#comments
tag = token_match.group(2)
type_ = 'tag'
if tag.startswith('<!--'):
# remove --[white space]> from the end of tag
if '--' in tag[4:].rstrip('>').rstrip().rstrip('-'):
type_ = 'text'
tokens.append([type_, tag])
previous_end = token_match.end()
token_match = tag_soup.match(text, token_match.end())
if previous_end < len(text):
tokens.append(['text', text[previous_end:]])
return tokens
| (text) |
21,624 | smartypants | convert_backticks |
Convert ````backticks''``-style double quotes in *text* into HTML curly
quote entities.
>>> print(convert_backticks("``Isn't this fun?''"))
“Isn't this fun?”
| def convert_backticks(text):
"""
Convert ````backticks''``-style double quotes in *text* into HTML curly
quote entities.
>>> print(convert_backticks("``Isn't this fun?''"))
“Isn't this fun?”
"""
text = re.sub('``', '“', text)
text = re.sub("''", '”', text)
return text
| (text) |
21,625 | smartypants | convert_dashes |
Convert ``--`` in *text* into em-dash HTML entities.
>>> quote = 'Nothing endures but change. -- Heraclitus'
>>> print(convert_dashes(quote))
Nothing endures but change. — Heraclitus
| def convert_dashes(text):
"""
Convert ``--`` in *text* into em-dash HTML entities.
>>> quote = 'Nothing endures but change. -- Heraclitus'
>>> print(convert_dashes(quote))
Nothing endures but change. — Heraclitus
"""
text = re.sub('--', '—', text)
return text
| (text) |
21,626 | smartypants | convert_dashes_oldschool |
Convert ``--`` and ``---`` in *text* into en-dash and em-dash HTML
entities, respectively.
>>> quote = 'Life itself is the proper binge. --- Julia Child (1912--2004)'
>>> print(convert_dashes_oldschool(quote))
Life itself is the proper binge. — Julia Child (1912–2004)
| def convert_dashes_oldschool(text):
"""
Convert ``--`` and ``---`` in *text* into en-dash and em-dash HTML
entities, respectively.
>>> quote = 'Life itself is the proper binge. --- Julia Child (1912--2004)'
>>> print(convert_dashes_oldschool(quote))
Life itself is the proper binge. — Julia Child (1912–2004)
"""
text = re.sub('---', '—', text) # em (yes, backwards)
text = re.sub('--', '–', text) # en (yes, backwards)
return text
| (text) |
21,627 | smartypants | convert_dashes_oldschool_inverted |
Convert ``--`` and ``---`` in *text* into em-dash and en-dash HTML
entities, respectively.
Two reasons why:
* First, unlike the en- and em-dash syntax supported by
:func:`convert_dashes_oldschool`, it's compatible with existing entries
written before SmartyPants 1.1, back when ``--`` was only used for
em-dashes.
* Second, em-dashes are more common than en-dashes, and so it sort of
makes sense that the shortcut should be shorter to type. (Thanks to Aaron
Swartz for the idea.)
>>> quote = 'Dare to be naïve. -- Buckminster Fuller (1895---1983)'
>>> print(convert_dashes_oldschool_inverted(quote))
Dare to be naïve. — Buckminster Fuller (1895–1983)
| def convert_dashes_oldschool_inverted(text):
"""
Convert ``--`` and ``---`` in *text* into em-dash and en-dash HTML
entities, respectively.
Two reasons why:
* First, unlike the en- and em-dash syntax supported by
:func:`convert_dashes_oldschool`, it's compatible with existing entries
written before SmartyPants 1.1, back when ``--`` was only used for
em-dashes.
* Second, em-dashes are more common than en-dashes, and so it sort of
makes sense that the shortcut should be shorter to type. (Thanks to Aaron
Swartz for the idea.)
>>> quote = 'Dare to be naïve. -- Buckminster Fuller (1895---1983)'
>>> print(convert_dashes_oldschool_inverted(quote))
Dare to be naïve. — Buckminster Fuller (1895–1983)
"""
text = re.sub('---', '–', text) # em
text = re.sub('--', '—', text) # en
return text
| (text) |
21,628 | smartypants | convert_ellipses |
Convert ``...`` in *text* into ellipsis HTML entities
>>> print(convert_ellipses('Huh...?'))
Huh…?
| def convert_ellipses(text):
"""
Convert ``...`` in *text* into ellipsis HTML entities
>>> print(convert_ellipses('Huh...?'))
Huh…?
"""
text = re.sub(r"""\.\.\.""", '…', text)
text = re.sub(r"""\. \. \.""", '…', text)
return text
| (text) |
21,629 | smartypants | convert_entities |
Convert numeric character references to, if *mode* is
- *0*: Unicode characters
- *1*: HTML named entities
- *2*: ASCII equivalents
>>> print(convert_entities('‘', 0))
‘
>>> print(convert_entities('‘SmartyPants’', 1))
‘SmartyPants’
>>> print(convert_entities('“Hello — world.”', 2))
"Hello -- world."
| def convert_entities(text, mode):
"""
Convert numeric character references to, if *mode* is
- *0*: Unicode characters
- *1*: HTML named entities
- *2*: ASCII equivalents
>>> print(convert_entities('‘', 0))
‘
>>> print(convert_entities('‘SmartyPants’', 1))
‘SmartyPants’
>>> print(convert_entities('“Hello — world.”', 2))
"Hello -- world."
"""
CTBL = {
'–': ('–', '–', '-'),
'—': ('—', '—', '--'),
'‘': ('‘', '‘', "'"),
'’': ('’', '’', "'"),
'“': ('“', '“', '"'),
'”': ('”', '”', '"'),
'…': ('…', '…', '...'),
}
for k, v in CTBL.items():
text = text.replace(k, v[mode])
return text
| (text, mode) |
21,630 | smartypants | convert_quotes |
Convert quotes in *text* into HTML curly quote entities.
>>> print(convert_quotes('"Isn\'t this fun?"'))
“Isn’t this fun?”
| def convert_quotes(text):
"""
Convert quotes in *text* into HTML curly quote entities.
>>> print(convert_quotes('"Isn\\'t this fun?"'))
“Isn’t this fun?”
"""
punct_class = r"""[!"#\$\%'()*+,-.\/:;<=>?\@\[\\\]\^_`{|}~]"""
# Special case if the very first character is a quote
# followed by punctuation at a non-word-break. Close the quotes by brute
# force:
text = re.sub(r"""^'(?=%s\\B)""" % (punct_class,), '’', text)
text = re.sub(r"""^"(?=%s\\B)""" % (punct_class,), '”', text)
# Special case for double sets of quotes, e.g.:
# <p>He said, "'Quoted' words in a larger quote."</p>
text = re.sub(r""""'(?=\w)""", '“‘', text)
text = re.sub(r"""'"(?=\w)""", '‘“', text)
# Special case for decade abbreviations (the '80s):
text = re.sub(r"""\b'(?=\d{2}s)""", '’', text)
close_class = r'[^\ \t\r\n\[\{\(\-]'
dec_dashes = '–|—'
# Get most opening single quotes:
opening_single_quotes_regex = re.compile(r"""
(
\s | # a whitespace char, or
| # a non-breaking space entity, or
-- | # dashes, or
&[mn]dash; | # named dash entities
%s | # or decimal entities
&\#x201[34]; # or hex
)
' # the quote
(?=\w) # followed by a word character
""" % (dec_dashes,), re.VERBOSE)
text = opening_single_quotes_regex.sub(r'\1‘', text)
closing_single_quotes_regex = re.compile(r"""
(%s)
'
(?!\s | s\b | \d)
""" % (close_class,), re.VERBOSE)
text = closing_single_quotes_regex.sub(r'\1’', text)
closing_single_quotes_regex = re.compile(r"""
(%s)
'
(\s | s\b)
""" % (close_class,), re.VERBOSE)
text = closing_single_quotes_regex.sub(r'\1’\2', text)
# Any remaining single quotes should be opening ones:
text = re.sub("'", '‘', text)
# Get most opening double quotes:
opening_double_quotes_regex = re.compile(r"""
(
\s | # a whitespace char, or
| # a non-breaking space entity, or
-- | # dashes, or
&[mn]dash; | # named dash entities
%s | # or decimal entities
&\#x201[34]; # or hex
)
" # the quote
(?=\w) # followed by a word character
""" % (dec_dashes,), re.VERBOSE)
text = opening_double_quotes_regex.sub(r'\1“', text)
# Double closing quotes:
closing_double_quotes_regex = re.compile(r"""
#(%s)? # character that indicates the quote should be closing
"
(?=\s)
""" % (close_class,), re.VERBOSE)
text = closing_double_quotes_regex.sub('”', text)
closing_double_quotes_regex = re.compile(r"""
(%s) # character that indicates the quote should be closing
"
""" % (close_class,), re.VERBOSE)
text = closing_double_quotes_regex.sub(r'\1”', text)
# Any remaining quotes should be opening ones.
text = re.sub('"', '“', text)
return text
| (text) |
21,631 | smartypants | convert_single_backticks |
Convert ```backticks'``-style single quotes in *text* into HTML curly
quote entities.
>>> print(convert_single_backticks("`Isn't this fun?'"))
‘Isn’t this fun?’
| def convert_single_backticks(text):
"""
Convert ```backticks'``-style single quotes in *text* into HTML curly
quote entities.
>>> print(convert_single_backticks("`Isn't this fun?'"))
‘Isn’t this fun?’
"""
text = re.sub('`', '‘', text)
text = re.sub("'", '’', text)
return text
| (text) |
21,632 | smartypants | process_escapes |
Processe the following backslash escape sequences in *text*. This is useful
if you want to force a "dumb" quote or other character to appear.
+--------+-----------+-----------+
| Escape | Value | Character |
+========+===========+===========+
| ``\\`` | ``\`` | ``\`` |
+--------+-----------+-----------+
| ``\"`` | ``"`` | ``"`` |
+--------+-----------+-----------+
| ``\'`` | ``'`` | ``'`` |
+--------+-----------+-----------+
| ``\.`` | ``.`` | ``.`` |
+--------+-----------+-----------+
| ``\-`` | ``-`` | ``-`` |
+--------+-----------+-----------+
| ``\``` | ````` | ``\``` |
+--------+-----------+-----------+
>>> print(process_escapes(r'\\'))
\
>>> print(smartypants(r'"smarty" \"pants\"'))
“smarty” "pants"
| def process_escapes(text):
r"""
Processe the following backslash escape sequences in *text*. This is useful
if you want to force a "dumb" quote or other character to appear.
+--------+-----------+-----------+
| Escape | Value | Character |
+========+===========+===========+
| ``\\`` | ``\`` | ``\`` |
+--------+-----------+-----------+
| ``\"`` | ``"`` | ``"`` |
+--------+-----------+-----------+
| ``\'`` | ``'`` | ``'`` |
+--------+-----------+-----------+
| ``\.`` | ``.`` | ``.`` |
+--------+-----------+-----------+
| ``\-`` | ``-`` | ``-`` |
+--------+-----------+-----------+
| ``\``` | ````` | ``\``` |
+--------+-----------+-----------+
>>> print(process_escapes(r'\\'))
\
>>> print(smartypants(r'"smarty" \"pants\"'))
“smarty” "pants"
"""
text = re.sub(r'\\\\', '\', text)
text = re.sub(r'\\"', '"', text)
text = re.sub(r"\\'", ''', text)
text = re.sub(r'\\\.', '.', text)
text = re.sub(r'\\-', '-', text)
text = re.sub(r'\\`', '`', text)
return text
| (text) |
21,634 | smartypants | smartypants |
SmartyPants function
>>> print(smartypants('"foo" -- bar'))
“foo” — bar
>>> print(smartypants('"foo" -- bar', Attr.d))
"foo" — bar
| def smartypants(text, attr=None):
"""
SmartyPants function
>>> print(smartypants('"foo" -- bar'))
“foo” — bar
>>> print(smartypants('"foo" -- bar', Attr.d))
"foo" — bar
"""
skipped_tag_stack = []
if attr is None:
attr = Attr.default
do_quotes = attr & Attr.q
do_backticks = attr & Attr.mask_b
do_dashes = attr & Attr.mask_d
do_ellipses = attr & Attr.e
do_entities = attr & Attr.mask_o
convert_quot = attr & Attr.w
tokens = _tokenize(text)
result = []
in_pre = False
prev_token_last_char = ""
# This is a cheat, used to get some context
# for one-character tokens that consist of
# just a quote char. What we do is remember
# the last character of the previous text
# token, to use as context to curl single-
# character quote tokens correctly.
tags_to_skip_regex = _tags_to_skip_regex()
for cur_token in tokens:
if cur_token[0] == "tag":
# Don't mess with quotes inside some tags. This does not handle
# self <closing/> tags!
result.append(cur_token[1])
skip_match = tags_to_skip_regex.match(cur_token[1])
if skip_match:
if not skip_match.group(1):
skipped_tag_stack.append(skip_match.group(2).lower())
in_pre = True
else:
if len(skipped_tag_stack) > 0:
_tag = skipped_tag_stack[-1]
if skip_match.group(2).lower() == _tag:
skipped_tag_stack.pop()
else:
pass
# This close doesn't match the open. This isn't
# XHTML. We should barf here.
if len(skipped_tag_stack) == 0:
in_pre = False
else:
t = cur_token[1]
# Remember last char of this token before processing.
last_char = t[-1:]
if not in_pre:
t = process_escapes(t)
if convert_quot:
t = re.sub('"', '"', t)
if do_dashes:
if do_dashes == Attr.d:
t = convert_dashes(t)
if do_dashes == Attr.D:
t = convert_dashes_oldschool(t)
if do_dashes == Attr.i:
t = convert_dashes_oldschool_inverted(t)
if do_ellipses:
t = convert_ellipses(t)
# Note: backticks need to be processed before quotes.
if do_backticks == Attr.b:
t = convert_backticks(t)
if do_backticks == Attr.B:
t = convert_single_backticks(t)
if do_quotes:
if t == "'":
# Special case: single-character ' token
if re.match("\S", prev_token_last_char):
t = "’"
else:
t = "‘"
elif t == '"':
# Special case: single-character " token
if re.match("\S", prev_token_last_char):
t = "”"
else:
t = "“"
else:
# Normal case:
t = convert_quotes(t)
if do_entities:
mode = (0 if do_entities == Attr.u else
1 if do_entities == Attr.h else
2 if do_entities == Attr.s else
3) # would result in key error
t = convert_entities(t, mode)
prev_token_last_char = last_char
result.append(t)
return "".join(result)
| (text, attr=None) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.