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 ensureExists(cls, values, defaults=None, **context):
""" Defines a new record for the given class based on the inputted set of keywords. If a record already ... |
# require at least some arguments to be set
if not values:
return cls()
# lookup the record from the database
q = orb.Query()
for key, value in values.items():
column = cls.schema().column(key)
if not column:
raise orb.errors... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def processEvent(cls, event):
""" Processes the given event by dispatching it to any waiting callbacks. :param event: <orb.Event> """ |
callbacks = cls.callbacks(type(event))
keep_going = True
remove_callbacks = []
for callback, record, once in callbacks:
if record is not None and record != event.record:
continue
callback(event)
if once:
remove_callba... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch(cls, key, **context):
""" Looks up a record based on the given key. This will use the default id field, as well as any keyable properties if the given ... |
# include any keyable columns for lookup
if isinstance(key, basestring) and not key.isdigit():
keyable_columns = cls.schema().columns(flags=orb.Column.Flags.Keyable)
if keyable_columns:
base_q = orb.Query()
for col in keyable_columns:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inflate(cls, values, **context):
""" Returns a new record instance for the given class with the values defined from the database. :param cls | <subclass of o... |
context = orb.Context(**context)
# inflate values from the database into the given class type
if isinstance(values, Model):
record = values
values = dict(values)
else:
record = None
schema = cls.schema()
polymorphs = schema.columns(f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def removeCallback(cls, eventType, func, record=None):
""" Removes a callback from the model's event callbacks. :param eventType: <str> :param func: <callable> "... |
callbacks = cls.callbacks()
callbacks.setdefault(eventType, [])
for i in xrange(len(callbacks[eventType])):
my_func, my_record, _ = callbacks[eventType][i]
if func == my_func and record == my_record:
del callbacks[eventType][i]
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 select(cls, **context):
""" Selects records for the class based on the inputted \ options. If no db is specified, then the current \ global database will be ... |
rset_type = getattr(cls, 'Collection', orb.Collection)
return rset_type(model=cls, **context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def jinja_template(template_name, name='data', mimetype="text/html"):
""" Meta-renderer for rendering jinja templates """ |
def jinja_renderer(result, errors):
template = get_jinja_template(template_name)
context = {name: result or Mock(), 'errors': errors, 'enumerate': enumerate}
rendered = template.render(**context)
return {'body': rendered, 'mimetype': mimetype}
return jinja_renderer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partial_jinja_template(template_name, name='data', mimetype="text/html"):
""" Partial render of jinja templates. This is useful if you want to re-render the ... |
def partial_jinja_renderer(result, errors):
template = get_jinja_template(template_name)
old = template.environment.undefined
template.environment.undefined = DebugUndefined
context = {name: result or Mock(), 'errors': errors}
rendered = template.render(**context)
te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lazy_jinja_template(template_name, name='data', mimetype='text/html'):
""" Jinja template renderer that does not render the template at all. Instead of retur... |
def lazy_jinja_renderer(result, errors):
template = get_jinja_template(template_name)
context = {name: result or Mock(), 'errors': errors}
data = ('jinja2', template, context)
return {'body': data, 'mimetype': mimetype}
return lazy_jinja_renderer |
<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_renderers(self, attrs):
""" Go through the passed in list of attributes and register those renderers in the render map. """ |
for method in attrs:
func = getattr(self, method)
mimetypes = getattr(func, 'mimetypes', [])
for mimetype in mimetypes:
if not '/' in mimetype:
self.reject_map[mimetype] = func
if mimetype not in self.render_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 render(self, result, mimetype, errors=None):
""" Render a model result into `mimetype` format. """ |
available_mimetypes = [x for x in self.render_map.keys() if '/' in x]
render_func = None
if '/' not in mimetype:
# naked superformat (does not correspond to a mimetype)
render_func = self.reject_map.get(mimetype, None)
if not render_func:
rai... |
<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_html(self, result, errors):
""" Try to display any object in sensible HTML. """ |
h1 = htmlize(type(result))
out = []
result = pre_process_json(result)
if not hasattr(result, 'items'):
# result is a non-container
header = "<tr><th>Value</th></tr>"
if type(result) is list:
result = htmlize_list(result)
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 install_twisted():
""" If twisted is available, make `emit' return a DeferredList This has been successfully tested with Twisted 14.0 and later. """ |
global emit, _call_partial
try:
from twisted.internet import defer
emit = _emit_twisted
_call_partial = defer.maybeDeferred
return True
except ImportError:
_call_partial = lambda fn, *a, **kw: fn(*a, **kw)
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 _call(callback, args=[], kwargs={}):
""" Calls a callback with optional args and keyword args lists. This method exists so we can inspect the `_max_calls` at... |
if not hasattr(callback, '_max_calls'):
callback._max_calls = None
# None implies no callback limit
if callback._max_calls is None:
return _call_partial(callback, *args, **kwargs)
# Should the signal be disconnected?
if callback._max_calls <= 0:
return disconnect(callback)... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _on(on_signals, callback, max_calls=None):
""" Proxy for `smokesignal.on`, which is compatible as both a function call and a decorator. This method cannot be... |
if not callable(callback):
raise AssertionError('Signal callbacks must be callable')
# Support for lists of signals
if not isinstance(on_signals, (list, tuple)):
on_signals = [on_signals]
callback._max_calls = max_calls
# Register the callback
for signal in on_signals:
... |
<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_from(callback, signals):
""" Removes a callback from specified signal registries and prevents it from responding to any emitted signal. :param cal... |
# Support for lists of signals
if not isinstance(signals, (list, tuple)):
signals = [signals]
# Remove callback from receiver list if it responds to the signal
for signal in signals:
if responds_to(callback, signal):
receivers[signal].remove(callback) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clear(*signals):
""" Clears all callbacks for a particular signal or signals """ |
signals = signals if signals else receivers.keys()
for signal in signals:
receivers[signal].clear() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, record, values):
""" Validates whether or not this index's requirements are satisfied by the inputted record and values. If this index fails v... |
schema = record.schema()
columns = self.columns()
try:
column_values = [values[col] for col in columns]
except KeyError as err:
msg = 'Missing {0} from {1}.{2} index'.format(err[0].name(),
record.schema().... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def StaticServe(base_path='/views/static/'):
""" Meta program for serving any file based on the path """ |
def get_file(path=RAW_INVOCATION_ARGS):
fullpath = get_config('project_path') + os.path.join(base_path, path)
try:
mime, encoding = mimetypes.guess_type(fullpath)
return open(fullpath, 'rb'), mime or 'application/octet-stream'
except IOError:
raise DataNo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def SingleStaticServe(file_path):
""" Meta program for serving a single file. Useful for favicon.ico and robots.txt """ |
def get_file():
mime, encoding = mimetypes.guess_type(file_path)
fullpath = os.path.join(get_config('project_path'), file_path)
return open(fullpath, 'rb'), mime or 'application/octet-stream'
class SingleStaticServe(Program):
controllers = ['http-get']
model = [get_file... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def onSync(self, event):
""" Initializes the database by defining any additional structures that are required during selection. """ |
SETUP = self.statement('SETUP')
if SETUP:
sql, data = SETUP(self.database())
if event.context.dryRun:
print sql % data
else:
self.execute(sql, data, writeAccess=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 close(self):
""" Closes the connection to the database for this connection. :return <bool> closed """ |
for pool in self.__pool.values():
while not pool.empty():
conn = pool.get_nowait()
try:
self._close(conn)
except Exception:
pass
# reset the pool size after closing all connections
self.__poolSi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(self, model, context):
""" Returns the count of records that will be loaded for the inputted information. :param model | <subclass of orb.Model> contex... |
SELECT_COUNT = self.statement('SELECT COUNT')
try:
sql, data = SELECT_COUNT(model, context)
except orb.errors.QueryIsNull:
return 0
else:
if context.dryRun:
print sql % data
return 0
else:
t... |
<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):
""" Commits the changes to the current database connection. :return <bool> success """ |
with self.native(writeAccess=True) as conn:
if not self._closed(conn):
return self._commit(conn) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def createModel(self, model, context, owner='', includeReferences=True):
""" Creates a new table in the database based cff the inputted schema information. If th... |
CREATE = self.statement('CREATE')
sql, data = CREATE(model, includeReferences=includeReferences, owner=owner)
if not sql:
log.error('Failed to create {0}'.format(model.schema().dbname()))
return False
else:
if context.dryRun:
print sql... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, records, context):
""" Removes the inputted record from the database. :param records | <orb.Collection> context | <orb.Context> :return <int> nu... |
# include various schema records to remove
DELETE = self.statement('DELETE')
sql, data = DELETE(records, context)
if context.dryRun:
print sql % data
return 0
else:
return self.execute(sql, data, writeAccess=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 insert(self, records, context):
""" Inserts the table instance into the database. If the dryRun flag is specified, then the command will be logged but not ex... |
INSERT = self.statement('INSERT')
sql, data = INSERT(records)
if context.dryRun:
print sql, data
return [], 0
else:
return self.execute(sql, data, writeAccess=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 isConnected(self):
""" Returns whether or not this connection is currently active. :return <bool> connected """ |
for pool in self.__pool.values():
if not pool.empty():
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 native(self, writeAccess=False, isolation_level=None):
""" Opens a new database connection to the database defined by the inputted database. :return <varaint... |
host = self.database().writeHost() if writeAccess else self.database().host()
conn = self.open(writeAccess=writeAccess)
try:
if isolation_level is not None:
if conn.isolation_level == isolation_level:
isolation_level = None
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self, writeAccess=False):
""" Returns the sqlite database for the current thread. :return <variant> || None """ |
host = self.database().writeHost() if writeAccess else self.database().host()
pool = self.__pool[host]
if self.__poolSize[host] >= self.__maxSize or pool.qsize():
if pool.qsize() == 0:
log.warning('Waiting for connection to database!!!')
return pool.get(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rollback(self):
""" Rolls back changes to this database. """ |
with self.native(writeAccess=True) as conn:
return self._rollback(conn) |
<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(self, records, context):
""" Updates the modified data in the database for the inputted record. If the dryRun flag is specified then the command will ... |
UPDATE = self.statement('UPDATE')
sql, data = UPDATE(records)
if context.dryRun:
print sql, data
return [], 0
else:
return self.execute(sql, data, writeAccess=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 type(self):
""" Type of a valid object. Type may be a JSON type name or a list of such names. Valid JSON type names are ``string``, ``number``, ``integer``, ... |
value = self._schema.get("type", "any")
if not isinstance(value, (basestring, dict, list)):
raise SchemaError(
"type value {0!r} is not a simple type name, nested "
"schema nor a list of those".format(value))
if isinstance(value, list):
ty... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def properties(self):
"""Schema for particular properties of the object.""" |
value = self._schema.get("properties", {})
if not isinstance(value, dict):
raise SchemaError(
"properties value {0!r} is not an object".format(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 items(self):
""" Schema or a list of schemas describing particular elements of the object. A single schema applies to all the elements. Each element of the o... |
value = self._schema.get("items", {})
if not isinstance(value, (list, dict)):
raise SchemaError(
"items value {0!r} is neither a list nor an object".
format(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 optional(self):
"""Flag indicating an optional property.""" |
value = self._schema.get("optional", False)
if value is not False and value is not True:
raise SchemaError(
"optional value {0!r} is not a boolean".format(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 additionalProperties(self):
"""Schema for all additional properties, or False.""" |
value = self._schema.get("additionalProperties", {})
if not isinstance(value, dict) and value is not False:
raise SchemaError(
"additionalProperties value {0!r} is neither false nor"
" an object".format(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 requires(self):
"""Additional object or objects required by this object.""" |
# NOTE: spec says this can also be a list of strings
value = self._schema.get("requires", {})
if not isinstance(value, (basestring, dict)):
raise SchemaError(
"requires value {0!r} is neither a string nor an"
" object".format(value))
return va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximum(self):
"""Maximum value of the object.""" |
value = self._schema.get("maximum", None)
if value is None:
return
if not isinstance(value, NUMERIC_TYPES):
raise SchemaError(
"maximum value {0!r} is not a numeric type".format(
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 minimumCanEqual(self):
"""Flag indicating if maximum value is inclusive or exclusive.""" |
if self.minimum is None:
raise SchemaError("minimumCanEqual requires presence of minimum")
value = self._schema.get("minimumCanEqual", True)
if value is not True and value is not False:
raise SchemaError(
"minimumCanEqual value {0!r} is not a boolean".for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maximumCanEqual(self):
"""Flag indicating if the minimum value is inclusive or exclusive.""" |
if self.maximum is None:
raise SchemaError("maximumCanEqual requires presence of maximum")
value = self._schema.get("maximumCanEqual", True)
if value is not True and value is not False:
raise SchemaError(
"maximumCanEqual value {0!r} is not a boolean".for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pattern(self):
""" Regular expression describing valid objects. .. note:: JSON schema specifications says that this value SHOULD follow the ``EMCA 262/Perl 5... |
value = self._schema.get("pattern", None)
if value is None:
return
try:
return re.compile(value)
except re.error as ex:
raise SchemaError(
"pattern value {0!r} is not a valid regular expression:"
" {1}".format(value, st... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def maxLength(self):
"""Maximum length of object.""" |
value = self._schema.get("maxLength", None)
if value is None:
return
if not isinstance(value, int):
raise SchemaError(
"maxLength value {0!r} is not an integer".format(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 enum(self):
""" Enumeration of allowed object values. The enumeration must not contain duplicates. """ |
value = self._schema.get("enum", None)
if value is None:
return
if not isinstance(value, list):
raise SchemaError(
"enum value {0!r} is not a list".format(value))
if len(value) == 0:
raise SchemaError(
"enum value {0!r}... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def title(self):
""" Title of the object. This schema element is purely informative. """ |
value = self._schema.get("title", None)
if value is None:
return
if not isinstance(value, basestring):
raise SchemaError(
"title value {0!r} is not a string".format(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 divisibleBy(self):
"""Integer that divides the object without reminder.""" |
value = self._schema.get("divisibleBy", 1)
if value is None:
return
if not isinstance(value, NUMERIC_TYPES):
raise SchemaError(
"divisibleBy value {0!r} is not a numeric type".
format(value))
if value < 0:
raise SchemaE... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def disallow(self):
""" Description of disallowed objects. Disallow must be a type name, a nested schema or a list of those. Type name must be one of ``string``,... |
value = self._schema.get("disallow", None)
if value is None:
return
if not isinstance(value, (basestring, dict, list)):
raise SchemaError(
"disallow value {0!r} is not a simple type name, nested "
"schema nor a list of those".format(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 validate(schema_text, data_text, deserializer=_default_deserializer):
""" Validate specified JSON text with specified schema. Both arguments are converted to... |
schema = Schema(deserializer(schema_text))
data = deserializer(data_text)
return Validator.validate(schema, 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 activate_user(activation_key):
""" Validate an activation key and activate the corresponding ``User`` if valid. If the key is valid and has not expired, retu... |
# Make sure the key we're trying conforms to the pattern of a
# SHA1 hash; if it doesn't, no point trying to look it up in
# the database.
if SHA1_RE.search(activation_key):
try:
profile = RegistrationProfile.objects.get(
activation_key=activation_key)
except... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_RTS(self, opcode):
""" Program control is returned from the subroutine to the calling program. The return address is pulled from the stack. sourc... |
ea = self.pull_word(self.system_stack_pointer)
# log.info("%x|\tRTS to $%x \t| %s" % (
# self.last_op_address,
# ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
self.program_counter.set(ea) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_BSR_JSR(self, opcode, ea):
""" Program control is transferred to the effective address after storing the return address on the hardware stack. A ... |
# log.info("%x|\tJSR/BSR to $%x \t| %s" % (
# self.last_op_address,
# ea, self.cfg.mem_info.get_shortest(ea)
# ))
self.push_word(self.system_stack_pointer, self.program_counter.value)
self.program_counter.set(ea) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_BHI(self, opcode, ea):
""" Causes a branch if the previous operation caused neither a carry nor a zero result. When used after a subtract or comp... |
if self.C == 0 and self.Z == 0:
# log.info("$%x BHI branch to $%x, because C==0 and Z==0 \t| %s" % (
# self.program_counter, ea, self.cfg.mem_info.get_shortest(ea)
# ))
self.program_counter.set(ea) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_BLS(self, opcode, ea):
""" Causes a branch if the previous operation caused either a carry or a zero result. When used after a subtract or compar... |
# if (self.C|self.Z) == 0:
if self.C == 1 or self.Z == 1:
# log.info("$%x BLS branch to $%x, because C|Z==1 \t| %s" % (
# self.program_counter, ea, self.cfg.mem_info.get_shortest(ea)
# ))
self.program_counter.set(ea) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_LD8(self, opcode, m, register):
""" Loads the contents of memory location M into the designated register. source code forms: LDA P; LDB P CC bits... |
# log.debug("$%x LD8 %s = $%x" % (
# self.program_counter,
# register.name, m,
# ))
register.set(m)
self.clear_NZV()
self.update_NZ_8(m) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ST16(self, opcode, ea, register):
""" Writes the contents of a 16-bit register into two consecutive memory locations. source code forms: STD P; S... |
value = register.value
# log.debug("$%x ST16 store value $%x from %s at $%x \t| %s" % (
# self.program_counter,
# value, register.name, ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
self.clear_NZV()
self.update_NZ_16(value)
return ea, v... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ST8(self, opcode, ea, register):
""" Writes the contents of an 8-bit register into a memory location. source code forms: STA P; STB P CC bits "HN... |
value = register.value
# log.debug("$%x ST8 store value $%x from %s at $%x \t| %s" % (
# self.program_counter,
# value, register.name, ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
self.clear_NZV()
self.update_NZ_8(value)
return ea, val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_native(self, obj):
"""Remove password field when serializing an object""" |
ret = super(UserSerializer, self).to_native(obj)
del ret['password']
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def serve_websocket(request, port):
"""Start UWSGI websocket loop and proxy.""" |
env = request.environ
# Send HTTP response 101 Switch Protocol downstream
uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))
# Map the websocket URL to the upstream localhost:4000x Notebook instance
parts = urlparse(request.url)
parts = parts._replace(scheme=... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handshake_headers(self):
""" List of headers appropriate for the upgrade handshake. """ |
headers = [
('Host', self.host),
('Connection', 'Upgrade'),
('Upgrade', 'WebSocket'),
('Sec-WebSocket-Key', self.key.decode('utf-8')),
# Origin is proxyed from the downstream server, don't set it twice
# ('Origin', self.url),
(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def received_message(self, m):
"""Push upstream messages to downstream.""" |
# TODO: No support for binary messages
m = str(m)
logger.debug("Incoming upstream WS: %s", m)
uwsgi.websocket_send(m)
logger.debug("Send ok") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Combine async uwsgi message loop with ws4py message loop. TODO: This could do some serious optimizations and behave asynchronously correct inst... |
self.sock.setblocking(False)
try:
while not self.terminated:
logger.debug("Doing nothing")
time.sleep(0.050)
logger.debug("Asking for downstream msg")
msg = uwsgi.websocket_recv_nb()
if msg:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_content(self, url):
"""Returns the content of a cached resource. Args: url: The url of the resource Returns: The content of the cached resource or None i... |
cache_path = self._url_to_path(url)
try:
with open(cache_path, 'rb') as f:
return f.read()
except IOError:
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_path(self, url):
"""Returns the path of a cached resource. Args: url: The url of the resource Returns: The path to the cached resource or None if not in ... |
cache_path = self._url_to_path(url)
if os.path.exists(cache_path):
return cache_path
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 put_content(self, url, content):
"""Stores the content of a resource into the disk cache. Args: url: The url of the resource content: The content of the reso... |
cache_path = self._url_to_path(url)
# Ensure that cache directories exist
try:
dir = os.path.dirname(cache_path)
os.makedirs(dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise Error('Failed to create cache directories for ' %... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def put_path(self, url, path):
"""Puts a resource already on disk into the disk cache. Args: url: The original url of the resource path: The resource already ava... |
cache_path = self._url_to_path(url)
# Ensure that cache directories exist
try:
dir = os.path.dirname(cache_path)
os.makedirs(dir)
except OSError as e:
if e.errno != errno.EEXIST:
raise Error('Failed to create cache directories for ' %... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def size(self):
"""Returns the size of the cache in bytes.""" |
total_size = 0
for dir_path, dir_names, filenames in os.walk(self.dir):
for f in filenames:
fp = os.path.join(dir_path, f)
total_size += os.path.getsize(fp)
return total_size |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def opcode(*opcodes):
"""A decorator for opcodes""" |
def decorator(func):
setattr(func, "_is_opcode", True)
setattr(func, "_opcodes", opcodes)
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_named_notebook(fname, context):
"""Create a named notebook if one doesn't exist.""" |
if os.path.exists(fname):
return
from nbformat import v4 as nbf
# Courtesy of http://nbviewer.ipython.org/gist/fperez/9716279
text = "Welcome to *pyramid_notebook!* Use *File* *>* *Shutdown* to close this."
cells = [nbf.new_markdown_cell(text)]
greeting = context.get("greeting")
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def crc32(self, data):
""" Calculate a ZIP 32-bit CRC from data in memory. Origin code by Johann E. Klasek, j AT klasek at """ |
data_address = 0x1000 # position of the test data
self.cpu.memory.load(data_address, data) # write test data into RAM
self.cpu.index_x.set(data_address + len(data)) # end address
addr_hi, addr_lo = divmod(data_address, 0x100) # start address
self.cpu_test_run(start=0x0100, end... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push_irq_registers(self):
""" push PC, U, Y, X, DP, B, A, CC on System stack pointer """ |
self.cycles += 1
self.push_word(self.system_stack_pointer, self.program_counter.value) # PC
self.push_word(self.system_stack_pointer, self.user_stack_pointer.value) # U
self.push_word(self.system_stack_pointer, self.index_y.value) # Y
self.push_word(self.system_stack_pointer, se... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push_firq_registers(self):
""" FIRQ - Fast Interrupt Request push PC and CC on System stack pointer """ |
self.cycles += 1
self.push_word(self.system_stack_pointer, self.program_counter.value) # PC
self.push_byte(self.system_stack_pointer, self.get_cc_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 text2sentences(text, labels):
'''
Splits given text at predicted positions from `labels`
'''
sentence = ''
for i, label in enumerate(labels):
if label == '1':
if sentence:
yield sentence
sentence = ''
else:
sentence += text[i]
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reconstruct_url(environ, port):
"""Reconstruct the remote url from the given WSGI ``environ`` dictionary. :param environ: the WSGI environment :type environ:... |
# From WSGI spec, PEP 333
url = environ.get('PATH_INFO', '')
if not url.startswith(('http://', 'https://')):
url = '%s://%s%s' % (
environ['wsgi.url_scheme'],
environ['HTTP_HOST'],
url
)
# Fix ;arg=value in url
if '%3B' in url:
url, arg = ... |
<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_summaries(client, filter=None):
""" Generate presentation summaries in a reverse chronological order. A filter class can be supplied to filter summaries ... |
try:
index = 0
while True:
rb = _RightBarPage(client, index)
summaries = rb.summaries()
if filter is not None:
summaries = filter.filter(summaries)
for summary in summaries:
yield summary
index += len... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summaries(self):
"""Return a list of all the presentation summaries contained in this page""" |
def create_summary(div):
def get_id(div):
return get_url(div).rsplit('/')[-1]
def get_url(div):
return client.get_url(div.find('h2', class_='itemtitle').a['href'])
def get_desc(div):
return div.p.get_text(strip=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 make_startup(notebook_context, config_file, bootstrap_py=PYRAMID_BOOSTRAP, bootstrap_greeting=PYRAMID_GREETING, cwd=""):
"""Populate notebook context with st... |
# Set up some default imports and variables
nc = notebook_context
add_greeting(nc, "\nAvailable variables and functions:")
# http://docs.pylonsproject.org/projects/pyramid/en/1.1-branch/narr/commandline.html#writing-a-script
if config_file is not None:
assert type(config_file) == str, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def include_sqlalchemy_models(nc, Base):
"""Include all SQLAlchemy models in the script context. :param nc: notebook_context dictionary :param Base: SQLAlchemy m... |
from sqlalchemy.ext.declarative.clsregistry import _ModuleMarker
# Include all SQLAlchemy models in the local namespace
for name, klass in Base._decl_class_registry.items():
print(name, klass)
if isinstance(klass, _ModuleMarker):
continue
add_script(nc, get_import_sta... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_OR(self, opcode, m, register):
""" Performs an inclusive OR operation between the contents of accumulator A or B and the contents of memory locat... |
a = register.value
r = a | m
register.set(r)
self.clear_NZV()
self.update_NZ_8(r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ANDCC(self, opcode, m, register):
""" Performs a logical AND between the condition code register and the immediate byte specified in the instruct... |
assert register == self.cc_register
old_cc = self.get_cc_value()
new_cc = old_cc & m
self.set_cc(new_cc) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_LSR_memory(self, opcode, ea, m):
""" Logical shift right memory location """ |
r = self.LSR(m)
# log.debug("$%x LSR memory value $%x >> 1 = $%x and write it to $%x \t| %s" % (
# self.program_counter,
# m, r, ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
return ea, r & 0xff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_LSR_register(self, opcode, register):
""" Logical shift right accumulator """ |
a = register.value
r = self.LSR(a)
# log.debug("$%x LSR %s value $%x >> 1 = $%x" % (
# self.program_counter,
# register.name, a, r
# ))
register.set(r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ASR_memory(self, opcode, ea, m):
""" Arithmetic shift memory right """ |
r = self.ASR(m)
# log.debug("$%x ASR memory value $%x >> 1 | Carry = $%x and write it to $%x \t| %s" % (
# self.program_counter,
# m, r, ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
return ea, r & 0xff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ASR_register(self, opcode, register):
""" Arithmetic shift accumulator right """ |
a = register.value
r = self.ASR(a)
# log.debug("$%x ASR %s value $%x >> 1 | Carry = $%x" % (
# self.program_counter,
# register.name, a, r
# ))
register.set(r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ROL_memory(self, opcode, ea, m):
""" Rotate memory left """ |
r = self.ROL(m)
# log.debug("$%x ROL memory value $%x << 1 | Carry = $%x and write it to $%x \t| %s" % (
# self.program_counter,
# m, r, ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
return ea, r & 0xff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ROL_register(self, opcode, register):
""" Rotate accumulator left """ |
a = register.value
r = self.ROL(a)
# log.debug("$%x ROL %s value $%x << 1 | Carry = $%x" % (
# self.program_counter,
# register.name, a, r
# ))
register.set(r) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ROR_memory(self, opcode, ea, m):
""" Rotate memory right """ |
r = self.ROR(m)
# log.debug("$%x ROR memory value $%x >> 1 | Carry = $%x and write it to $%x \t| %s" % (
# self.program_counter,
# m, r, ea,
# self.cfg.mem_info.get_shortest(ea)
# ))
return ea, r & 0xff |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instruction_ROR_register(self, opcode, register):
""" Rotate accumulator right """ |
a = register.value
r = self.ROR(a)
# log.debug("$%x ROR %s value $%x >> 1 | Carry = $%x" % (
# self.program_counter,
# register.name, a, r
# ))
register.set(r) |
<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_ea_indexed(self):
""" Calculate the address for all indexed addressing modes """ |
addr, postbyte = self.read_pc_byte()
# log.debug("\tget_ea_indexed(): postbyte: $%02x (%s) from $%04x",
# postbyte, byte2bit_string(postbyte), addr
# )
rr = (postbyte >> 5) & 3
try:
register_str = self.INDEX_POSTBYTE2STR[rr]
except KeyError:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def discover_python(self):
"""Get the Python interpreter we need to use to run our Notebook daemon.""" |
python = sys.executable
#: XXX fix this hack, uwsgi sets itself as Python
#: Make better used Python interpreter autodiscovery
if python.endswith("/uwsgi"):
python = python.replace("/uwsgi", "/python")
return python |
<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_pid(self, name):
"""Get PID file name for a named notebook.""" |
pid_file = os.path.join(self.get_work_folder(name), "notebook.pid")
return pid_file |
<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_manager_cmd(self):
"""Get our daemon script path.""" |
cmd = os.path.abspath(os.path.join(os.path.dirname(__file__), "server", "notebook_daemon.py"))
assert os.path.exists(cmd)
return cmd |
<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_notebook_daemon_command(self, name, action, port=0, *extra):
""" Assume we launch Notebook with the same Python which executed us. """ |
return [self.python, self.cmd, action, self.get_pid(name), self.get_work_folder(name), port, self.kill_timeout] + list(extra) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exec_notebook_daemon_command(self, name, cmd, port=0):
"""Run a daemon script command.""" |
cmd = self.get_notebook_daemon_command(name, cmd, port)
# Make all arguments explicit strings
cmd = [str(arg) for arg in cmd]
logger.info("Running notebook command: %s", " ".join(cmd))
# print("XXX - DEBUG - Running notebook command:", " ".join(cmd))
# Add support for... |
<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_notebook_status(self, name):
"""Get the running named Notebook status. :return: None if no notebook is running, otherwise context dictionary """ |
context = comm.get_context(self.get_pid(name))
if not context:
return None
return context |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_notebook(self, name, context: dict, fg=False):
"""Start new IPython Notebook daemon. :param name: The owner of the Notebook will be *name*. He/she gets... |
assert context
assert type(context) == dict
assert "context_hash" in context
assert type(context["context_hash"]) == int
http_port = self.pick_port()
assert http_port
context = context.copy()
context["http_port"] = http_port
# We can't proxy web... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_notebook_on_demand(self, name, context):
"""Start notebook if not yet running with these settings. Return the updated settings with a port info. :retur... |
if self.is_running(name):
last_context = self.get_context(name)
logger.info("Notebook context change detected for %s", name)
if not self.is_same_context(context, last_context):
self.stop_notebook(name)
# Make sure we don't get race condition ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def failsafe(func):
""" Wraps an app factory to provide a fallback in case of import errors. Takes a factory function to generate a Flask app. If there is an err... |
@functools.wraps(func)
def wrapper(*args, **kwargs):
extra_files = []
try:
return func(*args, **kwargs)
except:
exc_type, exc_val, exc_tb = sys.exc_info()
traceback.print_exc()
tb = exc_tb
while tb:
filename = tb.tb_fram... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(cls, schema, obj):
""" Validate specified JSON object obj with specified schema. :param schema: Schema to validate against :type schema: :class:`jso... |
if not isinstance(schema, Schema):
raise ValueError(
"schema value {0!r} is not a Schema"
" object".format(schema))
self = cls()
self.validate_toplevel(schema, obj)
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 _report_error(self, legacy_message, new_message=None, schema_suffix=None):
""" Report an error during validation. There are two error messages. The legacy me... |
object_expr = self._get_object_expression()
schema_expr = self._get_schema_expression()
if schema_suffix:
schema_expr += schema_suffix
raise ValidationError(legacy_message, new_message, object_expr,
schema_expr) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _push_property_schema(self, prop):
"""Construct a sub-schema from a property of the current schema.""" |
schema = Schema(self._schema.properties[prop])
self._push_schema(schema, ".properties." + prop) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.