text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k β |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_cookie(self):
""" Find a list of all cookies for a given domain """ |
return_cookies = []
origin_domain = self.request_object.dest_addr
for cookie in self.cookiejar:
for cookie_morsals in cookie[0].values():
cover_domain = cookie_morsals['domain']
if cover_domain == '':
if origin_domain == cookie[1]:
return_cookies.append(cookie[0])
else:
# Domain match algorithm
bvalue = cover_domain.lower()
hdn = origin_domain.lower()
nend = hdn.find(bvalue)
if nend is not False:
return_cookies.append(cookie[0])
return return_cookies |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_response(self):
""" Get the response from the socket """ |
self.sock.setblocking(0)
our_data = []
# Beginning time
begin = time.time()
while True:
# If we have data then if we're passed the timeout break
if our_data and time.time() - begin > self.HTTP_TIMEOUT:
break
# If we're dataless wait just a bit
elif time.time() - begin > self.HTTP_TIMEOUT * 2:
break
# Recv data
try:
data = self.sock.recv(self.RECEIVE_BYTES)
if data:
our_data.append(data)
begin = time.time()
else:
# Sleep for sometime to indicate a gap
time.sleep(self.HTTP_TIMEOUT)
except socket.error as err:
# Check if we got a timeout
if err.errno == errno.EAGAIN:
pass
# SSL will return SSLWantRead instead of EAGAIN
elif sys.platform == 'win32' and \
err.errno == errno.WSAEWOULDBLOCK:
pass
elif (self.request_object.protocol == 'https' and
err[0] == ssl.SSL_ERROR_WANT_READ):
continue
# If we didn't it's an error
else:
raise errors.TestError(
'Failed to connect to server',
{
'host': self.request_object.dest_addr,
'port': self.request_object.port,
'proto': self.request_object.protocol,
'message': err,
'function': 'http.HttpUA.get_response'
})
if ''.join(our_data) == '':
raise errors.TestError(
'No response from server. Request likely timed out.',
{
'host': self.request_object.dest_addr,
'port': self.request_object.port,
'proto': self.request_object.protocol,
'msg': 'Please send the request and check Wireshark',
'function': 'http.HttpUA.get_response'
})
self.response_object = HttpResponse(''.join(our_data), self)
try:
self.sock.shutdown(1)
self.sock.close()
except socket.error as err:
raise errors.TestError(
'We were unable to close the socket as expected.',
{
'msg': err,
'function': 'http.HttpUA.get_response'
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def process_regex(self, key):
""" Extract the value of key from dictionary if available and process it as a python regex """ |
return re.compile(self.output_dict[key]) if \
key in self.output_dict else None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instantiate_database(sqlite_file='ftwj.sqlite'):
""" Create journal database for FTW runs """ |
table_name = 'ftw'
col1 = 'rule_id'
col1_t = 'INTEGER'
col2 = 'test_id'
col2_t = 'STRING'
col3 = 'time_start'
col3_t = 'TEXT'
col4 = 'time_end'
col4_t = 'TEXT'
col5 = 'response_blob'
col5_t = 'TEXT'
col6 = 'status_code'
col6_t = 'INTEGER'
col7 = 'stage'
col7_t = 'INTEGER'
conn = sqlite3.connect(sqlite_file)
cur = conn.cursor()
q = 'CREATE TABLE {tn}({col1} {col1_t},{col2} {col2_t},{col3} {col3_t},{col4} {col4_t},{col5} {col5_t},{col6} {col6_t},{col7} {col7_t})'.format(
tn=table_name,
col1=col1, col1_t=col1_t,
col2=col2, col2_t=col2_t,
col3=col3, col3_t=col3_t,
col4=col4, col4_t=col4_t,
col5=col5, col5_t=col5_t,
col6=col6, col6_t=col6_t,
col7=col7, col7_t=col7_t)
cur.execute(q)
conn.commit()
conn.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_rulesets(ruledir, recurse):
""" List of ruleset objects extracted from the yaml directory """ |
if os.path.isdir(ruledir) and recurse:
yaml_files = [y for x in os.walk(ruledir) for y in glob(os.path.join(x[0], '*.yaml'))]
elif os.path.isdir(ruledir) and not recurse:
yaml_files = get_files(ruledir, 'yaml')
elif os.path.isfile(ruledir):
yaml_files = [ruledir]
extracted_files = extract_yaml(yaml_files)
rulesets = []
for extracted_yaml in extracted_files:
rulesets.append(ruleset.Ruleset(extracted_yaml))
return rulesets |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extract_yaml(yaml_files):
""" Take a list of yaml_files and load them to return back to the testing program """ |
loaded_yaml = []
for yaml_file in yaml_files:
try:
with open(yaml_file, 'r') as fd:
loaded_yaml.append(yaml.safe_load(fd))
except IOError as e:
print('Error reading file', yaml_file)
raise e
except yaml.YAMLError as e:
print('Error parsing file', yaml_file)
raise e
except Exception as e:
print('General error')
raise e
return loaded_yaml |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def deserialize(cls, raw_bytes):
""" Deserializes the given raw bytes into an instance. Since this is a subclass of ``Part`` but a top-level one (i.e. no other subclass of ``Part`` would have a ``Response`` as a part) this merely has to parse the raw bytes and discard the resulting offset. """ |
instance, _ = cls.parse(raw_bytes, offset=0)
return instance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self, parts=None):
""" Returns a two-element tuple with the ``struct`` format and values. Iterates over the applicable sub-parts and calls `render()` on them, accumulating the format string and values. Optionally takes a subset of parts to render, default behavior is to render all sub-parts belonging to the class. """ |
if not parts:
parts = self.parts
fmt = []
data = []
for name, part_class in parts:
if issubclass(part_class, Primitive):
part = part_class(getattr(self, name, None))
else:
part = getattr(self, name, None)
part_format, part_data = part.render()
fmt.extend(part_format)
data.extend(part_data)
return "".join(fmt), data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self):
""" Returns the ``struct`` format and list of the size and value. The format is derived from the size primitive and the length of the resulting encoded value (e.g. the format for a string of 'foo' ends up as 'h3s'. .. note :: The value is expected to be string-able (wrapped in ``str()``) and is then encoded as UTF-8. """ |
size_format = self.size_primitive.fmt
if self.value is None:
return size_format, [-1]
value = self.render_value(self.value)
size = len(value)
fmt = "%s%ds" % (size_format, size)
return fmt, [size, value] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def of(cls, part_class):
""" Creates a new class with the ``item_class`` attribute properly set. """ |
copy = type(
"VectorOf%s" % part_class.__name__,
cls.__bases__, dict(cls.__dict__)
)
copy.item_class = part_class
return copy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def render(self):
""" Creates a composite ``struct`` format and the data to render with it. The format and data are prefixed with a 32-bit integer denoting the number of elements, after which each of the items in the array value are ``render()``-ed and added to the format and data as well. """ |
value = self.value
if value is None:
value = []
fmt = [Int.fmt]
data = [len(value)]
for item_value in value:
if issubclass(self.item_class, Primitive):
item = self.item_class(item_value)
else:
item = item_value
item_format, item_data = item.render()
fmt.extend(item_format)
data.extend(item_data)
return "".join(fmt), data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse(cls, buff, offset):
""" Parses a raw buffer at offset and returns the resulting array value. Starts off by `parse()`-ing the 32-bit element count, followed by parsing items out of the buffer "count" times. """ |
count, offset = Int.parse(buff, offset)
values = []
for _ in range(count):
value, new_offset = cls.item_class.parse(buff, offset)
values.append(value)
offset = new_offset
return values, offset |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def round_robin(members, items):
""" Default allocator with a round robin approach. In this algorithm, each member of the group is cycled over and given an item until there are no items left. This assumes roughly equal capacity for each member and aims for even distribution of item counts. """ |
allocation = collections.defaultdict(set)
for member, item in zip(itertools.cycle(members), items):
allocation[member].add(item)
return allocation |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def xfrange(start, stop, step=1, maxSize=-1):
""" Returns a generator that yields the frames from start to stop, inclusive. In other words it adds or subtracts a frame, as necessary, to return the stop value as well, if the stepped range would touch that value. Args: start (int):
stop (int):
step (int):
Note that the sign will be ignored maxSize (int):
Returns: generator: Raises: :class:`fileseq.exceptions.MaxSizeException`: if size is exceeded """ |
if start <= stop:
stop, step = stop + 1, abs(step)
else:
stop, step = stop - 1, -abs(step)
if maxSize >= 0:
size = lenRange(start, stop, step)
if size > maxSize:
raise exceptions.MaxSizeException(
"Size %d > %s (MAX_FRAME_SIZE)" % (size, maxSize))
# because an xrange is an odd object all its own, we wrap it in a
# generator expression to get a proper Generator
return (f for f in xrange(start, stop, step)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unique(seen, *iterables):
""" Get the unique items in iterables while preserving order. Note that this mutates the seen set provided only when the returned generator is used. Args: seen (set):
either an empty set, or the set of things already seen *iterables: one or more iterable lists to chain together Returns: generator: """ |
_add = seen.add
# return a generator of the unique items and the set of the seen items
# the seen set will mutate when the generator is iterated over
return (i for i in chain(*iterables) if i not in seen and not _add(i)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def copy(self):
""" Create a deep copy of this sequence Returns: :obj:`.FileSequence`: """ |
fs = self.__class__.__new__(self.__class__)
fs.__dict__ = self.__dict__.copy()
fs._frameSet = None
if self._frameSet is not None:
fs._frameSet = self._frameSet.copy()
return fs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format(self, template="{basename}{range}{padding}{extension}"):
"""Return the file sequence as a formatted string according to the given template. Utilizes the python string format syntax. Available keys include: * basename - the basename of the sequence. * extension - the file extension of the sequence. * start - the start frame. * end - the end frame. * length - the length of the frame range. * padding - the detecting amount of padding. * inverted - the inverted frame range. (returns "" if none) * dirname - the directory name. If asking for the inverted range value, and the new inverted range exceeded :const:`fileseq.constants.MAX_FRAME_SIZE`, a ``MaxSizeException`` will be raised. Args: template (str):
Returns: str: Raises: :class:`fileseq.exceptions.MaxSizeException`: If frame size exceeds :const:`fileseq.constants.MAX_FRAME_SIZE` """ |
# Potentially expensive if inverted range is large
# and user never asked for it in template
inverted = (self.invertedFrameRange() or "") if "{inverted}" in template else ""
return template.format(
basename=self.basename(),
extension=self.extension(), start=self.start(),
end=self.end(), length=len(self),
padding=self.padding(),
range=self.frameRange() or "",
inverted=inverted,
dirname=self.dirname()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setDirname(self, dirname):
""" Set a new directory name for the sequence. Args: dirname (str):
the new directory name """ |
# Make sure the dirname always ends in
# a path separator character
sep = utils._getPathSep(dirname)
if not dirname.endswith(sep):
dirname += sep
self._dir = utils.asString(dirname) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setExtension(self, ext):
""" Set a new file extension for the sequence. Note: A leading period will be added if none is provided. Args: ext (str):
the new file extension """ |
if ext[0] != ".":
ext = "." + ext
self._ext = utils.asString(ext) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frame(self, frame):
""" Return a path go the given frame in the sequence. Integer or string digits are treated as a frame number and padding is applied, all other values are passed though. Examples: /foo/bar.0001.exr /foo/bar.#.exr Args: frame (int or str):
the desired frame number or a char to pass through (ie. #) Returns: str: """ |
try:
zframe = str(int(frame)).zfill(self._zfill)
except ValueError:
zframe = frame
# There may have been no placeholder for frame IDs in
# the sequence, in which case we don't want to insert
# a frame ID
if self._zfill == 0:
zframe = ""
return "".join((self._dir, self._base, zframe, self._ext)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def yield_sequences_in_list(paths):
""" Yield the discrete sequences within paths. This does not try to determine if the files actually exist on disk, it assumes you already know that. Args: paths (list[str]):
a list of paths Yields: :obj:`FileSequence`: """ |
seqs = {}
_check = DISK_RE.match
for match in ifilter(None, imap(_check, imap(utils.asString, paths))):
dirname, basename, frame, ext = match.groups()
if not basename and not ext:
continue
key = (dirname, basename, ext)
seqs.setdefault(key, set())
if frame:
seqs[key].add(frame)
for (dirname, basename, ext), frames in seqs.iteritems():
# build the FileSequence behind the scenes, rather than dupe work
seq = FileSequence.__new__(FileSequence)
seq._dir = dirname or ''
seq._base = basename or ''
seq._ext = ext or ''
if frames:
seq._frameSet = FrameSet(set(imap(int, frames))) if frames else None
seq._pad = FileSequence.getPaddingChars(min(imap(len, frames)))
else:
seq._frameSet = None
seq._pad = ''
seq.__init__(str(seq))
yield seq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findSequencesOnDisk(cls, pattern, include_hidden=False, strictPadding=False):
""" Yield the sequences found in the given directory. Examples: The `pattern` can also specify glob-like shell wildcards including the following: * ``?`` - 1 wildcard character * ``*`` - 1 or more wildcard character * ``{foo,bar}`` - either 'foo' or 'bar' Exact frame ranges are not considered, and padding characters are converted to wildcards (``#`` or ``@``) Examples: Args: pattern (str):
directory to scan, or pattern to filter in directory include_hidden (bool):
if true, show .hidden files as well strictPadding (bool):
if True, ignore files with padding length different from pattern Returns: list: """ |
# reserve some functions we're going to need quick access to
_not_hidden = lambda f: not f.startswith('.')
_match_pattern = None
_filter_padding = None
_join = os.path.join
seq = None
dirpath = pattern
# Support the pattern defining a filter for the files
# in the existing directory
if not os.path.isdir(pattern):
dirpath, filepat = os.path.split(pattern)
if not os.path.isdir(dirpath):
return []
# Start building a regex for filtering files
seq = cls(filepat)
patt = seq.basename().replace('.', r'\.')
if seq.padding():
patt += '\d+'
if seq.extension():
patt += seq.extension()
# Convert braces groups into regex capture groups
view = bytearray(patt)
matches = re.finditer(r'{(.*?)(?:,(.*?))*}', patt)
for match in reversed(list(matches)):
i, j = match.span()
view[i:j] = '(%s)' % '|'.join([m.strip() for m in match.groups()])
view = view.replace('*', '.*')
view = view.replace('?', '.')
view += '$'
try:
_match_pattern = re.compile(str(view)).match
except re.error:
msg = 'Invalid file pattern: {}'.format(filepat)
raise FileSeqException(msg)
if seq.padding() and strictPadding:
_filter_padding = functools.partial(cls._filterByPaddingNum, num=seq.zfill())
# Get just the immediate files under the dir.
# Avoids testing the os.listdir() for files as
# a second step.
ret = next(os.walk(dirpath), None)
files = ret[-1] if ret else []
# collapse some generators to get us the files that match our regex
if not include_hidden:
files = ifilter(_not_hidden, files)
# Filter by files that match the provided file pattern
if _match_pattern:
files = ifilter(_match_pattern, files)
# Filter by files that match the frame padding in the file pattern
if _filter_padding:
# returns a generator
files = _filter_padding(files)
# Ensure our dirpath ends with a path separator, so
# that we can control which sep is used during the
# os.path.join
sep = utils._getPathSep(dirpath)
if not dirpath.endswith(sep):
dirpath += sep
files = (_join(dirpath, f) for f in files)
files = list(files)
seqs = list(FileSequence.yield_sequences_in_list(files))
if _filter_padding and seq:
pad = cls.conformPadding(seq.padding())
# strict padding should preserve the original padding
# characters in the found sequences.
for s in seqs:
s.setPadding(pad)
return seqs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def findSequenceOnDisk(cls, pattern, strictPadding=False):
""" Search for a specific sequence on disk. The padding characters used in the `pattern` are used to filter the frame values of the files on disk (if `strictPadding` is True). Examples: Find sequence matching basename and extension, and a wildcard for any frame. returns bar.1.exr bar.10.exr, bar.100.exr, bar.1000.exr, inclusive Find exactly 4-padded sequence, i.e. seq/bar1-100#.exr returns only frames bar1000.exr through bar9999.exr Args: pattern (str):
the sequence pattern being searched for strictPadding (bool):
if True, ignore files with padding length different from `pattern` Returns: str: Raises: :class:`.FileSeqException`: if no sequence is found on disk """ |
seq = cls(pattern)
if seq.frameRange() == '' and seq.padding() == '':
if os.path.isfile(pattern):
return seq
patt = seq.format('{dirname}{basename}*{extension}')
ext = seq.extension()
basename = seq.basename()
pad = seq.padding()
globbed = iglob(patt)
if pad and strictPadding:
globbed = cls._filterByPaddingNum(globbed, seq.zfill())
pad = cls.conformPadding(pad)
matches = cls.yield_sequences_in_list(globbed)
for match in matches:
if match.basename() == basename and match.extension() == ext:
if pad and strictPadding:
match.setPadding(pad)
return match
msg = 'no sequence found on disk matching {0}'
raise FileSeqException(msg.format(pattern)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _filterByPaddingNum(cls, iterable, num):
""" Yield only path elements from iterable which have a frame padding that matches the given target padding number Args: iterable (collections.Iterable):
num (int):
Yields: str: """ |
_check = DISK_RE.match
for item in iterable:
# Add a filter for paths that don't match the frame
# padding of a given number
matches = _check(item)
if not matches:
if num <= 0:
# Not a sequence pattern, but we were asked
# to match on a zero padding
yield item
continue
frame = matches.group(3) or ''
if not frame:
if num <= 0:
# No frame value was parsed, but we were asked
# to match on a zero padding
yield item
continue
# We have a frame number
if frame[0] == '0' or frame[:2] == '-0':
if len(frame) == num:
# A frame leading with '0' is explicitly
# padded and can only be a match if its exactly
# the target padding number
yield item
continue
if len(frame) >= num:
# A frame that does not lead with '0' can match
# a padding width >= to the target padding number
yield item
continue |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPaddingNum(chars):
""" Given a supported group of padding characters, return the amount of padding. Args: chars (str):
a supported group of padding characters Returns: int: Raises: ValueError: if unsupported padding character is detected """ |
match = PRINTF_SYNTAX_PADDING_RE.match(chars)
if match:
return int(match.group(1))
try:
return sum([PAD_MAP[char] for char in chars])
except KeyError:
msg = "Detected an unsupported padding character: \"{}\"."
msg += " Supported padding characters: {} or printf syntax padding"
msg += " %<int>d"
raise ValueError(msg.format(char, str(PAD_MAP.keys()))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def conformPadding(cls, chars):
""" Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PAD_MAP, then it is returned unmodified. Example:: '#' -> '#' '@@@@' -> '@@@@' '%04d' -> '#' Args: chars (str):
input padding chars Returns: str: conformed padding chars Raises: ValueError: If chars contains invalid padding characters """ |
pad = chars
if pad and pad[0] not in PAD_MAP:
pad = cls.getPaddingChars(cls.getPaddingNum(pad))
return pad |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _cast_to_frameset(cls, other):
""" Private method to simplify comparison operations. Args: other (:class:`FrameSet` or set or frozenset or or iterable):
item to be compared Returns: :class:`FrameSet` Raises: :class:`NotImplemented`: if a comparison is impossible """ |
if isinstance(other, FrameSet):
return other
try:
return FrameSet(other)
except Exception:
return NotImplemented |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def issubset(self, other):
""" Check if the contents of `self` is a subset of the contents of `other.` Args: other (:class:`FrameSet`):
Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` """ |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items <= other.items |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def issuperset(self, other):
""" Check if the contents of `self` is a superset of the contents of `other.` Args: other (:class:`FrameSet`):
Returns: bool: :class:`NotImplemented`: if `other` fails to convert to a :class:`FrameSet` """ |
other = self._cast_to_frameset(other)
if other is NotImplemented:
return NotImplemented
return self.items >= other.items |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _maxSizeCheck(cls, obj):
""" Raise a MaxSizeException if ``obj`` exceeds MAX_FRAME_SIZE Args: obj (numbers.Number or collection):
Raises: :class:`fileseq.exceptions.MaxSizeException`: """ |
fail = False
size = 0
if isinstance(obj, numbers.Number):
if obj > constants.MAX_FRAME_SIZE:
fail = True
size = obj
elif hasattr(obj, '__len__'):
size = len(obj)
fail = size > constants.MAX_FRAME_SIZE
if fail:
raise MaxSizeException('Frame size %s > %s (MAX_FRAME_SIZE)' \
% (size, constants.MAX_FRAME_SIZE)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def padFrameRange(frange, zfill):
""" Return the zero-padded version of the frame range string. Args: frange (str):
a frame range to test zfill (int):
Returns: str: """ |
def _do_pad(match):
"""
Substitutes padded for unpadded frames.
"""
result = list(match.groups())
result[1] = pad(result[1], zfill)
if result[4]:
result[4] = pad(result[4], zfill)
return ''.join((i for i in result if i))
return PAD_RE.sub(_do_pad, frange) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def framesToFrameRanges(frames, zfill=0):
""" Converts a sequence of frames to a series of padded frame range strings. Args: frames (collections.Iterable):
sequence of frames to process zfill (int):
width for zero padding Yields: str: """ |
_build = FrameSet._build_frange_part
curr_start = None
curr_stride = None
curr_frame = None
last_frame = None
curr_count = 0
for curr_frame in frames:
if curr_start is None:
curr_start = curr_frame
last_frame = curr_frame
curr_count += 1
continue
if curr_stride is None:
curr_stride = abs(curr_frame-curr_start)
new_stride = abs(curr_frame-last_frame)
if curr_stride == new_stride:
last_frame = curr_frame
curr_count += 1
elif curr_count == 2 and curr_stride != 1:
yield _build(curr_start, curr_start, None, zfill)
curr_start = last_frame
curr_stride = new_stride
last_frame = curr_frame
else:
yield _build(curr_start, last_frame, curr_stride, zfill)
curr_stride = None
curr_start = curr_frame
last_frame = curr_frame
curr_count = 1
if curr_count == 2 and curr_stride != 1:
yield _build(curr_start, curr_start, None, zfill)
yield _build(curr_frame, curr_frame, None, zfill)
else:
yield _build(curr_start, curr_frame, curr_stride, zfill) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def framesToFrameRange(frames, sort=True, zfill=0, compress=False):
""" Converts an iterator of frames into a frame range string. Args: frames (collections.Iterable):
sequence of frames to process sort (bool):
sort the sequence before processing zfill (int):
width for zero padding compress (bool):
remove any duplicates before processing Returns: str: """ |
if compress:
frames = unique(set(), frames)
frames = list(frames)
if not frames:
return ''
if len(frames) == 1:
return pad(frames[0], zfill)
if sort:
frames.sort()
return ','.join(FrameSet.framesToFrameRanges(frames, zfill)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _parse_optional_params(self, oauth_params, req_kwargs):
'''
Parses and sets optional OAuth parameters on a request.
:param oauth_param: The OAuth parameter to parse.
:type oauth_param: str
:param req_kwargs: The keyworded arguments passed to the request
method.
:type req_kwargs: dict
'''
params = req_kwargs.get('params', {})
data = req_kwargs.get('data') or {}
for oauth_param in OPTIONAL_OAUTH_PARAMS:
if oauth_param in params:
oauth_params[oauth_param] = params.pop(oauth_param)
if oauth_param in data:
oauth_params[oauth_param] = data.pop(oauth_param)
if params:
req_kwargs['params'] = params
if data:
req_kwargs['data'] = data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_oauth_params(self, req_kwargs):
'''Prepares OAuth params for signing.'''
oauth_params = {}
oauth_params['oauth_consumer_key'] = self.consumer_key
oauth_params['oauth_nonce'] = sha1(
str(random()).encode('ascii')).hexdigest()
oauth_params['oauth_signature_method'] = self.signature.NAME
oauth_params['oauth_timestamp'] = int(time())
if self.access_token is not None:
oauth_params['oauth_token'] = self.access_token
oauth_params['oauth_version'] = self.VERSION
self._parse_optional_params(oauth_params, req_kwargs)
return oauth_params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sign(url, app_id, app_secret, hash_meth='sha1', **params):
'''
A signature method which generates the necessary Ofly parameters.
:param app_id: The oFlyAppId, i.e. "application ID".
:type app_id: str
:param app_secret: The oFlyAppSecret, i.e. "shared secret".
:type app_secret: str
:param hash_meth: The hash method to use for signing, defaults to
"sha1".
:type hash_meth: str
:param \*\*params: Additional parameters.
:type \*\*\params: dict
'''
hash_meth_str = hash_meth
if hash_meth == 'sha1':
hash_meth = sha1
elif hash_meth == 'md5':
hash_meth = md5
else:
raise TypeError('hash_meth must be one of "sha1", "md5"')
now = datetime.utcnow()
milliseconds = now.microsecond // 1000
time_format = '%Y-%m-%dT%H:%M:%S.{0}Z'.format(milliseconds)
ofly_params = {'oflyAppId': app_id,
'oflyHashMeth': hash_meth_str.upper(),
'oflyTimestamp': now.strftime(time_format)}
url_path = urlsplit(url).path
signature_base_string = app_secret + url_path + '?'
if len(params):
signature_base_string += get_sorted_params(params) + '&'
signature_base_string += get_sorted_params(ofly_params)
if not isinstance(signature_base_string, bytes):
signature_base_string = signature_base_string.encode('utf-8')
ofly_params['oflyApiSig'] = \
hash_meth(signature_base_string).hexdigest()
all_params = dict(tuple(ofly_params.items()) + tuple(params.items()))
return get_sorted_params(all_params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _get_auth_header(self):
''' Constructs and returns an authentication header. '''
realm = 'realm="{realm}"'.format(realm=self.realm)
params = ['{k}="{v}"'.format(k=k, v=quote(str(v), safe=''))
for k, v in self.oauth_params.items()]
return 'OAuth ' + ','.join([realm] + params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _remove_qs(self, url):
'''
Removes a query string from a URL before signing.
:param url: The URL to strip.
:type url: str
'''
scheme, netloc, path, query, fragment = urlsplit(url)
return urlunsplit((scheme, netloc, path, '', fragment)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _normalize_request_parameters(self, oauth_params, req_kwargs):
'''
This process normalizes the request parameters as detailed in the OAuth
1.0 spec.
Additionally we apply a `Content-Type` header to the request of the
`FORM_URLENCODE` type if the `Content-Type` was previously set, i.e. if
this is a `POST` or `PUT` request. This ensures the correct header is
set as per spec.
Finally we sort the parameters in preparation for signing and return
a URL encoded string of all normalized parameters.
:param oauth_params: OAuth params to sign with.
:type oauth_params: dict
:param req_kwargs: Request kwargs to normalize.
:type req_kwargs: dict
'''
normalized = []
params = req_kwargs.get('params', {})
data = req_kwargs.get('data', {})
headers = req_kwargs.get('headers', {})
# process request parameters
for k, v in params.items():
if v is not None:
normalized += [(k, v)]
# process request data
if 'Content-Type' in headers and \
headers['Content-Type'] == FORM_URLENCODED:
for k, v in data.items():
normalized += [(k, v)]
# extract values from our list of tuples
all_normalized = []
for t in normalized:
k, v = t
if is_basestring(v) and not isinstance(v, bytes):
v = v.encode('utf-8')
all_normalized += [(k, v)]
# add in the params from oauth_params for signing
for k, v in oauth_params.items():
if (k, v) in all_normalized: # pragma: no cover
continue
all_normalized += [(k, v)]
# sort the params as per the OAuth 1.0/a spec
all_normalized.sort()
# finally encode the params as a string
return urlencode(all_normalized, True)\
.replace('+', '%20')\
.replace('%7E', '~') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def sign(self, consumer_secret, access_token_secret, method, url,
oauth_params, req_kwargs):
'''Sign request using PLAINTEXT method.
:param consumer_secret: Consumer secret.
:type consumer_secret: str
:param access_token_secret: Access token secret (optional).
:type access_token_secret: str
:param method: Unused
:type method: str
:param url: Unused
:type url: str
:param oauth_params: Unused
:type oauth_params: dict
:param req_kwargs: Unused
:type req_kwargs: dict
'''
key = self._escape(consumer_secret) + b'&'
if access_token_secret:
key += self._escape(access_token_secret)
return key.decode() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_request_token(self,
method='GET',
decoder=parse_utf8_qsl,
key_token='oauth_token',
key_token_secret='oauth_token_secret',
**kwargs):
'''
Return a request token pair.
:param method: A string representation of the HTTP method to be used,
defaults to `GET`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key_token: The key the access token will be decoded by, defaults
to 'oauth_token'.
:type string:
:param key_token_secret: The key the access token will be decoded by,
defaults to 'oauth_token_secret'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
r = self.get_raw_request_token(method=method, **kwargs)
request_token, request_token_secret = \
process_token_request(r, decoder, key_token, key_token_secret)
return request_token, request_token_secret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_access_token(self,
request_token,
request_token_secret,
method='GET',
decoder=parse_utf8_qsl,
key_token='oauth_token',
key_token_secret='oauth_token_secret',
**kwargs):
'''
Returns an access token pair.
:param request_token: The request token as returned by
:meth:`get_request_token`.
:type request_token: str
:param request_token_secret: The request token secret as returned by
:meth:`get_request_token`.
:type request_token_secret: str
:param method: A string representation of the HTTP method to be
used, defaults to `GET`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key_token: The key the access token will be decoded by, defaults
to 'oauth_token'.
:type string:
:param key_token_secret: The key the access token will be decoded by,
defaults to 'oauth_token_secret'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
r = self.get_raw_access_token(request_token,
request_token_secret,
method=method,
**kwargs)
access_token, access_token_secret = \
process_token_request(r, decoder, key_token, key_token_secret)
return access_token, access_token_secret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def get_access_token(self,
method='POST',
decoder=parse_utf8_qsl,
key='access_token',
**kwargs):
'''
Returns an access token.
:param method: A string representation of the HTTP method to be used,
defaults to `POST`.
:type method: str
:param decoder: A function used to parse the Response content. Should
return a dictionary.
:type decoder: func
:param key: The key the access token will be decoded by, defaults to
'access_token'.
:type string:
:param \*\*kwargs: Optional arguments. Same as Requests.
:type \*\*kwargs: dict
'''
r = self.get_raw_access_token(method, **kwargs)
access_token, = process_token_request(r, decoder, key)
return access_token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_logged_in(username=None):
"""Checks if user is logged in if `username` is passed check if specified user is logged in username can be a list""" |
if username:
if not isinstance(username, (list, tuple)):
username = [username]
return 'simple_logged_in' in session and get_username() in username
return 'simple_logged_in' in session |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def login_required(function=None, username=None, basic=False, must=None):
"""Decorate views to require login @login_required @login_required() @login_required(username='admin') @login_required(username=['admin', 'jon']) @login_required(basic=True) @login_required(must=[function, another_function]) """ |
if function and not callable(function):
raise ValueError(
'Decorator receives only named arguments, '
'try login_required(username="foo")'
)
def check(validators):
"""Return in the first validation error, else return None"""
if validators is None:
return
if not isinstance(validators, (list, tuple)):
validators = [validators]
for validator in validators:
error = validator(get_username())
if error is not None:
return SimpleLogin.get_message('auth_error', error), 403
def dispatch(fun, *args, **kwargs):
if basic and request.is_json:
return dispatch_basic_auth(fun, *args, **kwargs)
if is_logged_in(username=username):
return check(must) or fun(*args, **kwargs)
elif is_logged_in():
return SimpleLogin.get_message('access_denied'), 403
else:
flash(SimpleLogin.get_message('login_required'), 'warning')
return redirect(url_for('simplelogin.login', next=request.path))
def dispatch_basic_auth(fun, *args, **kwargs):
simplelogin = current_app.extensions['simplelogin']
auth_response = simplelogin.basic_auth()
if auth_response is True:
return check(must) or fun(*args, **kwargs)
else:
return auth_response
if function:
@wraps(function)
def simple_decorator(*args, **kwargs):
"""This is for when decorator is @login_required"""
return dispatch(function, *args, **kwargs)
return simple_decorator
def decorator(f):
"""This is for when decorator is @login_required(...)"""
@wraps(f)
def wrap(*args, **kwargs):
return dispatch(f, *args, **kwargs)
return wrap
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_message(message, *args, **kwargs):
"""Helper to get internal messages outside this instance""" |
msg = current_app.extensions['simplelogin'].messages.get(message)
if msg and (args or kwargs):
return msg.format(*args, **kwargs)
return msg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_my_users(user):
"""Check if user exists and its credentials. Take a look at encrypt_app.py and encrypt_cli.py to see how to encrypt passwords """ |
user_data = my_users.get(user['username'])
if not user_data:
return False # <--- invalid credentials
elif user_data.get('password') == user['password']:
return True # <--- user is logged in!
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_user(**data):
"""Creates user with encrypted password""" |
if 'username' not in data or 'password' not in data:
raise ValueError('username and password are required.')
# Hash the user password
data['password'] = generate_password_hash(
data.pop('password'),
method='pbkdf2:sha256'
)
# Here you insert the `data` in your users database
# for this simple example we are recording in a json file
db_users = json.load(open('users.json'))
# add the new created user to json
db_users[data['username']] = data
# commit changes to database
json.dump(db_users, open('users.json', 'w'))
return data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_app(f):
"""Calls function passing app as first argument""" |
@wraps(f)
def decorator(*args, **kwargs):
app = create_app()
configure_extensions(app)
configure_views(app)
return f(app=app, *args, **kwargs)
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adduser(app, username, password):
"""Add new user with admin access""" |
with app.app_context():
create_user(username=username, password=password)
click.echo('user created!') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pulse_data(self, value):
"""Pulse the `enable` flag to process value.""" |
if self._i2c_expander == 'PCF8574':
self.bus.write_byte(self._address, ((value & ~PCF8574_E) | self._backlight))
c.usleep(1)
self.bus.write_byte(self._address, value | PCF8574_E | self._backlight)
c.usleep(1)
self.bus.write_byte(self._address, ((value & ~PCF8574_E) | self._backlight))
c.usleep(100)
elif self._i2c_expander in ['MCP23008', 'MCP23017']:
self._mcp_data &= ~MCP230XX_DATAMASK
self._mcp_data |= value << MCP230XX_DATASHIFT
self._mcp_data &= ~MCP230XX_E
self.bus.write_byte_data(self._address, self._mcp_gpio, self._mcp_data)
c.usleep(1)
self._mcp_data |= MCP230XX_E
self.bus.write_byte_data(self._address, self._mcp_gpio, self._mcp_data)
c.usleep(1)
self._mcp_data &= ~MCP230XX_E
self.bus.write_byte_data(self._address, self._mcp_gpio, self._mcp_data)
c.usleep(100) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write4bits(self, value):
"""Write 4 bits of data into the data bus.""" |
for i in range(4):
bit = (value >> i) & 0x01
GPIO.output(self.pins[i + 7], bit)
self._pulse_enable() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pulse_enable(self):
"""Pulse the `enable` flag to process data.""" |
GPIO.output(self.pins.e, 0)
c.usleep(1)
GPIO.output(self.pins.e, 1)
c.usleep(1)
GPIO.output(self.pins.e, 0)
c.usleep(100) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_string(self, value):
""" Write the specified unicode string to the display. To control multiline behavior, use newline (``\\n``) and carriage return (``\\r``) characters. Lines that are too long automatically continue on next line, as long as ``auto_linebreaks`` has not been disabled. Make sure that you're only passing unicode objects to this function. The unicode string is then converted to the correct LCD encoding by using the charmap specified at instantiation time. If you're dealing with bytestrings (the default string type in Python 2), convert it to a unicode object using the ``.decode(encoding)`` method and the appropriate encoding. Example for UTF-8 encoded strings: .. code:: 'Temperature: 30\xc2\xb0C' u'Temperature: 30\xb0C' """ |
encoded = self.codec.encode(value) # type: List[int]
ignored = False
for [char, lookahead] in c.sliding_window(encoded, lookahead=1):
# If the previous character has been ignored, skip this one too.
if ignored is True:
ignored = False
continue
# Write regular chars
if char not in [codecs.CR, codecs.LF]:
self.write(char)
continue
# We're now left with only CR and LF characters. If an auto
# linebreak happened recently, and the lookahead matches too,
# ignore this write.
if self.recent_auto_linebreak is True:
crlf = (char == codecs.CR and lookahead == codecs.LF)
lfcr = (char == codecs.LF and lookahead == codecs.CR)
if crlf or lfcr:
ignored = True
continue
# Handle newlines and carriage returns
row, col = self.cursor_pos
if char == codecs.LF:
if row < self.lcd.rows - 1:
self.cursor_pos = (row + 1, col)
else:
self.cursor_pos = (0, col)
elif char == codecs.CR:
if self.text_align_mode == 'left':
self.cursor_pos = (row, 0)
else:
self.cursor_pos = (row, self.lcd.cols - 1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(self):
"""Overwrite display with blank characters and reset cursor position.""" |
self.command(c.LCD_CLEARDISPLAY)
self._cursor_pos = (0, 0)
self._content = [[0x20] * self.lcd.cols for _ in range(self.lcd.rows)]
c.msleep(2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def home(self):
"""Set cursor to initial position and reset any shifting.""" |
self.command(c.LCD_RETURNHOME)
self._cursor_pos = (0, 0)
c.msleep(2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shift_display(self, amount):
"""Shift the display. Use negative amounts to shift left and positive amounts to shift right.""" |
if amount == 0:
return
direction = c.LCD_MOVERIGHT if amount > 0 else c.LCD_MOVELEFT
for i in range(abs(amount)):
self.command(c.LCD_CURSORSHIFT | c.LCD_DISPLAYMOVE | direction)
c.usleep(50) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write(self, value):
# type: (int) -> None """Write a raw byte to the LCD.""" |
# Get current position
row, col = self._cursor_pos
# Write byte if changed
try:
if self._content[row][col] != value:
self._send_data(value)
self._content[row][col] = value # Update content cache
unchanged = False
else:
unchanged = True
except IndexError as e:
# Position out of range
if self.auto_linebreaks is True:
raise e
self._send_data(value)
unchanged = False
# Update cursor position.
if self.text_align_mode == 'left':
if self.auto_linebreaks is False or col < self.lcd.cols - 1:
# No newline, update internal pointer
newpos = (row, col + 1)
if unchanged:
self.cursor_pos = newpos
else:
self._cursor_pos = newpos
self.recent_auto_linebreak = False
else:
# Newline, reset pointer
if row < self.lcd.rows - 1:
self.cursor_pos = (row + 1, 0)
else:
self.cursor_pos = (0, 0)
self.recent_auto_linebreak = True
else:
if self.auto_linebreaks is False or col > 0:
# No newline, update internal pointer
newpos = (row, col - 1)
if unchanged:
self.cursor_pos = newpos
else:
self._cursor_pos = newpos
self.recent_auto_linebreak = False
else:
# Newline, reset pointer
if row < self.lcd.rows - 1:
self.cursor_pos = (row + 1, self.lcd.cols - 1)
else:
self.cursor_pos = (0, self.lcd.cols - 1)
self.recent_auto_linebreak = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cursor(lcd, row, col):
""" Context manager to control cursor position. DEPRECATED. """ |
warnings.warn('The `cursor` context manager is deprecated', DeprecationWarning)
lcd.cursor_pos = (row, col)
yield |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sliding_window(seq, lookahead):
""" Create a sliding window with the specified number of lookahead characters. """ |
it = itertools.chain(iter(seq), ' ' * lookahead) # Padded iterator
window_size = lookahead + 1
result = tuple(itertools.islice(it, window_size))
if len(result) == window_size:
yield result
for elem in it:
result = result[1:] + (elem,)
yield result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_params():
""" get the cmdline params """ |
parser = argparse.ArgumentParser()
parser.add_argument("--connect-timeout",
type=float,
default=10.0,
help="ZK connect timeout")
parser.add_argument("--run-once",
type=str,
default="",
help="Run a command non-interactively and exit")
parser.add_argument("--run-from-stdin",
action="store_true",
default=False,
help="Read cmds from stdin, run them and exit")
parser.add_argument("--sync-connect",
action="store_true",
default=False,
help="Connect synchronously.")
parser.add_argument("--readonly",
action="store_true",
default=False,
help="Enable readonly.")
parser.add_argument("--tunnel",
type=str,
help="Create a ssh tunnel via this host",
default=None)
parser.add_argument("--version",
action="store_true",
default=False,
help="Display version and exit.")
parser.add_argument("hosts",
nargs="*",
help="ZK hosts to connect")
params = parser.parse_args()
return CLIParams(
params.connect_timeout,
params.run_once,
params.run_from_stdin,
params.sync_connect,
params.hosts,
params.readonly,
params.tunnel,
params.version
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_unbuffered_mode():
""" make output unbuffered """ |
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.stdout) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(cls, acl):
""" transform an ACL to a dict """ |
return {
"perms": acl.perms,
"id": {
"scheme": acl.id.scheme,
"id": acl.id.id
}
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_dict(cls, acl_dict):
""" ACL from dict """ |
perms = acl_dict.get("perms", Permissions.ALL)
id_dict = acl_dict.get("id", {})
id_scheme = id_dict.get("scheme", "world")
id_id = id_dict.get("id", "anyone")
return ACL(perms, Id(id_scheme, id_id)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connected(func):
""" check connected, fails otherwise """ |
@wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if not self.connected:
self.show_output("Not connected.")
else:
try:
return func(*args, **kwargs)
except APIError:
self.show_output("ZooKeeper internal error.")
except AuthFailedError:
self.show_output("Authentication failed.")
except NoAuthError:
self.show_output("Not authenticated.")
except BadVersionError:
self.show_output("Bad version.")
except ConnectionLoss:
self.show_output("Connection loss.")
except NotReadOnlyCallError:
self.show_output("Not a read-only operation.")
except BadArgumentsError:
self.show_output("Bad arguments.")
except SessionExpiredError:
self.show_output("Session expired.")
except UnimplementedError as ex:
self.show_output("Not implemented by the server: %s." % str(ex))
except ZookeeperError as ex:
self.show_output("Unknown ZooKeeper error: %s" % str(ex))
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_add_auth(self, params):
""" \x1b[1mNAME\x1b[0m add_auth - Authenticates the session \x1b[1mSYNOPSIS\x1b[0m add_auth <scheme> <credential> \x1b[1mEXAMPLES\x1b[0m > add_auth digest super:s3cr3t """ |
self._zk.add_auth(params.scheme, params.credential) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_set_acls(self, params):
""" \x1b[1mNAME\x1b[0m set_acls - Sets ACLs for a given path \x1b[1mSYNOPSIS\x1b[0m set_acls <path> <acls> [recursive] \x1b[1mOPTIONS\x1b[0m * recursive: recursively set the acls on the children \x1b[1mEXAMPLES\x1b[0m > set_acls /some/path 'world:anyone:r digest:user:aRxISyaKnTP2+OZ9OmQLkq04bvo=:cdrwa' > set_acls /some/path 'world:anyone:r username_password:user:p@ass0rd:cdrwa' > set_acls /path 'world:anyone:r' true """ |
try:
acls = ACLReader.extract(shlex.split(params.acls))
except ACLReader.BadACL as ex:
self.show_output("Failed to set ACLs: %s.", ex)
return
def set_acls(path):
try:
self._zk.set_acls(path, acls)
except (NoNodeError, BadVersionError, InvalidACLError, ZookeeperError) as ex:
self.show_output("Failed to set ACLs: %s. Error: %s", str(acls), str(ex))
if params.recursive:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
set_acls(cpath)
set_acls(params.path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_get_acls(self, params):
""" \x1b[1mNAME\x1b[0m get_acls - Gets ACLs for a given path \x1b[1mSYNOPSIS\x1b[0m get_acls <path> [depth] [ephemerals] \x1b[1mOPTIONS\x1b[0m * depth: -1 is no recursion, 0 is infinite recursion, N > 0 is up to N levels (default: 0) * ephemerals: include ephemerals (default: false) \x1b[1mEXAMPLES\x1b[0m > get_acls /zookeeper [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))] > get_acls /zookeeper -1 /zookeeper: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))] /zookeeper/config: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))] /zookeeper/quota: [ACL(perms=31, acl_list=['ALL'], id=Id(scheme=u'world', id=u'anyone'))] """ |
def replace(plist, oldv, newv):
try:
plist.remove(oldv)
plist.insert(0, newv)
except ValueError:
pass
for path, acls in self._zk.get_acls_recursive(params.path, params.depth, params.ephemerals):
replace(acls, READ_ACL_UNSAFE[0], "WORLD_READ")
replace(acls, OPEN_ACL_UNSAFE[0], "WORLD_ALL")
self.show_output("%s: %s", path, acls) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_watch(self, params):
""" \x1b[1mNAME\x1b[0m watch - Recursively watch for all changes under a path. \x1b[1mSYNOPSIS\x1b[0m watch <start|stop|stats> <path> [options] \x1b[1mDESCRIPTION\x1b[0m watch start <path> [debug] [depth] with debug=true, print watches as they fire. depth is the level for recursively setting watches: * -1: recurse all the way * 0: don't recurse, only watch the given path * > 0: recurse up to <level> children watch stats <path> [repeat] [sleep] with repeat=0 this command will loop until interrupted. sleep sets the pause duration in between each iteration. watch stop <path> \x1b[1mEXAMPLES\x1b[0m > watch start /foo/bar > watch stop /foo/bar > watch stats /foo/bar """ |
wm = get_watch_manager(self._zk)
if params.command == "start":
debug = to_bool(params.debug)
children = to_int(params.sleep, -1)
wm.add(params.path, debug, children)
elif params.command == "stop":
wm.remove(params.path)
elif params.command == "stats":
repeat = to_int(params.debug, 1)
sleep = to_int(params.sleep, 1)
if repeat == 0:
while True:
wm.stats(params.path)
time.sleep(sleep)
else:
for _ in range(0, repeat):
wm.stats(params.path)
time.sleep(sleep)
else:
self.show_output("watch <start|stop|stats> <path> [verbose]") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_child_count(self, params):
""" \x1b[1mNAME\x1b[0m child_count - Prints the child count for paths \x1b[1mSYNOPSIS\x1b[0m child_count [path] [depth] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * max_depth: max recursion limit (0 is no limit) (default: 1) \x1b[1mEXAMPLES\x1b[0m > child-count / /zookeeper: 2 /foo: 0 /bar: 3 """ |
for child, level in self._zk.tree(params.path, params.depth, full_path=True):
self.show_output("%s: %d", child, self._zk.child_count(child)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_du(self, params):
""" \x1b[1mNAME\x1b[0m du - Total number of bytes under a path \x1b[1mSYNOPSIS\x1b[0m du [path] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) \x1b[1mEXAMPLES\x1b[0m > du / 90 """ |
self.show_output(pretty_bytes(self._zk.du(params.path))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_find(self, params):
""" \x1b[1mNAME\x1b[0m find - Find znodes whose path matches a given text \x1b[1mSYNOPSIS\x1b[0m find [path] [match] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * match: the string to match in the paths (default: '') \x1b[1mEXAMPLES\x1b[0m > find / foo /foo2 /fooish/wayland /fooish/xorg /copy/foo """ |
for path in self._zk.find(params.path, params.match, 0):
self.show_output(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_summary(self, params):
""" \x1b[1mNAME\x1b[0m summary - Prints summarized details of a path's children \x1b[1mSYNOPSIS\x1b[0m summary [path] [top] \x1b[1mDESCRIPTION\x1b[0m The results are sorted by name. \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * top: number of results to be displayed (0 is all) (default: 0) \x1b[1mEXAMPLES\x1b[0m > summary /services/registrations Created Last modified Owner Name Thu Oct 11 09:14:39 2014 Thu Oct 11 09:14:39 2014 - bar Thu Oct 16 18:54:39 2014 Thu Oct 16 18:54:39 2014 - foo Thu Oct 12 10:04:01 2014 Thu Oct 12 10:04:01 2014 0x14911e869aa0dc1 member_0000001 """ |
self.show_output("%s%s%s%s",
"Created".ljust(32),
"Last modified".ljust(32),
"Owner".ljust(23),
"Name")
results = sorted(self._zk.stat_map(params.path))
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
offs = 1 if params.path == "/" else len(params.path) + 1
for i in range(start, end):
path, stat = results[i]
self.show_output(
"%s%s%s%s",
time.ctime(stat.created).ljust(32),
time.ctime(stat.last_modified).ljust(32),
("0x%x" % stat.ephemeralOwner).ljust(23),
path[offs:]
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_grep(self, params):
""" \x1b[1mNAME\x1b[0m grep - Prints znodes with a value matching the given text \x1b[1mSYNOPSIS\x1b[0m grep [path] <content> [show_matches] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * show_matches: show the content that matched (default: false) \x1b[1mEXAMPLES\x1b[0m > grep / unbound true /passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin /copy/passwd: unbound:x:992:991:Unbound DNS resolver:/etc/unbound:/sbin/nologin """ |
self.grep(params.path, params.content, 0, params.show_matches) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_get(self, params):
""" \x1b[1mNAME\x1b[0m get - Gets the znode's value \x1b[1mSYNOPSIS\x1b[0m get <path> [watch] \x1b[1mOPTIONS\x1b[0m * watch: set a (data) watch on the path (default: false) \x1b[1mEXAMPLES\x1b[0m > get /foo bar # sets a watch > get /foo true bar # trigger the watch > set /foo 'notbar' WatchedEvent(type='CHANGED', state='CONNECTED', path=u'/foo') """ |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
value, _ = self._zk.get(params.path, **kwargs)
# maybe it's compressed?
if value is not None:
try:
value = zlib.decompress(value)
except:
pass
self.show_output(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_exists(self, params):
""" \x1b[1mNAME\x1b[0m exists - Gets the znode's stat information \x1b[1mSYNOPSIS\x1b[0m exists <path> [watch] [pretty_date] \x1b[1mOPTIONS\x1b[0m * watch: set a (data) watch on the path (default: false) \x1b[1mEXAMPLES\x1b[0m exists /foo Stat( czxid=101, mzxid=102, ctime=1382820644375, mtime=1382820693801, version=1, cversion=0, aversion=0, ephemeralOwner=0, dataLength=6, numChildren=0, pzxid=101 ) # sets a watch > exists /foo true # trigger the watch > rm /foo WatchedEvent(type='DELETED', state='CONNECTED', path=u'/foo') """ |
watcher = lambda evt: self.show_output(str(evt))
kwargs = {"watch": watcher} if params.watch else {}
pretty = params.pretty_date
path = self.resolve_path(params.path)
stat = self._zk.exists(path, **kwargs)
if stat:
session = stat.ephemeralOwner if stat.ephemeralOwner else 0
self.show_output("Stat(")
self.show_output(" czxid=0x%x", stat.czxid)
self.show_output(" mzxid=0x%x", stat.mzxid)
self.show_output(" ctime=%s", time.ctime(stat.created) if pretty else stat.ctime)
self.show_output(" mtime=%s", time.ctime(stat.last_modified) if pretty else stat.mtime)
self.show_output(" version=%s", stat.version)
self.show_output(" cversion=%s", stat.cversion)
self.show_output(" aversion=%s", stat.aversion)
self.show_output(" ephemeralOwner=0x%x", session)
self.show_output(" dataLength=%s", stat.dataLength)
self.show_output(" numChildren=%s", stat.numChildren)
self.show_output(" pzxid=0x%x", stat.pzxid)
self.show_output(")")
else:
self.show_output("Path %s doesn't exist", params.path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_create(self, params):
""" \x1b[1mNAME\x1b[0m create - Creates a znode \x1b[1mSYNOPSIS\x1b[0m create <path> <value> [ephemeral] [sequence] [recursive] [async] \x1b[1mOPTIONS\x1b[0m * ephemeral: make the znode ephemeral (default: false) * sequence: make the znode sequential (default: false) * recursive: recursively create the path (default: false) * async: don't block waiting on the result (default: false) \x1b[1mEXAMPLES\x1b[0m > create /foo 'bar' # create an ephemeral znode > create /foo1 '' true # create an ephemeral|sequential znode > create /foo1 '' true true # recursively create a path > create /very/long/path/here '' false false true # check the new subtree > tree . βββ zookeeper β βββ config β βββ quota βββ very β βββ long β β βββ path β β β βββ here """ |
try:
kwargs = {"acl": None, "ephemeral": params.ephemeral, "sequence": params.sequence}
if not self.in_transaction:
kwargs["makepath"] = params.recursive
if params.asynchronous and not self.in_transaction:
self.client_context.create_async(params.path, decoded(params.value), **kwargs)
else:
self.client_context.create(params.path, decoded(params.value), **kwargs)
except NodeExistsError:
self.show_output("Path %s exists", params.path)
except NoNodeError:
self.show_output("Missing path in %s (try recursive?)", params.path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_set(self, params):
""" \x1b[1mNAME\x1b[0m set - Updates the znode's value \x1b[1mSYNOPSIS\x1b[0m set <path> <value> [version] \x1b[1mOPTIONS\x1b[0m * version: only update if version matches (default: -1) \x1b[1mEXAMPLES\x1b[0m > set /foo 'bar' > set /foo 'verybar' 3 """ |
self.set(params.path, decoded(params.value), version=params.version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, path, value, version):
""" sets a znode's data """ |
if self.in_transaction:
self.client_context.set_data(path, value, version=version)
else:
self.client_context.set(path, value, version=version) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_rm(self, params):
""" \x1b[1mNAME\x1b[0m rm - Remove the znode \x1b[1mSYNOPSIS\x1b[0m \x1b[1mEXAMPLES\x1b[0m > rm /foo > rm /foo /bar """ |
for path in params.paths:
try:
self.client_context.delete(path)
except NotEmptyError:
self.show_output("%s is not empty.", path)
except NoNodeError:
self.show_output("%s doesn't exist.", path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_txn(self, params):
""" \x1b[1mNAME\x1b[0m txn - Create and execute a transaction \x1b[1mSYNOPSIS\x1b[0m \x1b[1mDESCRIPTION\x1b[0m Allowed cmds are check, create, rm and set. Check parameters are: check <path> <version> For create, rm and set see their help menu for their respective parameters. \x1b[1mEXAMPLES\x1b[0m > txn 'create /foo "start"' 'check /foo 0' 'set /foo "end"' 'rm /foo 1' """ |
try:
with self.transaction():
for cmd in params.cmds:
try:
self.onecmd(cmd)
except AttributeError:
# silently swallow unrecognized commands
pass
except BadVersionError:
self.show_output("Bad version.")
except NoNodeError:
self.show_output("Missing path.")
except NodeExistsError:
self.show_output("One of the paths exists.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_session_info(self, params):
""" \x1b[1mNAME\x1b[0m session_info - Shows information about the current session \x1b[1mSYNOPSIS\x1b[0m session_info [match] \x1b[1mOPTIONS\x1b[0m * match: only include lines that match (default: '') \x1b[1mEXAMPLES\x1b[0m > session_info state=CONNECTED xid=4 last_zxid=0x000000505f8be5b3 timeout=10000 client=('127.0.0.1', 60348) server=('127.0.0.1', 2181) """ |
fmt_str = """state=%s
sessionid=%s
auth_info=%s
protocol_version=%d
xid=%d
last_zxid=0x%.16x
timeout=%d
client=%s
server=%s
data_watches=%s
child_watches=%s"""
content = fmt_str % (
self._zk.client_state,
self._zk.sessionid,
list(self._zk.auth_data),
self._zk.protocol_version,
self._zk.xid,
self._zk.last_zxid,
self._zk.session_timeout,
self._zk.client,
self._zk.server,
",".join(self._zk.data_watches),
",".join(self._zk.child_watches)
)
output = get_matching(content, params.match)
self.show_output(output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_mntr(self, params):
""" \x1b[1mNAME\x1b[0m mntr - Executes the mntr four-letter command \x1b[1mSYNOPSIS\x1b[0m mntr [hosts] [match] \x1b[1mOPTIONS\x1b[0m * hosts: the hosts to connect to (default: the current connected host) * match: only output lines that include the given string (default: '') \x1b[1mEXAMPLES\x1b[0m > mntr zk_version 3.5.0--1, built on 11/14/2014 10:45 GMT zk_min_latency 0 zk_max_latency 8 zk_avg_latency 0 """ |
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.mntr(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_cons(self, params):
""" \x1b[1mNAME\x1b[0m cons - Executes the cons four-letter command \x1b[1mSYNOPSIS\x1b[0m cons [hosts] [match] \x1b[1mOPTIONS\x1b[0m * hosts: the hosts to connect to (default: the current connected host) * match: only output lines that include the given string (default: '') \x1b[1mEXAMPLES\x1b[0m > cons /127.0.0.1:40535[0](queued=0,recved=1,sent=0) """ |
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.cons(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_dump(self, params):
""" \x1b[1mNAME\x1b[0m dump - Executes the dump four-letter command \x1b[1mSYNOPSIS\x1b[0m dump [hosts] [match] \x1b[1mOPTIONS\x1b[0m * hosts: the hosts to connect to (default: the current connected host) * match: only output lines that include the given string (default: '') \x1b[1mEXAMPLES\x1b[0m > dump SessionTracker dump: Session Sets (3)/(1):
0 expire at Fri Nov 14 02:49:52 PST 2014: 0 expire at Fri Nov 14 02:49:56 PST 2014: 1 expire at Fri Nov 14 02:50:00 PST 2014: 0x149adea89940107 ephemeral nodes dump: Sessions with Ephemerals (0):
""" |
hosts = params.hosts if params.hosts != "" else None
if hosts is not None and invalid_hosts(hosts):
self.show_output("List of hosts has the wrong syntax.")
return
if self._zk is None:
self._zk = XClient()
try:
content = get_matching(self._zk.dump(hosts), params.match)
self.show_output(content)
except XClient.CmdFailed as ex:
self.show_output(str(ex)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_rmr(self, params):
""" \x1b[1mNAME\x1b[0m rmr - Delete a path and all its children \x1b[1mSYNOPSIS\x1b[0m \x1b[1mEXAMPLES\x1b[0m > rmr /foo > rmr /foo /bar """ |
for path in params.paths:
self._zk.delete(path, recursive=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_child_watch(self, params):
""" \x1b[1mNAME\x1b[0m child_watch - Watch a path for child changes \x1b[1mSYNOPSIS\x1b[0m child_watch <path> [verbose] \x1b[1mOPTIONS\x1b[0m * verbose: prints list of znodes (default: false) \x1b[1mEXAMPLES\x1b[0m # only prints the current number of children > child_watch / # prints num of children along with znodes listing > child_watch / true """ |
get_child_watcher(self._zk, print_func=self.show_output).update(
params.path, params.verbose) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_diff(self, params):
""" \x1b[1mNAME\x1b[0m diff - Display the differences between two paths \x1b[1mSYNOPSIS\x1b[0m diff <src> <dst> \x1b[1mDESCRIPTION\x1b[0m The output is interpreted as: -- means the znode is missing in /new-configs ++ means the znode is new in /new-configs +- means the znode's content differ between /configs and /new-configs \x1b[1mEXAMPLES\x1b[0m > diff /configs /new-configs -- service-x/hosts ++ service-x/hosts.json +- service-x/params """ |
count = 0
for count, (diff, path) in enumerate(self._zk.diff(params.path_a, params.path_b), 1):
if diff == -1:
self.show_output("-- %s", path)
elif diff == 0:
self.show_output("-+ %s", path)
elif diff == 1:
self.show_output("++ %s", path)
if count == 0:
self.show_output("Branches are equal.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_json_valid(self, params):
""" \x1b[1mNAME\x1b[0m json_valid - Checks znodes for valid JSON \x1b[1mSYNOPSIS\x1b[0m json_valid <path> [recursive] \x1b[1mOPTIONS\x1b[0m * recursive: recurse to all children (default: false) \x1b[1mEXAMPLES\x1b[0m > json_valid /some/valid/json_znode yes. > json_valid /some/invalid/json_znode no. > json_valid /configs true /configs/a: yes. /configs/b: no. """ |
def check_valid(path, print_path):
result = "no"
value, _ = self._zk.get(path)
if value is not None:
try:
x = json.loads(value)
result = "yes"
except ValueError:
pass
if print_path:
self.show_output("%s: %s.", os.path.basename(path), result)
else:
self.show_output("%s.", result)
if not params.recursive:
check_valid(params.path, False)
else:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
check_valid(cpath, True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_json_cat(self, params):
""" \x1b[1mNAME\x1b[0m json_cat - Pretty prints a znode's JSON \x1b[1mSYNOPSIS\x1b[0m json_cat <path> [recursive] \x1b[1mOPTIONS\x1b[0m * recursive: recurse to all children (default: false) \x1b[1mEXAMPLES\x1b[0m > json_cat /configs/clusters { "dc0": { "network": "10.2.0.0/16", }, } > json_cat /configs true /configs/clusters: { "dc0": { "network": "10.2.0.0/16", }, } /configs/dns_servers: [ "10.2.0.1", "10.3.0.1" ] """ |
def json_output(path, print_path):
value, _ = self._zk.get(path)
if value is not None:
try:
value = json.dumps(json.loads(value), indent=4)
except ValueError:
pass
if print_path:
self.show_output("%s:\n%s", os.path.basename(path), value)
else:
self.show_output(value)
if not params.recursive:
json_output(params.path, False)
else:
for cpath, _ in self._zk.tree(params.path, 0, full_path=True):
json_output(cpath, True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_json_count_values(self, params):
""" \x1b[1mNAME\x1b[0m json_count_values - Gets the frequency of the values associated with the given keys \x1b[1mSYNOPSIS\x1b[0m json_count_values <path> <keys> [top] [minfreq] [reverse] [report_errors] [print_path] \x1b[1mOPTIONS\x1b[0m * top: number of results to show (0 is all) (default: 0) * minfreq: minimum frequency to be displayed (default: 1) * reverse: sort in descending order (default: true) * report_errors: report bad znodes (default: false) * print_path: print the path if there are results (default: false) \x1b[1mEXAMPLES\x1b[0m > json_count_values /configs/primary_service endpoint.host 10.20.0.2 3 10.20.0.4 3 10.20.0.5 3 10.20.0.6 1 10.20.0.7 1 """ |
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
values = defaultdict(int)
for path, data in path_map.get():
try:
value = Keys.value(json_deserialize(data), params.keys)
values[value] += 1
except BadJSON as ex:
if params.report_errors:
self.show_output("Path %s has bad JSON.", path)
except Keys.Missing as ex:
if params.report_errors:
self.show_output("Path %s is missing key %s.", path, ex)
results = sorted(values.items(), key=lambda item: item[1], reverse=params.reverse)
results = [r for r in results if r[1] >= params.minfreq]
# what slice do we want?
if params.top == 0:
start, end = 0, len(results)
elif params.top > 0:
start, end = 0, params.top if params.top < len(results) else len(results)
else:
start = len(results) + params.top if abs(params.top) < len(results) else 0
end = len(results)
if len(results) > 0 and params.print_path:
self.show_output(params.path)
for i in range(start, end):
value, frequency = results[i]
self.show_output("%s = %d", value, frequency)
# if no results were found we call it a failure (i.e.: exit(1) from --run-once)
if len(results) == 0:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_json_dupes_for_keys(self, params):
""" \x1b[1mNAME\x1b[0m json_duples_for_keys - Gets the duplicate znodes for the given keys \x1b[1mSYNOPSIS\x1b[0m json_dupes_for_keys <path> <keys> [prefix] [report_errors] [first] \x1b[1mDESCRIPTION\x1b[0m Znodes with duplicated keys are sorted and all but the first (original) one are printed. \x1b[1mOPTIONS\x1b[0m * prefix: only include matching znodes * report_errors: turn on error reporting (i.e.: bad JSON in a znode) * first: print the first, non duplicated, znode too. \x1b[1mEXAMPLES\x1b[0m > json_cat /configs/primary_service true member_0000000186 { "status": "ALIVE", "serviceEndpoint": { "http": { "host": "10.0.0.2", "port": 31994 } }, "shard": 0 } member_0000000187 { "status": "ALIVE", "serviceEndpoint": { "http": { "host": "10.0.0.2", "port": 31994 } }, "shard": 0 } > json_dupes_for_keys /configs/primary_service shard member_0000000187 """ |
try:
Keys.validate(params.keys)
except Keys.Bad as ex:
self.show_output(str(ex))
return
path_map = PathMap(self._zk, params.path)
dupes_by_path = defaultdict(lambda: defaultdict(list))
for path, data in path_map.get():
parent, child = split(path)
if not child.startswith(params.prefix):
continue
try:
value = Keys.value(json_deserialize(data), params.keys)
dupes_by_path[parent][value].append(path)
except BadJSON as ex:
if params.report_errors:
self.show_output("Path %s has bad JSON.", path)
except Keys.Missing as ex:
if params.report_errors:
self.show_output("Path %s is missing key %s.", path, ex)
dupes = []
for _, paths_by_value in dupes_by_path.items():
for _, paths in paths_by_value.items():
if len(paths) > 1:
paths.sort()
paths = paths if params.first else paths[1:]
for path in paths:
idx = bisect.bisect(dupes, path)
dupes.insert(idx, path)
for dup in dupes:
self.show_output(dup)
# if no dupes were found we call it a failure (i.e.: exit(1) from --run-once)
if len(dupes) == 0:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_edit(self, params):
""" \x1b[1mNAME\x1b[0m edit - Opens up an editor to modify and update a znode. \x1b[1mSYNOPSIS\x1b[0m edit <path> \x1b[1mDESCRIPTION\x1b[0m If the content has not changed, the znode won't be updated. $EDITOR must be set for zk-shell to find your editor. \x1b[1mEXAMPLES\x1b[0m # make sure $EDITOR is set in your shell > edit /configs/webservers/primary # change something and save > get /configs/webservers/primary # updated content """ |
if os.getuid() == 0:
self.show_output("edit cannot be run as root.")
return
editor = os.getenv("EDITOR", os.getenv("VISUAL", "/usr/bin/vi"))
if editor is None:
self.show_output("No editor found, please set $EDITOR")
return
editor = which(editor)
if not editor:
self.show_output("Cannot find executable editor, please set $EDITOR")
return
st = os.stat(editor)
if (st.st_mode & statlib.S_ISUID) or (st.st_mode & statlib.S_ISUID):
self.show_output("edit cannot use setuid/setgid binaries.")
return
# copy content to tempfile
value, stat = self._zk.get(params.path)
_, tmppath = tempfile.mkstemp()
with open(tmppath, "w") as fh:
fh.write(value if value else "")
# launch editor
rv = os.system("%s %s" % (editor, tmppath))
if rv != 0:
self.show_output("%s did not exit successfully" % editor)
try:
os.unlink(tmppath)
except OSError: pass
return
# did it change? if so, save it
with open(tmppath, "r") as fh:
newvalue = fh.read()
if newvalue != value:
self.set(params.path, decoded(newvalue), stat.version)
try:
os.unlink(tmppath)
except OSError: pass |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_loop(self, params):
""" \x1b[1mNAME\x1b[0m loop - Runs commands in a loop \x1b[1mSYNOPSIS\x1b[0m \x1b[1mDESCRIPTION\x1b[0m Runs <cmds> <repeat> times (0 means forever), with a pause of <pause> secs inbetween each <cmd> (0 means no pause). \x1b[1mEXAMPLES\x1b[0m > loop 3 0 "get /foo" > loop 3 0 "get /foo" "get /bar" """ |
repeat = params.repeat
if repeat < 0:
self.show_output("<repeat> must be >= 0.")
return
pause = params.pause
if pause < 0:
self.show_output("<pause> must be >= 0.")
return
cmds = params.cmds
i = 0
with self.transitions_disabled():
while True:
for cmd in cmds:
try:
self.onecmd(cmd)
except Exception as ex:
self.show_output("Command failed: %s.", ex)
if pause > 0.0:
time.sleep(pause)
i += 1
if repeat > 0 and i >= repeat:
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_fill(self, params):
""" \x1b[1mNAME\x1b[0m fill - Fills a znode with the given value \x1b[1mSYNOPSIS\x1b[0m fill <path> <char> <count> \x1b[1mEXAMPLES\x1b[0m > fill /some/znode X 1048576 """ |
self._zk.set(params.path, decoded(params.val * params.repeat)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_time(self, params):
""" \x1b[1mNAME\x1b[0m time - Measures elapsed seconds after running commands \x1b[1mSYNOPSIS\x1b[0m \x1b[1mEXAMPLES\x1b[0m > time 'loop 10 0 "create /foo_ bar ephemeral=false sequence=true"' Took 0.05585 seconds """ |
start = time.time()
for cmd in params.cmds:
try:
self.onecmd(cmd)
except Exception as ex:
self.show_output("Command failed: %s.", ex)
elapsed = "{0:.5f}".format(time.time() - start)
self.show_output("Took %s seconds" % elapsed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def do_echo(self, params):
""" \x1b[1mNAME\x1b[0m echo - displays formatted data \x1b[1mSYNOPSIS\x1b[0m \x1b[1mEXAMPLES\x1b[0m > echo hello hello > echo 'The value of /foo is %s' 'get /foo' bar """ |
values = []
with self.output_context() as context:
for cmd in params.cmds:
rv = self.onecmd(cmd)
val = "" if rv is False else context.value.rstrip("\n")
values.append(val)
context.reset()
try:
self.show_output(params.fmtstr, *values)
except TypeError:
self.show_output("Bad format string or missing arguments.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connected_socket(address, timeout=3):
""" yields a connected socket """ |
sock = socket.create_connection(address, timeout)
yield sock
sock.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bytes(self, *args, **kwargs):
""" no string decoding performed """ |
return super(XClient, self).get(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_acls_recursive(self, path, depth, include_ephemerals):
"""A recursive generator wrapper for get_acls :param path: path from which to start :param depth: depth of the recursion (-1 no recursion, 0 means no limit) :param include_ephemerals: get ACLs for ephemerals too """ |
yield path, self.get_acls(path)[0]
if depth == -1:
return
for tpath, _ in self.tree(path, depth, full_path=True):
try:
acls, stat = self.get_acls(tpath)
except NoNodeError:
continue
if not include_ephemerals and stat.ephemeralOwner != 0:
continue
yield tpath, acls |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.