output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def add_range(self, start, stop, step=1, pad=0):
"""
Add a range (start, stop, step and padding length) to RangeSet.
Like the Python built-in function range(), the last element is
the largest start + i * step less than stop.
"""
assert start < stop, "please provide ordere... | Write a Python 3 function that can
add a range to the RangeSet. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return a shallow copy of a RangeSet. | Can you generate a brief explanation for the following Python 3 code
def copy(self):
cpy = self.__class__()
cpy._autostep = self._autostep
cpy.padding = self.padding
cpy.update(self)
return cpy | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _wrap_set_op(self, fun, arg):
"""Wrap built-in set operations for RangeSet to workaround built-in set
base class issues (RangeSet.__new/init__ not called)"""
result = fun(self, arg)
result._autostep = self._autostep
result.padding = self.padding
return result | Can you create a Python 3 function that
wraps built - in set operations for RangeSet to workaround built - in set operations. | As a Python code analyst, you investigate and solve complex coding mysteries |
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 a... | Can you implement a function in Python 3 that
returns the intersection of two sets as a new set instance. | As a python code expert, you are capable of creating scripts from specifications. |
Return the difference of two sets as a new set. | Given the following Python 3 function, write the documentation
def difference(self, 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.
# ORIGINA... | As a Python code composer, you craft elegant and concise scripts. |
Report whether this set contains another set. | Given the following Python 3 function, write the documentation
def issubset(self, other):
self._binary_sanity_check(other)
return set.issubset(self, other) | You are a Python code architect, reviewing and designing scalable and efficient code |
def issuperset(self, other):
"""Report whether this RangeSet contains another set."""
self._binary_sanity_check(other)
return set.issuperset(self, other) | How would you code a function in Python 3 to
report whether this RangeSet contains another set. | You are a Python code generator, capable of creating scripts from specifications. |
def difference_update(self, other, strict=False):
"""Remove all elements of another set from this RangeSet.
If strict is True, raise KeyError if an element cannot be removed.
(strict is a RangeSet addition)"""
if strict and other not in self:
raise KeyError(other.dif... | Write a Python 3 script to
update this RangeSet with the difference of the elements of another set. | You are a Python code architect, reviewing and designing scalable and efficient code |
Add all integers from an iterable. | How would you explain what the following Python 3 function does
def update(self, iterable):
if isinstance(iterable, RangeSet):
# keep padding unless is has not been defined yet
if self.padding is None and iterable.padding is not None:
self.padding = iterable.padding
... | You are a Python code analyst, evaluating scripts for potential improvements. |
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)) | Write a Python 3 script for
updating a set of all the items in the set with the union of itself and several others. | You are a Python code generator, capable of creating scripts from specifications. |
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 | Create a Python 3 function to
add an element to a RangeSet. | As a Python code analyst, you investigate and solve complex coding mysteries |
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 | How would you code a function in Python 3 to
remove element from the RangeSet. | You are a Python code architect, reviewing and designing scalable and efficient code |
Open a file with the specified mode. | Make a summary of the following Python 3 code
def _open(filename, mode="r"):
if filename.endswith(".gz"):
return GzipFile(filename, mode, COMPRESSION_LEVEL)
elif filename == "-":
if mode == "r":
return _stdin
elif mode == "w":
return _stdout
else:
# TO... | You are a Python code generator, capable of creating scripts from specifications. |
def _radixPass(a, b, r, n, K):
"""
Stable sort of the sequence a according to the keys given in r.
>>> a=range(5)
>>> b=[0]*5
>>> r=[2,1,3,0,4]
>>> _radixPass(a, b, r, 5, 5)
>>> b
[3, 1, 0, 2, 4]
When n is less than the length of a, the end of b must be left unaltered.
>>> b=[... | How would you code a function in Python 3 to
stable sort of the sequence a according to the keys given in r. >>> a=range(5) >>> b=[0]*5 >>> r=[2,1,3,0,4] >>> _radixPass(a, b, r, 5, 5) >>> b [3, 1, 0, 2, 4] When n is less than the length of a, the end of b must be left unaltered. >>> b=[5]*5 >>> _radixPass(a, b, r, 2, 2... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the number of atomic operations in _radixPass. | Explain what the following Python 3 code does
def _nbOperations(n):
if n < 2:
return 0
else:
n0 = (n + 2) // 3
n02 = n0 + n // 3
return 3 * (n02) + n0 + _nbOperations(n02) | As a Python code translator, you convert algorithms and pseudocode into Python. |
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 at offset start2.
>>> _longestCommonPrefix("abcdef", "abcghj")
3
>>> _longestCommonPrefix("abcghj", "abcdef")
3
>>> _longes... | Write a Python 3 script to
return the length of the longest common prefix of seq1 and seq2 starting at offset start1 and start2. | You are a Python code generator, capable of creating scripts from specifications. |
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+1,
their LCP is stored at position i+1.
A zero is stored at position 0 of the output.
>>> SA=SuffixArray("abba", unit=UNIT_BYTE)
... | How would you code a function in Python 3 to
compute the longest common prefix for every adjacent suffixes. | You are a Python code architect, reviewing and designing scalable and efficient code |
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', 'charac... | Write a Python 3 script for
parsing the command line arguments. | You are a Python code generator, capable of creating scripts from specifications. |
def addFeatureSA(self, callback, default=None, name=None):
"""
Add a feature to the suffix array.
The callback must return a sequence such that
the feature at position i is attached to the suffix referenced by
self.SA[i].
It is called with one argument: the instance of S... | Can you write a function in Python 3 where it
adds a feature to the suffix array. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def addFeature(self, callback, default=None, name=None, arguments=None):
"""
Add a feature to the suffix array.
The callback must return the feature corresponding to the suffix at
position self.SA[i].
The callback must be callable (a function or lambda).
The argument nam... | How would you implement a function in Python 3 that
adds a feature to the suffix array. | As a python code expert, you are capable of creating scripts from specifications. |
Return a string of length tokens in the original form. | Explain what the following Python 3 code does
def reprString(self, string, length):
if isinstance(string, int):
length = min(length, self.length - string)
string = self.string[string:string + length]
voc = self.voc
res = self.tokSep.join((voc[id] for id in string[:length... | As a Python code analyst, you investigate and solve complex coding mysteries |
def toFile(self, filename):
"""
Save the suffix array instance including all features attached in
filename. Accept any filename following the _open conventions,
for example if it ends with .gz the file created will be a compressed
GZip file.
"""
start = _time()
... | Write a Python 3 script to
save the suffix array instance to a file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load a suffix array instance from a file created by toFile. | Can you tell what is the following Python 3 function doing
def fromFile(cls, filename):
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.vo... | As a Python code composer, you craft elegant and concise scripts. |
This method searches for a single entry in the string in the dictionary. | Given the following Python 3 function, write the documentation
def _findOne(self, subString):
SA = self.SA
LCPs = self._LCP_values
string = self.string
try:
subString = _array("i", [self.tokId[c] for c in self.tokenize(subString)])
except KeyError:
# if a... | As a python code expert, you are capable of creating scripts from specifications. |
Escape special characters < and < and > to HTML - safe sequences. | How would you explain what the following Python 3 function does
def escape(s, quote=False):
if s is None:
return ''
elif hasattr(s, '__html__'):
return s.__html__()
elif not isinstance(s, basestring):
s = unicode(s)
s = s.replace('&', '&').replace('<', '<').replace('>', '&... | As a python code expert, you are capable of creating scripts from specifications. |
def add(self, *args, **kwargs):
"""Add a new entry to the feed. This function can either be called
with a :class:`FeedEntry` or some keyword and positional arguments
that are forwarded to the :class:`FeedEntry` constructor.
"""
if len(args) == 1 and not kwargs and isinstance(arg... | Implement a Python 3 function for
adding a new entry to the feed. | You are a Python code analyst, evaluating scripts for potential improvements. |
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'},)
... | How would you code a function in Python 3 to
return a generator that yields pieces of XML. | As a Python code composer, you craft elegant and concise scripts. |
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' % e... | Write a Python 3 function for
yielding pieces of ATOM XML. | As a Python code analyst, you investigate and solve complex coding mysteries |
Serialize a value into a form value | Can you tell what is the following Python 3 function doing
def serialize(value, field):
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
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get version without importing the lib | Can you generate the documentation for the following Python 3 function
def get_version(package):
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 '__v... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Check that the backend is valid. | How would you explain what the following Python 3 function does
def _check_backend():
# Django 1.10 does not allow
# both settings to be set
middleware = set(
getattr(settings, 'MIDDLEWARE', None) or
getattr(settings, 'MIDDLEWARE_CLASSES', None) or
[])
# Deprecated alias
if ... | As a Python code composer, you craft elegant and concise scripts. |
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 be an instance of :py:class:`djconfig.forms.ConfigForm`
:param bool check_middleware: Check\
:py:class:`djconf... | How would you code a function in Python 3 to
register a config form into the registry. | You are a Python code analyst, evaluating scripts for potential improvements. |
Reloads the cache with the current values from the database. | Can you tell what is the following Python 3 function doing
def _reload(self):
ConfigModel = apps.get_model('djconfig.Config')
cache = {}
data = dict(
ConfigModel.objects
.all()
.values_list('key', 'value'))
# populate cache with initial form v... | As a Python code analyst, you investigate and solve complex coding mysteries |
Reload the config if the config \
MimeType model has been updated. | Make a summary of the following Python 3 code
def _reload_maybe(self):
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
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def save(self):
"""
Save the config with the cleaned data,\
update the last modified date so\
the config is reloaded on other process/nodes.\
Reload the config so it can be called right away.
"""
assert self.__class__ in conf.config._registry,\
'%(clas... | Create a Python 3 function to
save the config with the cleaned data. | You are a Python code architect, reviewing and designing scalable and efficient code |
def register(conf, conf_admin, **options):
"""
Register a new admin section.
:param conf: A subclass of ``djconfig.admin.Config``
:param conf_admin: A subclass of ``djconfig.admin.ConfigAdmin``
:param options: Extra options passed to ``django.contrib.admin.site.register``
"""
assert issubcl... | Create a Python 3 function for
registering a new admin section. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def Mixed(*types):
"""Mixed type, used to indicate a field in a schema can be
one of many types. Use as a last resort only.
The Mixed type can be used directly as a class to indicate
any type is permitted for a given field:
`"my_field": {"type": Mixed}`
It can also be instantiated with list of s... | Write a Python 3 function that can
mix type is used to indicate a field in a schema. | As a Python code analyst, you investigate and solve complex coding mysteries |
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("{} i... | Create a Python 3 function for
validating that a field value matches one of the values AttributeNames given to this validator. | You are a Python code generator, capable of creating scripts from specifications. |
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 | Create a Python 3 function for
returning a validator that checks that a field value is greater than or equal to the given value. | As a Python code analyst, you investigate and solve complex coding mysteries |
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 | Create a Python 3 function to
return a validator that checks that a field value is less than or equal to the max_value given to this validator. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a validator that checks that a field value is greater than the given value. | Explain what the following Python 3 code does
def gt(gt_value):
def validate(value):
if value <= gt_value:
return e("{} is not greater than {}", value, gt_value)
return validate | You are a Python code generator, capable of creating scripts from specifications. |
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 | Write a Python 3 function that can
return a validator that checks that a field value is less than the given value. | You are a Python code architect, reviewing and designing scalable and efficient code |
Validates that a field value is between the two values
articles. | Can you generate the documentation for the following Python 3 function
def between(min_value, max_value):
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 l... | You are a Python code architect, reviewing and designing scalable and efficient code |
Validates that a field value s length is between the bounds given to this
validator. | Can you tell what is the following Python 3 function doing
def length(min=None, max=None):
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 a... | As a Python code composer, you craft elegant and concise scripts. |
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 | Write a Python 3 function for
validating that a field value matches the regex pattern | As a python code expert, you are capable of creating scripts from specifications. |
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 dou... | Implement a Python 3 function for
validating that a value is a valid email address. | As a Python code analyst, you investigate and solve complex coding mysteries |
Validates that a fields value is a valid URL. | How would you explain what the following Python 3 function does
def is_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...
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Validates that all items in the given field list value are distinct | Make a summary of the following Python 3 code
def distinct():
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 | As a Python code analyst, you investigate and solve complex coding mysteries |
def apply_defaults(self, instance):
"""Applies the defaults described by the this schema to the given
document instance as appropriate. Defaults are only applied to
fields which are currently unset."""
for field, spec in self.doc_spec.iteritems():
field_type = spec['type']
... | Implement a function in Python 3 to
apply the defaults described by this schema to the given articles document instance as appropriate. | As a Python code analyst, you investigate and solve complex coding mysteries |
Validates the given document against this schema. Raises ValidationException if there are any failures. | Given the following Python 3 function, write the documentation
def validate(self, instance):
errors = {}
self._validate_instance(instance, errors)
if len(errors) > 0:
raise ValidationException(errors) | You are a Python code architect, reviewing and designing scalable and efficient code |
Verifies that this schema s doc spec is valid and makes sense. | Given the following Python 3 function, write the documentation
def _verify(self, path_prefix=None):
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_f... | As a Python code analyst, you investigate and solve complex coding mysteries |
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 declara... | Can you create a Python 3 function that
verifies a given field specification is valid recursing into nested schemas if required. | You are a Python code generator, capable of creating scripts from specifications. |
Verify that the type in the spec is valid | Given the following Python 3 function, write the documentation
def _verify_type(self, spec, path):
field_type = spec['type']
if isinstance(field_type, Schema):
# Nested documents cannot have validation
if not set(spec.keys()).issubset(set(['type', 'required', 'nullable', 'defaul... | As a Python code analyst, you investigate and solve complex coding mysteries |
Verifies that the default value specified in the given spec is valid. | Can you generate the documentation for the following Python 3 function
def _verify_default(self, spec, path):
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
... | You are a Python code generator, capable of creating scripts from specifications. |
Verify thats the validates argument is valid. | Here you have a function in Python 3, explain what it does
def _verify_validates(self, spec, path):
validates = spec['validates']
if isinstance(validates, list):
for validator in validates:
self._verify_validator(validator, path)
else:
self._verify_valida... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Verifies that a given validator associated with the field at the given path is legitimate. | Make a summary of the following Python 3 code
def _verify_validator(self, validator, path):
# Validator should be a function
if not callable(validator):
raise SchemaFormatException("Invalid validations for {}", path)
# Validator should accept a single argument
(args, vararg... | As a Python code analyst, you investigate and solve complex coding mysteries |
Validates that the given instance of a document conforms to the given schema s base - schema and validations. | Can you generate a brief explanation for the following Python 3 code
def _validate_instance(self, instance, errors, path_prefix=''):
if not isinstance(instance, dict):
errors[path_prefix] = "Expected instance of dict to validate against schema."
return
# validate against the sc... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 validation failures are added to the given errors
collection."""
# Check if the value is None and add an error if the field is not n... | Write a Python 3 script for
validating that the given value is valid given the associated field spec and path. Any validation failures are added to the given errors collection. | You are a Python code analyst, evaluating scripts for potential improvements. |
Loads and parses an INI style configuration file using Python s built - in
configparser module. | Here you have a function in Python 3, explain what it does
def load_config(path=None, defaults=None):
if defaults is None:
defaults = DEFAULT_FILES
config = ConfigParser(allow_no_value=True)
if defaults:
config.read(defaults)
if path:
with open(path) as fh:
config... | You are a Python code architect, reviewing and designing scalable and efficient code |
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 options as key => value pairs.
"""
settings = defaultdict(lambda: {})
for section in config.sections():
for key, val in conf... | Write a Python 3 script to
convert a ConfigParser object into a dictionary. | As a python code expert, you are capable of creating scripts from specifications. |
Bind or connect the nanomsg socket to some address | Make a summary of the following Python 3 code
def initialize(self, timeouts):
# 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(timeou... | As a Python code analyst, you investigate and solve complex coding mysteries |
Sets socket timeouts for send and receive respectively | How would you explain what the following Python 3 function does
def _set_timeouts(self, timeouts):
(send_timeout, recv_timeout) = (None, None)
try:
(send_timeout, recv_timeout) = timeouts
except TypeError:
raise EndpointError(
'`timeouts` must be a pair ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def send(self, payload):
""" Encode and sign (optional) the send through socket """
payload = self.encode(payload)
payload = self.sign(payload)
self.socket.send(payload) | Write a Python 3 script for
encoding and sign the payload through the socket | As a Python code composer, you craft elegant and concise scripts. |
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 | How would you code a function in Python 3 to
receive from socket authenticate and decode payload | You are a Python code generator, capable of creating scripts from specifications. |
def sign(self, payload):
""" Sign payload using the supplied authenticator """
if self.authenticator:
return self.authenticator.signed(payload)
return payload | Create a Python 3 function to
sign the payload using the authenticator | As a Python code composer, you craft elegant and concise scripts. |
Verify the authenticity of the payload. | Can you generate the documentation for the following Python 3 function
def verify(self, payload):
if not self.authenticator:
return payload
try:
self.authenticator.auth(payload)
return self.authenticator.unsigned(payload)
except AuthenticatorInvalidSignature:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Encode a single object. | How would you explain what the following Python 3 function does
def encode(self, payload):
try:
return self.encoder.encode(payload)
except Exception as exception:
raise EncodeError(str(exception)) | As a Python code composer, you craft elegant and concise scripts. |
Start and listen for calls | Given the following Python 3 function, write the documentation
def start(self):
if threading.current_thread().name == 'MainThread':
signal.signal(signal.SIGINT, self.stop)
logging.info('Started on {}'.format(self.address))
while True:
self.process() | As a python code expert, you are capable of creating scripts from specifications. |
Shutdown process (this method is also a signal handler) | Here you have a function in Python 3, explain what it does
def stop(self, dummy_signum=None, dummy_frame=None):
logging.info('Shutting down ...')
self.socket.close()
sys.exit(0) | As a Python code composer, you craft elegant and concise scripts. |
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... | Write a Python 3 function for
summarizing 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_page: home page url | As a Python code translator, you convert algorithms and pseudocode into Python. |
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
... | Write a Python 3 script for
adding report data to a list of all test set items | As a python code expert, you are capable of creating scripts from specifications. |
Parse a given subscription into a tuple of tag message and function ID | Make a summary of the following Python 3 code
def parse(self, 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... | As a Python code translator, you convert algorithms and pseudocode into Python. |
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) | Create a Python 3 function for
subscribing to something and register a function | As a python code expert, you are capable of creating scripts from specifications. |
Receive a subscription from the socket and process it | Given the following Python 3 function, write the documentation
def process(self):
subscription = None
result = None
try:
subscription = self.socket.recv()
except AuthenticateError as exception:
logging.error(
'Subscriber error while authenticati... | You are a Python code generator, capable of creating scripts from specifications. |
Builds the payload for the subscription | Here you have a function in Python 3, explain what it does
def build_payload(self, tag, message):
message = self.encode(message)
message = self.sign(message)
payload = bytes(tag.encode('utf-8')) + message
return payload | As a Python code analyst, you investigate and solve complex coding mysteries |
Publish a message down the socket | Explain what the following Python 3 code does
def publish(self, tag, message):
payload = self.build_payload(tag, message)
self.socket.send(payload) | As a Python code analyst, you investigate and solve complex coding mysteries |
def start_service(addr, n, authenticator):
""" Start a service """
s = Subscriber(addr, authenticator=authenticator)
def do_something(line):
pass
s.subscribe('test', do_something)
started = time.time()
for _ in range(n):
s.process()
s.socket.close()
duration = time.ti... | How would you implement a function in Python 3 that
starts a new subscriber service | You are a Python code generator, capable of creating scripts from specifications. |
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 = re... | Write a Python 3 function that can
get a Webpack object for a given webpack config. | As a Python code analyst, you investigate and solve complex coding mysteries |
Add pyramid_webpack methods and config to the app | Make a summary of the following Python 3 code
def includeme(config):
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.config... | As a Python code analyst, you investigate and solve complex coding mysteries |
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()
sta... | Can you implement a function in Python 3 that
loads and cache the webpack - stats file | As a Python code translator, you convert algorithms and pseudocode into Python. |
Load the webpack - stats file | Can you generate a brief explanation for the following Python 3 code
def _load_stats(self):
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... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a filter from the extensions and ignore files | Here you have a function in Python 3, explain what it does
def _chunk_filter(self, extensions):
if isinstance(extensions, six.string_types):
extensions = extensions.split()
def _filter(chunk):
""" Exclusion filter """
name = chunk['name']
if extensions is... | As a Python code composer, you craft elegant and concise scripts. |
Add a url property to a chunk and return it | How would you explain what the following Python 3 function does
def _add_url(self, chunk):
if 'url' in chunk:
return chunk
public_path = chunk.get('publicPath')
if public_path:
chunk['url'] = public_path
else:
fullpath = posixpath.join(self.state.stati... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get all the chunks contained in a bundle. | How would you explain what the following Python 3 function does
def get_bundle(self, bundle_name, extensions=None):
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}.... | You are a Python code generator, capable of creating scripts from specifications. |
def _unique_names():
"""Generates unique sequences of bytes.
"""
characters = ("abcdefghijklmnopqrstuvwxyz"
"0123456789")
characters = [characters[i:i + 1] for i in irange(len(characters))]
rng = random.Random()
while True:
letters = [rng.choice(characters) for i in ira... | Can you implement a function in Python 3 that
generates unique names of bytes. | You are a Python code architect, reviewing and designing scalable and efficient code |
def escape_queue(s):
"""Escapes the path to a queue, e.g. preserves ~ at the begining.
"""
if isinstance(s, PosixPath):
s = unicode_(s)
elif isinstance(s, bytes):
s = s.decode('utf-8')
if s.startswith('~/'):
return '~/' + shell_escape(s[2:])
else:
return shell_esc... | Can you implement a function in Python 3 that
escapes the path to a queue e. g. preserves ~ at the begining. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Parses the SSH destination argument. | Given the following Python 3 function, write the documentation
def parse_ssh_destination(destination):
match = _re_ssh.match(destination)
if not match:
raise InvalidDestination("Invalid destination: %s" % destination)
user, password, host, port = match.groups()
info = {}
if user:
inf... | As a python code expert, you are capable of creating scripts from specifications. |
def _ssh_client(self):
"""Gets an SSH client to connect with.
"""
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.RejectPolicy())
return ssh | Implement a Python 3 function for
getting an SSH client to connect with. | You are a Python code generator, capable of creating scripts from specifications. |
def get_client(self):
"""Gets the SSH client.
This will check that the connection is still alive first, and reconnect
if necessary.
"""
if self._ssh is None:
self._connect()
return self._ssh
else:
try:
chan = self._ssh.... | Can you write a function in Python 3 where it
gets the SSH client. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _call(self, cmd, get_output):
"""Calls a command through the SSH connection.
Remote stderr gets printed to this program's stderr. Output is captured
and may be returned.
"""
server_err = self.server_logger()
chan = self.get_client().get_transport().open_session()
... | Implement a Python 3 function for
calling a command through the SSH connection and returns the exit status and output. | You are a Python code architect, reviewing and designing scalable and efficient code |
Calls a command through SSH.
| Can you generate the documentation for the following Python 3 function
def check_call(self, cmd):
ret, _ = self._call(cmd, False)
if ret != 0: # pragma: no cover
raise RemoteCommandFailure(command=cmd, ret=ret) | You are a Python code analyst, evaluating scripts for potential improvements. |
def check_output(self, cmd):
"""Calls a command through SSH and returns its output.
"""
ret, output = self._call(cmd, True)
if ret != 0: # pragma: no cover
raise RemoteCommandFailure(command=cmd, ret=ret)
logger.debug("Output: %r", output)
return output | Create a Python 3 function for
calling a command through SSH and returns its output. | You are a Python code analyst, evaluating scripts for potential improvements. |
Resolves the queue location on the server. | Here you have a function in Python 3, explain what it does
def _resolve_queue(self, queue, depth=0, links=None):
if depth == 0:
logger.debug("resolve_queue(%s)", queue)
answer = self.check_output(
'if [ -d %(queue)s ]; then '
' cd %(queue)s; echo "dir"; cat version... | As a Python code composer, you craft elegant and concise scripts. |
Gets the actual location of the queue or None. | Can you generate the documentation for the following Python 3 function
def _get_queue(self):
if self._queue is None:
self._links = []
queue, depth = self._resolve_queue(self.queue, links=self._links)
if queue is None and depth > 0:
raise QueueLinkBroken
... | As a Python code composer, you craft elegant and concise scripts. |
Installs the runtime at the target location. | Make a summary of the following Python 3 code
def setup(self, links=None, force=False, only_links=False):
if not links:
links = []
if only_links:
logger.info("Only creating links")
for link in links:
self.check_call('echo "tejdir:" %(queue)s > %(link)... | You are a Python code analyst, evaluating scripts for potential improvements. |
Actually installs the runtime.
| Can you tell what is the following Python 3 function doing
def _setup(self):
# Expands ~user in queue
if self.queue.path[0:1] == b'/':
queue = self.queue
else:
if self.queue.path[0:1] == b'~':
output = self.check_output('echo %s' %
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def submit(self, job_id, directory, script=None):
"""Submits a job to the queue.
If the runtime is not there, it will be installed. If it is a broken
chain of links, error.
"""
if job_id is None:
job_id = '%s_%s_%s' % (Path(directory).unicodename,
... | Implement a Python 3 function for
submitting a job to the queue. | As a python code expert, you are capable of creating scripts from specifications. |
def status(self, job_id):
"""Gets the status of a previously-submitted job.
"""
check_jobid(job_id)
queue = self._get_queue()
if queue is None:
raise QueueDoesntExist
ret, output = self._call('%s %s' % (
shell_escape(queue / ... | Write a Python 3 function that can
get the status of a previously - submitted job. | You are a Python code architect, reviewing and designing scalable and efficient code |
Downloads files from server. | Can you generate the documentation for the following Python 3 function
def download(self, job_id, files, **kwargs):
check_jobid(job_id)
if not files:
return
if isinstance(files, string_types):
files = [files]
directory = False
recursive = kwargs.pop('recu... | You are a Python code architect, reviewing and designing scalable and efficient code |
Kills a job on the server. | Explain what the following Python 3 code does
def kill(self, job_id):
check_jobid(job_id)
queue = self._get_queue()
if queue is None:
raise QueueDoesntExist
ret, output = self._call('%s %s' % (
shell_escape(queue / 'commands/kill'),
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.