_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q251300 | Artist.get_listener_count | train | def get_listener_count(self):
"""Returns the number of listeners on the network."""
if hasattr(self, "listener_count"):
return self.listener_count
else:
self.listener_count = _number(
| python | {
"resource": ""
} |
q251301 | Artist.is_streamable | train | def is_streamable(self):
"""Returns True if the artist is streamable."""
return bool(
_number(
| python | {
"resource": ""
} |
q251302 | Artist.get_similar | train | def get_similar(self, limit=None):
"""Returns the similar artists on the network."""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
names = _extract_all(doc, "name")
matches = ... | python | {
"resource": ""
} |
q251303 | Artist.get_top_albums | train | def get_top_albums(self, limit=None, cacheable=True):
"""Returns a list of the top albums."""
params = self._get_params()
if limit:
| python | {
"resource": ""
} |
q251304 | Artist.get_top_tracks | train | def get_top_tracks(self, limit=None, cacheable=True):
"""Returns a list of the most played Tracks by this artist."""
| python | {
"resource": ""
} |
q251305 | Country.get_top_artists | train | def get_top_artists(self, limit=None, cacheable=True):
"""Returns a sequence of the most played artists."""
params = self._get_params()
if limit:
params["limit"] = limit
| python | {
"resource": ""
} |
q251306 | Track.get_duration | train | def get_duration(self):
"""Returns the track duration."""
| python | {
"resource": ""
} |
q251307 | Track.get_userloved | train | def get_userloved(self):
"""Whether the user loved this track"""
if not self.username:
return
params = self._get_params()
params["username"] = self.username
| python | {
"resource": ""
} |
q251308 | Track.is_streamable | train | def is_streamable(self):
"""Returns True if the track is available at Last.fm."""
| python | {
"resource": ""
} |
q251309 | Track.is_fulltrack_available | train | def is_fulltrack_available(self):
"""Returns True if the full track is available for streaming."""
doc = self._request(self.ws_prefix + ".getInfo", True)
return ( | python | {
"resource": ""
} |
q251310 | Track.get_album | train | def get_album(self):
"""Returns the album object of this track."""
doc = self._request(self.ws_prefix + ".getInfo", True)
albums = doc.getElementsByTagName("album")
if len(albums) == 0:
return
| python | {
"resource": ""
} |
q251311 | Track.get_similar | train | def get_similar(self, limit=None):
"""
Returns similar tracks for this track on the network,
based on listening data.
"""
params = self._get_params()
if limit:
params["limit"] = limit
doc = self._request(self.ws_prefix + ".getSimilar", True, params)
... | python | {
"resource": ""
} |
q251312 | User.get_artist_tracks | train | def get_artist_tracks(self, artist, cacheable=False):
"""
Get a list of tracks by a given artist scrobbled by this user,
including scrobble time.
"""
# Not implemented:
# "Can be limited to specific timeranges, defaults to all time."
warnings.warn(
"U... | python | {
"resource": ""
} |
q251313 | User.get_friends | train | def get_friends(self, limit=50, cacheable=False):
"""Returns a list of the user's friends. """
seq = []
for node in _collect_nodes(
limit, self, | python | {
"resource": ""
} |
q251314 | User.get_loved_tracks | train | def get_loved_tracks(self, limit=50, cacheable=True):
"""
Returns this user's loved track as a sequence of LovedTrack objects in
reverse order of their timestamp, all the way back to the first track.
If limit==None, it will try to pull all the available data.
This method uses c... | python | {
"resource": ""
} |
q251315 | User.get_now_playing | train | def get_now_playing(self):
"""
Returns the currently playing track, or None if nothing is playing.
"""
params = self._get_params()
params["limit"] = "1"
doc = self._request(self.ws_prefix + ".getRecentTracks", False, params)
| python | {
"resource": ""
} |
q251316 | User.get_recent_tracks | train | def get_recent_tracks(self, limit=10, cacheable=True, time_from=None, time_to=None):
"""
Returns this user's played track as a sequence of PlayedTrack objects
in reverse order of playtime, all the way back to the first track.
Parameters:
limit : If None, it will try to pull all ... | python | {
"resource": ""
} |
q251317 | User.get_country | train | def get_country(self):
"""Returns the name of the country of the user."""
doc = self._request(self.ws_prefix + ".getInfo", True)
country = _extract(doc, "country")
| python | {
"resource": ""
} |
q251318 | User.is_subscriber | train | def is_subscriber(self):
"""Returns whether the user is a subscriber or not. True or | python | {
"resource": ""
} |
q251319 | User.get_playcount | train | def get_playcount(self):
"""Returns the user's playcount so far."""
doc | python | {
"resource": ""
} |
q251320 | User.get_registered | train | def get_registered(self):
"""Returns the user's registration date."""
| python | {
"resource": ""
} |
q251321 | User.get_unixtime_registered | train | def get_unixtime_registered(self):
"""Returns the user's registration date as a UNIX timestamp."""
doc = self._request(self.ws_prefix + ".getInfo", True)
| python | {
"resource": ""
} |
q251322 | User.get_tagged_albums | train | def get_tagged_albums(self, tag, limit=None, cacheable=True):
"""Returns the albums tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "album"
if limit:
params["limit"] | python | {
"resource": ""
} |
q251323 | User.get_tagged_artists | train | def get_tagged_artists(self, tag, limit=None):
"""Returns the artists tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "artist"
if limit:
params["limit"] | python | {
"resource": ""
} |
q251324 | User.get_tagged_tracks | train | def get_tagged_tracks(self, tag, limit=None, cacheable=True):
"""Returns the tracks tagged by a user."""
params = self._get_params()
params["tag"] = tag
params["taggingtype"] = "track"
if limit:
params["limit"] | python | {
"resource": ""
} |
q251325 | User.get_track_scrobbles | train | def get_track_scrobbles(self, artist, track, cacheable=False):
"""
Get a list of this user's scrobbles of this artist's track,
including scrobble time.
"""
params = self._get_params()
params["artist"] = artist
params["track"] = track
seq = []
for... | python | {
"resource": ""
} |
q251326 | _Search.get_total_result_count | train | def get_total_result_count(self):
"""Returns the total count of all the results."""
| python | {
"resource": ""
} |
q251327 | _Search._retrieve_page | train | def _retrieve_page(self, page_index):
"""Returns the node of matches to be processed"""
params = self._get_params()
params["page"] = str(page_index)
| python | {
"resource": ""
} |
q251328 | AlbumSearch.get_next_page | train | def get_next_page(self):
"""Returns the next page of results as a sequence of Album objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("album"):
seq.append(
Album(
_extract(node, "ar... | python | {
"resource": ""
} |
q251329 | ArtistSearch.get_next_page | train | def get_next_page(self):
"""Returns the next page of results as a sequence of Artist objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("artist"):
| python | {
"resource": ""
} |
q251330 | TrackSearch.get_next_page | train | def get_next_page(self):
"""Returns the next page of results as a sequence of Track objects."""
master_node = self._retrieve_next_page()
seq = []
for node in master_node.getElementsByTagName("track"):
track = Track(
_extract(node, "artist"),
... | python | {
"resource": ""
} |
q251331 | Beautify.write_file | train | def write_file(self, fp, data):
"""Write output to a file."""
| python | {
"resource": ""
} |
q251332 | Beautify.detect_function_style | train | def detect_function_style(self, test_record):
"""Returns the index for the function declaration style detected in the given string
or None if no function declarations are detected."""
index = 0
# IMPORTANT: apply regex sequentially and stop on the first match:
| python | {
"resource": ""
} |
q251333 | Beautify.change_function_style | train | def change_function_style(self, stripped_record, func_decl_style):
"""Converts a function definition syntax from the 'func_decl_style' to the one that has been
set in self.apply_function_style and returns the string with the converted syntax."""
if func_decl_style is None:
return ... | python | {
"resource": ""
} |
q251334 | Beautify.beautify_file | train | def beautify_file(self, path):
"""Beautify bash script file."""
error = False
if(path == '-'):
data = sys.stdin.read()
result, error = self.beautify_string(data, '(stdin)')
sys.stdout.write(result)
else: # named file
data = self.read_file(... | python | {
"resource": ""
} |
q251335 | Beautify.main | train | def main(self):
"""Main beautifying function."""
error = False
parser = argparse.ArgumentParser(
description="A Bash beautifier for the masses, version {}".format(self.get_version()), add_help=False)
parser.add_argument('--indent-size', '-i', nargs=1, type=int, default=4,
... | python | {
"resource": ""
} |
q251336 | init_default | train | def init_default(required, default, optional_default):
"""
Returns optional default if field is not required and
default was not provided.
:param bool required: whether the field is required in a given | python | {
"resource": ""
} |
q251337 | to_child_field | train | def to_child_field(cls):
"""
Returns an callable instance that will convert a value to a Child object.
:param cls: Valid class type of the Child.
:return: instance of ChildConverter.
"""
class ChildConverter(object):
def __init__(self, cls):
self._cls = cls
@prope... | python | {
"resource": ""
} |
q251338 | to_mapping_field | train | def to_mapping_field(cls, key): # pragma: no mccabe
"""
Returns a callable instance that will convert a value to a Mapping.
:param cls: Valid class type of the items in the Sequence.
:param key: Attribute name of the key value in each item of cls instance.
:return: instance of the MappingConverter... | python | {
"resource": ""
} |
q251339 | to_date_field | train | def to_date_field(formatter):
"""
Returns a callable instance that will convert a string to a Date.
:param formatter: String that represents data format for parsing.
:return: instance of the DateConverter.
"""
class DateConverter(object):
| python | {
"resource": ""
} |
q251340 | to_datetime_field | train | def to_datetime_field(formatter):
"""
Returns a callable instance that will convert a string to a DateTime.
:param formatter: String that represents data format for parsing.
:return: instance of the DateTimeConverter.
"""
class DateTimeConverter(object):
def __init__(self, formatter):
... | python | {
"resource": ""
} |
q251341 | to_time_field | train | def to_time_field(formatter):
"""
Returns a callable instance that will convert a string to a Time.
:param formatter: String that represents data format for parsing.
:return: instance of the TimeConverter.
"""
class TimeConverter(object):
def __init__(self, formatter):
self... | python | {
"resource": ""
} |
q251342 | to_dict | train | def to_dict(obj, **kwargs):
"""
Convert an object into dictionary. Uses singledispatch to allow for
clean extensions for custom class types.
Reference: https://pypi.python.org/pypi/singledispatch
:param obj: object instance
:param kwargs: keyword arguments such as suppress_private_attr,
... | python | {
"resource": ""
} |
q251343 | related_obj_to_dict | train | def related_obj_to_dict(obj, **kwargs):
""" Covert a known related object to a dictionary. """
# Explicitly discard formatter kwarg, should not be cascaded down.
kwargs.pop('formatter', None)
# If True, remove fields that start with an underscore (e.g. _secret)
suppress_private_attr = kwargs.get("... | python | {
"resource": ""
} |
q251344 | convert_key_to_attr_names | train | def convert_key_to_attr_names(cls, original):
""" convert key names to their corresponding attribute names """
attrs = fields(cls)
updated = {}
keys_pulled = set()
for a in attrs:
key_name = a.metadata.get('key') or a.name
if key_name in original:
updated[a.name] = origi... | python | {
"resource": ""
} |
q251345 | to_yaml | train | def to_yaml(obj, stream=None, dumper_cls=yaml.Dumper, default_flow_style=False,
**kwargs):
"""
Serialize a Python object into a YAML stream with OrderedDict and
default_flow_style defaulted to False.
If stream is None, return the produced string instead.
OrderedDict reference: http://s... | python | {
"resource": ""
} |
q251346 | from_yaml | train | def from_yaml(stream, cls=None, loader_cls=yaml.Loader,
object_pairs_hook=OrderedDict, **extras):
"""
Convert a YAML stream into a class via the OrderedLoader class.
"""
class OrderedLoader(loader_cls):
pass
def construct_mapping(loader, node):
| python | {
"resource": ""
} |
q251347 | from_json | train | def from_json(stream, cls=None, object_pairs_hook=OrderedDict, **extras):
"""
Convert a JSON string or stream into specified class.
"""
stream = stream.read() if | python | {
"resource": ""
} |
q251348 | BooleanField | train | def BooleanField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new bool field on a model.
:param default: any boolean value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in... | python | {
"resource": ""
} |
q251349 | ChildField | train | def ChildField(cls, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new child field on a model.
:param cls: class (or name) of the model to be related.
:param default: any object value of type cls
:param bool required: whether or not the object is invalid i... | python | {
"resource": ""
} |
q251350 | DateField | train | def DateField(formatter=types.DEFAULT_DATE_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new date field on a model.
:param formatter: date formatter string (default: "%Y-%m-%d")
:param default: any date or string that can be converted to a date value
... | python | {
"resource": ""
} |
q251351 | DateTimeField | train | def DateTimeField(formatter=types.DEFAULT_DATETIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new datetime field on a model.
:param formatter: datetime formatter string (default: "ISO_FORMAT")
:param default: any datetime or string that can be c... | python | {
"resource": ""
} |
q251352 | TimeField | train | def TimeField(formatter=types.DEFAULT_TIME_FORMAT, default=NOTHING,
required=True, repr=True, cmp=True, key=None):
"""
Create new time field on a model.
:param formatter: time formatter string (default: "%H:%M:%S")
:param default: any time or string that can be converted to a time value
... | python | {
"resource": ""
} |
q251353 | FloatField | train | def FloatField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new float field on a model.
:param default: any float value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in obje... | python | {
"resource": ""
} |
q251354 | IntegerField | train | def IntegerField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new int field on a model.
:param default: any integer value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear in ... | python | {
"resource": ""
} |
q251355 | MappingField | train | def MappingField(cls, child_key, default=NOTHING, required=True, repr=False,
key=None):
"""
Create new mapping field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param child_key: key field on the child object to be used as the map key.
:param def... | python | {
"resource": ""
} |
q251356 | RegexField | train | def RegexField(regex, default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new str field on a model.
:param regex: regex validation string (e.g. "[^@]+@[^@]+" for email)
:param default: any string value
:param bool required: whether or not the object is invalid ... | python | {
"resource": ""
} |
q251357 | SequenceField | train | def SequenceField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new sequence field on a model.
:param cls: class (or name) of the model to be related in Sequence.
:param default: any TypedSequence or list
:param bool required: whether or not the object is invalid if not pro... | python | {
"resource": ""
} |
q251358 | SetField | train | def SetField(cls, default=NOTHING, required=True, repr=False, key=None):
"""
Create new set field on a model.
:param cls: class (or name) of the model to be related in Set.
:param default: any TypedSet or set
:param bool required: whether or not the object is invalid if not provided.
:param boo... | python | {
"resource": ""
} |
q251359 | DecimalField | train | def DecimalField(default=NOTHING, required=True, repr=True, cmp=True,
key=None):
"""
Create new decimal field on a model.
:param default: any decimal value
:param bool required: whether or not the object is invalid if not provided.
:param bool repr: include this field should appear... | python | {
"resource": ""
} |
q251360 | run_clingo | train | def run_clingo(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
) -> Tuple[str, str]:
"""
Run draco and return stderr and stdout
"""
# default args
files = files or DRACO_LP
if rela... | python | {
"resource": ""
} |
q251361 | run | train | def run(
draco_query: List[str],
constants: Dict[str, str] = None,
files: List[str] = None,
relax_hard=False,
silence_warnings=False,
debug=False,
clear_cache=False,
) -> Optional[Result]:
""" Run clingo to compute a completion of a partial spec or violations. """
# Clear file cache... | python | {
"resource": ""
} |
q251362 | DogeDeque.get | train | def get(self):
"""
Get one item. This will rotate the deque one step. Repeated gets will
return different items.
"""
self.index += 1
# If we've gone through the entire deque once, shuffle it again to
# simulate ever-flowing random. self.shuffle() will run __ini... | python | {
"resource": ""
} |
q251363 | DogeDeque.shuffle | train | def shuffle(self):
"""
Shuffle the deque
Deques themselves do not support this, so this will make all items into
a list, shuffle that list, clear the deque, and then re-init the deque.
"""
| python | {
"resource": ""
} |
q251364 | FrequencyBasedDogeDeque.get | train | def get(self):
"""
Get one item and prepare to get an item with lower
rank on the next call.
"""
if len(self) < 1:
return "wow"
if self.index >= len(self):
self.index = | python | {
"resource": ""
} |
q251365 | onscreen_len | train | def onscreen_len(s):
"""
Calculate the length of a unicode string on screen,
accounting for double-width characters
"""
| python | {
"resource": ""
} |
q251366 | Doge.setup_seasonal | train | def setup_seasonal(self):
"""
Check if there's some seasonal holiday going on, setup appropriate
Shibe picture and load holiday words.
Note: if there are two or more holidays defined for a certain date,
the first one takes precedence.
"""
# If we've specified a... | python | {
"resource": ""
} |
q251367 | Doge.apply_text | train | def apply_text(self):
"""
Apply text around doge
"""
# Calculate a random sampling of lines that are to have text applied
# onto them. Return value is a sorted list of line index integers.
linelen = len(self.lines)
affected = sorted(random.sample(range(linelen),... | python | {
"resource": ""
} |
q251368 | Doge.load_doge | train | def load_doge(self):
"""
Return pretty ASCII Shibe.
wow
"""
if self.ns.no_shibe:
return ['']
with open(self.doge_path) as f:
if sys.version_info < (3, 0):
if locale.getpreferredencoding() == 'UTF-8':
doge_lin... | python | {
"resource": ""
} |
q251369 | Doge.get_real_data | train | def get_real_data(self):
"""
Grab actual data from the system
"""
ret = []
username = os.environ.get('USER')
if username:
ret.append(username)
editor = os.environ.get('EDITOR')
if editor:
editor = editor.split('/')[-1]
... | python | {
"resource": ""
} |
q251370 | Doge.get_stdin_data | train | def get_stdin_data(self):
"""
Get words from stdin.
"""
if self.tty.in_is_tty:
# No pipez found
return False
if sys.version_info < (3, 0):
stdin_lines = (l.decode('utf-8') for l in sys.stdin.xreadlines())
else:
stdin_line... | python | {
"resource": ""
} |
q251371 | Doge.get_processes | train | def get_processes(self):
"""
Grab a shuffled list of all currently running process names
"""
procs = set()
try:
# POSIX ps, so it should work in most environments where doge would
p = sp.Popen(['ps', '-A', '-o', 'comm='], stdout=sp.PIPE)
out... | python | {
"resource": ""
} |
q251372 | TTYHandler.get_tty_size | train | def get_tty_size(self):
"""
Get the current terminal size without using a subprocess
http://stackoverflow.com/questions/566746
I have no clue what-so-fucking ever over how this works or why it
returns the size of the terminal in both cells and pixels. But hey, it
does.
... | python | {
"resource": ""
} |
q251373 | _coords | train | def _coords(shape):
"""
Return a list of lists of coordinates of the polygon. The list consists
firstly of the list of exterior coordinates followed by zero or | python | {
"resource": ""
} |
q251374 | _union_in_blocks | train | def _union_in_blocks(contours, block_size):
"""
Generator which yields a valid shape for each block_size multiple of
input contours. This merges together the contours for each block before
yielding them.
"""
n_contours = len(contours)
for i in range(0, n_contours, block_size):
| python | {
"resource": ""
} |
q251375 | _polytree_node_to_shapely | train | def _polytree_node_to_shapely(node):
"""
Recurses down a Clipper PolyTree, extracting the results as Shapely
objects.
Returns a tuple of (list of polygons, list of children)
"""
polygons = []
children = []
for ch in node.Childs:
p, c = _polytree_node_to_shapely(ch)
poly... | python | {
"resource": ""
} |
q251376 | make_valid_pyclipper | train | def make_valid_pyclipper(shape):
"""
Use the pyclipper library to "union" a polygon on its own. This operation
uses the even-odd rule to determine which points are in the interior of
the polygon, and can reconstruct the orientation of the polygon from that.
The pyclipper library is robust, and uses ... | python | {
"resource": ""
} |
q251377 | make_valid_polygon | train | def make_valid_polygon(shape):
"""
Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly u... | python | {
"resource": ""
} |
q251378 | make_it_valid | train | def make_it_valid(shape):
"""
Attempt to make any polygon or multipolygon valid.
"""
if shape.is_empty:
return shape
elif shape.type == 'MultiPolygon':
| python | {
"resource": ""
} |
q251379 | _decode_lines | train | def _decode_lines(geom):
"""
Decode a linear MVT geometry into a list of Lines.
Each individual linestring in the MVT is extracted to a separate entry in
the list of lines.
"""
lines = []
current_line = []
current_moveto = None
# to keep track of the position. we'll adapt the move... | python | {
"resource": ""
} |
q251380 | _reorder_lines | train | def _reorder_lines(lines):
"""
Reorder lines so that the distance from the end of one to the beginning of
the next is minimised.
"""
x = 0
y = 0
new_lines = []
# treat the list of lines as a stack, off which we keep popping the best
# one to add next.
while lines:
# loo... | python | {
"resource": ""
} |
q251381 | _rewrite_geometry | train | def _rewrite_geometry(geom, new_lines):
"""
Re-encode a list of Lines with absolute MoveTos as a continuous stream of
MVT geometry commands, each relative to the last. Replace geom with that
stream.
"""
new_geom = []
x = 0
y = 0
for line in new_lines:
moveto, endsat, lineto_... | python | {
"resource": ""
} |
q251382 | optimise_tile | train | def optimise_tile(tile_bytes):
"""
Decode a sequence of bytes as an MVT tile and reorder the string table of
its layers and the order of its multilinestrings to save a few bytes.
"""
t = tile()
t.ParseFromString(tile_bytes)
for layer in t.layers:
sto = StringTableOptimiser()
... | python | {
"resource": ""
} |
q251383 | GeometryEncoder.coords_on_grid | train | def coords_on_grid(self, x, y):
""" Snap coordinates on the grid with integer coordinates """
if isinstance(x, float):
x = int(self._round(x))
if isinstance(y, float):
| python | {
"resource": ""
} |
q251384 | GeometryEncoder.encode_arc | train | def encode_arc(self, coords):
""" Appends commands to _geometry to create an arc.
- Returns False if nothing was added
- Returns True and moves _last_x, _last_y if
some points where added
"""
last_x, last_y = self._last_x, self._last_y
float_x, flo... | python | {
"resource": ""
} |
q251385 | Daemonize.sigterm | train | def sigterm(self, signum, frame):
"""
These actions will be done after SIGTERM.
"""
| python | {
"resource": ""
} |
q251386 | Daemonize.exit | train | def exit(self):
"""
Cleanup pid file at exit.
"""
| python | {
"resource": ""
} |
q251387 | js_reverse_inline | train | def js_reverse_inline(context):
"""
Outputs a string of javascript that can generate URLs via the use
of the names given to those URLs.
"""
if 'request' in context:
default_urlresolver = | python | {
"resource": ""
} |
q251388 | ArchiveIterator._iterate_records | train | def _iterate_records(self):
""" iterate over each record
"""
raise_invalid_gzip = False
empty_record = False
while True:
try:
self.record = self._next_record(self.next_line)
if raise_invalid_gzip:
self._raise_invali... | python | {
"resource": ""
} |
q251389 | ArchiveIterator._consume_blanklines | train | def _consume_blanklines(self):
""" Consume blank lines that are between records
- For warcs, there are usually 2
- For arcs, may be 1 or 0
- For block gzipped files, these are at end of each gzip envelope
and are included in record length which is the full gzip envelope
... | python | {
"resource": ""
} |
q251390 | ArchiveIterator.read_to_end | train | def read_to_end(self, record=None):
""" Read remainder of the stream
If a digester is included, update it
with the data read
"""
# no current record to read
if not self.record:
return None
# already at end of this record, don't read until it is consu... | python | {
"resource": ""
} |
q251391 | ArchiveIterator._next_record | train | def _next_record(self, next_line):
""" Use loader to parse the record from the reader stream
Supporting warc and arc records
"""
record = self.loader.parse_record_stream(self.reader,
next_line,
... | python | {
"resource": ""
} |
q251392 | LimitReader.wrap_stream | train | def wrap_stream(stream, content_length):
"""
If given content_length is an int > 0, wrap the stream
in a LimitReader. Otherwise, return the stream unaltered
"""
try:
content_length = int(content_length)
if content_length >= 0:
# optimize: i... | python | {
"resource": ""
} |
q251393 | StatusAndHeaders.replace_header | train | def replace_header(self, name, value):
"""
replace header with new value or add new header
return old header value, if any
"""
name_lower = name.lower()
for index in range(len(self.headers) - 1, -1, -1):
curr_name, curr_value = self.headers[index]
... | python | {
"resource": ""
} |
q251394 | StatusAndHeaders.validate_statusline | train | def validate_statusline(self, valid_statusline):
"""
Check that the statusline is valid, eg. starts with a numeric
code. If not, replace with passed in valid_statusline
| python | {
"resource": ""
} |
q251395 | StatusAndHeaders.add_range | train | def add_range(self, start, part_len, total_len):
"""
Add range headers indicating that this a partial response
"""
content_range = 'bytes {0}-{1}/{2}'.format(start,
start + part_len - 1,
| python | {
"resource": ""
} |
q251396 | StatusAndHeadersParser.parse | train | def parse(self, stream, full_statusline=None):
"""
parse stream for status line and headers
return a StatusAndHeaders object
support continuation headers starting with space or tab
"""
# status line w newlines intact
if full_statusline is None:
full_... | python | {
"resource": ""
} |
q251397 | StatusAndHeadersParser.split_prefix | train | def split_prefix(key, prefixs):
"""
split key string into prefix and remainder
for first matching prefix from a list
"""
key_upper = key.upper()
for prefix in prefixs:
| python | {
"resource": ""
} |
q251398 | Config.ask_questions | train | def ask_questions(self):
"""
Obtain config settings from the user.
"""
out_config = {}
for key in c.CONFIG_QUESTIONS:
section = key[1]
print
for question in section:
answer = utils.ask(question[1], question[2])
... | python | {
"resource": ""
} |
q251399 | log | train | def log(color, *args):
"""
Print a message with a specific color.
"""
if color in c.LOG_COLOR.keys():
out_color = c.LOG_COLOR[color]
else:
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.