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 upload_supervisor_app_conf(app_name, template_name=None, context=None):
"""Upload Supervisor app configuration from a template.""" |
default = {'app_name': app_name}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % app_name, u'supervisor/base.conf']
destination = u'/etc/supervisor/conf.d/%s.conf' % app_name
upload_template(template_name, destination, context=default, use_sudo=True)
supervisor_command(u'update') |
<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_supervisor_app(app_name):
"""Remove Supervisor app configuration.""" |
app = u'/etc/supervisor/conf.d/%s.conf' % app_name
if files.exists(app):
sudo(u'rm %s' % app)
supervisor_command(u'update') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_celery_conf(command='celeryd', app_name=None, template_name=None, context=None):
"""Upload Supervisor configuration for a celery command.""" |
app_name = app_name or command
default = {'app_name': app_name, 'command': command}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % command, u'supervisor/celery.conf']
upload_supervisor_app_conf(app_name=app_name, template_name=template_name, context=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 upload_gunicorn_conf(command='gunicorn', app_name=None, template_name=None, context=None):
"""Upload Supervisor configuration for a gunicorn server.""" |
app_name = app_name or command
default = {'app_name': app_name, 'command': command}
context = context or {}
default.update(context)
template_name = template_name or [u'supervisor/%s.conf' % command, u'supervisor/gunicorn.conf']
upload_supervisor_app_conf(app_name=app_name, template_name=template_name, context=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 notify(correlation_id, components, args = None):
""" Notifies multiple components. To be notified components must implement [[INotifiable]] interface. If they don't the call to this method has no effect. :param correlation_id: (optional) transaction id to trace execution through call chain. :param components: a list of components that are to be notified. :param args: notification arguments. """ |
if components == None:
return
args = args if args != None else Parameters()
for component in components:
Notifier.notify_one(correlation_id, component, args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, service_name, **params):
""" convinent access method for list. service_name describes the endpoint to call the `list` function on. images.list or apks.list. """ |
result = self._invoke_call(service_name, 'list', **params)
if result is not None:
return result.get(service_name, list())
return list() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list_inappproducts(self):
"""temp function to list inapp products.""" |
result = self.service.inappproducts().list(
packageName=self.package_name).execute()
if result is not None:
return result.get('inappproduct', list())
return list() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def commit(self):
"""commit current edits.""" |
request = self.edits().commit(**self.build_params()).execute()
print 'Edit "%s" has been committed' % (request['id'])
self.edit_id = 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 build_params(self, params={}):
""" build a params dictionary with current editId and packageName. use optional params parameter to merge additional params into resulting dictionary. """ |
z = params.copy()
z.update({'editId': self.edit_id, 'packageName': self.package_name})
return z |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_edit_id(self):
"""create edit id if edit id is None.""" |
if self.edit_id is None:
edit_request = self.edits().insert(
body={}, packageName=self.package_name)
result = edit_request.execute()
self.edit_id = result['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 upload_rabbitmq_environment_conf(template_name=None, context=None, restart=True):
"""Upload RabbitMQ environment configuration from a template.""" |
template_name = template_name or u'rabbitmq/rabbitmq-env.conf'
destination = u'/etc/rabbitmq/rabbitmq-env.conf'
upload_template(template_name, destination, context=context, use_sudo=True)
if restart:
restart_service(u'rabbitmq') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload_rabbitmq_conf(template_name=None, context=None, restart=True):
"""Upload RabbitMQ configuration from a template.""" |
template_name = template_name or u'rabbitmq/rabbitmq.config'
destination = u'/etc/rabbitmq/rabbitmq.config'
upload_template(template_name, destination, context=context, use_sudo=True)
if restart:
restart_service(u'rabbitmq') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queue_exc(*arg, **kw):
"""Queue undefined variable exception""" |
_self = arg[0]
if not isinstance(_self, AnsibleUndefinedVariable):
# Run for AnsibleUndefinedVariable instance
return
_rslt_q = None
for stack_trace in inspect.stack():
# Check if method to be skipped
if stack_trace[3] in SKIP_METHODS:
continue
_frame = stack_trace[0]
_locals = inspect.getargvalues(_frame).locals
if 'self' not in _locals:
continue
# Check if current frame instance of worker
if isinstance(_locals['self'], WorkerProcess):
# Get queue to add exception
_rslt_q = getattr(_locals['self'], '_rslt_q')
if not _rslt_q:
raise ValueError("No Queue found.")
# Add interceptor exception
_rslt_q.put(arg[3].message, interceptor=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 extract_worker_exc(*arg, **kw):
"""Get exception added by worker""" |
_self = arg[0]
if not isinstance(_self, StrategyBase):
# Run for StrategyBase instance only
return
# Iterate over workers to get their task and queue
for _worker_prc, _main_q, _rslt_q in _self._workers:
_task = _worker_prc._task
if _task.action == 'setup':
# Ignore setup
continue
# Do till queue is empty for the worker
while True:
try:
_exc = _rslt_q.get(block=False, interceptor=True)
RESULT[_task.name].add(_exc)
except Empty:
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 containsParamSubset(self, params):
""" Test whether this element contains at least all `params`, or more. Args: params (dict/SpecialDict):
Subset of parameters. Returns: bool: True if all `params` are contained in this element. """ |
for key in params.keys():
if key not in self.params:
return False
if params[key] != self.params[key]:
return False
return 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 get_skip(self, min_skip):
""" Gets the number of items to skip. :param min_skip: the minimum number of items to skip. :return: the number of items to skip. """ |
if self.skip == None:
return min_skip
if self.skip < min_skip:
return min_skip
return self.skip |
<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_take(self, max_take):
""" Gets the number of items to return in a page. :param max_take: the maximum number of items to return. :return: the number of items to return. """ |
if self.take == None:
return max_take
if self.take < 0:
return 0
if self.take > max_take:
return max_take
return self.take |
<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_value(value):
""" Converts specified value into PagingParams. :param value: value to be converted :return: a newly created PagingParams. """ |
if isinstance(value, PagingParams):
return value
if isinstance(value, AnyValueMap):
return PagingParams.from_map(value)
map = AnyValueMap.from_value(value)
return PagingParams.from_map(map) |
<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_map(map):
""" Creates a new PagingParams and sets it parameters from the specified map :param map: a AnyValueMap or StringValueMap to initialize this PagingParams :return: a newly created PagingParams. """ |
skip = map.get_as_nullable_integer("skip")
take = map.get_as_nullable_integer("take")
total = map.get_as_nullable_boolean("total")
return PagingParams(skip, take, total) |
<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_int(self, input_string):
""" Return integer type user input """ |
if input_string in ('--ensemble_size', '--ncpu'):
# was the flag set?
try:
index = self.args.index(input_string) + 1
except ValueError:
# it wasn't, so if it's required, exit
if input_string in self.required:
print("\n {flag} is required\n".format(flag=input_string))
print_short_help()
sys.exit(1)
# otherwise return the appropriate default
else:
return None
# the flag was set, so check if a value was set, otherwise exit
try:
if self.args[index] in self.flags:
print("\n {flag} was set but a value was not specified".format(flag=input_string))
print_short_help()
sys.exit(1)
except IndexError:
print("\n {flag} was set but a value was not specified".format(flag=input_string))
print_short_help()
sys.exit(1)
# a value was set, so check if its the correct type
try:
value = int(self.args[index])
except ValueError:
print("\n {flag} must be an integer".format(flag=input_string))
print_short_help()
sys.exit(1)
# verify the value provided is not negative
if value < 0:
print("\n {flag} must be an integer greater than 0".format(flag=input_string))
print_short_help()
sys.exit(1)
# everything checks out, so return the value
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(self, *args, **kwargs):
"""Tornado RequestHandler GET request endpoint for reporting status :param list args: positional args :param dict kwargs: keyword args """ |
self.set_status(self._status_response_code())
self.write(self._status_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 update_registered_subject_from_model_on_post_save(sender, instance, raw, created, using, **kwargs):
"""Updates RegisteredSubject from models using UpdatesOrCreatesRegistrationModelMixin.""" |
if not raw and not kwargs.get('update_fields'):
try:
instance.registration_update_or_create()
except AttributeError as e:
if 'registration_update_or_create' not in str(e):
raise AttributeError(str(e)) |
<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(ctx, test=False):
"""Publish to the cheeseshop.""" |
clean(ctx)
if test:
run('python setup.py register -r test sdist bdist_wheel', echo=True)
run('twine upload dist/* -r test', echo=True)
else:
run('python setup.py register sdist bdist_wheel', echo=True)
run('twine upload dist/*', echo=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 format_value(value,number_format):
"Convert number to string using a style string"
style,sufix,scale = decode_format(number_format)
fmt = "{0:" + style + "}" + sufix
return fmt.format(scale * 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 has_property(obj, name):
""" Checks if object has a property with specified name. :param obj: an object to introspect. :param name: a name of the property to check. :return: true if the object has the property and false if it doesn't. """ |
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
return True
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 get_property(obj, name):
""" Gets value of object property specified by its name. :param obj: an object to read property from. :param name: a name of the property to get. :return: the property value or null if property doesn't exist or introspection failed. """ |
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
try:
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
return property
except:
pass
return 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 get_property_names(obj):
""" Gets names of all properties implemented in specified object. :param obj: an objec to introspect. :return: a list with property names. """ |
property_names = []
for property_name in dir(obj):
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
property_names.append(property_name)
return property_names |
<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_properties(obj):
""" Get values of all properties in specified object and returns them as a map. :param obj: an object to get properties from. :return: a map, containing the names of the object's properties and their values. """ |
properties = {}
for property_name in dir(obj):
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
properties[property_name] = property
return properties |
<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_property(obj, name, value):
""" Sets value of object property specified by its name. If the property does not exist or introspection fails this method doesn't do anything and doesn't any throw errors. :param obj: an object to write property to. :param name: a name of the property to set. :param value: a new value for the property to set. """ |
if obj == None:
raise Exception("Object cannot be null")
if name == None:
raise Exception("Property name cannot be null")
name = name.lower()
try:
for property_name in dir(obj):
if property_name.lower() != name:
continue
property = getattr(obj, property_name)
if PropertyReflector._is_property(property, property_name):
setattr(obj, property_name, value)
except:
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 _compute_signature(self, body):
""" Computes the signature. Described at: http://crossbar.io/docs/HTTP-Bridge-Services-Caller/ Reference code is at: https://github.com/crossbario/crossbar/blob/master/crossbar/adapter/rest/common.py :return: (signature, none, timestamp) """ |
timestamp = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
nonce = randint(0, 2**53)
# Compute signature: HMAC[SHA256]_{secret} (key | timestamp | seq | nonce | body) => signature
hm = hmac.new(self.secret, None, hashlib.sha256)
hm.update(self.key)
hm.update(timestamp)
hm.update(str(self.sequence))
hm.update(str(nonce))
hm.update(body)
signature = base64.urlsafe_b64encode(hm.digest())
return signature, nonce, timestamp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exhaust(self, index = None):
"""Exhaust the iterator generating this LazyList's values. if index is None, this will exhaust the iterator completely. Otherwise, it will iterate over the iterator until either the list has a value for index or the iterator is exhausted. """ |
if self._exhausted:
return
if index is None:
ind_range = itertools.count(len(self))
else:
ind_range = range(len(self), index + 1)
for ind in ind_range:
try:
self._data.append(next(self._iterator))
except StopIteration: #iterator is fully exhausted
self._exhausted = True
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 binary_construct(tokens):
""" Construct proper instructions for binary expressions from a sequence of tokens at the same precedence level. For instance, if the tokens represent "1 + 2 + 3", this will return the instruction array "1 2 add_op 3 add_op". :param tokens: The sequence of tokens. :returns: An instance of ``Instructions`` containing the list of instructions. """ |
# Initialize the list of instructions we will return with the
# left-most element
instructions = [tokens[0]]
# Now process all the remaining tokens, building up the array we
# will return
for i in range(1, len(tokens), 2):
op, rhs = tokens[i:i + 2]
# Add the right-hand side
instructions.append(rhs)
# Now apply constant folding
instructions[-2:] = op.fold(instructions[-2:])
return instructions |
<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_rule(name, rule_text, do_raise=False):
""" Parses the given rule text. :param name: The name of the rule. Used when emitting log messages regarding a failure to parse the rule. :param rule_text: The text of the rule to parse. :param do_raise: If ``False`` and the rule fails to parse, a log message is emitted to the "policies" logger at level WARN, and a rule that always evaluates to ``False`` will be returned. If ``True``, a ``pyparsing.ParseException`` will be raised. :returns: An instance of ``policies.instructions.Instructions``, containing the instructions necessary to evaluate the authorization rule. """ |
try:
return rule.parseString(rule_text, parseAll=True)[0]
except pyparsing.ParseException as exc:
# Allow for debugging
if do_raise:
raise
# Get the logger and emit our log messages
log = logging.getLogger('policies')
log.warn("Failed to parse rule %r: %s" % (name, exc))
log.warn("Rule line: %s" % exc.line)
log.warn("Location : %s^" % (" " * (exc.col - 1)))
# Construct and return a fail-closed instruction
return Instructions([Constant(False), set_authz]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def callback(self, result):
""" Callbacks the deferreds previously produced by this object. @param result: The object which will be passed to the C{callback} method of all C{Deferred}s previously produced by this object's C{tee} method. @raise AlreadyCalledError: If L{callback} or L{errback} has already been called on this object. """ |
self._setResult(result)
self._isFailure = False
for d in self._deferreds:
d.callback(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 errback(self, failure):
""" Errbacks the deferreds previously produced by this object. @param failure: The object which will be passed to the C{errback} method of all C{Deferred}s previously produced by this object's C{tee} method. @raise AlreadyCalledError: If L{callback} or L{errback} has already been called on this object. """ |
self._setResult(failure)
self._isFailure = True
for d in self._deferreds:
d.errback(failure) |
<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_all_json_files(build_dir):
"""Return a list of pages to index""" |
html_files = []
for root, _, files in os.walk(build_dir):
for filename in fnmatch.filter(files, '*.fjson'):
if filename in ['search.fjson', 'genindex.fjson',
'py-modindex.fjson']:
continue
html_files.append(os.path.join(root, filename))
page_list = []
for filename in html_files:
try:
result = process_file(filename)
if result:
page_list.append(result)
# we're unsure which exceptions can be raised
except: # noqa
pass
return page_list |
<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_headers(data, filename):
"""Read headers from toc data.""" |
headers = []
if 'toc' in data:
for element in PyQuery(data['toc'])('a'):
headers.append(recurse_while_none(element))
if None in headers:
log.info('Unable to index file headers for: %s', filename)
return headers |
<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_gain(self, gain=1):
""" Set the gain """ |
if gain == 1:
self.i2c.write8(0x81, 0x02)
else:
self.i2c.write8(0x81, 0x12)
time.sleep(self.pause) |
<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_user_details(self, response):
"""Return user details from OAuth Profile Google App Engine App""" |
email = response['email']
username = response.get('nickname', email).split('@', 1)[0]
return {'username': username,
'email': email,
'fullname': '',
'first_name': '',
'last_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 makePickle(self, record):
""" Use JSON. """ |
#ei = record.exc_info
#if ei:
# dummy = self.format(record) # just to get traceback text into record.exc_text
# record.exc_info = None # to avoid Unpickleable error
s = '%s%s:%i:%s\n' % (self.prefix, record.name, int(record.created), self.format(record))
#if ei:
# record.exc_info = ei # for next handler
return 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 _read_pyc(source, pyc):
"""Possibly read a pytest pyc containing rewritten code. Return rewritten code if successful or None if not. """ |
try:
fp = open(pyc, "rb")
except IOError:
return None
try:
try:
mtime = int(os.stat(source).st_mtime)
data = fp.read(8)
except EnvironmentError:
return None
# Check for invalid or out of date pyc file.
if (len(data) != 8 or data[:4] != imp.get_magic() or
struct.unpack("<l", data[4:])[0] != mtime):
return None
co = marshal.load(fp)
if not isinstance(co, types.CodeType):
# That's interesting....
return None
return co
finally:
fp.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 _saferepr(obj):
"""Get a safe repr of an object for assertion error messages. The assertion formatting (util.format_explanation()) requires newlines to be escaped since they are a special character for it. Normally assertion.util.format_explanation() does this but for a custom repr it is possible to contain one of the special escape sequences, especially '\n{' and '\n}' are likely to be present in JSON reprs. """ |
repr = py.io.saferepr(obj)
if py.builtin._istext(repr):
t = py.builtin.text
else:
t = py.builtin.bytes
return repr.replace(t("\n"), t("\\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 _format_assertmsg(obj):
"""Format the custom assertion message given. For strings this simply replaces newlines with '\n~' so that util.format_explanation() will preserve them instead of escaping newlines. For other objects py.io.saferepr() is used first. """ |
# reprlib appears to have a bug which means that if a string
# contains a newline it gets escaped, however if an object has a
# .__repr__() which contains newlines it does not get escaped.
# However in either case we want to preserve the newline.
if py.builtin._istext(obj) or py.builtin._isbytes(obj):
s = obj
is_repr = False
else:
s = py.io.saferepr(obj)
is_repr = True
if py.builtin._istext(s):
t = py.builtin.text
else:
t = py.builtin.bytes
s = s.replace(t("\n"), t("\n~")).replace(t("%"), t("%%"))
if is_repr:
s = s.replace(t("\\n"), t("\n~"))
return 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 set_location(node, lineno, col_offset):
"""Set node location information recursively.""" |
def _fix(node, lineno, col_offset):
if "lineno" in node._attributes:
node.lineno = lineno
if "col_offset" in node._attributes:
node.col_offset = col_offset
for child in ast.iter_child_nodes(node):
_fix(child, lineno, col_offset)
_fix(node, lineno, col_offset)
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 mark_rewrite(self, *names):
"""Mark import names as needing to be re-written. The named module or package as well as any nested modules will be re-written on import. """ |
already_imported = set(names).intersection(set(sys.modules))
if already_imported:
for name in already_imported:
if name not in self._rewritten_names:
self._warn_already_imported(name)
self._must_rewrite.update(names) |
<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_with_pkg_resources(cls):
""" Ensure package resources can be loaded from this loader. May be called multiple times, as the operation is idempotent. """ |
try:
import pkg_resources
# access an attribute in case a deferred importer is present
pkg_resources.__name__
except ImportError:
return
# Since pytest tests are always located in the file system, the
# DefaultProvider is appropriate.
pkg_resources.register_loader_type(cls, pkg_resources.DefaultProvider) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def variable(self):
"""Get a new variable.""" |
# Use a character invalid in python identifiers to avoid clashing.
name = "@py_assert" + str(next(self.variable_counter))
self.variables.append(name)
return 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 helper(self, name, *args):
"""Call a helper in this module.""" |
py_name = ast.Name("@dessert_ar", ast.Load())
attr = ast.Attribute(py_name, "_" + name, ast.Load())
return ast_Call(attr, list(args), []) |
<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):
"""Handle expressions we don't have custom code for.""" |
assert isinstance(node, ast.expr)
res = self.assign(node)
return res, self.explanation_param(self.display(res)) |
<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_Assert(self, assert_):
"""Return the AST statements to replace the ast.Assert instance. This re-writes the test of an assertion to provide intermediate values and replace it with an if statement which raises an assertion error with a detailed explanation in case the expression is false. """ |
if isinstance(assert_.test, ast.Tuple) and self.config is not None:
fslocation = (self.module_path, assert_.lineno)
self.config.warn('R1', 'assertion is always true, perhaps '
'remove parentheses?', fslocation=fslocation)
self.statements = []
self.variables = []
self.variable_counter = itertools.count()
self.stack = []
self.on_failure = []
self.push_format_context()
# Rewrite assert into a bunch of statements.
top_condition, explanation = self.visit(assert_.test)
# Create failure message.
body = self.on_failure
negation = ast.UnaryOp(ast.Not(), top_condition)
self.statements.append(ast.If(negation, body, []))
if assert_.msg:
assertmsg = self.helper('format_assertmsg', assert_.msg)
explanation = "\n>assert " + explanation
else:
assertmsg = ast.Str("")
explanation = "assert " + explanation
if _MARK_ASSERTION_INTROSPECTION:
explanation = 'dessert* ' + explanation
template = ast.BinOp(assertmsg, ast.Add(), ast.Str(explanation))
msg = self.pop_format_context(template)
fmt = self.helper("format_explanation", msg, assertmsg)
err_name = ast.Name("AssertionError", ast.Load())
exc = ast_Call(err_name, [fmt], [])
if sys.version_info[0] >= 3:
raise_ = ast.Raise(exc, None)
else:
raise_ = ast.Raise(exc, None, None)
body.append(raise_)
# Clear temporary variables by setting them to None.
if self.variables:
variables = [ast.Name(name, ast.Store())
for name in self.variables]
clear = ast.Assign(variables, _NameConstant(None))
self.statements.append(clear)
# Fix line numbers.
for stmt in self.statements:
set_location(stmt, assert_.lineno, assert_.col_offset)
return self.statements |
<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_35(self, call):
""" visit `ast.Call` nodes on Python3.5 and after """ |
new_func, func_expl = self.visit(call.func)
arg_expls = []
new_args = []
new_kwargs = []
for arg in call.args:
res, expl = self.visit(arg)
arg_expls.append(expl)
new_args.append(res)
for keyword in call.keywords:
res, expl = self.visit(keyword.value)
new_kwargs.append(ast.keyword(keyword.arg, res))
if keyword.arg:
arg_expls.append(keyword.arg + "=" + expl)
else: ## **args have `arg` keywords with an .arg of None
arg_expls.append("**" + expl)
expl = "%s(%s)" % (func_expl, ', '.join(arg_expls))
new_call = ast.Call(new_func, new_args, new_kwargs)
res = self.assign(new_call)
res_expl = self.explanation_param(self.display(res))
outer_expl = "%s\n{%s = %s\n}" % (res_expl, res_expl, expl)
return res, outer_expl |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cancel(self):
'''
Cancel the scheduled task.
'''
if (not self.cancelled) and (self._fn is not None):
self._cancelled = True
self._drop_fn() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def result(self):
'''
The result from the executed task. Raises NotExecutedYet if not yet
executed.
'''
if self.cancelled or (self._fn is not None):
raise NotExecutedYet()
if self._fn_exc is not None:
six.reraise(*self._fn_exc)
else:
return self._fn_res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rows_to_columns(matrix):
#hammer """Takes a two dimensional array and returns an new one where rows in the first become columns in the second.""" |
num_rows = len(matrix)
num_cols = len(matrix[0])
data = []
for i in range(0, num_cols):
data.append([matrix[j][i] for j in range(0, num_rows)])
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 parse_link(html):
#hammer """Parses an HTML anchor tag, returning the href and content text. Any content before or after the anchor tag pair is ignored. :param html: Snippet of html to parse :returns: namedtuple('ParsedLink', ['url', 'text']) Example: .. code-block:: python ParsedLink('/foo/bar.html', 'Foo') """ |
parser = AnchorParser()
parser.feed(html)
return parser.ParsedLink(parser.url, parser.text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choices(cls):
"""Returns a "choices" list of tuples. Each member of the list is one of the possible items in the ``Enum``, with the first item in the pair being the value and the second the name. This is compatible with django's choices attribute in fields. :returns: List of tuples """ |
result = []
for name, member in cls.__members__.items():
result.append((member.value, name))
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 emit(self, **kwargs):
"""Emit signal by calling all connected slots. The arguments supplied have to match the signal definition. Args: kwargs: Keyword arguments to be passed to connected slots. Raises: :exc:`InvalidEmit`: If arguments don't match signal specification. """ |
self._ensure_emit_kwargs(kwargs)
for slot in self.slots:
slot(**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 connect(self, slot):
"""Connect ``slot`` to this singal. Args: slot (callable):
Callable object wich accepts keyword arguments. Raises: InvalidSlot: If ``slot`` doesn't accept keyword arguments. """ |
self._ensure_slot_args(slot)
if not self.is_connected(slot):
self.slots.append(slot) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disconnect(self, slot):
"""Disconnect ``slot`` from this signal.""" |
if self.is_connected(slot):
self.slots.remove(slot) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_task_data(rt, role):
"""Return the data for the task that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the task :rtype: depending on role :raises: None """ |
tfi = rt.get_taskfileinfo()
if not tfi:
return
return filesysitemdata.taskfileinfo_task_data(tfi, role) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_rtype_data(rt, role):
"""Return the data for the releasetype that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the releasetype :rtype: depending on role :raises: None """ |
tfi = rt.get_taskfileinfo()
if not tfi:
return
return filesysitemdata.taskfileinfo_rtype_data(tfi, role) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_descriptor_data(rt, role):
"""Return the data for the descriptor that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the descriptor :rtype: depending on role :raises: None """ |
tfi = rt.get_taskfileinfo()
if not tfi:
return
return filesysitemdata.taskfileinfo_descriptor_data(tfi, role) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_version_data(rt, role):
"""Return the data for the version that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the version :rtype: depending on role :raises: None """ |
tfi = rt.get_taskfileinfo()
if not tfi:
return
return filesysitemdata.taskfileinfo_version_data(tfi, role) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_status_data(rt, role):
"""Return the data for the status :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the status :rtype: depending on role :raises: None """ |
status = rt.status()
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
if status:
return status
else:
return "Not in scene!" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_uptodate_data(rt, role):
"""Return the data for the uptodate status :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the uptodate status :rtype: depending on role :raises: None """ |
uptodate = rt.uptodate()
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
if uptodate:
return "Yes"
else:
return "No"
if role == QtCore.Qt.ForegroundRole:
if uptodate:
return QtGui.QColor(*UPTODATE_RGB)
elif rt.status():
return QtGui.QColor(*OUTDATED_RGB) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_alien_data(rt, role):
"""Return the data for the alien status :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the alien status :rtype: depending on role :raises: None """ |
alien = rt.alien()
if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
if alien:
return "Yes"
else:
return "No" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_path_data(rt, role):
"""Return the data for the path that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the path :rtype: depending on role :raises: None """ |
tfi = rt.get_taskfileinfo()
if not tfi:
return
return filesysitemdata.taskfileinfo_path_data(tfi, role) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_restricted_data(rt, role, attr):
"""Return the data for restriction of the given attr of the given reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the restriction :rtype: depending on role :raises: None """ |
if role == QtCore.Qt.DisplayRole:
if rt.is_restricted(getattr(rt, attr, None)):
return "Restricted"
else:
return "Allowed" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reftrack_object_data(rt, role):
"""Return the reftrack for REFTRACK_OBJECT_ROLE :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data for the id :rtype: depending on the role :raises: None """ |
if role == QtCore.Qt.DisplayRole:
return str(rt)
if role == REFTRACK_OBJECT_ROLE:
return rt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filterAcceptsRow(self, row, parentindex):
"""Return True, if the filter accepts the given row of the parent :param row: the row to filter :type row: :class:`int` :param parentindex: the parent index :type parentindex: :class:`QtCore.QModelIndex` :returns: True, if the filter accepts the row :rtype: :class:`bool` :raises: None """ |
if not super(ReftrackSortFilterModel, self).filterAcceptsRow(row, parentindex):
return False
if parentindex.isValid():
m = parentindex.model()
else:
m = self.sourceModel()
i = m.index(row, 18, parentindex)
reftrack = i.data(REFTRACK_OBJECT_ROLE)
if not reftrack:
return True
else:
return self.filter_accept_reftrack(reftrack) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_accept_reftrack(self, reftrack):
"""Return True, if the filter accepts the given reftrack :param reftrack: the reftrack to filter :type reftrack: :class:`jukeboxcore.reftrack.Reftrack` :returns: True, if the filter accepts the reftrack :rtype: :class:`bool` :raises: None """ |
if reftrack.status() in self._forbidden_status:
return False
if reftrack.get_typ() in self._forbidden_types:
return False
if reftrack.uptodate() in self._forbidden_uptodate:
return False
if reftrack.alien() in self._forbidden_alien:
return False
return 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 set_forbidden_statuses(self, statuses):
"""Set all forbidden status values :param statuses: a list with forbidden status values :type statuses: list :returns: None :rtype: None :raises: None """ |
if self._forbidden_status == statuses:
return
self._forbidden_status = statuses
self.invalidateFilter() |
<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_forbidden_types(self, types):
"""Set all forbidden type values :param typees: a list with forbidden type values :type typees: list :returns: None :rtype: None :raises: None """ |
if self._forbidden_types == types:
return
self._forbidden_types = types
self.invalidateFilter() |
<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_forbidden_uptodate(self, uptodate):
"""Set all forbidden uptodate values :param uptodatees: a list with forbidden uptodate values :uptodate uptodatees: list :returns: None :ruptodate: None :raises: None """ |
if self._forbidden_uptodate == uptodate:
return
self._forbidden_uptodate = uptodate
self.invalidateFilter() |
<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_forbidden_alien(self, alien):
"""Set all forbidden alien values :param alienes: a list with forbidden alien values :alien alienes: list :returns: None :ralien: None :raises: None """ |
if self._forbidden_alien == alien:
return
self._forbidden_alien = alien
self.invalidateFilter() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getError(self, device=DEFAULT_DEVICE_ID, message=True):
""" Get the error message or value stored in the Qik 2s9v1 hardware. :Keywords: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. Defaults to the hardware's default value. message : `bool` If set to `True` a text message will be returned, if set to `False` the integer stored in the Qik will be returned. :Returns: A list of text messages, integers, or and empty list. See the `message` parameter above. """ |
return self._getError(device, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def getPWMFrequency(self, device=DEFAULT_DEVICE_ID, message=True):
""" Get the motor shutdown on error status stored on the hardware device. :Keywords: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. Defaults to the hardware's default value. message : `bool` If set to `True` a text message will be returned, if set to `False` the integer stored in the Qik will be returned. :Returns: A text message or an int. See the `message` parameter above. """ |
return self._getPWMFrequency(device, message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setM0Coast(self, device=DEFAULT_DEVICE_ID):
""" Set motor 0 to coast. :Keywords: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. Defaults to the hardware's default value. :Exceptions: * `SerialTimeoutException` If the low level serial package times out. * `SerialException` IO error when the port is not open. """ |
cmd = self._COMMAND.get('m0-coast')
self._writeData(cmd, device) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def setM1Coast(self, device=DEFAULT_DEVICE_ID):
""" Set motor 1 to coast. :Keywords: device : `int` The device is the integer number of the hardware devices ID and is only used with the Pololu Protocol. Defaults to the hardware's default value. :Exceptions: * `SerialTimeoutException` If the low level serial package times out. * `SerialException` IO error when the port is not open. """ |
cmd = self._COMMAND.get('m1-coast')
self._writeData(cmd, device) |
<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_action_model(actioncollection):
"""Create and return a new model for the given actioncollection :param actioncollection: the action collection that should get a model :type actioncollection: :class:`jukeboxcore.action.ActionCollection` :returns: the created model :rtype: :class:`TreeModel` :raises: None """ |
rootdata = ListItemData(["Name", "Description", "Status", "Message", "Traceback"])
root = TreeItem(rootdata)
for au in actioncollection.actions:
adata = ActionItemData(au)
TreeItem(adata, parent=root)
return TreeModel(root) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def auto_subscribe(self, app_manager):
"""Called to subscribe the handlers on init.""" |
for handler in app_manager.handler_classes:
app_manager.subscribe(handler.channel(), self) |
<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_payment(self, *, amount, currency, order=None, customer_id=None, billing_address=None, shipping_address=None, additional_details=None, statement_soft_descriptor=None):
""" Creates a payment object, which provides a single reference to all the transactions that make up a payment. This is the first step for all financial transactions. Args: amount: Amount must be greater than 0. The amount is formatted in Minor Units format. currency: The three character currency code in ISO-4217 format. order: Details of the order. customer_id: Identifier of the customer associated with this payment. billing_address: Billing address details. This will only be sent to providers who support billing addresses, in requests that support them. Note: The billing address details will be sent "as is", without any corrections or substitutions from the billing address in the token resource. shipping_address: Shipping address details. This will only be sent to providers who support shipping addresses, in requests that support them. Note: The shipping address details will be sent "as is", without any corrections or substitutions from the shipping address in the customer resource. additional_details: Optional additional data stored in key/value pairs. statement_soft_descriptor: The transaction description that will appear in the customer's credit card statement, which identifies the merchant and payment. Check the relevant provider sites to see if this field is supported. If so, see the required content and format. Note: This transaction description is generated by you. Providing a clear description helps your customers recognize their transactions, and reduces chargebacks. Returns: """ |
headers = self.client._get_private_headers()
payload = {
"amount": amount,
"currency": currency,
"order": order,
"customer_id": customer_id,
"billing_address": billing_address,
"shipping_address": shipping_address,
"additional_details": additional_details,
"statement_soft_descriptor": statement_soft_descriptor,
}
endpoint = '/payments'
return self.client._post(self.client.URL_BASE + endpoint, json=payload, headers=headers) |
<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_module_parser(mod, modname, parents=[], add_help=True):
""" Returns an argument parser for the sub-command's CLI. :param mod: the sub-command's python module :param modnam: the string name of the python module :return: ArgumentParser """ |
return argparse.ArgumentParser(
usage=configuration.EXECUTABLE_NAME + ' ' + modname + ' [options]',
description=mod.get_description(), parents=parents,
add_help=add_help) |
<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_application_parser(commands):
""" Builds an argument parser for the application's CLI. :param commands: :return: ArgumentParser """ |
parser = argparse.ArgumentParser(
description=configuration.APPLICATION_DESCRIPTION,
usage =configuration.EXECUTABLE_NAME + ' [sub-command] [options]',
add_help=False)
parser.add_argument(
'sub_command',
choices=[name for name in commands],
nargs="?")
parser.add_argument("-h", "--help", action="store_true")
return parser |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def registration_update_or_create(self):
"""Creates or Updates the registration model with attributes from this instance. Called from the signal """ |
if not getattr(self, self.registration_unique_field):
raise UpdatesOrCreatesRegistrationModelError(
f'Cannot update or create RegisteredSubject. '
f'Field value for \'{self.registration_unique_field}\' is None.')
registration_value = getattr(self, self.registration_unique_field)
registration_value = self.to_string(registration_value)
try:
obj = self.registration_model.objects.get(
**{self.registered_subject_unique_field: registration_value})
except self.registration_model.DoesNotExist:
pass
else:
self.registration_raise_on_illegal_value_change(obj)
registered_subject, created = self.registration_model.objects.update_or_create(
**{self.registered_subject_unique_field: registration_value},
defaults=self.registration_options)
return registered_subject, 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 registration_options(self):
"""Gathers values for common attributes between the registration model and this instance. """ |
registration_options = {}
rs = self.registration_model()
for k, v in self.__dict__.items():
if k not in DEFAULT_BASE_FIELDS + ['_state']:
try:
getattr(rs, k)
registration_options.update({k: v})
except AttributeError:
pass
registration_identifier = registration_options.get(
'registration_identifier')
if registration_identifier:
registration_options['registration_identifier'] = self.to_string(
registration_identifier)
return registration_options |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getProcessedImage(self):
"""Returns the image data after it has been processed by any normalization options in use. This method also sets the attributes self.levelMin and self.levelMax to indicate the range of data in the image.""" |
if self.imageDisp is None:
self.imageDisp = self.image
self.levelMin, self.levelMax = self._quickLevels(
self.imageDisp)
#list( map(float, self._quickLevels(self.imageDisp)))
return self.imageDisp |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Closes the widget nicely, making sure to clear the graphics scene and release memory.""" |
self.ui.graphicsView.close()
self.scene.clear()
del self.image
del self.imageDisp
super(ImageShowBasicWidget, self).close()
self.setParent(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 create_prj(self, ):
"""Create a project and store it in the self.project :returns: None :rtype: None :raises: None """ |
name = self.name_le.text()
short = self.short_le.text()
path = self.path_le.text()
semester = self.semester_le.text()
try:
prj = djadapter.models.Project(name=name, short=short, path=path, semester=semester)
prj.save()
self.project = prj
self.accept()
except:
log.exception("Could not create new project") |
<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_project(self, ):
"""Add a project and store it in the self.projects :returns: None :rtype: None :raises: None """ |
i = self.prj_tablev.currentIndex()
item = i.internalPointer()
if item:
project = item.internal_data()
if self._atype:
self._atype.projects.add(project)
elif self._dep:
self._dep.projects.add(project)
else:
project.users.add(self._user)
self.projects.append(project)
item.set_parent(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 create_seq(self, ):
"""Create a sequence and store it in the self.sequence :returns: None :rtype: None :raises: None """ |
name = self.name_le.text()
desc = self.desc_pte.toPlainText()
try:
seq = djadapter.models.Sequence(name=name, project=self._project, description=desc)
seq.save()
self.sequence = seq
self.accept()
except:
log.exception("Could not create new sequence") |
<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_atype(self, ):
"""Create a atype and store it in the self.atype :returns: None :rtype: None :raises: None """ |
name = self.name_le.text()
desc = self.desc_pte.toPlainText()
try:
atype = djadapter.models.Atype(name=name, description=desc)
atype.save()
for prj in self.projects:
atype.projects.add(prj)
self.atype = atype
self.accept()
except:
log.exception("Could not create new assettype") |
<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_atype(self, ):
"""Add a atype and store it in the self.atypes :returns: None :rtype: None :raises: None """ |
i = self.atype_tablev.currentIndex()
item = i.internalPointer()
if item:
atype = item.internal_data()
atype.projects.add(self._project)
self.atypes.append(atype)
item.set_parent(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 create_dep(self, ):
"""Create a dep and store it in the self.dep :returns: None :rtype: None :raises: None """ |
name = self.name_le.text()
short = self.short_le.text()
assetflag = self.asset_rb.isChecked()
ordervalue = self.ordervalue_sb.value()
desc = self.desc_pte.toPlainText()
try:
dep = djadapter.models.Department(name=name, short=short, assetflag=assetflag, ordervalue=ordervalue, description=desc)
dep.save()
for prj in self.projects:
dep.projects.add(prj)
self.dep = dep
self.accept()
except:
log.exception("Could not create new department.") |
<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_dep(self, ):
"""Add a dep and store it in the self.deps :returns: None :rtype: None :raises: None """ |
i = self.dep_tablev.currentIndex()
item = i.internalPointer()
if item:
dep = item.internal_data()
dep.projects.add(self._project)
self.deps.append(dep)
item.set_parent(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 create_user(self, ):
"""Create a user and store it in the self.user :returns: None :rtype: None :raises: None """ |
name = self.username_le.text()
if not name:
self.username_le.setPlaceholderText("Please provide a username.")
return
first = self.first_le.text()
last = self.last_le.text()
email = self.email_le.text()
try:
user = djadapter.models.User(username=name, first_name=first, last_name=last, email=email)
user.save()
for prj in self.projects:
prj.users.add(user)
for task in self.tasks:
task.users.add(user)
self.user = user
self.accept()
except:
log.exception("Could not create new assettype") |
<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_user(self, ):
"""Add a user and store it in the self.users :returns: None :rtype: None :raises: None """ |
i = self.user_tablev.currentIndex()
item = i.internalPointer()
if item:
user = item.internal_data()
if self._project:
self._project.users.add(user)
else:
self._task.users.add(user)
self.users.append(user)
item.set_parent(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 create_shot(self, ):
"""Create a shot and store it in the self.shot :returns: None :rtype: None :raises: None """ |
name = self.name_le.text()
if not name:
self.name_le.setPlaceholderText("Please enter a name!")
return
desc = self.desc_pte.toPlainText()
try:
shot = djadapter.models.Shot(sequence=self.sequence, project=self.sequence.project, name=name, description=desc)
shot.save()
self.shot = shot
self.accept()
except:
log.exception("Could not create new shot") |
<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_asset(self, ):
"""Create a asset and store it in the self.asset :returns: None :rtype: None :raises: None """ |
name = self.name_le.text()
if not name:
self.name_le.setPlaceholderText("Please enter a name!")
return
desc = self.desc_pte.toPlainText()
if not self.atype:
atypei = self.atype_cb.currentIndex()
assert atypei >= 0
self.atype = self.atypes[atypei]
try:
asset = djadapter.models.Asset(atype=self.atype, project=self.project, name=name, description=desc)
asset.save()
self.asset = asset
self.accept()
except:
log.exception("Could not create new asset") |
<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_asset(self, ):
"""Add a asset and store it in the self.assets :returns: None :rtype: None :raises: None """ |
i = self.asset_treev.currentIndex()
item = i.internalPointer()
if item:
asset = item.internal_data()
if not isinstance(asset, djadapter.models.Asset):
return
if self._shot:
self._shot.assets.add(asset)
else:
self._asset.assets.add(asset)
self.assets.append(asset)
item.set_parent(None) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.