repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
welbornprod/colr | colr/progress.py | AnimatedProgress._advance_frame | def _advance_frame(self):
""" Sets `self.current_frame` to the next frame, looping to the
beginning if needed.
"""
self.current_frame += 1
if self.current_frame == self.frame_len:
self.current_frame = 0 | python | def _advance_frame(self):
""" Sets `self.current_frame` to the next frame, looping to the
beginning if needed.
"""
self.current_frame += 1
if self.current_frame == self.frame_len:
self.current_frame = 0 | Sets `self.current_frame` to the next frame, looping to the
beginning if needed. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L568-L574 |
welbornprod/colr | colr/progress.py | AnimatedProgress._get_delay | def _get_delay(self, userdelay, frameslist):
""" Get the appropriate delay value to use, trying in this order:
userdelay
frameslist.delay
default_delay
The user can override the frameslist's delay by specifiying a
value, and if neither are... | python | def _get_delay(self, userdelay, frameslist):
""" Get the appropriate delay value to use, trying in this order:
userdelay
frameslist.delay
default_delay
The user can override the frameslist's delay by specifiying a
value, and if neither are... | Get the appropriate delay value to use, trying in this order:
userdelay
frameslist.delay
default_delay
The user can override the frameslist's delay by specifiying a
value, and if neither are given the default is used. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L576-L590 |
welbornprod/colr | colr/progress.py | AnimatedProgress.write_char_delay | def write_char_delay(self, ctl, delay):
""" Write the formatted format pieces in order, applying a delay
between characters for the text only.
"""
for i, fmt in enumerate(self.fmt):
if '{text' in fmt:
# The text will use a write delay.
ctl.... | python | def write_char_delay(self, ctl, delay):
""" Write the formatted format pieces in order, applying a delay
between characters for the text only.
"""
for i, fmt in enumerate(self.fmt):
if '{text' in fmt:
# The text will use a write delay.
ctl.... | Write the formatted format pieces in order, applying a delay
between characters for the text only. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L600-L624 |
welbornprod/colr | colr/progress.py | ProgressBar.update | def update(self, percent=None, text=None):
""" Update the progress bar percentage and message. """
if percent is not None:
self.percent = percent
if text is not None:
self.message = text
super().update() | python | def update(self, percent=None, text=None):
""" Update the progress bar percentage and message. """
if percent is not None:
self.percent = percent
if text is not None:
self.message = text
super().update() | Update the progress bar percentage and message. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress.py#L754-L760 |
welbornprod/colr | colr/progress_frames.py | cls_get_by_name | def cls_get_by_name(cls, name):
""" Return a class attribute by searching the attributes `name` attribute.
"""
try:
val = getattr(cls, name)
except AttributeError:
for attr in (a for a in dir(cls) if not a.startswith('_')):
try:
val = getattr(cls, attr)
... | python | def cls_get_by_name(cls, name):
""" Return a class attribute by searching the attributes `name` attribute.
"""
try:
val = getattr(cls, name)
except AttributeError:
for attr in (a for a in dir(cls) if not a.startswith('_')):
try:
val = getattr(cls, attr)
... | Return a class attribute by searching the attributes `name` attribute. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L39-L60 |
welbornprod/colr | colr/progress_frames.py | cls_names | def cls_names(cls, wanted_cls, registered=True):
""" Return a list of attributes for all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
return [
fset.name
for fset in cls_sets(cls, wanted_cls, registered=registered)
] | python | def cls_names(cls, wanted_cls, registered=True):
""" Return a list of attributes for all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
return [
fset.name
for fset in cls_sets(cls, wanted_cls, registered=registered)
] | Return a list of attributes for all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L63-L70 |
welbornprod/colr | colr/progress_frames.py | cls_register | def cls_register(cls, frameset, new_class, init_args, name=None):
""" Register a new FrameSet or FrameSet subclass as a member/attribute
of a class.
Returns the new FrameSet or FrameSet subclass.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
... | python | def cls_register(cls, frameset, new_class, init_args, name=None):
""" Register a new FrameSet or FrameSet subclass as a member/attribute
of a class.
Returns the new FrameSet or FrameSet subclass.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
... | Register a new FrameSet or FrameSet subclass as a member/attribute
of a class.
Returns the new FrameSet or FrameSet subclass.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
init_args : A list of properties from the `frameset` to try to use
... | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L73-L101 |
welbornprod/colr | colr/progress_frames.py | cls_sets | def cls_sets(cls, wanted_cls, registered=True):
""" Return a list of all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
sets = []
for attr in dir(cls):
if attr.startswith('_'):
continue
val = getattr(cls, attr, None)
... | python | def cls_sets(cls, wanted_cls, registered=True):
""" Return a list of all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type.
"""
sets = []
for attr in dir(cls):
if attr.startswith('_'):
continue
val = getattr(cls, attr, None)
... | Return a list of all `wanted_cls` attributes in this
class, where `wanted_cls` is the desired attribute type. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L104-L118 |
welbornprod/colr | colr/progress_frames.py | _build_color_variants | def _build_color_variants(cls):
""" Build colorized variants of all frames and return a list of
all frame object names.
"""
# Get the basic frame types first.
frametypes = cls.sets(registered=False)
_colornames = [
# 'black', disabled for now, it won't show on my terminal.
'... | python | def _build_color_variants(cls):
""" Build colorized variants of all frames and return a list of
all frame object names.
"""
# Get the basic frame types first.
frametypes = cls.sets(registered=False)
_colornames = [
# 'black', disabled for now, it won't show on my terminal.
'... | Build colorized variants of all frames and return a list of
all frame object names. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L808-L832 |
welbornprod/colr | colr/progress_frames.py | FrameSet.from_barset | def from_barset(
cls, barset, name=None, delay=None,
use_wrapper=True, wrapper=None):
""" Copy a BarSet's frames to create a new FrameSet.
Arguments:
barset : An existing BarSet object to copy frames from.
name : A name for the new... | python | def from_barset(
cls, barset, name=None, delay=None,
use_wrapper=True, wrapper=None):
""" Copy a BarSet's frames to create a new FrameSet.
Arguments:
barset : An existing BarSet object to copy frames from.
name : A name for the new... | Copy a BarSet's frames to create a new FrameSet.
Arguments:
barset : An existing BarSet object to copy frames from.
name : A name for the new FrameSet.
delay : Delay for the animation.
use_wrapper : Whether to use the old bar... | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L378-L402 |
welbornprod/colr | colr/progress_frames.py | BarSet.as_gradient | def as_gradient(self, name=None, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.gradient`.
Arguments:
name : Starting color name. One of `Colr.gradient_names`.
"""
return self._as_gradient(
('wrapper', ),
name=n... | python | def as_gradient(self, name=None, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.gradient`.
Arguments:
name : Starting color name. One of `Colr.gradient_names`.
"""
return self._as_gradient(
('wrapper', ),
name=n... | Wrap each frame in a Colr object, using `Colr.gradient`.
Arguments:
name : Starting color name. One of `Colr.gradient_names`. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L440-L450 |
welbornprod/colr | colr/progress_frames.py | BarSet.as_percent | def as_percent(self, percent):
""" Return a string representing a percentage of this progress bar.
BarSet('1234567890', wrapper=('[, ']')).as_percent(50)
>>> '[12345 ]'
"""
if not self:
return self.wrap_str()
length = len(self)
# Using mod... | python | def as_percent(self, percent):
""" Return a string representing a percentage of this progress bar.
BarSet('1234567890', wrapper=('[, ']')).as_percent(50)
>>> '[12345 ]'
"""
if not self:
return self.wrap_str()
length = len(self)
# Using mod... | Return a string representing a percentage of this progress bar.
BarSet('1234567890', wrapper=('[, ']')).as_percent(50)
>>> '[12345 ]' | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L452-L469 |
welbornprod/colr | colr/progress_frames.py | BarSet.as_rainbow | def as_rainbow(self, offset=35, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.rainbow`. """
return self._as_rainbow(
('wrapper', ),
offset=offset,
style=style,
rgb_mode=rgb_mode,
) | python | def as_rainbow(self, offset=35, style=None, rgb_mode=False):
""" Wrap each frame in a Colr object, using `Colr.rainbow`. """
return self._as_rainbow(
('wrapper', ),
offset=offset,
style=style,
rgb_mode=rgb_mode,
) | Wrap each frame in a Colr object, using `Colr.rainbow`. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L471-L478 |
welbornprod/colr | colr/progress_frames.py | BarSet.from_char | def from_char(
cls, char, name=None, width=None, fill_char=None,
bounce=False, reverse=False, back_char=None, wrapper=None):
""" Create progress bar frames from a "moving" character.
The frames simulate movement of the character, from left to
right through empty s... | python | def from_char(
cls, char, name=None, width=None, fill_char=None,
bounce=False, reverse=False, back_char=None, wrapper=None):
""" Create progress bar frames from a "moving" character.
The frames simulate movement of the character, from left to
right through empty s... | Create progress bar frames from a "moving" character.
The frames simulate movement of the character, from left to
right through empty space (`fill_char`).
Arguments:
char : Character to move across the bar.
name : Name for the new ... | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L481-L515 |
welbornprod/colr | colr/progress_frames.py | BarSet.from_str | def from_str(cls, s, name=None, fill_char=None, wrapper=None):
""" Create progress bar frames from a single string.
The frames simulate growth, from an empty string to the final
string (`s`).
Arguments:
s : Final string for a complete progress bar.
... | python | def from_str(cls, s, name=None, fill_char=None, wrapper=None):
""" Create progress bar frames from a single string.
The frames simulate growth, from an empty string to the final
string (`s`).
Arguments:
s : Final string for a complete progress bar.
... | Create progress bar frames from a single string.
The frames simulate growth, from an empty string to the final
string (`s`).
Arguments:
s : Final string for a complete progress bar.
name : Name for the new BarSet.
fill_c... | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L518-L549 |
welbornprod/colr | colr/progress_frames.py | BarSet._generate_move | def _generate_move(
cls, char, width=None, fill_char=None,
bounce=False, reverse=True, back_char=None):
""" Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Charac... | python | def _generate_move(
cls, char, width=None, fill_char=None,
bounce=False, reverse=True, back_char=None):
""" Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Charac... | Yields strings that simulate movement of a character from left
to right. For use with `BarSet.from_char`.
Arguments:
char : Character to move across the progress bar.
width : Width for the progress bar.
Default: cl... | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L552-L597 |
welbornprod/colr | colr/progress_frames.py | BarSet.with_wrapper | def with_wrapper(self, wrapper=None, name=None):
""" Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper.
"""
name... | python | def with_wrapper(self, wrapper=None, name=None):
""" Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper.
"""
name... | Copy this BarSet, and return a new BarSet with the specified
name and wrapper.
If no name is given, `{self.name}_custom_wrapper` is used.
If no wrapper is given, the new BarSet will have no wrapper. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L599-L606 |
welbornprod/colr | colr/progress_frames.py | BarSet.wrap_str | def wrap_str(self, s=None, wrapper=None):
""" Wrap a string in self.wrapper, with some extra handling for
empty/None strings.
If `wrapper` is set, use it instead.
"""
wrapper = wrapper or (self.wrapper or ('', ''))
return str('' if s is None else s).join(wrapper) | python | def wrap_str(self, s=None, wrapper=None):
""" Wrap a string in self.wrapper, with some extra handling for
empty/None strings.
If `wrapper` is set, use it instead.
"""
wrapper = wrapper or (self.wrapper or ('', ''))
return str('' if s is None else s).join(wrapper) | Wrap a string in self.wrapper, with some extra handling for
empty/None strings.
If `wrapper` is set, use it instead. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L608-L614 |
welbornprod/colr | colr/progress_frames.py | Bars.register | def register(cls, barset, name=None):
""" Register a new BarSet as a member/attribute of this class.
Returns the new BarSet.
Arguments:
barset : An existing BarSet, or an iterable of strings.
name : New name for the BarSet, also used as the
... | python | def register(cls, barset, name=None):
""" Register a new BarSet as a member/attribute of this class.
Returns the new BarSet.
Arguments:
barset : An existing BarSet, or an iterable of strings.
name : New name for the BarSet, also used as the
... | Register a new BarSet as a member/attribute of this class.
Returns the new BarSet.
Arguments:
barset : An existing BarSet, or an iterable of strings.
name : New name for the BarSet, also used as the
classes attribute name.
... | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L632-L643 |
welbornprod/colr | colr/progress_frames.py | Frames.register | def register(cls, frameset, name=None):
""" Register a new FrameSet as a member/attribute of this class.
Returns the new FrameSet.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
name : New name for the FrameSet, also used as t... | python | def register(cls, frameset, name=None):
""" Register a new FrameSet as a member/attribute of this class.
Returns the new FrameSet.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
name : New name for the FrameSet, also used as t... | Register a new FrameSet as a member/attribute of this class.
Returns the new FrameSet.
Arguments:
frameset : An existing FrameSet, or an iterable of strings.
name : New name for the FrameSet, also used as the
classes attribute nam... | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/progress_frames.py#L685-L696 |
geertj/gruvi | lib/gruvi/transports.py | TransportError.from_errno | def from_errno(cls, errno):
"""Create a new instance from a :mod:`pyuv.errno` error code."""
message = '{}: {}'.format(pyuv.errno.errorcode.get(errno, errno),
pyuv.errno.strerror(errno))
return cls(message, errno) | python | def from_errno(cls, errno):
"""Create a new instance from a :mod:`pyuv.errno` error code."""
message = '{}: {}'.format(pyuv.errno.errorcode.get(errno, errno),
pyuv.errno.strerror(errno))
return cls(message, errno) | Create a new instance from a :mod:`pyuv.errno` error code. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L36-L40 |
geertj/gruvi | lib/gruvi/transports.py | BaseTransport.start | def start(self, protocol):
"""Bind to *protocol* and start calling callbacks on it. """
if self._protocol is not None:
raise TransportError('already started')
self._protocol = protocol
self._protocol.connection_made(self)
if self._readable:
self.resume_rea... | python | def start(self, protocol):
"""Bind to *protocol* and start calling callbacks on it. """
if self._protocol is not None:
raise TransportError('already started')
self._protocol = protocol
self._protocol.connection_made(self)
if self._readable:
self.resume_rea... | Bind to *protocol* and start calling callbacks on it. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L67-L77 |
geertj/gruvi | lib/gruvi/transports.py | BaseTransport.set_write_buffer_limits | def set_write_buffer_limits(self, high=None, low=None):
"""Set the low and high watermark for the write buffer."""
if high is None:
high = self.write_buffer_size
if low is None:
low = high // 2
if low > high:
low = high
self._write_buffer_high ... | python | def set_write_buffer_limits(self, high=None, low=None):
"""Set the low and high watermark for the write buffer."""
if high is None:
high = self.write_buffer_size
if low is None:
low = high // 2
if low > high:
low = high
self._write_buffer_high ... | Set the low and high watermark for the write buffer. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L96-L105 |
geertj/gruvi | lib/gruvi/transports.py | BaseTransport.close | def close(self):
"""Close the transport after all oustanding data has been written."""
if self._closing or self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
# If the write buffer is empty, close now. Otherwise d... | python | def close(self):
"""Close the transport after all oustanding data has been written."""
if self._closing or self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
# If the write buffer is empty, close now. Otherwise d... | Close the transport after all oustanding data has been written. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L163-L175 |
geertj/gruvi | lib/gruvi/transports.py | BaseTransport.abort | def abort(self):
"""Close the transport immediately."""
if self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
self._handle.close(self._on_close_complete)
assert self._handle.closed | python | def abort(self):
"""Close the transport immediately."""
if self._handle.closed:
return
elif self._protocol is None:
raise TransportError('transport not started')
self._handle.close(self._on_close_complete)
assert self._handle.closed | Close the transport immediately. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L177-L184 |
geertj/gruvi | lib/gruvi/transports.py | Transport.write | def write(self, data, handle=None):
"""Write *data* to the transport."""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecting a bytes-like instance, got {!r}"
.format(type(data).__name__))
if handle is not None and ... | python | def write(self, data, handle=None):
"""Write *data* to the transport."""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecting a bytes-like instance, got {!r}"
.format(type(data).__name__))
if handle is not None and ... | Write *data* to the transport. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L287-L311 |
geertj/gruvi | lib/gruvi/transports.py | Transport.write_eof | def write_eof(self):
"""Shut down the write direction of the transport."""
self._check_status()
if not self._writable:
raise TransportError('transport is not writable')
if self._closing:
raise TransportError('transport is closing')
try:
self._h... | python | def write_eof(self):
"""Shut down the write direction of the transport."""
self._check_status()
if not self._writable:
raise TransportError('transport is not writable')
if self._closing:
raise TransportError('transport is closing')
try:
self._h... | Shut down the write direction of the transport. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L318-L331 |
geertj/gruvi | lib/gruvi/transports.py | Transport.get_extra_info | def get_extra_info(self, name, default=None):
"""Get transport specific data.
In addition to the fields from :meth:`BaseTransport.get_extra_info`,
the following information is also available:
===================== ===================================================
Name ... | python | def get_extra_info(self, name, default=None):
"""Get transport specific data.
In addition to the fields from :meth:`BaseTransport.get_extra_info`,
the following information is also available:
===================== ===================================================
Name ... | Get transport specific data.
In addition to the fields from :meth:`BaseTransport.get_extra_info`,
the following information is also available:
===================== ===================================================
Name Description
===================== ==... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L337-L397 |
geertj/gruvi | lib/gruvi/transports.py | DatagramTransport._on_recv_complete | def _on_recv_complete(self, handle, addr, flags, data, error):
"""Callback used with handle.start_recv()."""
assert handle is self._handle
if error:
self._log.warning('pyuv error {} in recv callback', error)
self._protocol.error_received(TransportError.from_errno(error))
... | python | def _on_recv_complete(self, handle, addr, flags, data, error):
"""Callback used with handle.start_recv()."""
assert handle is self._handle
if error:
self._log.warning('pyuv error {} in recv callback', error)
self._protocol.error_received(TransportError.from_errno(error))
... | Callback used with handle.start_recv(). | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L424-L434 |
geertj/gruvi | lib/gruvi/transports.py | DatagramTransport._on_send_complete | def _on_send_complete(self, handle, error):
"""Callback used with handle.send()."""
assert handle is self._handle
self._write_buffer_size -= 1
assert self._write_buffer_size >= 0
if self._error:
self._log.debug('ignore sendto status {} after error', error)
# S... | python | def _on_send_complete(self, handle, error):
"""Callback used with handle.send()."""
assert handle is self._handle
self._write_buffer_size -= 1
assert self._write_buffer_size >= 0
if self._error:
self._log.debug('ignore sendto status {} after error', error)
# S... | Callback used with handle.send(). | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L456-L468 |
geertj/gruvi | lib/gruvi/transports.py | DatagramTransport.sendto | def sendto(self, data, addr=None):
"""Send a datagram containing *data* to *addr*.
The *addr* argument may be omitted only if the handle was bound to a
default remote address.
"""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecti... | python | def sendto(self, data, addr=None):
"""Send a datagram containing *data* to *addr*.
The *addr* argument may be omitted only if the handle was bound to a
default remote address.
"""
if not isinstance(data, (bytes, bytearray, memoryview)):
raise TypeError("data: expecti... | Send a datagram containing *data* to *addr*.
The *addr* argument may be omitted only if the handle was bound to a
default remote address. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/transports.py#L470-L493 |
geertj/gruvi | lib/gruvi/dbus.py | parse_dbus_address | def parse_dbus_address(address):
"""Parse a D-BUS address string into a list of addresses."""
if address == 'session':
address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
if not address:
raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
elif address == 'system':
addr... | python | def parse_dbus_address(address):
"""Parse a D-BUS address string into a list of addresses."""
if address == 'session':
address = os.environ.get('DBUS_SESSION_BUS_ADDRESS')
if not address:
raise ValueError('$DBUS_SESSION_BUS_ADDRESS not set')
elif address == 'system':
addr... | Parse a D-BUS address string into a list of addresses. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L98-L128 |
geertj/gruvi | lib/gruvi/dbus.py | parse_dbus_header | def parse_dbus_header(header):
"""Parse a D-BUS header. Return the message size."""
if six.indexbytes(header, 0) == ord('l'):
endian = '<'
elif six.indexbytes(header, 0) == ord('B'):
endian = '>'
else:
raise ValueError('illegal endianness')
if not 1 <= six.indexbytes(header, ... | python | def parse_dbus_header(header):
"""Parse a D-BUS header. Return the message size."""
if six.indexbytes(header, 0) == ord('l'):
endian = '<'
elif six.indexbytes(header, 0) == ord('B'):
endian = '>'
else:
raise ValueError('illegal endianness')
if not 1 <= six.indexbytes(header, ... | Parse a D-BUS header. Return the message size. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L188-L203 |
geertj/gruvi | lib/gruvi/dbus.py | TxdbusAuthenticator.getMechanismName | def getMechanismName(self):
"""Return the authentication mechanism name."""
if self._server_side:
mech = self._authenticator.current_mech
return mech.getMechanismName() if mech else None
else:
return getattr(self._authenticator, 'authMech', None) | python | def getMechanismName(self):
"""Return the authentication mechanism name."""
if self._server_side:
mech = self._authenticator.current_mech
return mech.getMechanismName() if mech else None
else:
return getattr(self._authenticator, 'authMech', None) | Return the authentication mechanism name. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L168-L174 |
geertj/gruvi | lib/gruvi/dbus.py | TxdbusAuthenticator.getUserName | def getUserName(self):
"""Return the authenticated user name (server side)."""
if not self._server_side:
return
mech = self._authenticator.current_mech
return mech.getUserName() if mech else None | python | def getUserName(self):
"""Return the authenticated user name (server side)."""
if not self._server_side:
return
mech = self._authenticator.current_mech
return mech.getUserName() if mech else None | Return the authenticated user name (server side). | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L176-L181 |
geertj/gruvi | lib/gruvi/dbus.py | DbusProtocol.get_unique_name | def get_unique_name(self):
"""Return the unique name of the D-BUS connection."""
self._name_acquired.wait()
if self._error:
raise compat.saved_exc(self._error)
elif self._transport is None:
raise DbusError('not connected')
return self._unique_name | python | def get_unique_name(self):
"""Return the unique name of the D-BUS connection."""
self._name_acquired.wait()
if self._error:
raise compat.saved_exc(self._error)
elif self._transport is None:
raise DbusError('not connected')
return self._unique_name | Return the unique name of the D-BUS connection. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L409-L416 |
geertj/gruvi | lib/gruvi/dbus.py | DbusProtocol.send_message | def send_message(self, message):
"""Send a D-BUS message.
The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance.
"""
if not isinstance(message, txdbus.DbusMessage):
raise TypeError('message: expecting DbusMessage instance (got {!r})',
... | python | def send_message(self, message):
"""Send a D-BUS message.
The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance.
"""
if not isinstance(message, txdbus.DbusMessage):
raise TypeError('message: expecting DbusMessage instance (got {!r})',
... | Send a D-BUS message.
The *message* argument must be ``gruvi.txdbus.DbusMessage`` instance. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L419-L432 |
geertj/gruvi | lib/gruvi/dbus.py | DbusProtocol.call_method | def call_method(self, service, path, interface, method, signature=None,
args=None, no_reply=False, auto_start=False, timeout=-1):
"""Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *s... | python | def call_method(self, service, path, interface, method, signature=None,
args=None, no_reply=False, auto_start=False, timeout=-1):
"""Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *s... | Call a D-BUS method and wait for its reply.
This method calls the D-BUS method with name *method* that resides on
the object at bus address *service*, at path *path*, on interface
*interface*.
The *signature* and *args* are optional arguments that can be used to
add parameters ... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L435-L475 |
geertj/gruvi | lib/gruvi/dbus.py | DbusClient.connect | def connect(self, address='session'):
"""Connect to *address* and wait until the connection is established.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'`... | python | def connect(self, address='session'):
"""Connect to *address* and wait until the connection is established.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'`... | Connect to *address* and wait until the connection is established.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to the D-BUS
session and sy... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L492-L513 |
geertj/gruvi | lib/gruvi/dbus.py | DbusServer.listen | def listen(self, address='session'):
"""Start listening on *address* for new connection.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to th... | python | def listen(self, address='session'):
"""Start listening on *address* for new connection.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to th... | Start listening on *address* for new connection.
The *address* argument must be a D-BUS server address, in the format
described in the D-BUS specification. It may also be one of the special
addresses ``'session'`` or ``'system'``, to connect to the D-BUS
session and system bus, respecti... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/dbus.py#L537-L553 |
geertj/gruvi | lib/gruvi/util.py | docfrom | def docfrom(base):
"""Decorator to set a function's docstring from another function."""
def setdoc(func):
func.__doc__ = (getattr(base, '__doc__') or '') + (func.__doc__ or '')
return func
return setdoc | python | def docfrom(base):
"""Decorator to set a function's docstring from another function."""
def setdoc(func):
func.__doc__ = (getattr(base, '__doc__') or '') + (func.__doc__ or '')
return func
return setdoc | Decorator to set a function's docstring from another function. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/util.py#L64-L69 |
geertj/gruvi | lib/gruvi/util.py | objref | def objref(obj):
"""Return a string that uniquely and compactly identifies an object."""
ref = _objrefs.get(obj)
if ref is None:
clsname = obj.__class__.__name__.split('.')[-1]
seqno = _lastids.setdefault(clsname, 1)
ref = '{}-{}'.format(clsname, seqno)
_objrefs[obj] = ref
... | python | def objref(obj):
"""Return a string that uniquely and compactly identifies an object."""
ref = _objrefs.get(obj)
if ref is None:
clsname = obj.__class__.__name__.split('.')[-1]
seqno = _lastids.setdefault(clsname, 1)
ref = '{}-{}'.format(clsname, seqno)
_objrefs[obj] = ref
... | Return a string that uniquely and compactly identifies an object. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/util.py#L75-L84 |
geertj/gruvi | lib/gruvi/util.py | delegate_method | def delegate_method(other, method, name=None):
"""Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argume... | python | def delegate_method(other, method, name=None):
"""Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argume... | Add a method to the current class that delegates to another method.
The *other* argument must be a property that returns the instance to
delegate to. Due to an implementation detail, the property must be defined
in the current class. The *method* argument specifies a method to delegate
to. It can be an... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/util.py#L94-L143 |
geertj/gruvi | lib/gruvi/http.py | accept_ws | def accept_ws(buf, pos):
"""Skip whitespace at the current buffer position."""
match = re_ws.match(buf, pos)
if not match:
return None, pos
return buf[match.start(0):match.end(0)], match.end(0) | python | def accept_ws(buf, pos):
"""Skip whitespace at the current buffer position."""
match = re_ws.match(buf, pos)
if not match:
return None, pos
return buf[match.start(0):match.end(0)], match.end(0) | Skip whitespace at the current buffer position. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L131-L136 |
geertj/gruvi | lib/gruvi/http.py | accept_lit | def accept_lit(char, buf, pos):
"""Accept a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, pos
return char, pos+1 | python | def accept_lit(char, buf, pos):
"""Accept a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, pos
return char, pos+1 | Accept a literal character at the current buffer position. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L138-L142 |
geertj/gruvi | lib/gruvi/http.py | expect_lit | def expect_lit(char, buf, pos):
"""Expect a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, len(buf)
return char, pos+1 | python | def expect_lit(char, buf, pos):
"""Expect a literal character at the current buffer position."""
if pos >= len(buf) or buf[pos] != char:
return None, len(buf)
return char, pos+1 | Expect a literal character at the current buffer position. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L144-L148 |
geertj/gruvi | lib/gruvi/http.py | accept_re | def accept_re(regexp, buf, pos):
"""Accept a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, pos
return buf[match.start(1):match.end(1)], match.end(0) | python | def accept_re(regexp, buf, pos):
"""Accept a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, pos
return buf[match.start(1):match.end(1)], match.end(0) | Accept a regular expression at the current buffer position. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L150-L155 |
geertj/gruvi | lib/gruvi/http.py | expect_re | def expect_re(regexp, buf, pos):
"""Require a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, len(buf)
return buf[match.start(1):match.end(1)], match.end(0) | python | def expect_re(regexp, buf, pos):
"""Require a regular expression at the current buffer position."""
match = regexp.match(buf, pos)
if not match:
return None, len(buf)
return buf[match.start(1):match.end(1)], match.end(0) | Require a regular expression at the current buffer position. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L157-L162 |
geertj/gruvi | lib/gruvi/http.py | parse_content_type | def parse_content_type(header):
"""Parse the "Content-Type" header."""
typ = subtyp = None; options = {}
typ, pos = expect_re(re_token, header, 0)
_, pos = expect_lit('/', header, pos)
subtyp, pos = expect_re(re_token, header, pos)
ctype = header[:pos] if subtyp else ''
while pos < len(heade... | python | def parse_content_type(header):
"""Parse the "Content-Type" header."""
typ = subtyp = None; options = {}
typ, pos = expect_re(re_token, header, 0)
_, pos = expect_lit('/', header, pos)
subtyp, pos = expect_re(re_token, header, pos)
ctype = header[:pos] if subtyp else ''
while pos < len(heade... | Parse the "Content-Type" header. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L165-L186 |
geertj/gruvi | lib/gruvi/http.py | parse_te | def parse_te(header):
"""Parse the "TE" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
_, pos = accept_ws(header, pos)
_, pos = accept_lit(';', header, pos)
_, pos = accept_ws(header, pos)
qvalue, pos = accept_r... | python | def parse_te(header):
"""Parse the "TE" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
_, pos = accept_ws(header, pos)
_, pos = accept_lit(';', header, pos)
_, pos = accept_ws(header, pos)
qvalue, pos = accept_r... | Parse the "TE" header. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L188-L203 |
geertj/gruvi | lib/gruvi/http.py | parse_trailer | def parse_trailer(header):
"""Parse the "Trailer" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
if name:
names.append(name)
_, pos = accept_ws(header, pos)
_, pos = expect_lit(',', header, pos)
_, p... | python | def parse_trailer(header):
"""Parse the "Trailer" header."""
pos = 0
names = []
while pos < len(header):
name, pos = expect_re(re_token, header, pos)
if name:
names.append(name)
_, pos = accept_ws(header, pos)
_, pos = expect_lit(',', header, pos)
_, p... | Parse the "Trailer" header. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L205-L216 |
geertj/gruvi | lib/gruvi/http.py | rfc1123_date | def rfc1123_date(timestamp=None):
"""Create a RFC1123 style Date header for *timestamp*."""
if timestamp is None:
timestamp = time.time()
timestamp = int(timestamp)
global _cached_timestamp, _cached_datestring
if timestamp != _cached_timestamp:
# The time stamp must be GMT, and canno... | python | def rfc1123_date(timestamp=None):
"""Create a RFC1123 style Date header for *timestamp*."""
if timestamp is None:
timestamp = time.time()
timestamp = int(timestamp)
global _cached_timestamp, _cached_datestring
if timestamp != _cached_timestamp:
# The time stamp must be GMT, and canno... | Create a RFC1123 style Date header for *timestamp*. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L227-L240 |
geertj/gruvi | lib/gruvi/http.py | parse_url | def parse_url(url, default_scheme='http', is_connect=False):
"""Parse an URL and return its components.
The *default_scheme* argument specifies the scheme in case URL is
an otherwise valid absolute URL but with a missing scheme.
The *is_connect* argument must be set to ``True`` if the URL was requeste... | python | def parse_url(url, default_scheme='http', is_connect=False):
"""Parse an URL and return its components.
The *default_scheme* argument specifies the scheme in case URL is
an otherwise valid absolute URL but with a missing scheme.
The *is_connect* argument must be set to ``True`` if the URL was requeste... | Parse an URL and return its components.
The *default_scheme* argument specifies the scheme in case URL is
an otherwise valid absolute URL but with a missing scheme.
The *is_connect* argument must be set to ``True`` if the URL was requested
with the HTTP CONNECT method. These URLs have a different form... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L303-L327 |
geertj/gruvi | lib/gruvi/http.py | get_header | def get_header(headers, name, default=None):
"""Return the value of header *name*.
The *headers* argument must be a list of ``(name, value)`` tuples. If the
header is found its associated value is returned, otherwise *default* is
returned. Header names are matched case insensitively.
"""
name =... | python | def get_header(headers, name, default=None):
"""Return the value of header *name*.
The *headers* argument must be a list of ``(name, value)`` tuples. If the
header is found its associated value is returned, otherwise *default* is
returned. Header names are matched case insensitively.
"""
name =... | Return the value of header *name*.
The *headers* argument must be a list of ``(name, value)`` tuples. If the
header is found its associated value is returned, otherwise *default* is
returned. Header names are matched case insensitively. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L350-L361 |
geertj/gruvi | lib/gruvi/http.py | remove_headers | def remove_headers(headers, name):
"""Remove all headers with name *name*.
The list is modified in-place and the updated list is returned.
"""
i = 0
name = name.lower()
for j in range(len(headers)):
if headers[j][0].lower() != name:
if i != j:
headers[i] = he... | python | def remove_headers(headers, name):
"""Remove all headers with name *name*.
The list is modified in-place and the updated list is returned.
"""
i = 0
name = name.lower()
for j in range(len(headers)):
if headers[j][0].lower() != name:
if i != j:
headers[i] = he... | Remove all headers with name *name*.
The list is modified in-place and the updated list is returned. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L363-L376 |
geertj/gruvi | lib/gruvi/http.py | create_chunk | def create_chunk(buf):
"""Create a chunk for the HTTP "chunked" transfer encoding."""
chunk = []
chunk.append(s2b('{:X}\r\n'.format(len(buf))))
chunk.append(buf)
chunk.append(b'\r\n')
return b''.join(chunk) | python | def create_chunk(buf):
"""Create a chunk for the HTTP "chunked" transfer encoding."""
chunk = []
chunk.append(s2b('{:X}\r\n'.format(len(buf))))
chunk.append(buf)
chunk.append(b'\r\n')
return b''.join(chunk) | Create a chunk for the HTTP "chunked" transfer encoding. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L379-L385 |
geertj/gruvi | lib/gruvi/http.py | create_chunked_body_end | def create_chunked_body_end(trailers=None):
"""Create the ending that terminates a chunked body."""
chunk = []
chunk.append('0\r\n')
if trailers:
for name, value in trailers:
chunk.append(name)
chunk.append(': ')
chunk.append(value)
chunk.append('\... | python | def create_chunked_body_end(trailers=None):
"""Create the ending that terminates a chunked body."""
chunk = []
chunk.append('0\r\n')
if trailers:
for name, value in trailers:
chunk.append(name)
chunk.append(': ')
chunk.append(value)
chunk.append('\... | Create the ending that terminates a chunked body. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L388-L399 |
geertj/gruvi | lib/gruvi/http.py | create_request | def create_request(version, method, url, headers):
"""Create a HTTP request header."""
# According to my measurements using b''.join is faster that constructing a
# bytearray.
message = []
message.append('{} {} HTTP/{}\r\n'.format(method, url, version))
for name, value in headers:
messag... | python | def create_request(version, method, url, headers):
"""Create a HTTP request header."""
# According to my measurements using b''.join is faster that constructing a
# bytearray.
message = []
message.append('{} {} HTTP/{}\r\n'.format(method, url, version))
for name, value in headers:
messag... | Create a HTTP request header. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L402-L414 |
geertj/gruvi | lib/gruvi/http.py | create_response | def create_response(version, status, headers):
"""Create a HTTP response header."""
message = []
message.append('HTTP/{} {}\r\n'.format(version, status))
for name, value in headers:
message.append(name)
message.append(': ')
message.append(value)
message.append('\r\n')
... | python | def create_response(version, status, headers):
"""Create a HTTP response header."""
message = []
message.append('HTTP/{} {}\r\n'.format(version, status))
for name, value in headers:
message.append(name)
message.append(': ')
message.append(value)
message.append('\r\n')
... | Create a HTTP response header. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L417-L427 |
geertj/gruvi | lib/gruvi/http.py | ParsedUrl.addr | def addr(self):
"""Address tuple that can be used with :func:`~gruvi.create_connection`."""
port = self.port
if port:
port = int(port)
else:
port = default_ports.get(self.scheme or 'http')
return (self.host, port) | python | def addr(self):
"""Address tuple that can be used with :func:`~gruvi.create_connection`."""
port = self.port
if port:
port = int(port)
else:
port = default_ports.get(self.scheme or 'http')
return (self.host, port) | Address tuple that can be used with :func:`~gruvi.create_connection`. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L277-L284 |
geertj/gruvi | lib/gruvi/http.py | ParsedUrl.target | def target(self):
"""The "target" i.e. local part of the URL, consisting of the path and query."""
target = self.path or '/'
if self.query:
target = '{}?{}'.format(target, self.query)
return target | python | def target(self):
"""The "target" i.e. local part of the URL, consisting of the path and query."""
target = self.path or '/'
if self.query:
target = '{}?{}'.format(target, self.query)
return target | The "target" i.e. local part of the URL, consisting of the path and query. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L292-L297 |
geertj/gruvi | lib/gruvi/http.py | HttpRequest.start_request | def start_request(self, method, url, headers=None, bodylen=None):
"""Start a new HTTP request.
The optional *headers* argument contains the headers to send. It must
be a sequence of ``(name, value)`` tuples.
The optional *bodylen* parameter is a hint that specifies the length of
... | python | def start_request(self, method, url, headers=None, bodylen=None):
"""Start a new HTTP request.
The optional *headers* argument contains the headers to send. It must
be a sequence of ``(name, value)`` tuples.
The optional *bodylen* parameter is a hint that specifies the length of
... | Start a new HTTP request.
The optional *headers* argument contains the headers to send. It must
be a sequence of ``(name, value)`` tuples.
The optional *bodylen* parameter is a hint that specifies the length of
the body that will follow. A length of -1 indicates no body, 0 means an
... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L513-L581 |
geertj/gruvi | lib/gruvi/http.py | HttpRequest.write | def write(self, buf):
"""Write *buf* to the request body."""
if not isinstance(buf, six.binary_type):
raise TypeError('buf: must be a bytes instance')
# Be careful not to write zero-length chunks as they indicate the end of a body.
if len(buf) == 0:
return
... | python | def write(self, buf):
"""Write *buf* to the request body."""
if not isinstance(buf, six.binary_type):
raise TypeError('buf: must be a bytes instance')
# Be careful not to write zero-length chunks as they indicate the end of a body.
if len(buf) == 0:
return
... | Write *buf* to the request body. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L584-L597 |
geertj/gruvi | lib/gruvi/http.py | HttpRequest.end_request | def end_request(self):
"""End the request body."""
if not self._chunked:
return
trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \
if self._trailer else None
ending = create_chunked_body_end(trailers)
self._protocol.writer.... | python | def end_request(self):
"""End the request body."""
if not self._chunked:
return
trailers = [(n, get_header(self._headers, n)) for n in self._trailer] \
if self._trailer else None
ending = create_chunked_body_end(trailers)
self._protocol.writer.... | End the request body. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L600-L607 |
geertj/gruvi | lib/gruvi/http.py | HttpProtocol.request | def request(self, method, url, headers=None, body=None):
"""Make a new HTTP request.
The *method* argument is the HTTP method as a string, for example
``'GET'`` or ``'POST'``. The *url* argument specifies the URL.
The optional *headers* argument specifies extra HTTP headers to use in
... | python | def request(self, method, url, headers=None, body=None):
"""Make a new HTTP request.
The *method* argument is the HTTP method as a string, for example
``'GET'`` or ``'POST'``. The *url* argument specifies the URL.
The optional *headers* argument specifies extra HTTP headers to use in
... | Make a new HTTP request.
The *method* argument is the HTTP method as a string, for example
``'GET'`` or ``'POST'``. The *url* argument specifies the URL.
The optional *headers* argument specifies extra HTTP headers to use in
the request. It must be a sequence of ``(name, value)`` tuple... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L1093-L1138 |
geertj/gruvi | lib/gruvi/http.py | HttpProtocol.getresponse | def getresponse(self):
"""Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :att... | python | def getresponse(self):
"""Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :att... | Wait for and return a HTTP response.
The return value will be a :class:`HttpMessage`. When this method
returns only the response header has been read. The response body can
be read using :meth:`~gruvi.Stream.read` and similar methods on
the message :attr:`~HttpMessage.body`.
No... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/http.py#L1141-L1160 |
unique1o1/Meta-Music | Metamusic/decoder.py | unique_hash | def unique_hash(filepath: str, blocksize: int=80)->str:
""" Small function to generate a hash to uniquely generate a file.
Default blocksize is `500`
"""
s = sha1()
with open(filepath, "rb") as f:
buf = f.read(blocksize)
s.update(buf)
return s.hexdigest() | python | def unique_hash(filepath: str, blocksize: int=80)->str:
""" Small function to generate a hash to uniquely generate a file.
Default blocksize is `500`
"""
s = sha1()
with open(filepath, "rb") as f:
buf = f.read(blocksize)
s.update(buf)
return s.hexdigest() | Small function to generate a hash to uniquely generate a file.
Default blocksize is `500` | https://github.com/unique1o1/Meta-Music/blob/8cd1b04011ae3671ece44cc6338d748f8d095eaf/Metamusic/decoder.py#L8-L16 |
unique1o1/Meta-Music | Metamusic/decoder.py | read | def read(filename: str, limit: Optional[int]=None) -> Tuple[list, int]:
"""
Reads any file supported by pydub (ffmpeg) and returns the data contained
within.
returns: (channels, samplerate)
"""
audiofile = AudioSegment.from_file(filename)
if limit:
audiofile = audiofile[:limit * 10... | python | def read(filename: str, limit: Optional[int]=None) -> Tuple[list, int]:
"""
Reads any file supported by pydub (ffmpeg) and returns the data contained
within.
returns: (channels, samplerate)
"""
audiofile = AudioSegment.from_file(filename)
if limit:
audiofile = audiofile[:limit * 10... | Reads any file supported by pydub (ffmpeg) and returns the data contained
within.
returns: (channels, samplerate) | https://github.com/unique1o1/Meta-Music/blob/8cd1b04011ae3671ece44cc6338d748f8d095eaf/Metamusic/decoder.py#L19-L39 |
unique1o1/Meta-Music | Metamusic/decoder.py | path_to_songname | def path_to_songname(path: str)->str:
"""
Extracts song name from a filepath. Used to identify which songs
have already been fingerprinted on disk.
"""
return os.path.splitext(os.path.basename(path))[0] | python | def path_to_songname(path: str)->str:
"""
Extracts song name from a filepath. Used to identify which songs
have already been fingerprinted on disk.
"""
return os.path.splitext(os.path.basename(path))[0] | Extracts song name from a filepath. Used to identify which songs
have already been fingerprinted on disk. | https://github.com/unique1o1/Meta-Music/blob/8cd1b04011ae3671ece44cc6338d748f8d095eaf/Metamusic/decoder.py#L42-L47 |
geertj/gruvi | lib/gruvi/endpoints.py | create_connection | def create_connection(protocol_factory, address, ssl=False, server_hostname=None,
local_address=None, family=0, flags=0, ipc=False, timeout=None,
mode='rw'):
"""Create a new client connection.
This method creates a new :class:`pyuv.Handle`, connects it to *address*,
... | python | def create_connection(protocol_factory, address, ssl=False, server_hostname=None,
local_address=None, family=0, flags=0, ipc=False, timeout=None,
mode='rw'):
"""Create a new client connection.
This method creates a new :class:`pyuv.Handle`, connects it to *address*,
... | Create a new client connection.
This method creates a new :class:`pyuv.Handle`, connects it to *address*,
and then waits for the connection to be established. When the connection is
established, the handle is wrapped in a transport, and a new protocol
instance is created by calling *protocol_factory*. ... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L33-L158 |
geertj/gruvi | lib/gruvi/endpoints.py | create_server | def create_server(protocol_factory, address=None, ssl=False, family=0, flags=0,
ipc=False, backlog=128):
"""
Create a new network server.
This creates one or more :class:`pyuv.Handle` instances bound to *address*,
puts them in listen mode and starts accepting new connections. For each... | python | def create_server(protocol_factory, address=None, ssl=False, family=0, flags=0,
ipc=False, backlog=128):
"""
Create a new network server.
This creates one or more :class:`pyuv.Handle` instances bound to *address*,
puts them in listen mode and starts accepting new connections. For each... | Create a new network server.
This creates one or more :class:`pyuv.Handle` instances bound to *address*,
puts them in listen mode and starts accepting new connections. For each
accepted connection, a new transport is created which is connected to a new
protocol instance obtained by calling *protocol_fa... | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L162-L203 |
geertj/gruvi | lib/gruvi/endpoints.py | Client.connect | def connect(self, address, **kwargs):
"""Connect to *address* and wait for the connection to be established.
See :func:`~gruvi.create_connection` for a description of *address*
and the supported keyword arguments.
"""
if self._transport:
raise RuntimeError('already c... | python | def connect(self, address, **kwargs):
"""Connect to *address* and wait for the connection to be established.
See :func:`~gruvi.create_connection` for a description of *address*
and the supported keyword arguments.
"""
if self._transport:
raise RuntimeError('already c... | Connect to *address* and wait for the connection to be established.
See :func:`~gruvi.create_connection` for a description of *address*
and the supported keyword arguments. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L250-L263 |
geertj/gruvi | lib/gruvi/endpoints.py | Client.close | def close(self):
"""Close the connection."""
if self._transport is None:
return
self._transport.close()
self._transport._closed.wait()
self._transport = None
self._protocol = None | python | def close(self):
"""Close the connection."""
if self._transport is None:
return
self._transport.close()
self._transport._closed.wait()
self._transport = None
self._protocol = None | Close the connection. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L266-L273 |
geertj/gruvi | lib/gruvi/endpoints.py | Server.handle_connection | def handle_connection(self, client, ssl):
"""Handle a new connection with handle *client*.
This method exists so that it can be overridden in subclass. It is not
intended to be called directly.
"""
if ssl:
context = ssl if hasattr(ssl, 'set_ciphers') \
... | python | def handle_connection(self, client, ssl):
"""Handle a new connection with handle *client*.
This method exists so that it can be overridden in subclass. It is not
intended to be called directly.
"""
if ssl:
context = ssl if hasattr(ssl, 'set_ciphers') \
... | Handle a new connection with handle *client*.
This method exists so that it can be overridden in subclass. It is not
intended to be called directly. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L331-L355 |
geertj/gruvi | lib/gruvi/endpoints.py | Server.listen | def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128):
"""Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments.
"""
ha... | python | def listen(self, address, ssl=False, family=0, flags=0, ipc=False, backlog=128):
"""Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments.
"""
ha... | Create a new transport, bind it to *address*, and start listening
for new connections.
See :func:`create_server` for a description of *address* and the
supported keyword arguments. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L371-L414 |
geertj/gruvi | lib/gruvi/endpoints.py | Server.close | def close(self):
"""Close the listening sockets and all accepted connections."""
for handle in self._handles:
if not handle.closed:
handle.close()
del self._handles[:]
for transport, _ in self.connections:
transport.close()
self._all_closed... | python | def close(self):
"""Close the listening sockets and all accepted connections."""
for handle in self._handles:
if not handle.closed:
handle.close()
del self._handles[:]
for transport, _ in self.connections:
transport.close()
self._all_closed... | Close the listening sockets and all accepted connections. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/endpoints.py#L417-L425 |
welbornprod/colr | colr/__main__.py | main | def main(argd=None):
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG, debug
# The argd parameter for main() is for testing purposes only.
argd = argd or docopt(
USAGESTR,
version=VERSIONSTR,
script=SCRIPT,
# Example usage of colr_docopt colors.
... | python | def main(argd=None):
""" Main entry point, expects doctopt arg dict as argd. """
global DEBUG, debug
# The argd parameter for main() is for testing purposes only.
argd = argd or docopt(
USAGESTR,
version=VERSIONSTR,
script=SCRIPT,
# Example usage of colr_docopt colors.
... | Main entry point, expects doctopt arg dict as argd. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L152-L219 |
welbornprod/colr | colr/__main__.py | debug | def debug(*args, **kwargs):
""" Just prints to stderr, unless printdebug is installed. Then it
will be replaced in `main()` by `printdebug.debug`.
"""
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
msg = kwargs.get('sep', ' ').join(str(a) for a in args)
print('debug... | python | def debug(*args, **kwargs):
""" Just prints to stderr, unless printdebug is installed. Then it
will be replaced in `main()` by `printdebug.debug`.
"""
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
msg = kwargs.get('sep', ' ').join(str(a) for a in args)
print('debug... | Just prints to stderr, unless printdebug is installed. Then it
will be replaced in `main()` by `printdebug.debug`. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L222-L229 |
welbornprod/colr | colr/__main__.py | dict_pop_or | def dict_pop_or(d, key, default=None):
""" Try popping a key from a dict.
Instead of raising KeyError, just return the default value.
"""
val = default
with suppress(KeyError):
val = d.pop(key)
return val | python | def dict_pop_or(d, key, default=None):
""" Try popping a key from a dict.
Instead of raising KeyError, just return the default value.
"""
val = default
with suppress(KeyError):
val = d.pop(key)
return val | Try popping a key from a dict.
Instead of raising KeyError, just return the default value. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L232-L239 |
welbornprod/colr | colr/__main__.py | get_colr | def get_colr(txt, argd):
""" Return a Colr instance based on user args. """
fore = parse_colr_arg(
get_name_arg(argd, '--fore', 'FORE', default=None),
rgb_mode=argd['--truecolor'],
)
back = parse_colr_arg(
get_name_arg(argd, '--back', 'BACK', default=None),
rgb_mode=argd[... | python | def get_colr(txt, argd):
""" Return a Colr instance based on user args. """
fore = parse_colr_arg(
get_name_arg(argd, '--fore', 'FORE', default=None),
rgb_mode=argd['--truecolor'],
)
back = parse_colr_arg(
get_name_arg(argd, '--back', 'BACK', default=None),
rgb_mode=argd[... | Return a Colr instance based on user args. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L242-L285 |
welbornprod/colr | colr/__main__.py | get_name_arg | def get_name_arg(argd, *argnames, default=None):
""" Return the first argument value given in a docopt arg dict.
When not given, return default.
"""
val = None
for argname in argnames:
if argd[argname]:
val = argd[argname].lower().strip()
break
return val if v... | python | def get_name_arg(argd, *argnames, default=None):
""" Return the first argument value given in a docopt arg dict.
When not given, return default.
"""
val = None
for argname in argnames:
if argd[argname]:
val = argd[argname].lower().strip()
break
return val if v... | Return the first argument value given in a docopt arg dict.
When not given, return default. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L288-L297 |
welbornprod/colr | colr/__main__.py | handle_err | def handle_err(*args):
""" Handle fatal errors, caught in __main__ scope.
If DEBUG is set, print a real traceback.
Otherwise, `print_err` any arguments passed.
"""
if DEBUG:
print_err(traceback.format_exc(), color=False)
else:
print_err(*args, newline=True) | python | def handle_err(*args):
""" Handle fatal errors, caught in __main__ scope.
If DEBUG is set, print a real traceback.
Otherwise, `print_err` any arguments passed.
"""
if DEBUG:
print_err(traceback.format_exc(), color=False)
else:
print_err(*args, newline=True) | Handle fatal errors, caught in __main__ scope.
If DEBUG is set, print a real traceback.
Otherwise, `print_err` any arguments passed. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L300-L308 |
welbornprod/colr | colr/__main__.py | justify | def justify(clr, argd):
""" Justify str/Colr based on user args. """
methodmap = {
'--ljust': clr.ljust,
'--rjust': clr.rjust,
'--center': clr.center,
}
for flag in methodmap:
if argd[flag]:
if argd[flag] in ('0', '-'):
val = get_terminal_size(... | python | def justify(clr, argd):
""" Justify str/Colr based on user args. """
methodmap = {
'--ljust': clr.ljust,
'--rjust': clr.rjust,
'--center': clr.center,
}
for flag in methodmap:
if argd[flag]:
if argd[flag] in ('0', '-'):
val = get_terminal_size(... | Justify str/Colr based on user args. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L311-L330 |
welbornprod/colr | colr/__main__.py | list_known_codes | def list_known_codes(s, unique=True, rgb_mode=False):
""" Find and print all known escape codes in a string,
using get_known_codes.
"""
total = 0
for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode):
total += 1
print(codedesc)
plural = 'code' if total == 1 els... | python | def list_known_codes(s, unique=True, rgb_mode=False):
""" Find and print all known escape codes in a string,
using get_known_codes.
"""
total = 0
for codedesc in get_known_codes(s, unique=unique, rgb_mode=rgb_mode):
total += 1
print(codedesc)
plural = 'code' if total == 1 els... | Find and print all known escape codes in a string,
using get_known_codes. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L333-L344 |
welbornprod/colr | colr/__main__.py | list_names | def list_names():
""" List all known color names. """
names = get_all_names()
# This is 375 right now. Probably won't ever change, but I'm not sure.
nameslen = len(names)
print('\nListing {} names:\n'.format(nameslen))
# Using 3 columns of names, still alphabetically sorted from the top down.
... | python | def list_names():
""" List all known color names. """
names = get_all_names()
# This is 375 right now. Probably won't ever change, but I'm not sure.
nameslen = len(names)
print('\nListing {} names:\n'.format(nameslen))
# Using 3 columns of names, still alphabetically sorted from the top down.
... | List all known color names. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L347-L387 |
welbornprod/colr | colr/__main__.py | parse_gradient_rgb_args | def parse_gradient_rgb_args(args):
""" Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were gi... | python | def parse_gradient_rgb_args(args):
""" Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were gi... | Parse one or two rgb args given with --gradientrgb.
Raises InvalidArg for invalid rgb values.
Returns a tuple of (start_rgb, stop_rgb), where the stop_rgb may be
None if only one arg value was given and start_rgb may be None if
no values were given. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L410-L422 |
welbornprod/colr | colr/__main__.py | print_err | def print_err(*args, **kwargs):
""" A wrapper for print() that uses stderr by default. """
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
color = dict_pop_or(kwargs, 'color', True)
# Use color if asked, but only if the file is a tty.
if color and kwargs['file'].isatty():
... | python | def print_err(*args, **kwargs):
""" A wrapper for print() that uses stderr by default. """
if kwargs.get('file', None) is None:
kwargs['file'] = sys.stderr
color = dict_pop_or(kwargs, 'color', True)
# Use color if asked, but only if the file is a tty.
if color and kwargs['file'].isatty():
... | A wrapper for print() that uses stderr by default. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L425-L447 |
welbornprod/colr | colr/__main__.py | read_stdin | def read_stdin():
""" Read text from stdin, and print a helpful message for ttys. """
if sys.stdin.isatty() and sys.stdout.isatty():
print('\nReading from stdin until end of file (Ctrl + D)...')
return sys.stdin.read() | python | def read_stdin():
""" Read text from stdin, and print a helpful message for ttys. """
if sys.stdin.isatty() and sys.stdout.isatty():
print('\nReading from stdin until end of file (Ctrl + D)...')
return sys.stdin.read() | Read text from stdin, and print a helpful message for ttys. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L450-L455 |
welbornprod/colr | colr/__main__.py | translate | def translate(usercodes, rgb_mode=False):
""" Translate one or more hex, term, or rgb value into the others.
Yields strings with the results for each code translated.
"""
for code in usercodes:
code = code.strip().lower()
if code.isalpha() and (code in codes['fore']):
# B... | python | def translate(usercodes, rgb_mode=False):
""" Translate one or more hex, term, or rgb value into the others.
Yields strings with the results for each code translated.
"""
for code in usercodes:
code = code.strip().lower()
if code.isalpha() and (code in codes['fore']):
# B... | Translate one or more hex, term, or rgb value into the others.
Yields strings with the results for each code translated. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L458-L479 |
welbornprod/colr | colr/__main__.py | translate_basic | def translate_basic(usercode):
""" Translate a basic color name to color with explanation. """
codenum = get_code_num(codes['fore'][usercode])
colorcode = codeformat(codenum)
msg = 'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'.format(
usercode,
codenum,
colorcode
)
if d... | python | def translate_basic(usercode):
""" Translate a basic color name to color with explanation. """
codenum = get_code_num(codes['fore'][usercode])
colorcode = codeformat(codenum)
msg = 'Name: {:>10}, Number: {:>3}, EscapeCode: {!r}'.format(
usercode,
codenum,
colorcode
)
if d... | Translate a basic color name to color with explanation. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L482-L493 |
welbornprod/colr | colr/__main__.py | try_float | def try_float(s, default=None, minimum=None):
""" Try parsing a string into a float.
If None is passed, default is returned.
On failure, InvalidFloat is raised.
"""
if not s:
return default
try:
val = float(s)
except (TypeError, ValueError):
raise InvalidNumbe... | python | def try_float(s, default=None, minimum=None):
""" Try parsing a string into a float.
If None is passed, default is returned.
On failure, InvalidFloat is raised.
"""
if not s:
return default
try:
val = float(s)
except (TypeError, ValueError):
raise InvalidNumbe... | Try parsing a string into a float.
If None is passed, default is returned.
On failure, InvalidFloat is raised. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L496-L509 |
welbornprod/colr | colr/__main__.py | try_int | def try_int(s, default=None, minimum=None):
""" Try parsing a string into an integer.
If None is passed, default is returned.
On failure, InvalidNumber is raised.
"""
if not s:
return default
try:
val = int(s)
except (TypeError, ValueError):
raise InvalidNumbe... | python | def try_int(s, default=None, minimum=None):
""" Try parsing a string into an integer.
If None is passed, default is returned.
On failure, InvalidNumber is raised.
"""
if not s:
return default
try:
val = int(s)
except (TypeError, ValueError):
raise InvalidNumbe... | Try parsing a string into an integer.
If None is passed, default is returned.
On failure, InvalidNumber is raised. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L512-L525 |
welbornprod/colr | colr/__main__.py | try_rgb | def try_rgb(s, default=None):
""" Try parsing a string into an rgb value (int, int, int),
where the ints are 0-255 inclusive.
If None is passed, default is returned.
On failure, InvalidArg is raised.
"""
if not s:
return default
try:
r, g, b = (int(x.strip()) for ... | python | def try_rgb(s, default=None):
""" Try parsing a string into an rgb value (int, int, int),
where the ints are 0-255 inclusive.
If None is passed, default is returned.
On failure, InvalidArg is raised.
"""
if not s:
return default
try:
r, g, b = (int(x.strip()) for ... | Try parsing a string into an rgb value (int, int, int),
where the ints are 0-255 inclusive.
If None is passed, default is returned.
On failure, InvalidArg is raised. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L528-L543 |
welbornprod/colr | colr/__main__.py | entry_point | def entry_point():
""" An entry point for setuptools. This is required because
`if __name__ == '__main__'` is not fired when the entry point
is 'main()'. This just wraps the old behavior in a function so
it can be called from setuptools.
"""
try:
mainret = main()
except (... | python | def entry_point():
""" An entry point for setuptools. This is required because
`if __name__ == '__main__'` is not fired when the entry point
is 'main()'. This just wraps the old behavior in a function so
it can be called from setuptools.
"""
try:
mainret = main()
except (... | An entry point for setuptools. This is required because
`if __name__ == '__main__'` is not fired when the entry point
is 'main()'. This just wraps the old behavior in a function so
it can be called from setuptools. | https://github.com/welbornprod/colr/blob/417117fdbddbc53142096685ac2af006b2bd0220/colr/__main__.py#L557-L578 |
geertj/gruvi | lib/gruvi/sslcompat.py | create_default_context | def create_default_context(purpose=None, **kwargs):
"""Create a new SSL context in the most secure way available on the current
Python version. See :func:`ssl.create_default_context`."""
if hasattr(ssl, 'create_default_context'):
# Python 2.7.9+, Python 3.4+: take a server_side boolean or None, in
... | python | def create_default_context(purpose=None, **kwargs):
"""Create a new SSL context in the most secure way available on the current
Python version. See :func:`ssl.create_default_context`."""
if hasattr(ssl, 'create_default_context'):
# Python 2.7.9+, Python 3.4+: take a server_side boolean or None, in
... | Create a new SSL context in the most secure way available on the current
Python version. See :func:`ssl.create_default_context`. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/sslcompat.py#L171-L187 |
geertj/gruvi | lib/gruvi/logging.py | get_logger | def get_logger(context=None, name=None):
"""Return a logger for *context*.
Return a :class:`ContextLogger` instance. The instance implements the
standard library's :class:`logging.Logger` interface.
"""
# Many class instances have their own logger. Share them to save memory if
# possible, i.e. ... | python | def get_logger(context=None, name=None):
"""Return a logger for *context*.
Return a :class:`ContextLogger` instance. The instance implements the
standard library's :class:`logging.Logger` interface.
"""
# Many class instances have their own logger. Share them to save memory if
# possible, i.e. ... | Return a logger for *context*.
Return a :class:`ContextLogger` instance. The instance implements the
standard library's :class:`logging.Logger` interface. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/logging.py#L37-L55 |
geertj/gruvi | lib/gruvi/logging.py | ContextLogger.thread_info | def thread_info(self):
"""Return a string identifying the current thread and fiber."""
tid = threading.current_thread().name
if tid == 'MainThread':
tid = 'Main'
current = fibers.current()
fid = getattr(current, 'name') if current.parent else 'Root'
return '{}... | python | def thread_info(self):
"""Return a string identifying the current thread and fiber."""
tid = threading.current_thread().name
if tid == 'MainThread':
tid = 'Main'
current = fibers.current()
fid = getattr(current, 'name') if current.parent else 'Root'
return '{}... | Return a string identifying the current thread and fiber. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/logging.py#L79-L86 |
geertj/gruvi | lib/gruvi/logging.py | ContextLogger.frame_info | def frame_info(self):
"""Return a string identifying the current frame."""
if not self._logger.isEnabledFor(logging.DEBUG):
return ''
f = sys._getframe(3)
fname = os.path.split(f.f_code.co_filename)[1]
return '{}:{}'.format(fname, f.f_lineno) | python | def frame_info(self):
"""Return a string identifying the current frame."""
if not self._logger.isEnabledFor(logging.DEBUG):
return ''
f = sys._getframe(3)
fname = os.path.split(f.f_code.co_filename)[1]
return '{}:{}'.format(fname, f.f_lineno) | Return a string identifying the current frame. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/logging.py#L88-L94 |
geertj/gruvi | lib/gruvi/stream.py | StreamBuffer.set_buffer_limits | def set_buffer_limits(self, high=None, low=None):
"""Set the low and high watermarks for the read buffer."""
if high is None:
high = self.default_buffer_size
if low is None:
low = high // 2
self._buffer_high = high
self._buffer_low = low | python | def set_buffer_limits(self, high=None, low=None):
"""Set the low and high watermarks for the read buffer."""
if high is None:
high = self.default_buffer_size
if low is None:
low = high // 2
self._buffer_high = high
self._buffer_low = low | Set the low and high watermarks for the read buffer. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/stream.py#L63-L70 |
geertj/gruvi | lib/gruvi/stream.py | StreamBuffer.feed | def feed(self, data):
"""Add *data* to the buffer."""
self._buffers.append(data)
self._buffer_size += len(data)
self._maybe_pause_transport()
self._can_read.set() | python | def feed(self, data):
"""Add *data* to the buffer."""
self._buffers.append(data)
self._buffer_size += len(data)
self._maybe_pause_transport()
self._can_read.set() | Add *data* to the buffer. | https://github.com/geertj/gruvi/blob/1d77ca439600b6ea7a19aa1ee85dca0f3be3f3f8/lib/gruvi/stream.py#L72-L77 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.