code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
morphlist = list(self._morph_rgb(start, stop, step=step))
if movefactor:
# Moving means we need the morph to wrap around.
morphlist.extend(self._morph_rgb(stop, start, step=step))
if movefactor < 0:
# Increase the start for each line.
def move():
popped = []
for _ in range(abs(movefactor)):
try:
popped.append(morphlist.pop(0))
except IndexError:
pass
morphlist.extend(popped)
return morphlist
else:
# Decrease start for each line.
def move():
for _ in range(movefactor):
try:
val = morphlist.pop(-1)
except IndexError:
pass
else:
morphlist.insert(0, val)
return morphlist
return '\n'.join((
self._gradient_rgb_line_from_morph(
line,
move() if movefactor else morphlist,
fore=fore,
back=back,
style=style,
)
for i, line in enumerate(text.splitlines())
))
|
def _gradient_rgb_lines(
self, text, start, stop, step=1,
fore=None, back=None, style=None, movefactor=None)
|
Yield colorized characters, morphing from one rgb value to
another. This treats each line separately.
| 3.054268
| 2.971889
| 1.027719
|
if fore and back:
raise ValueError('Both fore and back colors cannot be specified.')
pos = 0
end = len(text)
numbergen = self._iter_wave(numbers)
def make_color(n):
try:
r, g, b = n
except TypeError:
if rgb_mode:
return n, n, n
return n
return r, g, b
for value in numbergen:
lastchar = pos + step
yield self.color(
text[pos:lastchar],
fore=make_color(value) if fore is None else fore,
back=make_color(value) if fore is not None else back,
style=style
)
if lastchar >= end:
numbergen.send(True)
pos = lastchar
|
def _iter_text_wave(
self, text, numbers, step=1,
fore=None, back=None, style=None, rgb_mode=False)
|
Yield colorized characters from `text`, using a wave of `numbers`.
Arguments:
text : String to be colorized.
numbers : A list/tuple of numbers (256 colors).
step : Number of characters to colorize per color.
fore : Fore color to use (name or number).
(Back will be gradient)
back : Background color to use (name or number).
(Fore will be gradient)
style : Style name to use.
rgb_mode : Use number for rgb value.
This should never be used when the numbers
are rgb values themselves.
| 3.459455
| 3.309092
| 1.045439
|
up = True
pos = 0
i = 0
try:
end = len(iterable)
except TypeError:
iterable = list(iterable)
end = len(iterable)
# Stop on count, or run forever.
while (i < count) if count > 0 else True:
try:
stop = yield iterable[pos]
# End of generator (user sent the stop signal)
if stop:
break
except IndexError:
# End of iterable, when len(iterable) is < count.
up = False
# Change directions if needed, otherwise increment/decrement.
if up:
pos += 1
if pos == end:
up = False
pos = end - 2
else:
pos -= 1
if pos < 0:
up = True
pos = 1
i += 1
|
def _iter_wave(iterable, count=0)
|
Move from beginning to end, and then end to beginning, a number of
iterations through an iterable (must accept len(iterable)).
Example:
print(' -> '.join(_iter_wave('ABCD', count=8)))
>> A -> B -> C -> D -> C -> B -> A -> B
If `count` is less than 1, this will run forever.
You can stop it by sending a Truthy value into the generator:
gen = self._iter_wave('test')
for c in gen:
if c == 's':
# Stop the generator early.
gen.send(True)
print(c)
| 4.219707
| 3.861226
| 1.092841
|
pos1, pos2 = list(rgb1), list(rgb2)
indexes = [i for i, _ in enumerate(pos1)]
def step_value(a, b):
if a < b:
return step
if a > b:
return -step
return 0
steps = [step_value(pos1[x], pos2[x]) for x in indexes]
stepcnt = 0
while (pos1 != pos2):
stepcnt += 1
stop = yield tuple(pos1)
if stop:
break
for x in indexes:
if pos1[x] != pos2[x]:
pos1[x] += steps[x]
if (steps[x] < 0) and (pos1[x] < pos2[x]):
# Over stepped, negative.
pos1[x] = pos2[x]
if (steps[x] > 0) and (pos1[x] > pos2[x]):
# Over stepped, positive.
pos1[x] = pos2[x]
yield tuple(pos1)
|
def _morph_rgb(self, rgb1, rgb2, step=1)
|
Morph an rgb value into another, yielding each step along the way.
| 2.607846
| 2.496447
| 1.044623
|
return (
(c, self._rainbow_color(freq, offset + i / spread))
for i, c in enumerate(s)
)
|
def _rainbow_hex_chars(self, s, freq=0.1, spread=3.0, offset=0)
|
Iterate over characters in a string to build data needed for a
rainbow effect.
Yields tuples of (char, hexcode).
Arguments:
s : String to colorize.
freq : Frequency/"tightness" of colors in the rainbow.
Best results when in the range 0.0-1.0.
Default: 0.1
spread : Spread/width of colors.
Default: 3.0
offset : Offset for start of rainbow.
Default: 0
| 5.057742
| 4.731557
| 1.068938
|
fore = colorargs.get('fore', None)
back = colorargs.get('back', None)
style = colorargs.get('style', None)
if fore:
color_args = (lambda value: {
'back': value if rgb_mode else hex2term(value),
'style': style,
'fore': fore
})
else:
color_args = (lambda value: {
'fore': value if rgb_mode else hex2term(value),
'style': style,
'back': back
})
if rgb_mode:
method = self._rainbow_rgb_chars
else:
method = self._rainbow_hex_chars
return ''.join(
self.color(c, **color_args(hval))
for c, hval in method(
text,
freq=freq,
spread=spread,
offset=offset)
)
|
def _rainbow_line(
self, text, freq=0.1, spread=3.0, offset=0,
rgb_mode=False, **colorargs)
|
Create rainbow using the same offset for all text.
Arguments:
text : String to colorize.
freq : Frequency/"tightness" of colors in the rainbow.
Best results when in the range 0.0-1.0.
Default: 0.1
spread : Spread/width of colors.
Default: 3.0
offset : Offset for start of rainbow.
Default: 0
rgb_mode : If truthy, use RGB escape codes instead of
extended 256 and approximate hex match.
Keyword Arguments:
colorargs : Any extra arguments for the color function,
such as fore, back, style.
These need to be treated carefully to not
'overwrite' the rainbow codes.
| 2.779355
| 2.72645
| 1.019404
|
if not movefactor:
def factor(i):
return offset
else:
# Increase the offset for each line.
def factor(i):
return offset + (i * movefactor)
return '\n'.join(
self._rainbow_line(
line,
freq=freq,
spread=spread,
offset=factor(i),
rgb_mode=rgb_mode,
**colorargs)
for i, line in enumerate(text.splitlines()))
|
def _rainbow_lines(
self, text, freq=0.1, spread=3.0, offset=0, movefactor=0,
rgb_mode=False, **colorargs)
|
Create rainbow text, using the same offset for each line.
Arguments:
text : String to colorize.
freq : Frequency/"tightness" of colors in the rainbow.
Best results when in the range 0.0-1.0.
Default: 0.1
spread : Spread/width of colors.
Default: 3.0
offset : Offset for start of rainbow.
Default: 0
movefactor : Factor for offset increase on each new line.
Default: 0
rgb_mode : If truthy, use RGB escape codes instead of
extended 256 and approximate hex match.
Keyword Arguments:
fore, back, style : Other args for the color() function.
| 2.529328
| 2.722257
| 0.929129
|
# Borrowed from lolcat, translated from ruby.
red = math.sin(freq * i + 0) * 127 + 128
green = math.sin(freq * i + 2 * math.pi / 3) * 127 + 128
blue = math.sin(freq * i + 4 * math.pi / 3) * 127 + 128
return int(red), int(green), int(blue)
|
def _rainbow_rgb(self, freq, i)
|
Calculate a single rgb value for a piece of a rainbow.
Arguments:
freq : "Tightness" of colors (see self.rainbow())
i : Index of character in string to colorize.
| 2.100813
| 2.117628
| 0.99206
|
return (
(c, self._rainbow_rgb(freq, offset + i / spread))
for i, c in enumerate(s)
)
|
def _rainbow_rgb_chars(self, s, freq=0.1, spread=3.0, offset=0)
|
Iterate over characters in a string to build data needed for a
rainbow effect.
Yields tuples of (char, (r, g, b)).
Arguments:
s : String to colorize.
freq : Frequency/"tightness" of colors in the rainbow.
Best results when in the range 0.0-1.0.
Default: 0.1
spread : Spread/width of colors.
Default: 3.0
offset : Offset for start of rainbow.
Default: 0
| 4.66579
| 4.42079
| 1.05542
|
return self.chained(text=text, fore=fore, back=(r, g, b), style=style)
|
def b_rgb(self, r, g, b, text=None, fore=None, style=None)
|
A chained method that sets the back color to an RGB value.
Arguments:
r : Red value.
g : Green value.
b : Blue value.
text : Text to style if not building up color codes.
fore : Fore color for the text.
style : Style for the text.
| 6.001723
| 6.265464
| 0.957906
|
self.data = ''.join((
self.data,
self.color(text=text, fore=fore, back=back, style=style),
))
return self
|
def chained(self, text=None, fore=None, back=None, style=None)
|
Called by the various 'color' methods to colorize a single string.
The RESET_ALL code is appended to the string unless text is empty.
Raises ValueError on invalid color names.
Arguments:
text : String to colorize, or None for BG/Style change.
fore : Name of fore color to use.
back : Name of back color to use.
style : Name of style to use.
| 3.883551
| 4.556387
| 0.852331
|
has_args = (
(fore is not None) or
(back is not None) or
(style is not None)
)
if hasattr(text, '__colr__') and not has_args:
# Use custom __colr__ method in the absence of arguments.
return str(self._call_dunder_colr(text))
# Stringify everything before operating on it.
text = str(text) if text is not None else ''
if _disabled:
return text
# Considered to have unclosed codes if embedded codes exist and
# the last code was not a color code.
embedded_codes = get_codes(text)
has_end_code = embedded_codes and embedded_codes[-1] == closing_code
# Add closing code if not already added, there is text, and
# some kind of color/style was used (whether from args, or
# color codes were included in the text already).
# If the last code embedded in the text was a closing code,
# then it is not added.
# This can be overriden with `no_closing`.
needs_closing = (
text and
(not no_closing) and
(not has_end_code) and
(has_args or embedded_codes)
)
if needs_closing:
end = closing_code
else:
end = ''
return ''.join((
self.color_code(fore=fore, back=back, style=style),
text,
end,
))
|
def color(
self, text=None, fore=None, back=None, style=None,
no_closing=False)
|
A method that colorizes strings, not Colr objects.
Raises InvalidColr for invalid color names.
The 'reset_all' code is appended if text is given.
| 5.053883
| 4.896638
| 1.032113
|
# Map from style type to raw code formatter function.
colorcodes = []
resetcodes = []
userstyles = {'style': style, 'back': back, 'fore': fore}
for stype in userstyles:
stylearg = userstyles.get(stype, None)
if not stylearg:
# No value for this style name, don't use it.
continue
# Get escape code for this style.
code = self.get_escape_code(stype, stylearg)
stylename = str(stylearg).lower()
if (stype == 'style') and (stylename in ('0', )):
resetcodes.append(code)
elif stylename.startswith('reset'):
resetcodes.append(code)
else:
colorcodes.append(code)
# Reset codes come first, to not override colors.
return ''.join((''.join(resetcodes), ''.join(colorcodes)))
|
def color_code(self, fore=None, back=None, style=None)
|
Return the codes for this style/colors.
| 4.707881
| 4.640487
| 1.014523
|
return self.__class__(self.data.format(*args, **kwargs))
|
def format(self, *args, **kwargs)
|
Like str.format, except it returns a Colr.
| 5.593735
| 3.702949
| 1.510616
|
valuefmt = str(value).lower()
code = codes[codetype].get(valuefmt, None)
if code:
# Basic code from fore, back, or style.
return code
named_funcs = {
'fore': format_fore,
'back': format_back,
'style': format_style,
}
# Not a basic code, try known names.
converter = named_funcs.get(codetype, None)
if converter is None:
raise ValueError(
'Invalid code type. Expecting {}, got: {!r}'.format(
', '.join(named_funcs),
codetype
)
)
# Try as hex.
with suppress(ValueError):
value = int(hex2term(value, allow_short=True))
return converter(value, extended=True)
named_data = name_data.get(valuefmt, None)
if named_data is not None:
# A known named color.
try:
return converter(named_data['code'], extended=True)
except TypeError:
# Passing a known name as a style?
if codetype == 'style':
raise InvalidStyle(value)
raise
# Not a known color name/value, try rgb.
try:
r, g, b = (int(x) for x in value)
# This does not mean we have a 3 int tuple. It could '111'.
# The converter should catch it though.
except (TypeError, ValueError):
# Not an rgb value.
if codetype == 'style':
raise InvalidStyle(value)
try:
escapecode = converter(value)
except ValueError as ex:
raise InvalidColr(value) from ex
return escapecode
|
def get_escape_code(self, codetype, value)
|
Convert user arg to escape code.
| 5.085949
| 5.017601
| 1.013622
|
try:
# Try explicit offset (passed in with `name`).
offset = int(name)
except (TypeError, ValueError):
name = name.lower().strip() if name else 'black'
# Black and white are separate methods.
if name == 'black':
return self.gradient_black(
text=text,
fore=fore,
back=back,
style=style,
step=int(spread) if spread else 1,
linemode=linemode,
movefactor=movefactor,
rgb_mode=rgb_mode
)
elif name == 'white':
return self.gradient_black(
text=text,
fore=fore,
back=back,
style=style,
step=int(spread) if spread else 1,
linemode=linemode,
movefactor=movefactor,
reverse=True,
rgb_mode=rgb_mode
)
try:
# Get rainbow offset from known name.
offset = self.gradient_names[name]
except KeyError:
raise ValueError('Unknown gradient name: {}'.format(name))
return self.rainbow(
text=text,
fore=fore,
back=back,
style=style,
offset=offset,
freq=freq,
spread=spread or 3.0,
linemode=linemode,
movefactor=movefactor,
rgb_mode=rgb_mode,
)
|
def gradient(
self, text=None, name=None, fore=None, back=None, style=None,
freq=0.1, spread=None, linemode=True,
movefactor=2, rgb_mode=False)
|
Return a gradient by color name. Uses rainbow() underneath to
build the gradients, starting at a known offset.
Arguments:
text : Text to make gradient (self.data when not given).
The gradient text is joined to self.data when
this is used.
name : Color name for the gradient (same as fore names).
Default: black
fore : Fore color. Back will be gradient when used.
Default: None (fore is gradient)
back : Back color. Fore will be gradient when used.
Default: None (back=reset/normal)
style : Style for the gradient.
Default: None (reset/normal)
freq : Frequency of color change.
Higher means more colors.
Best when in the 0.0-1.0 range.
Default: 0.1
spread : Spread/width of each color (in characters).
Default: 3.0 for colors, 1 for black/white
linemode : Colorize each line in the input.
Default: True
movefactor : Factor for offset increase on each line when
using linemode.
Minimum value: 0
Default: 2
rgb_mode : Use true color (rgb) codes.
| 2.317665
| 2.248255
| 1.030873
|
gradargs = {
'step': step,
'fore': fore,
'back': back,
'style': style,
'reverse': reverse,
'rgb_mode': rgb_mode,
}
if linemode:
gradargs['movefactor'] = 2 if movefactor is None else movefactor
method = self._gradient_black_lines
else:
method = self._gradient_black_line
if text:
return self.__class__(
''.join((
self.data or '',
method(
text,
start or (255 if reverse else 232),
**gradargs)
))
)
# Operating on self.data.
return self.__class__(
method(
self.stripped(),
start or (255 if reverse else 232),
**gradargs)
)
|
def gradient_black(
self, text=None, fore=None, back=None, style=None,
start=None, step=1, reverse=False,
linemode=True, movefactor=2, rgb_mode=False)
|
Return a black and white gradient.
Arguments:
text : String to colorize.
This will always be greater than 0.
fore : Foreground color, background will be gradient.
back : Background color, foreground will be gradient.
style : Name of style to use for the gradient.
start : Starting 256-color number.
The `start` will be adjusted if it is not within
bounds.
This will always be > 15.
This will be adjusted to fit within a 6-length
gradient, or the 24-length black/white gradient.
step : Number of characters to colorize per color.
This allows a "wider" gradient.
linemode : Colorize each line in the input.
Default: True
movefactor : Factor for offset increase on each line when
using linemode.
Minimum value: 0
Default: 2
rgb_mode : Use true color (rgb) method and codes.
| 3.432805
| 3.67194
| 0.934875
|
gradargs = {
'step': step,
'fore': fore,
'back': back,
'style': style,
}
start = start or (0, 0, 0)
stop = stop or (255, 255, 255)
if linemode:
method = self._gradient_rgb_lines
gradargs['movefactor'] = movefactor
else:
method = self._gradient_rgb_line
if text:
return self.__class__(
''.join((
self.data or '',
method(
text,
start,
stop,
**gradargs
),
))
)
# Operating on self.data.
return self.__class__(
method(
self.stripped(),
start,
stop,
**gradargs
)
)
|
def gradient_rgb(
self, text=None, fore=None, back=None, style=None,
start=None, stop=None, step=1, linemode=True, movefactor=0)
|
Return a black and white gradient.
Arguments:
text : String to colorize.
fore : Foreground color, background will be gradient.
back : Background color, foreground will be gradient.
style : Name of style to use for the gradient.
start : Starting rgb value.
stop : Stopping rgb value.
step : Number of characters to colorize per color.
This allows a "wider" gradient.
This will always be greater than 0.
linemode : Colorize each line in the input.
Default: True
movefactor : Amount to shift gradient for each line when
`linemode` is set.
| 3.081911
| 3.074381
| 1.002449
|
if rgb_mode:
try:
colrval = hex2rgb(value, allow_short=True)
except ValueError:
raise InvalidColr(value)
else:
try:
colrval = hex2term(value, allow_short=True)
except ValueError:
raise InvalidColr(value)
return self.chained(text=text, fore=colrval, back=back, style=style)
|
def hex(self, value, text=None, back=None, style=None, rgb_mode=False)
|
A chained method that sets the fore color to an hex value.
Arguments:
value : Hex value to convert.
text : Text to style if not building up color codes.
back : Back color for the text.
style : Style for the text.
rgb_mode : If False, the closest extended code is used,
otherwise true color (rgb) mode is used.
| 3.557538
| 3.425175
| 1.038644
|
flat = []
for clr in colrs:
if isinstance(clr, (list, tuple, GeneratorType)):
# Flatten any lists, at least once.
flat.extend(str(c) for c in clr)
else:
flat.append(str(clr))
if colorkwargs:
fore = colorkwargs.get('fore', None)
back = colorkwargs.get('back', None)
style = colorkwargs.get('style', None)
flat = (
self.color(s, fore=fore, back=back, style=style)
for s in flat
)
return self.__class__(self.data.join(flat))
|
def join(self, *colrs, **colorkwargs)
|
Like str.join, except it returns a Colr.
Arguments:
colrs : One or more Colrs. If a list or tuple is passed as an
argument it will be flattened.
Keyword Arguments:
fore, back, style...
see color().
| 2.857291
| 2.859279
| 0.999305
|
return self.__class__(
self._str_strip('lstrip', chars),
no_closing=chars and (closing_code in chars),
)
|
def lstrip(self, chars=None)
|
Like str.lstrip, except it returns the Colr instance.
| 16.591484
| 12.854486
| 1.290716
|
print(self, *args, **kwargs)
self.data = ''
return self
|
def print(self, *args, **kwargs)
|
Chainable print method. Prints self.data and then clears it.
| 7.866806
| 3.052113
| 2.577495
|
if fore and back:
raise ValueError('Cannot use both fore and back with rainbow()')
rainbowargs = {
'freq': freq,
'spread': spread,
'offset': offset,
'fore': fore,
'back': back,
'style': style,
'rgb_mode': rgb_mode,
}
if linemode:
rainbowargs['movefactor'] = movefactor
method = self._rainbow_lines
else:
method = self._rainbow_line
if text:
# Prepend existing self.data to the rainbow text.
return self.__class__(
''.join((
self.data,
method(text, **rainbowargs)
))
)
# Operate on self.data.
return self.__class__(
method(self.stripped(), **rainbowargs)
)
|
def rainbow(
self, text=None, fore=None, back=None, style=None,
freq=0.1, offset=30, spread=3.0,
linemode=True, movefactor=2, rgb_mode=False)
|
Make rainbow gradient text.
Arguments:
text : Text to make gradient.
Default: self.data
fore : Fore color to use (makes back the rainbow).
Default: None
back : Back color to use (makes fore the rainbow).
Default: None
style : Style for the rainbow.
Default: None
freq : Frequency of color change, a higher value means
more colors.
Best results when in the range 0.0-1.0.
Default: 0.1
offset : Offset for start of rainbow.
Default: 30
spread : Spread/width of each color.
Default: 3.0,
linemode : Colorize each line in the input.
Default: True
movefactor : Factor for offset increase on each line when
using linemode.
Minimum value: 0
Default: 2
rgb_mode : Use RGB escape codes instead of extended 256 and
approximate hex matches.
| 3.0471
| 3.12434
| 0.975278
|
return self.__class__(
self._str_strip('rstrip', chars),
no_closing=chars and (closing_code in chars),
)
|
def rstrip(self, chars=None)
|
Like str.rstrip, except it returns the Colr instance.
| 18.751427
| 14.901057
| 1.258396
|
return self.__class__(
self._str_strip('strip', chars),
no_closing=chars and (closing_code in chars),
)
|
def strip(self, chars=None)
|
Like str.strip, except it returns the Colr instance.
| 20.488787
| 16.315269
| 1.255804
|
label_args = label_args or {'fore': 'red'}
value_args = value_args or {'fore': 'blue', 'style': 'bright'}
return Colr(self.default_format.format(
label=Colr(self.label, **label_args),
value=Colr(repr(self.value), **value_args),
))
|
def as_colr(self, label_args=None, value_args=None)
|
Like __str__, except it returns a colorized Colr instance.
| 2.854757
| 2.436772
| 1.171532
|
label_args = label_args or {'fore': 'red'}
type_args = type_args or {'fore': 'yellow'}
type_val_args = type_val_args or {'fore': 'grey'}
value_args = value_args or {'fore': 'blue', 'style': 'bright'}
return Colr(self.default_format.format(
label=Colr(':\n ').join(
Colr('Expecting color name/value', **label_args),
',\n '.join(
'{lbl:<5} ({val})'.format(
lbl=Colr(l, **type_args),
val=Colr(v, **type_val_args),
)
for l, v in self.accepted_values
)
),
value=Colr(repr(self.value), **value_args)
))
|
def as_colr(
self, label_args=None, type_args=None, type_val_args=None,
value_args=None)
|
Like __str__, except it returns a colorized Colr instance.
| 3.288301
| 3.152806
| 1.042976
|
label_args = label_args or {'fore': 'red'}
type_args = type_args or {'fore': 'yellow'}
type_val_args = type_val_args or {'fore': 'grey'}
value_args = value_args or {'fore': 'blue', 'style': 'bright'}
spec_args = spec_args or {'fore': 'blue'}
spec_repr = repr(self.spec)
spec_quote = spec_repr[0]
val_repr = repr(self.value)
val_quote = val_repr[0]
return Colr(self.default_format.format(
label=Colr(':\n ').join(
Colr('Bad format spec. color name/value', **label_args),
',\n '.join(
'{lbl:<5} ({val})'.format(
lbl=Colr(l, **type_args),
val=Colr(v, **type_val_args),
)
for l, v in self.accepted_values
)
),
spec=Colr('=').join(
Colr(v, **spec_args)
for v in spec_repr[1:-1].split('=')
).join((spec_quote, spec_quote)),
value=Colr(
val_repr[1:-1],
**value_args
).join((val_quote, val_quote)),
))
|
def as_colr(
self, label_args=None, type_args=None, type_val_args=None,
value_args=None, spec_args=None)
|
Like __str__, except it returns a colorized Colr instance.
| 3.008234
| 2.920432
| 1.030065
|
label_args = label_args or {'fore': 'red'}
type_args = type_args or {'fore': 'yellow'}
value_args = value_args or {'fore': 'blue', 'style': 'bright'}
return Colr(self.default_format.format(
label=Colr(':\n ').join(
Colr('Expecting style value', **label_args),
Colr(',\n ').join(
Colr(', ').join(
Colr(v, **type_args)
for v in t[1]
)
for t in _stylemap
)
),
value=Colr(repr(self.value), **value_args)
))
|
def as_colr(
self, label_args=None, type_args=None, value_args=None)
|
Like __str__, except it returns a colorized Colr instance.
| 4.052673
| 3.843014
| 1.054556
|
isatty = getattr(file, 'isatty', None)
if isatty is None:
raise TypeError(
'Cannot detect tty, file has no `isatty` method: {}'.format(
getattr(file, 'name', type(file).__name__)
)
)
if not isatty():
raise TypeError(
'This will not work, file object is not a tty: {}'.format(
getattr(file, 'name', type(file).__name__)
)
)
return True
|
def ensure_tty(file=sys.stdout)
|
Ensure a file object is a tty. It must have an `isatty` method that
returns True.
TypeError is raised if the method doesn't exist, or returns False.
| 2.702219
| 2.392602
| 1.129406
|
erase.display(method).write(file=file)
|
def erase_display(method=EraseMethod.ALL_MOVE, file=sys.stdout)
|
Clear the screen or part of the screen, and possibly moves the cursor
to the "home" position (1, 1). See `method` argument below.
Esc[<method>J
Arguments:
method: One of these possible values:
EraseMethod.END or 0:
Clear from cursor to the end of the screen.
EraseMethod.START or 1:
Clear from cursor to the start of the screen.
EraseMethod.ALL_MOVE or 2:
Clear all, and move home.
EraseMethod.ALL_ERASE or 3:
Clear all, and erase scrollback buffer.
EraseMethod.ALL_MOVE_ERASE or 4:
Like doing 2 and 3 in succession.
This is a feature of Colr. It is not standard.
Default: EraseMethod.ALL_MOVE (2)
| 17.033236
| 82.703644
| 0.205955
|
erase.line(method).write(file=file)
|
def erase_line(method=EraseMethod.ALL, file=sys.stdout)
|
Erase a line, or part of a line. See `method` argument below.
Cursor position does not change.
Esc[<method>K
Arguments:
method : One of these possible values:
EraseMethod.END or 0:
Clear from cursor to the end of the line.
EraseMethod.START or 1:
Clear from cursor to the start of the line.
EraseMethod.ALL or 2:
Clear the entire line.
Default: EraseMethod.ALL (2)
| 17.429485
| 84.661232
| 0.205873
|
move.back(columns).write(file=file)
|
def move_back(columns=1, file=sys.stdout)
|
Move the cursor back a number of columns.
Esc[<columns>D:
Moves the cursor back by the specified number of columns without
changing lines. If the cursor is already in the leftmost column,
ANSI.SYS ignores this sequence.
| 13.212356
| 64.176422
| 0.205876
|
move.column(column).write(file=file)
|
def move_column(column=1, file=sys.stdout)
|
Move the cursor to the specified column, default 1.
Esc[<column>G
| 14.742959
| 38.8727
| 0.379263
|
move.down(lines).write(file=file)
|
def move_down(lines=1, file=sys.stdout)
|
Move the cursor down a number of lines.
Esc[<lines>B:
Moves the cursor down by the specified number of lines without
changing columns. If the cursor is already on the bottom line,
ANSI.SYS ignores this sequence.
| 15.029803
| 50.186413
| 0.29948
|
move.forward(columns).write(file=file)
|
def move_forward(columns=1, file=sys.stdout)
|
Move the cursor forward a number of columns.
Esc[<columns>C:
Moves the cursor forward by the specified number of columns without
changing lines. If the cursor is already in the rightmost column,
ANSI.SYS ignores this sequence.
| 13.570612
| 55.153614
| 0.246051
|
move.next(lines).write(file=file)
|
def move_next(lines=1, file=sys.stdout)
|
Move the cursor to the beginning of the line, a number of lines down.
Default: 1
Esc[<lines>E
| 15.482288
| 45.669262
| 0.339009
|
move.pos(line=line, col=column).write(file=file)
|
def move_pos(line=1, column=1, file=sys.stdout)
|
Move the cursor to a new position. Values are 1-based, and default
to 1.
Esc[<line>;<column>H
or
Esc[<line>;<column>f
| 10.317538
| 20.057451
| 0.514399
|
move.prev(lines).write(file=file)
|
def move_prev(lines=1, file=sys.stdout)
|
Move the cursor to the beginning of the line, a number of lines up.
Default: 1
Esc[<lines>F
| 13.608455
| 40.191471
| 0.338591
|
move.up(lines).write(file=file)
|
def move_up(lines=1, file=sys.stdout)
|
Move the cursor up a number of lines.
Esc[ValueA:
Moves the cursor up by the specified number of lines without changing
columns. If the cursor is already on the top line, ANSI.SYS ignores
this sequence.
| 13.745725
| 53.140987
| 0.258665
|
kwargs.setdefault('file', sys.stdout)
kwargs.setdefault('end', '')
pos_save(file=kwargs['file'])
delay = None
with suppress(KeyError):
delay = kwargs.pop('delay')
if delay is None:
print(*args, **kwargs)
else:
for c in kwargs.get('sep', ' ').join(str(a) for a in args):
kwargs['file'].write(c)
kwargs['file'].flush()
sleep(delay)
if kwargs['end']:
kwargs['file'].write(kwargs['end'])
pos_restore(file=kwargs['file'])
# Must flush to see changes.
kwargs['file'].flush()
|
def print_inplace(*args, **kwargs)
|
Save cursor position, write some text, and then restore the position.
Arguments:
Same as `print()`.
Keyword Arguments:
Same as `print()`, except `end` defaults to '' (empty str),
and these:
delay : Time in seconds between character writes.
| 3.106008
| 3.021265
| 1.028049
|
kwargs.setdefault('file', sys.stdout)
print(*args, **kwargs)
kwargs['file'].flush()
|
def print_flush(*args, **kwargs)
|
Like `print()`, except the file is `.flush()`ed afterwards.
| 3.222153
| 2.505953
| 1.2858
|
kwargs.setdefault('file', sys.stdout)
kwargs.setdefault('end', '')
delay = None
with suppress(KeyError):
delay = kwargs.pop('delay')
erase_line()
# Move to the beginning of the line.
move_column(1, file=kwargs['file'])
if delay is None:
print(*args, **kwargs)
else:
for c in kwargs.get('sep', ' ').join(str(a) for a in args):
kwargs['file'].write(c)
kwargs['file'].flush()
sleep(delay)
if kwargs['end']:
kwargs['file'].write(kwargs['end'])
kwargs['file'].flush()
|
def print_overwrite(*args, **kwargs)
|
Move to the beginning of the current line, and print some text.
Arguments:
Same as `print()`.
Keyword Arguments:
Same as `print()`, except `end` defaults to '' (empty str),
and these:
delay : Time in seconds between character writes.
| 3.112555
| 3.050559
| 1.020323
|
scroll.down(lines).write(file=file)
|
def scroll_down(lines=1, file=sys.stdout)
|
Scroll the whole page down a number of lines, new lines are added to
the top.
Esc[<lines>T
| 17.269308
| 31.460703
| 0.548917
|
scroll.up(lines).write(file=file)
|
def scroll_up(lines=1, file=sys.stdout)
|
Scroll the whole page up a number of lines, new lines are added to
the bottom.
Esc[<lines>S
| 15.516645
| 30.823534
| 0.503403
|
return self.chained(erase.display(method))
|
def erase_display(self, method=EraseMethod.ALL_MOVE)
|
Clear the screen or part of the screen.
Arguments:
method: One of these possible values:
EraseMethod.END or 0:
Clear from cursor to the end of the screen.
EraseMethod.START or 1:
Clear from cursor to the start of the screen.
EraseMethod.ALL_MOVE or 2:
Clear all, and move home.
EraseMethod.ALL_ERASE or 3:
Clear all, and erase scrollback buffer.
EraseMethod.ALL_MOVE_ERASE or 4:
Like doing 2 and 3 in succession.
This is a feature of Colr. It is not standard.
Default: EraseMethod.ALL_MOVE (2)
| 41.339214
| 65.262535
| 0.633429
|
return self.chained(erase.line(method=method))
|
def erase_line(self, method=EraseMethod.ALL)
|
Erase a line, or part of a line.
Arguments:
method : One of these possible values:
EraseMethod.END or 0:
Clear from cursor to the end of the line.
EraseMethod.START or 1:
Clear from cursor to the start of the line.
EraseMethod.ALL or 2:
Clear the entire line.
Default: EraseMethod.ALL (2)
| 26.040079
| 33.136776
| 0.785836
|
codes = self.data.split(escape_sequence)
if not codes:
return ''
return ''.join((escape_sequence, codes[-1]))
|
def last_code(self)
|
Return the last escape code in `self.data`.
If no escape codes are found, '' is returned.
| 9.468235
| 5.166511
| 1.832617
|
return self.chained(move.pos(line=line, column=column))
|
def move_pos(self, line=1, column=1)
|
Move the cursor to a new position.
Default: line 1, column 1
| 12.078508
| 14.922333
| 0.809425
|
# Subtracting one from the count means the code mentioned is
# truly repeated exactly `count` times.
# Control().move_up().repeat(3) ==
# Control().move_up().move_up().move_up()
try:
return self.__class__(''.join((
str(self),
self.last_code() * (count - 1),
)))
except TypeError as ex:
raise TypeError(
'`count` must be an integer. Got: {!r}'.format(count)
) from ex
|
def repeat(self, count=2)
|
Repeat the last control code a number of times.
Returns a new Control with this one's data and the repeated code.
| 6.977489
| 6.191569
| 1.126934
|
try:
return self.__class__(''.join(str(self) * count))
except TypeError:
raise TypeError(
'`count` must be an integer. Got: {!r}'.format(count)
)
|
def repeat_all(self, count=2)
|
Repeat this entire Control code a number of times.
Returns a new Control with this one's data repeated.
| 4.702276
| 4.168819
| 1.127964
|
if not hexval:
raise ValueError(
'Expecting hex string (#RGB, #RRGGBB), got nothing: {!r}'.format(
hexval
)
)
try:
hexval = hexval.strip().lstrip('#')
except AttributeError:
raise ValueError(
'Expecting hex string (#RGB, #RRGGBB), got: ({}) {!r}'.format(
type(hexval).__name__,
hexval
)
)
if allow_short:
hexval = fix_hex(hexval)
if not len(hexval) == 6:
raise ValueError(
'Not a length 3 or 6 hex string (#RGB, #RRGGBB), got: {}'.format(
hexval
)
)
try:
val = tuple(
int(''.join(hexval[i:i + 2]), 16)
for i in range(0, len(hexval), 2)
)
except ValueError:
# Bad hex string.
raise ValueError('Invalid hex value: {}'.format(hexval))
# Only needed to satisft typing. `return val` would work fine.
r, g, b = val
return r, g, b
|
def hex2rgb(hexval: str, allow_short: bool = False) -> RGB
|
Return a tuple of (R, G, B) from a hex color.
| 2.978774
| 2.912093
| 1.022898
|
return rgb2term(*hex2rgb(hexval, allow_short=allow_short))
|
def hex2term(hexval: str, allow_short: bool = False) -> str
|
Convert a hex value into the nearest terminal code number.
| 5.308904
| 4.174057
| 1.271881
|
return rgb2termhex(*hex2rgb(hexval, allow_short=allow_short))
|
def hex2termhex(hexval: str, allow_short: bool = False) -> str
|
Convert a hex value into the nearest terminal color matched hex.
| 5.610908
| 3.519236
| 1.594354
|
for code in sorted(term2hex_map):
print(' '.join((
'\033[48;5;{code}m{code:<3}:{hexval:<6}\033[0m',
'\033[38;5;{code}m{code:<3}:{hexval:<6}\033[0m'
)).format(code=code, hexval=term2hex_map[code]))
|
def print_all() -> None
|
Print all 256 xterm color codes.
| 3.819411
| 2.994205
| 1.275601
|
return '{:02x}{:02x}{:02x}'.format(r, g, b)
|
def rgb2hex(r: int, g: int, b: int) -> str
|
Convert rgb values to a hex code.
| 2.83791
| 2.075357
| 1.367432
|
return hex2term_map[rgb2termhex(r, g, b)]
|
def rgb2term(r: int, g: int, b: int) -> str
|
Convert an rgb value to a terminal code.
| 14.516825
| 8.108134
| 1.790403
|
incs = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]
res = []
parts = r, g, b
for part in parts:
if (part < 0) or (part > 255):
raise ValueError(
'Expecting 0-255 for RGB code, got: {!r}'.format(parts)
)
i = 0
while i < len(incs) - 1:
s, b = incs[i], incs[i + 1] # smaller, bigger
if s <= part <= b:
s1 = abs(s - part)
b1 = abs(b - part)
if s1 < b1:
closest = s
else:
closest = b
res.append(closest)
break
i += 1
# Convert back into nearest hex value.
return rgb2hex(*res)
|
def rgb2termhex(r: int, g: int, b: int) -> str
|
Convert an rgb value to the nearest hex value that matches a term code.
The hex value will be one in `hex2term_map`.
| 3.365723
| 3.096089
| 1.087089
|
try:
val = term2hex_map.get('{:02}'.format(int(code), default))
except ValueError:
raise ValueError(
'Expecting an int or number string, got: {} ({})'.format(
code,
getattr(code, '__name__', type(code).__name__)))
return val
|
def term2hex(code: Numeric, default: Optional[str] = None) -> str
|
Convenience function for term2hex_map.get(code, None).
Accepts strs or ints in the form of: 1, 01, 123.
Returns `default` if the code is not found.
| 5.959526
| 4.748889
| 1.254931
|
if -1 < code < 256:
self.code = '{:02}'.format(code)
self.hexval = term2hex(code)
self.rgb = hex2rgb(self.hexval)
else:
raise ValueError(' '.join((
'Code must be in the range 0-255, inclusive.',
'Got: {} ({})'
)).format(code, getattr(code, '__name__', type(code).__name__)))
|
def _init_code(self, code: int) -> None
|
Initialize from an int terminal code.
| 3.900998
| 3.452839
| 1.129794
|
self.hexval = hex2termhex(fix_hex(hexval))
self.code = hex2term(self.hexval)
self.rgb = hex2rgb(self.hexval)
|
def _init_hex(self, hexval: str) -> None
|
Initialize from a hex value string.
| 6.606351
| 5.531696
| 1.194272
|
if self.rgb_mode:
self.rgb = (r, g, b)
self.hexval = rgb2hex(r, g, b)
else:
self.rgb = hex2rgb(rgb2termhex(r, g, b))
self.hexval = rgb2termhex(r, g, b)
self.code = hex2term(self.hexval)
|
def _init_rgb(self, r: int, g: int, b: int) -> None
|
Initialize from red, green, blue args.
| 3.182705
| 2.856157
| 1.114331
|
if self.rgb_mode:
colorcode = '\033[38;2;{};{};{}m'.format(*self.rgb)
else:
colorcode = '\033[38;5;{}m'.format(self.code)
return '{code}{s}\033[0m'.format(code=colorcode, s=self)
|
def example(self) -> str
|
Same as str(self), except the color codes are actually used.
| 3.022236
| 2.486077
| 1.215665
|
c = cls()
c._init_code(code)
return c
|
def from_code(cls, code: int) -> 'ColorCode'
|
Return a ColorCode from a terminal code.
| 7.522565
| 5.845274
| 1.286948
|
c = cls()
c._init_hex(hexval)
return c
|
def from_hex(cls, hexval: str) -> 'ColorCode'
|
Return a ColorCode from a hex string.
| 7.296002
| 5.792008
| 1.259667
|
c = cls()
c._init_rgb(r, g, b)
return c
|
def from_rgb(cls, r: int, g: int, b: int) -> 'ColorCode'
|
Return a ColorCode from a RGB tuple.
| 5.227483
| 4.116353
| 1.269931
|
'''Used as a decorator for automatically making session commits'''
def wrap(**kwarg):
with session_withcommit() as session:
a = func(**kwarg)
session.add(a)
return session.query(songs).order_by(
songs.song_id.desc()).first().song_id
return wrap
|
def commit(func)
|
Used as a decorator for automatically making session commits
| 7.841915
| 5.855361
| 1.339271
|
with session_withcommit() as session:
val = session.query(songs).all()
for row in val:
yield row
|
def get_songs()->Iterator
|
Return songs that have the fingerprinted flag set TRUE (1).
| 10.598174
| 8.878196
| 1.193731
|
try:
hub = _local.hub
except AttributeError:
# The Hub can only be instantiated from the root fiber. No other fibers
# can run until the Hub is there, so the root will always be the first
# one to call get_hub().
assert fibers.current().parent is None
hub = _local.hub = Hub()
return hub
|
def get_hub()
|
Return the instance of the hub.
| 7.827002
| 7.377745
| 1.060893
|
hub = get_hub()
try:
with switch_back(secs, hub):
hub.switch()
except Timeout:
pass
|
def sleep(secs)
|
Sleep for *secs* seconds. The *secs* argument can be an int or a float.
| 13.019621
| 14.296601
| 0.910679
|
if self._hub is None or not self._fiber.is_alive():
return
self._hub.run_callback(self._fiber.switch, value)
self._hub = self._fiber = None
|
def switch(self, value=None)
|
Switch back to the origin fiber. The fiber is switch in next time
the event loop runs.
| 6.788916
| 4.823166
| 1.407564
|
# The might seem redundant with self._fiber.cancel(exc), but it isn't
# as self._fiber might be a "raw" fibers.Fiber() that doesn't have a
# cancel() method.
if self._hub is None or not self._fiber.is_alive():
return
self._hub.run_callback(self._fiber.throw, typ, val, tb)
self._hub = self._fiber = None
|
def throw(self, typ, val=None, tb=None)
|
Throw an exception into the origin fiber. The exception is thrown
the next time the event loop runs.
| 8.427432
| 7.861089
| 1.072044
|
if self._loop is None:
return
if fibers.current().parent is not None:
raise RuntimeError('close() may only be called in the root fiber')
elif compat.get_thread_ident() != self._thread:
raise RuntimeError('cannot close() from a different thread')
self._closing = True
self._interrupt_loop()
# Note how we are switching to the Hub without a switchback condition
# being in place. This works because the hub is our child and upon
# a child fiber exit its parent is switched in.
self.switch()
|
def close(self)
|
Close the hub and wait for it to be closed.
This may only be called in the root fiber. After this call returned,
Gruvi cannot be used anymore in the current thread. The main use case
for calling this method is to clean up resources in a multi-threaded
program where you want to exit a thead but not yet the entire process.
| 10.715832
| 9.144408
| 1.171845
|
if self._loop is None or not self.is_alive():
raise RuntimeError('hub is closed/dead')
elif fibers.current() is self:
raise RuntimeError('cannot switch to myself')
elif compat.get_thread_ident() != self._thread:
raise RuntimeError('cannot switch from a different thread')
value = super(Hub, self).switch()
# A fiber exit will cause its parent to be switched to. All fibers in
# the system should be children of the Hub, *except* the Hub itself
# which is a child of the root fiber. So do an explicit check here to
# see if the Hub exited unexpectedly, and if so raise an error.
if fibers.current().parent is None and not self.is_alive() \
and self._loop is not None:
raise RuntimeError('hub exited unexpectedly')
return value
|
def switch(self)
|
Switch to the hub.
This method pauses the current fiber and runs the event loop. The
caller should ensure that it has set up appropriate callbacks so that
it will get scheduled again, preferably using :class:`switch_back`. In
this case then return value of this method will be an ``(args,
kwargs)`` tuple containing the arguments passed to the switch back
instance.
If this method is called from the root fiber then there are two
additional cases. If the hub exited due to a call to :meth:`close`,
then this method returns None. And if the hub exited due to a
exception, that exception is re-raised here.
| 6.222111
| 5.45582
| 1.140454
|
for i in range(len(self._callbacks)):
callback, args = self._callbacks.popleft()
try:
callback(*args)
except Exception:
self._log.exception('Ignoring exception in callback:')
|
def _run_callbacks(self)
|
Run registered callbacks.
| 3.708784
| 3.459443
| 1.072075
|
if self._loop is None:
raise RuntimeError('hub is closed')
elif not callable(callback):
raise TypeError('"callback": expecting a callable')
self._callbacks.append((callback, args)) # thread-safe
self._interrupt_loop()
|
def run_callback(self, callback, *args)
|
Queue a callback.
The *callback* will be called with positional arguments *args* in the
next iteration of the event loop. If you add multiple callbacks, they
will be called in the order that you added them. The callback will run
in the Hub's fiber.
This method is thread-safe: it is allowed to queue a callback from a
different thread than the one running the Hub.
| 7.091252
| 6.533297
| 1.085402
|
method = message.get('method')
msgid = message.get('id')
error = message.get('error')
if method and msgid is not None:
return 'method call "{}", id = "{}"'.format(method, msgid)
elif method:
return 'notification "{}"'.format(method)
elif error is not None and msgid is not None:
return 'error reply to id = "{}"'.format(msgid)
elif error is not None:
code = error.get('code', '(none)')
return 'error reply: {}'.format(errorcode.get(code, code))
else:
return 'method return for id = "{}"'.format(msgid)
|
def message_info(message)
|
Return a string describing a message, for debugging purposes.
| 3.319474
| 3.13478
| 1.058918
|
msgid = self._id_template.format(self._next_id)
self._next_id += 1
return msgid
|
def next_id(self)
|
Return a unique message ID.
| 4.806779
| 3.5808
| 1.342376
|
clsname = 'JsonRpcV{}'.format(version.rstrip('.0'))
cls = globals()[clsname]
return cls(version)
|
def create(version)
|
Return a new instance for *version*, which can be either `'1.0'`
or `'2.0'`.
| 9.714378
| 8.650903
| 1.122932
|
if self._error:
raise compat.saved_exc(self._error)
elif self._transport is None:
raise JsonRpcError('not connected')
self._version.check_message(message)
self._writer.write(serialize(message))
|
def send_message(self, message)
|
Send a raw JSON-RPC message.
The *message* argument must be a dictionary containing a valid JSON-RPC
message according to the version passed into the constructor.
| 8.633469
| 7.646422
| 1.129086
|
message = self._version.create_request(method, args)
msgid = message['id']
try:
with switch_back(self._timeout) as switcher:
self._method_calls[msgid] = switcher
self.send_message(message)
args, _ = self._hub.switch()
finally:
self._method_calls.pop(msgid, None)
response = args[0]
assert response['id'] == msgid
error = response.get('error')
if error is not None:
raise JsonRpcError('error response calling "{}"'.format(method), error)
return response['result']
|
def call_method(self, method, *args)
|
Call a JSON-RPC method and wait for its result.
The *method* is called with positional arguments *args*.
On success, the ``result`` field from the JSON-RPC response is
returned. On error, a :class:`JsonRpcError` is raised, which you can
use to access the ``error`` field of the JSON-RPC response.
| 4.717465
| 4.49833
| 1.048715
|
message = self._version.create_request(method, args, notification=True)
self.send_message(message)
|
def send_notification(self, method, *args)
|
Send a JSON-RPC notification.
The notification *method* is sent with positional arguments *args*.
| 6.376943
| 6.820117
| 0.93502
|
message = self._version.create_response(request, result, error)
self.send_message(message)
|
def send_response(self, request, result=None, error=None)
|
Respond to a JSON-RPC method call.
This is a response to the message in *request*. If *error* is not
provided, then this is a succesful response, and the value in *result*,
which may be ``None``, is passed back to the client. if *error* is
provided and not ``None`` then an error is sent back. In this case
*error* must be a dictionary as specified by the JSON-RPC spec.
| 6.107928
| 6.30113
| 0.969339
|
sig = getattr(pobj, 'dbusSignature', None)
if sig is not None:
return sig
elif isinstance(pobj, int): return 'i'
elif isinstance(pobj, six.integer_types): return 'x'
elif isinstance(pobj, float): return 'd'
elif isinstance(pobj, six.string_types): return 's'
elif isinstance(pobj, list):
vtype = type(pobj[0])
same = True
for v in pobj[1:]:
if not vtype is type(v):
same = False
if same:
return 'a' + sigFromPy(pobj[0])
else:
return 'av'
elif isinstance(pobj, dict):
same = True
vtype = None
for k,v in six.iteritems(pobj):
if vtype is None:
vtype = type(v)
elif not vtype is type(v):
same = False
if same:
return 'a{' + sigFromPy(k) + sigFromPy(v) + '}'
else:
return 'a{' + sigFromPy(k) + 'v}'
else:
raise MarshallingError('Invalid Python type for variant: ' + repr(pobj))
|
def sigFromPy( pobj )
|
Returns the DBus signature type for the argument. If the argument is an
instance of one of the type wrapper classes, the exact type signature
corresponding to the wrapper class will be used. If the object has a
variable named 'dbusSignature', the value of that variable will be
used. Otherwise, a generic type will be used (i.e "i" for a Python int)
@rtype: C{string}
@returns: The DBus signature for the supplied Python object
| 2.323407
| 2.358946
| 0.984934
|
i = 0
start = 0
end = len(compoundSig)
def find_end( idx, b, e ):
depth = 1
while idx < end:
subc = compoundSig[idx]
if subc == b:
depth += 1
elif subc == e:
depth -= 1
if depth == 0:
return idx
idx += 1
while i < end:
c = compoundSig[i]
if c == '(':
x = find_end(i+1, '(', ')')
yield compoundSig[i:x+1]
i = x
elif c == '{':
x = find_end(i+1, '{', '}')
yield compoundSig[i:x+1]
i = x
elif c == 'a':
start = i
g = genCompleteTypes( compoundSig[i+1:] )
ct = six.next(g)
i += len(ct)
yield 'a' + ct
else:
yield c
i += 1
|
def genCompleteTypes( compoundSig )
|
Generator function used to iterate over each complete,
top-level type contained in in a signature. Ex::
"iii" => [ 'i', 'i', 'i' ]
"i(ii)i" => [ 'i', '(ii)', 'i' ]
"i(i(ii))i" => [ 'i', '(i(ii))', 'i' ]
| 2.548773
| 2.550318
| 0.999394
|
chunks = list()
bstart = startByte
if hasattr(variableList, 'dbusOrder'):
order = getattr(variableList, 'dbusOrder')
variableList = [ getattr(variableList, attr_name) for attr_name in order ]
for ct, var in zip(genCompleteTypes( compoundSignature ), variableList):
tcode = ct[0]
padding = pad[tcode]( startByte )
if padding:
startByte += len(padding)
chunks.append( padding )
nbytes, vchunks = marshallers[ tcode ]( ct, var, startByte, lendian )
startByte += nbytes
chunks.extend( vchunks )
return startByte - bstart, chunks
|
def marshal( compoundSignature, variableList, startByte = 0, lendian=True )
|
Encodes the Python objects in variableList into the DBus wire-format
matching the supplied compoundSignature. This function retuns a list of
binary strings is rather than a single string to simplify the recursive
marshalling algorithm. A single string may be easily obtained from the
result via: ''.join(list_of_binary_strings)
@type compoundSignature: C{string}
@param compoundSignature: DBus signature specifying the types of the
variables to encode
@type variableList: C{list}
@param variableList: List of variables to encode (length of the list
must exactly match the number of variables specified
in compoundSignature
@type startByte: C{int}
@param startByte: Used during recursive marshalling to ensure data
alignment requirements are met
@type lendian: C{bool}
@param lendian: True if the data should be serialized in
little-endian format
@returns: (number_of_encoded_bytes, list_of_binary_strings)
| 5.921398
| 6.093809
| 0.971707
|
values = list()
start_offset = offset
for ct in genCompleteTypes( compoundSignature ):
tcode = ct[0]
offset += len(pad[tcode]( offset ))
nbytes, value = unmarshallers[ tcode ]( ct, data, offset, lendian )
offset += nbytes
values.append( value )
return offset - start_offset, values
|
def unmarshal( compoundSignature, data, offset = 0, lendian = True )
|
Unmarshals DBus encoded data.
@type compoundSignature: C{string}
@param compoundSignature: DBus signature specifying the encoded value types
@type data: C{string}
@param data: Binary data
@type offset: C{int}
@param offset: Offset within data at which data for compoundSignature
starts (used during recursion)
@type lendian: C{bool}
@param lendian: True if data is encoded in little-endian format
@returns: (number_of_bytes_decoded, list_of_values)
| 8.396681
| 9.319103
| 0.901018
|
fiber = Fiber(func, args, **kwargs)
fiber.start()
return fiber
|
def spawn(func, *args, **kwargs)
|
Spawn a new fiber.
A new :class:`Fiber` is created with main function *func* and positional
arguments *args*. The keyword arguments are passed to the :class:`Fiber`
constructor, not to the main function. The fiber is then scheduled to start
by calling its :meth:`~Fiber.start` method.
The fiber instance is returned.
| 6.587849
| 9.247536
| 0.71239
|
target = getattr(self._target, '__qualname__', self._target.__name__)
self._log.debug('starting fiber {}, target {}', self.name, target)
self._hub.run_callback(self.switch)
|
def start(self)
|
Schedule the fiber to be started in the next iteration of the
event loop.
| 8.489883
| 6.768002
| 1.254415
|
if not self.is_alive():
return
if message is None:
message = 'cancelled by Fiber.cancel()'
self._hub.run_callback(self.throw, Cancelled, Cancelled(message))
|
def cancel(self, message=None)
|
Schedule the fiber to be cancelled in the next iteration of the
event loop.
Cancellation works by throwing a :class:`~gruvi.Cancelled` exception
into the fiber. If *message* is provided, it will be set as the value
of the exception.
| 8.249596
| 7.140136
| 1.155384
|
# align by diffs
diff_counter: dict = {}
largest = 0
largest_count = 0
song_id = -1
for sid, diff in matches:
if diff not in diff_counter:
diff_counter[diff] = {}
if sid not in diff_counter[diff]:
diff_counter[diff][sid] = 0
diff_counter[diff][sid] += 1
if diff_counter[diff][sid] > largest_count:
largest = diff
largest_count = diff_counter[diff][sid]
song_id = sid
# extract idenfication
song = database.get_song_by_id(song_id)
if song:
songname = song.song_name
else:
return None
# return match info
nseconds = round(
float(largest) / fingerprint.DEFAULT_FS *
fingerprint.DEFAULT_WINDOW_SIZE * fingerprint.DEFAULT_OVERLAP_RATIO,
5
)
song = {
'song_id': song_id,
'song_name': songname,
MetaMusic.CONFIDENCE: largest_count,
MetaMusic.OFFSET: int(largest),
'offset_seconds': nseconds,
'file_sha1': binascii.hexlify(song.file_sha1).decode('utf-8'),
}
return song
|
def align_matches(self, matches: list)->Optional[dict]
|
Finds hash matches that align in time with other matches and finds
consensus about which hashes are "true" signal from the audio.
Returns a dictionary with match information.
| 3.581374
| 3.665572
| 0.97703
|
if isinstance(address, six.string_types):
return address
elif isinstance(address, tuple) and len(address) >= 2 and ':' in address[0]:
return '[{}]:{}'.format(address[0], address[1])
elif isinstance(address, tuple) and len(address) >= 2:
return '{}:{}'.format(*address)
else:
raise TypeError('illegal address type: {!s}'.format(type(address)))
|
def saddr(address)
|
Return a string representation for an address.
The *address* paramater can be a pipe name, an IP address tuple, or a
socket address.
The return value is always a ``str`` instance.
| 2.346036
| 2.429117
| 0.965798
|
if not isinstance(address, six.string_types):
raise TypeError('expecting a string')
if address.startswith('['):
p1 = address.find(']:')
if p1 == -1:
raise ValueError
return (address[1:p1], int(address[p1+2:]))
elif ':' in address:
p1 = address.find(':')
return (address[:p1], int(address[p1+1:]))
else:
return address
|
def paddr(address)
|
Parse a string representation of an address.
This function is the inverse of :func:`saddr`.
| 2.228286
| 2.36068
| 0.943917
|
hub = get_hub()
with switch_back(timeout) as switcher:
request = pyuv.dns.getaddrinfo(hub.loop, node, service, family,
socktype, protocol, flags, callback=switcher)
switcher.add_cleanup(request.cancel)
result = hub.switch()
result, error = result[0]
if error:
message = pyuv.errno.strerror(error)
raise pyuv.error.UVError(error, message)
return result
|
def getaddrinfo(node, service=0, family=0, socktype=0, protocol=0, flags=0, timeout=30)
|
Resolve an Internet *node* name and *service* into a socket address.
The *family*, *socktype* and *protocol* are optional arguments that specify
the address family, socket type and protocol, respectively. The *flags*
argument allows you to pass flags to further modify the resolution process.
See the :func:`socket.getaddrinfo` function for a detailed description of
these arguments.
The return value is a list of ``(family, socktype, proto, canonname,
sockaddr)`` tuples. The fifth element (``sockaddr``) is the socket address.
It will be a 2-tuple ``(addr, port)`` for an IPv4 address, and a 4-tuple
``(addr, port, flowinfo, scopeid)`` for an IPv6 address.
The address resolution is performed in the libuv thread pool.
| 4.420155
| 5.159818
| 0.856649
|
hub = get_hub()
with switch_back(timeout) as switcher:
request = pyuv.dns.getnameinfo(hub.loop, sockaddr, flags, callback=switcher)
switcher.add_cleanup(request.cancel)
result = hub.switch()
result, error = result[0]
if error:
message = pyuv.errno.strerror(error)
raise pyuv.error.UVError(error, message)
return result
|
def getnameinfo(sockaddr, flags=0, timeout=30)
|
Resolve a socket address *sockaddr* back to a ``(node, service)`` tuple.
The *flags* argument can be used to modify the resolution process. See the
:func:`socket.getnameinfo` function for more information.
The address resolution is performed in the libuv thread pool.
| 4.875609
| 5.56909
| 0.875477
|
return codegrabpat.findall(str(s))
|
def get_codes(s: Union[str, 'ChainedBase']) -> List[str]
|
Grab all escape codes from a string.
Returns a list of all escape codes.
| 80.976723
| 61.245247
| 1.322172
|
indices = {}
i = 0
codes = get_codes(s)
for code in codes:
codeindex = s.index(code)
realindex = i + codeindex
indices[realindex] = code
codelen = len(code)
i = realindex + codelen
s = s[codeindex + codelen:]
return indices
|
def get_code_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]
|
Retrieve a dict of {index: escape_code} for a given string.
If no escape codes are found, an empty dict is returned.
| 3.142089
| 3.237846
| 0.970425
|
codes = get_code_indices(s)
if not codes:
# This function is not for non-escape-code stuff, but okay.
return {i: c for i, c in enumerate(s)}
indices = {}
for codeindex in sorted(codes):
code = codes[codeindex]
if codeindex == 0:
indices[codeindex] = code
continue
# Grab characters before codeindex.
start = max(indices or {0: ''}, key=int)
startcode = indices.get(start, '')
startlen = start + len(startcode)
indices.update({i: s[i] for i in range(startlen, codeindex)})
indices[codeindex] = code
if not indices:
return {i: c for i, c in enumerate(s)}
lastindex = max(indices, key=int)
lastitem = indices[lastindex]
start = lastindex + len(lastitem)
textlen = len(s)
if start < (textlen - 1):
# Grab chars after last code.
indices.update({i: s[i] for i in range(start, textlen)})
return indices
|
def get_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]
|
Retrieve a dict of characters and escape codes with their real index
into the string as the key.
| 3.371908
| 3.27824
| 1.028573
|
return codepat.sub('', str(s) if (s or (s == 0)) else '')
|
def strip_codes(s: Union[str, 'ChainedBase']) -> str
|
Strip all color codes from a string.
Returns empty string for "falsey" inputs (except 0).
| 22.404245
| 16.43046
| 1.36358
|
if self._poll is None:
raise RuntimeError('poll instance is closed')
if events & ~(READABLE|WRITABLE):
raise ValueError('illegal event mask: {}'.format(events))
if events & READABLE:
self._readers += 1
if events & WRITABLE:
self._writers += 1
handle = add_callback(self, callback, events)
self._sync()
return handle
|
def add_callback(self, events, callback)
|
Add a new callback.
| 3.992176
| 4.000916
| 0.997816
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.