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 visit_Bytes(self, node: ast.Bytes) -> bytes: """Recompute the value as the bytes at the node.""" |
result = node.s
self.recomputed_values[node] = result
return node.s |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_List(self, node: ast.List) -> List[Any]: """Visit the elements and assemble the results into a list.""" |
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a list")
result = [self.visit(node=elt) for elt in node.elts]
self.recomputed_values[node] = result
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Visit the elements and assemble the results into a tuple.""" |
if isinstance(node.ctx, ast.Store):
raise NotImplementedError("Can not compute the value of a Store on a tuple")
result = tuple(self.visit(node=elt) for elt in node.elts)
self.recomputed_values[node] = result
return 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 visit_Set(self, node: ast.Set) -> Set[Any]: """Visit the elements and assemble the results into a set.""" |
result = set(self.visit(node=elt) for elt in node.elts)
self.recomputed_values[node] = result
return 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 visit_Dict(self, node: ast.Dict) -> Dict[Any, Any]: """Visit keys and values and assemble a dictionary with the results.""" |
recomputed_dict = dict() # type: Dict[Any, Any]
for key, val in zip(node.keys, node.values):
recomputed_dict[self.visit(node=key)] = self.visit(node=val)
self.recomputed_values[node] = recomputed_dict
return recomputed_dict |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_NameConstant(self, node: ast.NameConstant) -> Any: """Forward the node value as a result.""" |
self.recomputed_values[node] = node.value
return node.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 visit_Name(self, node: ast.Name) -> Any: """Load the variable by looking it up in the variable look-up and in the built-ins.""" |
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError("Can only compute a value of Load on a name {}, but got context: {}".format(
node.id, node.ctx))
result = None # type: Optional[Any]
if node.id in self._name_to_value:
result = self._name... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_UnaryOp(self, node: ast.UnaryOp) -> Any: """Visit the node operand and apply the operation on the result.""" |
if isinstance(node.op, ast.UAdd):
result = +self.visit(node=node.operand)
elif isinstance(node.op, ast.USub):
result = -self.visit(node=node.operand)
elif isinstance(node.op, ast.Not):
result = not self.visit(node=node.operand)
elif isinstance(node.op... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_BinOp(self, node: ast.BinOp) -> Any: """Recursively visit the left and right operand, respectively, and apply the operation on the results.""" |
# pylint: disable=too-many-branches
left = self.visit(node=node.left)
right = self.visit(node=node.right)
if isinstance(node.op, ast.Add):
result = left + right
elif isinstance(node.op, ast.Sub):
result = left - right
elif isinstance(node.op, ast... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_BoolOp(self, node: ast.BoolOp) -> Any: """Recursively visit the operands and apply the operation on them.""" |
values = [self.visit(value_node) for value_node in node.values]
if isinstance(node.op, ast.And):
result = functools.reduce(lambda left, right: left and right, values, True)
elif isinstance(node.op, ast.Or):
result = functools.reduce(lambda left, right: left or right, va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Compare(self, node: ast.Compare) -> Any: """Recursively visit the comparators and apply the operations on them.""" |
# pylint: disable=too-many-branches
left = self.visit(node=node.left)
comparators = [self.visit(node=comparator) for comparator in node.comparators]
result = None # type: Optional[Any]
for comparator, op in zip(comparators, node.ops):
if isinstance(op, ast.Eq):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Call(self, node: ast.Call) -> Any: """Visit the function and the arguments and finally make the function call with them.""" |
func = self.visit(node=node.func)
args = [] # type: List[Any]
for arg_node in node.args:
if isinstance(arg_node, ast.Starred):
args.extend(self.visit(node=arg_node))
else:
args.append(self.visit(node=arg_node))
kwargs = dict() ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_IfExp(self, node: ast.IfExp) -> Any: """Visit the ``test``, and depending on its outcome, the ``body`` or ``orelse``.""" |
test = self.visit(node=node.test)
if test:
result = self.visit(node=node.body)
else:
result = self.visit(node=node.orelse)
self.recomputed_values[node] = result
return 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 visit_Attribute(self, node: ast.Attribute) -> Any: """Visit the node's ``value`` and get the attribute from the result.""" |
value = self.visit(node=node.value)
if not isinstance(node.ctx, ast.Load):
raise NotImplementedError(
"Can only compute a value of Load on the attribute {}, but got context: {}".format(node.attr, node.ctx))
result = getattr(value, node.attr)
self.recomputed... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_Slice(self, node: ast.Slice) -> slice: """Visit ``lower``, ``upper`` and ``step`` and recompute the node as a ``slice``.""" |
lower = None # type: Optional[int]
if node.lower is not None:
lower = self.visit(node=node.lower)
upper = None # type: Optional[int]
if node.upper is not None:
upper = self.visit(node=node.upper)
step = None # type: Optional[int]
if node.step... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Visit each dimension of the advanced slicing and assemble the dimensions in a tuple.""" |
result = tuple(self.visit(node=dim) for dim in node.dims)
self.recomputed_values[node] = result
return 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 visit_Subscript(self, node: ast.Subscript) -> Any: """Visit the ``slice`` and a ``value`` and get the element.""" |
value = self.visit(node=node.value)
a_slice = self.visit(node=node.slice)
result = value[a_slice]
self.recomputed_values[node] = result
return 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 _execute_comprehension(self, node: Union[ast.ListComp, ast.SetComp, ast.GeneratorExp, ast.DictComp]) -> Any: """Compile the generator or comprehension from th... |
args = [ast.arg(arg=name) for name in sorted(self._name_to_value.keys())]
func_def_node = ast.FunctionDef(
name="generator_expr",
args=ast.arguments(args=args, kwonlyargs=[], kw_defaults=[], defaults=[]),
decorator_list=[],
body=[ast.Return(node)])
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_GeneratorExp(self, node: ast.GeneratorExp) -> Any: """Compile the generator expression as a function and call it.""" |
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
# Do not set the computed value of the node since its representation would be non-informative.
return 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 visit_ListComp(self, node: ast.ListComp) -> Any: """Compile the list comprehension as a function and call it.""" |
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
return 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 visit_SetComp(self, node: ast.SetComp) -> Any: """Compile the set comprehension as a function and call it.""" |
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
return 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 visit_DictComp(self, node: ast.DictComp) -> Any: """Compile the dictionary comprehension as a function and call it.""" |
result = self._execute_comprehension(node=node)
for generator in node.generators:
self.visit(generator.iter)
self.recomputed_values[node] = result
return 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 visit_Return(self, node: ast.Return) -> Any: # pylint: disable=no-self-use """Raise an exception that this node is unexpected.""" |
raise AssertionError("Unexpected return node during the re-computation: {}".format(ast.dump(node))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generic_visit(self, node: ast.AST) -> None: """Raise an exception that this node has not been handled.""" |
raise NotImplementedError("Unhandled recomputation of the node: {} {}".format(type(node), node)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize_words(string):
""" Tokenize input text to words. :param string: Text to tokenize :type string: str or unicode :return: words :rtype: list of strings... |
string = six.text_type(string)
return re.findall(WORD_TOKENIZATION_RULES, string) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize_text(string):
""" Tokenize input text to paragraphs, sentences and words. Tokenization to paragraphs is done using simple Newline algorithm For sent... |
string = six.text_type(string)
rez = []
for part in string.split('\n'):
par = []
for sent in tokenize_sents(part):
par.append(tokenize_words(sent))
if par:
rez.append(par)
return rez |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromlist(cls, rnglist, autostep=None):
"""Class method that returns a new RangeSet with ranges from provided list.""" |
inst = RangeSet(autostep=autostep)
inst.updaten(rnglist)
return inst |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contiguous(self):
"""Object-based iterator over contiguous range sets.""" |
pad = self.padding or 0
for sli in self._contiguous_slices():
yield RangeSet.fromone(slice(sli.start, sli.stop, sli.step), 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 _contiguous_slices(self):
"""Internal iterator over contiguous slices in RangeSet.""" |
k = j = None
for i in self._sorted():
if k is None:
k = j = i
if i - j > 1:
yield slice(k, j + 1, 1)
k = i
j = i
if k is not None:
yield slice(k, j + 1, 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 copy(self):
"""Return a shallow copy of a RangeSet.""" |
cpy = self.__class__()
cpy._autostep = self._autostep
cpy.padding = self.padding
cpy.update(self)
return cpy |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def intersection(self, other):
"""Return the intersection of two RangeSets as a new RangeSet. (I.e. all elements that are in both sets.) """ |
#NOTE: This is a work around
# Python 3 return as the result of set.intersection a new set instance.
# Python 2 however returns as a the result a ClusterShell.RangeSet.RangeSet instance.
# ORIGINAL CODE: return self._wrap_set_op(set.intersection, other)
copy = self.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 difference(self, other):
"""Return the difference of two RangeSets as a new RangeSet. (I.e. all elements that are in this set and not in the other.) """ |
#NOTE: This is a work around
# Python 3 return as the result of set.intersection a new set instance.
# Python 2 however returns as a the result a ClusterShell.RangeSet.RangeSet instance.
# ORIGINAL CODE: return self._wrap_set_op(set.difference, other)
copy = self.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 issubset(self, other):
"""Report whether another set contains this RangeSet.""" |
self._binary_sanity_check(other)
return set.issubset(self, other) |
<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):
"""Report whether this RangeSet contains another set.""" |
self._binary_sanity_check(other)
return set.issuperset(self, other) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def updaten(self, rangesets):
""" Update a rangeset with the union of itself and several others. """ |
for rng in rangesets:
if isinstance(rng, set):
self.update(rng)
else:
self.update(RangeSet(rng)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, element, pad=0):
"""Add an element to a RangeSet. This has no effect if the element is already present. """ |
set.add(self, int(element))
if pad > 0 and self.padding is None:
self.padding = 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 discard(self, element):
"""Remove element from the RangeSet if it is a member. If the element is not a member, do nothing. """ |
try:
i = int(element)
set.discard(self, i)
except ValueError:
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 _open(filename, mode="r"):
""" Universal open file facility. With normal files, this function behaves as the open builtin. With gzip-ed files, it decompress ... |
if filename.endswith(".gz"):
return GzipFile(filename, mode, COMPRESSION_LEVEL)
elif filename == "-":
if mode == "r":
return _stdin
elif mode == "w":
return _stdout
else:
# TODO: set encoding to UTF-8?
return open(filename, mode=mode) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _radixPass(a, b, r, n, K):
""" Stable sort of the sequence a according to the keys given in r. [3, 1, 0, 2, 4] When n is less than the length of a, the end o... |
c = _array("i", [0] * (K + 1)) # counter array
for i in range(n): # count occurrences
c[r[a[i]]] += 1
sum = 0
for i in range(K + 1): # exclusive prefix sums
t = c[i]
c[i] = sum
sum += t
for a_i in a[:n]: # sort
b[c[r[a_i]]] = a_i
c[r[a_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 _nbOperations(n):
""" Exact number of atomic operations in _radixPass. """ |
if n < 2:
return 0
else:
n0 = (n + 2) // 3
n02 = n0 + n // 3
return 3 * (n02) + n0 + _nbOperations(n02) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _longestCommonPrefix(seq1, seq2, start1=0, start2=0):
""" Returns the length of the longest common prefix of seq1 starting at offset start1 and seq2 starting... |
len1 = len(seq1) - start1
len2 = len(seq2) - start2
# We set seq2 as the shortest sequence
if len1 < len2:
seq1, seq2 = seq2, seq1
start1, start2 = start2, start1
len1, len2 = len2, len1
# if seq2 is empty returns 0
if len2 == 0:
return 0
i = 0
pos2 =... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def LCP(SA):
""" Compute the longest common prefix for every adjacent suffixes. The result is a list of same size as SA. Given two suffixes at positions i and i+... |
string = SA.string
length = SA.length
lcps = _array("i", [0] * length)
SA = SA.SA
if _trace:
delta = max(length // 100, 1)
for i, pos in enumerate(SA):
if i % delta == 0:
percent = float((i + 1) * 100) / length
print >> _stderr, "Compute_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parseArgv():
""" Command line option parser. """ |
parser = OptionParser()
parser.usage = r""" cat <TEXT> | %prog [--unit <UNIT>] [--output <SA_FILE>]
Create the suffix array of TEXT with the processing UNIT and optionally store it in SA_FILE for subsequent use.
UNIT may be set to 'byte', 'character' (given an encoding with the --encoding option) or 'word', w... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
""" Entry point for the standalone script. """ |
(options, strings) = parseArgv()
global _suffixArray, _trace
#############
# Verbosity #
#############
_trace = options.verbose
###################
# Processing unit #
###################
if options.unit == "byte":
options.unit = UNIT_BYTE
elif options.unit == "cha... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize(self, string):
""" Tokenizer utility. When processing byte, outputs the string unaltered. The character unit type is used for unicode data, the stri... |
if self.unit == UNIT_WORD:
# the EOL character is treated as a word, hence a substitution
# before split
return [token for token in string.replace("\n", " \n ").split(self.tokSep) if token != ""]
elif self.unit == UNIT_CHARACTER:
return string.decode(sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def toFile(self, filename):
""" Save the suffix array instance including all features attached in filename. Accept any filename following the _open conventions, ... |
start = _time()
fd = _open(filename, "w")
savedData = [self.string, self.unit, self.voc, self.vocSize, self.SA, self.features]
for featureName in self.features:
featureValues = getattr(self, "_%s_values" % featureName)
featureDefault = getattr(self, "%s_default... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fromFile(cls, filename):
""" Load a suffix array instance from filename, a file created by toFile. Accept any filename following the _open conventions. """ |
self = cls.__new__(cls) # new instance which does not call __init__
start = _time()
savedData = _loads(_open(filename, "r").read())
# load common attributes
self.string, self.unit, self.voc, self.vocSize, self.SA, features = savedData[:6]
self.length = len(self.SA)
... |
<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(self, subString, features=[]):
""" Dichotomy search of subString in the suffix array. As soon as a suffix which starts with subString is found, it uses ... |
SA = self.SA
LCPs = self._LCP_values
string = self.string
middle = self._findOne(subString)
if middle is False:
return _array('i')
subString = _array("i", [self.tokId[c] for c in self.tokenize(subString)])
lenSubString = len(subString)
####... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(self):
"""Return a generator that yields pieces of XML.""" |
# atom demands either an author element in every entry or a global one
if not self.author:
if False in map(lambda e: bool(e.author), self.entries):
self.author = ({'name': u'unbekannter Autor'},)
if not self.updated:
dates = sorted([entry.updated for ent... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate(self):
"""Yields pieces of ATOM XML.""" |
base = ''
if self.xml_base:
base = ' xml:base="%s"' % escape(self.xml_base, True)
yield u'<entry%s>\n' % base
yield u' ' + _make_text_block('title', self.title, self.title_type)
yield u' <id>%s</id>\n' % escape(self.id)
yield u' <updated>%s</updated>\n' % ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def override_djconfig(**new_cache_values):
""" Temporarily override config values. This is similar to :py:func:`django.test.override_settings`,\ use it in testin... |
def decorator(func):
@wraps(func)
def func_wrapper(*args, **kw):
old_cache_values = {
key: getattr(conf.config, key)
for key in new_cache_values}
conf.config._set_many(new_cache_values)
try:
# todo: make a note ab... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serialize(value, field):
""" Form values serialization :param object value: A value to be serialized\ for saving it into the database and later\ loading it i... |
assert isinstance(field, forms.Field)
if isinstance(field, forms.ModelMultipleChoiceField):
return json.dumps([v.pk for v in value])
# todo: remove
if isinstance(value, models.Model):
return value.pk
return 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 get_version(package):
"""Get version without importing the lib""" |
with io.open(os.path.join(BASE_DIR, package, '__init__.py'), encoding='utf-8') as fh:
return [
l.split('=', 1)[1].strip().strip("'").strip('"')
for l in fh.readlines()
if '__version__' in l][0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _register(self, form_class, check_middleware=True):
""" Register a config form into the registry :param object form_class: The form class to register.\ Must ... |
if not issubclass(form_class, _ConfigFormBase):
raise ValueError(
"The form does not inherit from `forms.ConfigForm`")
self._registry.add(form_class)
if check_middleware:
_check_backend() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reload(self):
""" Gets every registered form's field value.\ If a field name is found in the db, it will load it from there.\ Otherwise, the initial value f... |
ConfigModel = apps.get_model('djconfig.Config')
cache = {}
data = dict(
ConfigModel.objects
.all()
.values_list('key', 'value'))
# populate cache with initial form values,
# then with cleaned database values,
# then with raw d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _reload_maybe(self):
""" Reload the config if the config\ model has been updated. This is called\ once on every request by the middleware.\ Should not be cal... |
ConfigModel = apps.get_model('djconfig.Config')
data = dict(
ConfigModel.objects
.filter(key='_updated_at')
.values_list('key', 'value'))
if (not hasattr(self, '_updated_at') or
self._updated_at != data.get('_updated_at')):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(conf, conf_admin, **options):
""" Register a new admin section. :param conf: A subclass of ``djconfig.admin.Config`` :param conf_admin: A subclass o... |
assert issubclass(conf_admin, ConfigAdmin), (
'conf_admin is not a ConfigAdmin subclass')
assert issubclass(
getattr(conf_admin, 'change_list_form', None),
ConfigForm), 'No change_list_form set'
assert issubclass(conf, Config), (
'conf is not a Config subclass')
assert c... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def one_of(*args):
""" Validates that a field value matches one of the values given to this validator. """ |
if len(args) == 1 and isinstance(args[0], list):
items = args[0]
else:
items = list(args)
def validate(value):
if not value in items:
return e("{} is not in the list {}", value, items)
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gte(min_value):
""" Validates that a field value is greater than or equal to the value given to this validator. """ |
def validate(value):
if value < min_value:
return e("{} is not greater than or equal to {}", value, min_value)
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lte(max_value):
""" Validates that a field value is less than or equal to the value given to this validator. """ |
def validate(value):
if value > max_value:
return e("{} is not less than or equal to {}", value, max_value)
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def gt(gt_value):
""" Validates that a field value is greater than the value given to this validator. """ |
def validate(value):
if value <= gt_value:
return e("{} is not greater than {}", value, gt_value)
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lt(lt_value):
""" Validates that a field value is less than the value given to this validator. """ |
def validate(value):
if value >= lt_value:
return e("{} is not less than {}", value, lt_value)
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def between(min_value, max_value):
""" Validates that a field value is between the two values given to this validator. """ |
def validate(value):
if value < min_value:
return e("{} is not greater than or equal to {}",
value, min_value)
if value > max_value:
return e("{} is not less than or equal to {}",
value, max_value)
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def length(min=None, max=None):
""" Validates that a field value's length is between the bounds given to this validator. """ |
def validate(value):
if min and len(value) < min:
return e("{} does not have a length of at least {}", value, min)
if max and len(value) > max:
return e("{} does not have a length of at most {}", value, max)
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def match(pattern):
""" Validates that a field value matches the regex given to this validator. """ |
regex = re.compile(pattern)
def validate(value):
if not regex.match(value):
return e("{} does not match the pattern {}", value, pattern)
return validate |
<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_email():
""" Validates that a fields value is a valid email address. """ |
email = (
ur'(?!^\.)' # No dot at start
ur'(?!.*\.@)' # No dot before at sign
ur'(?!.*@\.)' # No dot after at sign
ur'(?!.*\.$)' # No dot at the end
ur'(?!.*\.\.)' # No double dots anywhere
ur'^\S+' # Starts with one or more non-whitespace characte... |
<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_url():
""" Validates that a fields value is a valid URL. """ |
# Stolen from Django
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def each_item(*validators):
""" A wrapper which applies the given validators to each item in a field value of type `list`. Example usage in a Schema: "my_list_fi... |
def validate(value):
for item in value:
for validator in validators:
error = validator(item)
if error:
return error
return None
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def distinct():
""" Validates that all items in the given field list value are distinct, i.e. that the list contains no duplicates. """ |
def validate(value):
for i, item in enumerate(value):
if item in value[i+1:]:
return e("{} is not a distinct set of values", value)
return validate |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_defaults(self, instance):
"""Applies the defaults described by the this schema to the given document instance as appropriate. Defaults are only applied... |
for field, spec in self.doc_spec.iteritems():
field_type = spec['type']
if field not in instance:
if 'default' in spec:
default = spec['default']
if callable(default):
instance[field] = default()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, instance):
"""Validates the given document against this schema. Raises a ValidationException if there are any failures.""" |
errors = {}
self._validate_instance(instance, errors)
if len(errors) > 0:
raise ValidationException(errors) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _verify(self, path_prefix=None):
"""Verifies that this schema's doc spec is valid and makes sense.""" |
for field, spec in self.doc_spec.iteritems():
path = self._append_path(path_prefix, field)
# Standard dict-based spec
if isinstance(spec, dict):
self._verify_field_spec(spec, path)
else:
raise SchemaFormatException("Invalid field ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _verify_field_spec(self, spec, path):
"""Verifies a given field specification is valid, recursing into nested schemas if required.""" |
# Required should be a boolean
if 'required' in spec and not isinstance(spec['required'], bool):
raise SchemaFormatException("{} required declaration should be True or False", path)
# Required should be a boolean
if 'nullable' in spec and not isinstance(spec['nullable'], b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _verify_type(self, spec, path):
"""Verify that the 'type' in the spec is valid""" |
field_type = spec['type']
if isinstance(field_type, Schema):
# Nested documents cannot have validation
if not set(spec.keys()).issubset(set(['type', 'required', 'nullable', 'default'])):
raise SchemaFormatException("Unsupported field spec item at {}. Items: "+re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _verify_default(self, spec, path):
"""Verifies that the default specified in the given spec is valid.""" |
field_type = spec['type']
default = spec['default']
# If it's a function there's nothing we can really do except assume its valid
if callable(default):
return
if isinstance(field_type, Array):
# Verify we'd got a list as our default
if not 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 _verify_validates(self, spec, path):
"""Verify thats the 'validates' argument is valid.""" |
validates = spec['validates']
if isinstance(validates, list):
for validator in validates:
self._verify_validator(validator, path)
else:
self._verify_validator(validates, 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 _verify_validator(self, validator, path):
"""Verifies that a given validator associated with the field at the given path is legitimate.""" |
# Validator should be a function
if not callable(validator):
raise SchemaFormatException("Invalid validations for {}", path)
# Validator should accept a single argument
(args, varargs, keywords, defaults) = getargspec(validator)
if len(args) != 1:
raise... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_instance(self, instance, errors, path_prefix=''):
"""Validates that the given instance of a document conforms to the given schema's structure and v... |
if not isinstance(instance, dict):
errors[path_prefix] = "Expected instance of dict to validate against schema."
return
# validate against the schema level validators
self._apply_validations(errors, path_prefix, self._validates, instance)
# Loop over each fiel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_value(self, value, field_spec, path, errors):
"""Validates that the given field value is valid given the associated field spec and path. Any valida... |
# Check if the value is None and add an error if the field is not nullable.
# Note that for backward compatibility reasons, the default value of 'nullable'
# is the inverse of 'required' (which use to mean both that the key be present
# and not set to None).
if value is 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 as_dict(config):
""" Converts a ConfigParser object into a dictionary. The resulting dictionary has sections as keys which point to a dict of the sections op... |
settings = defaultdict(lambda: {})
for section in config.sections():
for key, val in config.items(section):
settings[section][key] = val
return settings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize(self, timeouts):
""" Bind or connect the nanomsg socket to some address """ |
# Bind or connect to address
if self.bind is True:
self.socket.bind(self.address)
else:
self.socket.connect(self.address)
# Set send and recv timeouts
self._set_timeouts(timeouts) |
<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_timeouts(self, timeouts):
""" Set socket timeouts for send and receive respectively """ |
(send_timeout, recv_timeout) = (None, None)
try:
(send_timeout, recv_timeout) = timeouts
except TypeError:
raise EndpointError(
'`timeouts` must be a pair of numbers (2, 3) which represent '
'the timeout values for send and receive respe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def receive(self, decode=True):
""" Receive from socket, authenticate and decode payload """ |
payload = self.socket.recv()
payload = self.verify(payload)
if decode:
payload = self.decode(payload)
return payload |
<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, payload):
""" Sign payload using the supplied authenticator """ |
if self.authenticator:
return self.authenticator.signed(payload)
return payload |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(self, payload):
""" Verify payload authenticity via the supplied authenticator """ |
if not self.authenticator:
return payload
try:
self.authenticator.auth(payload)
return self.authenticator.unsigned(payload)
except AuthenticatorInvalidSignature:
raise
except Exception as exception:
raise AuthenticateError(str(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
""" Start and listen for calls """ |
if threading.current_thread().name == 'MainThread':
signal.signal(signal.SIGINT, self.stop)
logging.info('Started on {}'.format(self.address))
while True:
self.process() |
<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_summary(list_all=[], **kwargs):
''' summarize the report data
@param list_all: a list which save the report data
@param kwargs: such as
show_all: True/False report show all status cases
proj_name: project name
home_pag... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_report_data(list_all=[], module_name="TestModule", **kwargs):
''' add report data to a list
@param list_all: a list which save the report data
@param module_name: test set name or test module name
@param kwargs: such as
case_name: testcase name
... |
<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(self, subscription):
""" Fetch the function registered for a certain subscription """ |
for name in self.methods:
tag = bytes(name.encode('utf-8'))
if subscription.startswith(tag):
fun = self.methods.get(name)
message = subscription[len(tag):]
return tag, message, fun
return None, None, 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 subscribe(self, tag, fun, description=None):
""" Subscribe to something and register a function """ |
self.methods[tag] = fun
self.descriptions[tag] = description
self.socket.set_string_option(nanomsg.SUB, nanomsg.SUB_SUBSCRIBE, tag) |
<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(self):
""" Receive a subscription from the socket and process it """ |
subscription = None
result = None
try:
subscription = self.socket.recv()
except AuthenticateError as exception:
logging.error(
'Subscriber error while authenticating request: {}'
.format(exception), exc_info=1)
except A... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish(self, tag, message):
""" Publish a message down the socket """ |
payload = self.build_payload(tag, message)
self.socket.send(payload) |
<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_webpack(request, name='DEFAULT'):
""" Get the Webpack object for a given webpack config. Called at most once per request per config name. """ |
if not hasattr(request, '_webpack_map'):
request._webpack_map = {}
wp = request._webpack_map.get(name)
if wp is None:
wp = request._webpack_map[name] = Webpack(request, name)
return wp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def includeme(config):
""" Add pyramid_webpack methods and config to the app """ |
settings = config.registry.settings
root_package_name = config.root_package.__name__
config.registry.webpack = {
'DEFAULT': WebpackState(settings, root_package_name)
}
for extra_config in aslist(settings.get('webpack.configs', [])):
state = WebpackState(settings, root_package_name, ... |
<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_setting(self, setting, default=None, name=None, inherit=True):
""" Helper function to fetch settings, inheriting from the base """ |
if name is None:
name = self.name
if name == 'DEFAULT':
return self._settings.get('webpack.{0}'.format(setting), default)
else:
val = self._settings.get('webpack.{0}.{1}'.format(name, setting),
SENTINEL)
if val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_stats(self, cache=None, wait=None):
""" Load and cache the webpack-stats file """ |
if cache is None:
cache = not self.debug
if wait is None:
wait = self.debug
if not cache or self._stats is None:
self._stats = self._load_stats()
start = time.time()
while wait and self._stats.get('status') == 'compiling':
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_stats(self):
""" Load the webpack-stats file """ |
for attempt in range(0, 3):
try:
with self.stats_file.open() as f:
return json.load(f)
except ValueError:
# If we failed to parse the JSON, it's possible that the
# webpack process is writing to it concurrently and it's... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _chunk_filter(self, extensions):
""" Create a filter from the extensions and ignore files """ |
if isinstance(extensions, six.string_types):
extensions = extensions.split()
def _filter(chunk):
""" Exclusion filter """
name = chunk['name']
if extensions is not None:
if not any(name.endswith(e) for e in extensions):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_url(self, chunk):
""" Add a 'url' property to a chunk and return it """ |
if 'url' in chunk:
return chunk
public_path = chunk.get('publicPath')
if public_path:
chunk['url'] = public_path
else:
fullpath = posixpath.join(self.state.static_view_path,
chunk['name'])
chunk['url']... |
<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_bundle(self, bundle_name, extensions=None):
""" Get all the chunks contained in a bundle """ |
if self.stats.get('status') == 'done':
bundle = self.stats.get('chunks', {}).get(bundle_name, None)
if bundle is None:
raise KeyError('No such bundle {0!r}.'.format(bundle_name))
test = self._chunk_filter(extensions)
return [self._add_url(c) for c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.