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 exists for the query, the first found record is returned, otherwise a new record is created and returned. :param values | <dict> """
# 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.ColumnNotFound(schema=cls.schema(), column=key) elif column.testFlag(column.Flags.Virtual): continue if (isinstance(column, orb.AbstractStringColumn) and not column.testFlag(column.Flags.CaseSensitive) and not column.testFlag(column.Flags.I18n) and isinstance(value, (str, unicode))): q &= orb.Query(key).lower() == value.lower() else: q &= orb.Query(key) == value record = cls.select(where=q).first() if record is None: record = cls(context=orb.Context(**context)) record.update(values) record.update(defaults or {}) record.save() return record
<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_callbacks.append((callback, record)) if event.preventDefault: keep_going = False break for callback, record in remove_callbacks: cls.removeCallback(type(event), callback, record=record) return keep_going
<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 key is a string. :param key: <variant> :param context: <orb.Context> :return: <orb.Model> || None """
# 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: base_q |= orb.Query(col) == key context.setdefault('where', base_q) else: context.setdefault('where', orb.Query(cls) == key) else: context.setdefault('where', orb.Query(cls) == key) # don't have slicing for lookup by id context['page'] = None context['pageSize'] = None context['start'] = None context['limit'] = None return cls.select(**context).first()
<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 orb.Table> values | <dict> values :return <orb.Table> """
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(flags=orb.Column.Flags.Polymorphic).values() column = polymorphs[0] if polymorphs else None # attempt to expand the class to its defined polymorphic type if column and column.field() in values: morph_cls_name = values.get(column.name(), values.get(column.field())) morph_cls = orb.system.model(morph_cls_name) id_col = schema.idColumn().name() if morph_cls and morph_cls != cls: try: record = morph_cls(values[id_col], context=context) except KeyError: raise orb.errors.RecordNotFound(schema=morph_cls.schema(), column=values.get(id_col)) if record is None: event = orb.events.LoadEvent(record=record, data=values) record = cls(loadEvent=event, context=context) return record
<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 used. If the inflated flag is specified, then \ the results will be inflated to class instances. If the flag is left as None, then results will be auto-inflated if no columns were supplied. If columns were supplied, then the results will not be inflated by default. If the groupBy flag is specified, then the groupBy columns will be added to the beginning of the ordered search (to ensure proper paging). See the Table.groupRecords methods for more details. :note From version 0.6.0 on, this method now accepts a mutable keyword dictionary of values. You can supply any member value for either the <orb.LookupOptions> or <orb.Context>, as well as the keyword 'lookup' to an instance of <orb.LookupOptions> and 'context' for an instance of the <orb.Context> :return [ <cls>, .. ] || { <variant> grp: <variant> result, .. } """
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 template in the output middleware phase. These templates are rendered in a way that all undefined variables will be kept in the emplate intact. """
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) template.environment.undefined = old return {'body': rendered, 'mimetype': mimetype} return partial_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 lazy_jinja_template(template_name, name='data', mimetype='text/html'): """ Jinja template renderer that does not render the template at all. Instead of returns the context and template object blended together. Make sure to add ``giotto.middleware.RenderLazytemplate`` to the output middleware stread of any program that uses this renderer. """
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: self.render_map[mimetype] = func else: # about to redefine an already defined renderer. # make sure this new render method is not on a base class. base_classes = self.__class__.mro()[1:] from_baseclass = any([x for x in base_classes if func.__name__ in dir(x)]) if not from_baseclass: self.render_map[mimetype] = func
<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: raise NoViewMethod("Unknown Superformat: %s" % mimetype) if not render_func and available_mimetypes: target_mimetype = mimeparse.best_match(available_mimetypes, mimetype) render_func = self.render_map.get(target_mimetype, None) if not render_func: raise NoViewMethod("%s not supported for this program" % mimetype) principle_mimetype = render_func.mimetypes[0] if GiottoControl in render_func.__class__.mro(): # redirection defined as view (not wrapped in lambda) return {'body': render_func, 'persist': render_func.persist} if callable(self.persist): # persist (cookie data) can be either an object, or a callable) persist = self.persist(result) else: persist = self.persist # render functins can take either one or two arguments, both are # supported by the API arg_names = inspect.getargspec(render_func).args num_args = len(set(arg_names) - set(['self', 'cls'])) if num_args == 2: data = render_func(result, errors or Mock()) else: # if the renderer only has one argument, don't pass in the 2nd arg. data = render_func(result) if GiottoControl in data.__class__.mro(): # render function returned a control object return {'body': data, 'persist': persist} if not hasattr(data, 'items'): # view returned string data = {'body': data, 'mimetype': principle_mimetype} else: # result is a dict in for form {body: XX, mimetype: xx} if not 'mimetype' in data and target_mimetype == '*/*': data['mimetype'] = '' if not 'mimetype' in data: data['mimetype'] = target_mimetype data['persist'] = persist 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 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) else: result = htmlize(result) out = ["<tr><td>" + result + "</td></tr>"] elif hasattr(result, 'lower'): out = ["<tr><td>" + result + "</td></tr>"] else: # object is a dict header = "<tr><th>Key</th><th>Value</th></tr>" for key, value in result.items(): v = htmlize(value) row = "<tr><td>{0}</td><td>{1}</td></tr>".format(key, v) out.append(row) env = Environment(loader=PackageLoader('giotto')) template = env.get_template('generic.html') rendered = template.render({'header': h1, 'table_header': header, 'table_body': out}) return {'body': rendered, 'mimetype': 'text/html'}
<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` attribute that's set by `_on`. If this value is None, the callback is considered to have no limit. Otherwise, an integer value is expected and decremented until there are no remaining calls """
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) callback._max_calls -= 1 return _call_partial(callback, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _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 used as a decorator :param signals: A single signal or list/tuple of signals that callback should respond to :param callback: A callable that should repond to supplied signal(s) :param max_calls: Integer maximum calls for callback. None for no limit. """
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: receivers[signal].add(callback) # Setup responds_to partial for use later if not hasattr(callback, 'responds_to'): callback.responds_to = partial(responds_to, callback) # Setup signals partial for use later. if not hasattr(callback, 'signals'): callback.signals = partial(signals, callback) # Setup disconnect partial for user later if not hasattr(callback, 'disconnect'): callback.disconnect = partial(disconnect, callback) # Setup disconnect_from partial for user later if not hasattr(callback, 'disconnect_from'): callback.disconnect_from = partial(disconnect_from, callback) return 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 disconnect_from(callback, signals): """ Removes a callback from specified signal registries and prevents it from responding to any emitted signal. :param callback: A callable registered with smokesignal :param signals: A single signal or list/tuple of signals """
# 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 validation, a ValidationError will be raised. :param record | subclass of <orb.Table> values | {<orb.Column>: <variant>, ..} :return <bool> """
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().name(), self.name()) raise errors.InvalidIndexArguments(self.schema(), msg=msg) # # ensure a unique record is preserved # if self.unique(): # lookup = getattr(record, self.name()) # other = lookup(*column_values) # if other and other != record: # msg = 'A record already exists with the same {0} combination.'.format(', '.join(self.columnNames())) # raise errors.IndexValidationError(self, msg=msg) 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 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 DataNotFound("File does not exist") class StaticServe(Program): controllers = ['http-get'] model = [get_file] view = FileView() return StaticServe()
<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] view = FileView() return SingleStaticServe()
<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.__poolSize.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 count(self, model, context): """ Returns the count of records that will be loaded for the inputted information. :param model | <subclass of orb.Model> context | <orb.Context> :return <int> """
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: try: rows, _ = self.execute(sql, data) except orb.errors.EmptyCommand: rows = [] return sum([row['count'] for row in rows])
<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 the dryRun flag is specified, then the SQLConnection will only be logged to the current logger, and not actually executed in the database. :param model | <orb.Model> context | <orb.Context> :return <bool> success """
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 % data else: self.execute(sql, data, writeAccess=True) log.info('Created {0}'.format(model.schema().dbname())) 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 delete(self, records, context): """ Removes the inputted record from the database. :param records | <orb.Collection> context | <orb.Context> :return <int> number of rows removed """
# 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 executed. :param records | <orb.Table> lookup | <orb.LookupOptions> options | <orb.Context> :return <dict> changes """
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> native connection """
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: conn.set_isolation_level(isolation_level) yield conn except Exception: if self._closed(conn): conn = None self.close() else: conn = self._rollback(conn) raise else: if not self._closed(conn): self._commit(conn) finally: if conn is not None and not self._closed(conn): if isolation_level is not None: conn.set_isolation_level(isolation_level) self.__pool[host].put(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 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() else: db = self.database() # process a pre-connect event event = orb.events.ConnectionEvent() db.onPreConnect(event) self.__poolSize[host] += 1 try: conn = self._open(self.database(), writeAccess=writeAccess) except Exception: self.__poolSize[host] -= 1 raise else: event = orb.events.ConnectionEvent(success=conn is not None, native=conn) db.onPostConnect(event) return 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 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 be logged but not executed. :param record | <orb.Table> lookup | <orb.LookupOptions> options | <orb.Context> :return <dict> changes """
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``, ``boolean``, ``object``, ``array``, ``any`` (default). """
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): type_list = value # Union types have to have at least two alternatives if len(type_list) < 2: raise SchemaError( "union type {0!r} is too short".format(value)) else: type_list = [value] seen = set() for js_type in type_list: if isinstance(js_type, dict): # no nested validation here pass elif isinstance(js_type, list): # no nested validation here pass else: if js_type in seen: raise SchemaError( ("type value {0!r} contains duplicate element" " {1!r}").format(value, js_type)) else: seen.add(js_type) if js_type not in ( "string", "number", "integer", "boolean", "object", "array", "null", "any"): raise SchemaError( "type value {0!r} is not a simple type " "name".format(js_type)) 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 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 object must match that schema. A list of schemas describes particular elements of the object. """
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 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 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".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 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".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 pattern(self): """ Regular expression describing valid objects. .. note:: JSON schema specifications says that this value SHOULD follow the ``EMCA 262/Perl 5`` format. We cannot support this so we support python regular expressions instead. This is still valid but should be noted for clarity. :returns: None or compiled regular expression """
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, str(ex)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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} does not contain any" " elements".format(value)) seen = set() for item in value: if item in seen: raise SchemaError( "enum value {0!r} contains duplicate element" " {1!r}".format(value, item)) else: seen.add(item) 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 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 SchemaError( "divisibleBy value {0!r} cannot be" " negative".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 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``, ``number``, ``integer``, ``boolean``, ``object``, ``array``, ``null`` or ``any``. """
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)) if isinstance(value, list): disallow_list = value else: disallow_list = [value] seen = set() for js_disallow in disallow_list: if isinstance(js_disallow, dict): # no nested validation here pass else: if js_disallow in seen: raise SchemaError( "disallow value {0!r} contains duplicate element" " {1!r}".format(value, js_disallow)) else: seen.add(js_disallow) if js_disallow not in ( "string", "number", "integer", "boolean", "object", "array", "null", "any"): raise SchemaError( "disallow value {0!r} is not a simple type" " name".format(js_disallow)) return disallow_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 validate(schema_text, data_text, deserializer=_default_deserializer): """ Validate specified JSON text with specified schema. Both arguments are converted to JSON objects with :func:`simplejson.loads`, if present, or :func:`json.loads`. :param schema_text: Text of the JSON schema to check against :type schema_text: :class:`str` :param data_text: Text of the JSON object to check :type data_text: :class:`str` :param deserializer: Function to convert the schema and data to JSON objects :type deserializer: :class:`callable` :returns: Same as :meth:`json_schema_validator.validator.Validator.validate` :raises: Whatever may be raised by simplejson (in particular :class:`simplejson.decoder.JSONDecoderError`, a subclass of :class:`ValueError`) or json :raises: Whatever may be raised by :meth:`json_schema_validator.validator.Validator.validate`. In particular :class:`json_schema_validator.errors.ValidationError` and :class:`json_schema_validator.errors.SchemaError` """
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, return the ``User`` after activating. If the key is not valid or has expired, return ``False``. If the key is valid but the ``User`` is already active, return ``False``. To prevent reactivation of an account which has been deactivated by site administrators, the activation key is reset to the string constant ``RegistrationProfile.ACTIVATED`` after successful activation. """
# 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 RegistrationProfile.DoesNotExist: return False if not profile.activation_key_expired(): user = profile.user user.is_active = True user.save() profile.activation_key = RegistrationProfile.ACTIVATED profile.save() return user 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 instruction_RTS(self, opcode): """ Program control is returned from the subroutine to the calling program. The return address is pulled from the stack. source code forms: RTS CC bits "HNZVC": ----- """
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 return from subroutine (RTS) instruction is used to reverse this process and must be the last instruction executed in a subroutine. source code forms: BSR dd; LBSR DDDD; JSR EA CC bits "HNZVC": ----- """
# 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 compare operation on unsigned binary values, this instruction will branch if the register was higher than the memory register. Generally not useful after INC/DEC, LD/TST, and TST/CLR/COM instructions. source code forms: BHI dd; LBHI DDDD CC bits "HNZVC": ----- """
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 compare operation on unsigned binary values, this instruction will branch if the register was lower than or the same as the memory register. Generally not useful after INC/DEC, LD/ST, and TST/CLR/COM instructions. source code forms: BLS dd; LBLS DDDD CC bits "HNZVC": ----- """
# 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 "HNZVC": -aa0- """
# 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; STX P; STY P; STS P; STU P CC bits "HNZVC": -aa0- """
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, 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 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 "HNZVC": -aa0- """
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, 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 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="ws", netloc="localhost:{}".format(port)) url = urlunparse(parts) # Proxy initial connection headers headers = [(header, value) for header, value in request.headers.items() if header.lower() in CAPTURE_CONNECT_HEADERS] logger.info("Connecting to upstream websockets: %s, headers: %s", url, headers) ws = ProxyClient(url, headers=headers) ws.connect() # TODO: Will complain loudly about already send headers - how to abort? return httpexceptions.HTTPOk()
<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), ('Sec-WebSocket-Version', str(max(WS_VERSION))) ] if self.protocols: headers.append(('Sec-WebSocket-Protocol', ','.join(self.protocols))) if self.extra_headers: headers.extend(self.extra_headers) logger.info("Handshake headers: %s", headers) 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 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 instead of just sleep(). """
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: logger.debug("Incoming downstream WS: %s", msg) self.send(msg) s = self.stream self.opened() logger.debug("Asking for upstream msg {s}".format(s=s)) try: bytes = self.sock.recv(self.reading_buffer_size) if bytes: self.process(bytes) except BlockingIOError: pass except Exception as e: logger.exception(e) finally: logger.info("Terminating WS proxy loop") self.terminate()
<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 if not in the cache """
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 the cache """
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 resource Raises: CacheError: If the content cannot be put in cache """
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 ' % cache_path) try: with open(cache_path, 'wb') as f: f.write(content) except IOError: raise Error('Failed to cache content as %s for %s' % (cache_path, 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 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 available on disk Raises: CacheError: If the file cannot be put in cache """
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 ' % cache_path) # Remove the resource already exist try: os.unlink(cache_path) except OSError: pass try: # First try hard link to avoid wasting disk space & overhead os.link(path, cache_path) except OSError: try: # Use file copy as fallaback shutil.copyfile(path, cache_path) except IOError: raise Error('Failed to cache %s as %s for %s' % (path, cache_path, 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 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") if greeting: cells.append(nbf.new_markdown_cell(greeting)) cells.append(nbf.new_code_cell('')) nb = nbf.new_notebook(cells=cells) with open(fname, 'w') as f: writer = JSONWriter() writer.write(nb, 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 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=None, mem=bytearray([ # 0100| .ORG $100 0x10, 0xCE, 0x40, 0x00, # 0100| LDS #$4000 # 0104| CRCHH: EQU $ED # 0104| CRCHL: EQU $B8 # 0104| CRCLH: EQU $83 # 0104| CRCLL: EQU $20 # 0104| CRCINITH: EQU $FFFF # 0104| CRCINITL: EQU $FFFF # 0104| ; CRC 32 bit in DP (4 bytes) # 0104| CRC: EQU $80 0xCE, addr_hi, addr_lo, # 0104| LDU #.... ; start address in u 0x34, 0x10, # 010C| PSHS x ; end address +1 to TOS 0xCC, 0xFF, 0xFF, # 010E| LDD #CRCINITL 0xDD, 0x82, # 0111| STD crc+2 0x8E, 0xFF, 0xFF, # 0113| LDX #CRCINITH 0x9F, 0x80, # 0116| STX crc # 0118| ; d/x contains the CRC # 0118| BL: 0xE8, 0xC0, # 0118| EORB ,u+ ; XOR with lowest byte 0x10, 0x8E, 0x00, 0x08, # 011A| LDY #8 ; bit counter # 011E| RL: 0x1E, 0x01, # 011E| EXG d,x # 0120| RL1: 0x44, # 0120| LSRA ; shift CRC right, beginning with high word 0x56, # 0121| RORB 0x1E, 0x01, # 0122| EXG d,x 0x46, # 0124| RORA ; low word 0x56, # 0125| RORB 0x24, 0x12, # 0126| BCC cl # 0128| ; CRC=CRC XOR polynomic 0x88, 0x83, # 0128| EORA #CRCLH ; apply CRC polynomic low word 0xC8, 0x20, # 012A| EORB #CRCLL 0x1E, 0x01, # 012C| EXG d,x 0x88, 0xED, # 012E| EORA #CRCHH ; apply CRC polynomic high word 0xC8, 0xB8, # 0130| EORB #CRCHL 0x31, 0x3F, # 0132| LEAY -1,y ; bit count down 0x26, 0xEA, # 0134| BNE rl1 0x1E, 0x01, # 0136| EXG d,x ; CRC: restore correct order 0x27, 0x04, # 0138| BEQ el ; leave bit loop # 013A| CL: 0x31, 0x3F, # 013A| LEAY -1,y ; bit count down 0x26, 0xE0, # 013C| BNE rl ; bit loop # 013E| EL: 0x11, 0xA3, 0xE4, # 013E| CMPU ,s ; end address reached? 0x26, 0xD5, # 0141| BNE bl ; byte loop 0xDD, 0x82, # 0143| STD crc+2 ; CRC low word 0x9F, 0x80, # 0145| STX crc ; CRC high word ])) d = self.cpu.accu_d.value x = self.cpu.index_x.value crc32 = x * 0x10000 + d return crc32 ^ 0xFFFFFFFF
<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, self.index_x.value) # X self.push_byte(self.system_stack_pointer, self.direct_page.value) # DP self.push_byte(self.system_stack_pointer, self.accu_b.value) # B self.push_byte(self.system_stack_pointer, self.accu_a.value) # A 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 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] if sentence: yield sentence
<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: :class:`collections.MutableMapping` :returns: the remote url to proxy :rtype: :class:`basestring` """
# 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 = url.split('%3B', 1) url = ';'.join([url, arg.replace('%3D', '=')]) # Stick query string back in try: query_string = environ['QUERY_STRING'] except KeyError: pass else: url += '?' + query_string parsed = urlparse(url) replaced = parsed._replace(netloc="localhost:{}".format(port)) url = urlunparse(replaced) environ['reconstructed_url'] = url return url
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_summaries(client, filter=None): """ Generate presentation summaries in a reverse chronological order. A filter class can be supplied to filter summaries or bound the fetching process. """
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(summaries) except StopIteration: 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 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) def get_auth(div): return div.find('span', class_='author').a['title'] def get_date(div): str = div.find('span', class_='author').get_text() str = str.replace('\n', ' ') str = str.replace(six.u('\xa0'), ' ') match = re.search(r'on\s+(\w{3} [0-9]{1,2}, 20[0-9]{2})', str) return datetime.datetime.strptime(match.group(1), "%b %d, %Y") def get_title(div): return div.find('h2', class_='itemtitle').a['title'] return { 'id': get_id(div), 'url': get_url(div), 'desc': get_desc(div), 'auth': get_auth(div), 'date': get_date(div), 'title': get_title(div), } videos = self.soup.findAll('div', {'class': 'news_type_video'}) return [create_summary(div) for div in videos]
<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 startup.py initialization file skeleton and greeting. This will set up context ``startup`` and ``greeting`` for their default values. :param notebook_context: Dictionary of notebook context info to be to passed to NotebookManager :param config_file: The current .ini file used to start up the Pyramid. This is used to pass it around to ``pyramid.paster.boostrap()`` to initialize dummy request object and such. :param bootstrap_py: startup.py script header which sets up environment creation :parma bootstrap_greeting: Markdown snippet which sets up start of greeting text :param cwd: Optional forced working directory. If not set use the directory of a config file. """
# 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, "Got bad config_file {}".format(config_file) config_file = os.path.abspath(config_file) assert os.path.exists(config_file), "Passed in bad config file: {}".format(config_file) add_script(nc, bootstrap_py.format(config_uri=config_file, cwd=cwd)) add_greeting(nc, bootstrap_greeting) add_script(nc, "import datetime") add_greeting(nc, "* **datetime** - Python [datetime module](https://docs.python.org/3.5/library/datetime.html)") add_script(nc, "import time") add_greeting(nc, "* **time** - Python [time module](https://docs.python.org/3.5/library/time.html)") try: # Commonly used with Pyramid applications import transaction # noQA add_script(nc, "import transaction\n") add_greeting(nc, "* **transaction** - Zope [transaction manager](http://zodb.readthedocs.org/en/latest/transactions.html), e.g. `transaction.commit()`") except ImportError: 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 include_sqlalchemy_models(nc, Base): """Include all SQLAlchemy models in the script context. :param nc: notebook_context dictionary :param Base: SQLAlchemy model Base class from where the all models inherit. """
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_statement(klass)) add_greeting(nc, "* **{}** - {}".format(klass.__name__, get_dotted_path(klass)))
<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 location M and the result is stored in accumulator A or B. source code forms: ORA P; ORB P CC bits "HNZVC": -aa0- """
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 instruction and places the result in the condition code register. source code forms: ANDCC #xx CC bits "HNZVC": ddddd """
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: raise RuntimeError("Register $%x doesn't exists! (postbyte: $%x)" % (rr, postbyte)) register_obj = self.register_str2object[register_str] register_value = register_obj.value # log.debug("\t%02x == register %s: value $%x", # rr, register_obj.name, register_value # ) if not is_bit_set(postbyte, bit=7): # bit 7 == 0 # EA = n, R - use 5-bit offset from post-byte offset = signed5(postbyte & 0x1f) ea = register_value + offset # log.debug( # "\tget_ea_indexed(): bit 7 == 0: reg.value: $%04x -> ea=$%04x + $%02x = $%04x", # register_value, register_value, offset, ea # ) return ea addr_mode = postbyte & 0x0f self.cycles += 1 offset = None # TODO: Optimized this, maybe use a dict mapping... if addr_mode == 0x0: # log.debug("\t0000 0x0 | ,R+ | increment by 1") ea = register_value register_obj.increment(1) elif addr_mode == 0x1: # log.debug("\t0001 0x1 | ,R++ | increment by 2") ea = register_value register_obj.increment(2) self.cycles += 1 elif addr_mode == 0x2: # log.debug("\t0010 0x2 | ,R- | decrement by 1") register_obj.decrement(1) ea = register_obj.value elif addr_mode == 0x3: # log.debug("\t0011 0x3 | ,R-- | decrement by 2") register_obj.decrement(2) ea = register_obj.value self.cycles += 1 elif addr_mode == 0x4: # log.debug("\t0100 0x4 | ,R | No offset") ea = register_value elif addr_mode == 0x5: # log.debug("\t0101 0x5 | B, R | B register offset") offset = signed8(self.accu_b.value) elif addr_mode == 0x6: # log.debug("\t0110 0x6 | A, R | A register offset") offset = signed8(self.accu_a.value) elif addr_mode == 0x8: # log.debug("\t1000 0x8 | n, R | 8 bit offset") offset = signed8(self.read_pc_byte()[1]) elif addr_mode == 0x9: # log.debug("\t1001 0x9 | n, R | 16 bit offset") offset = signed16(self.read_pc_word()[1]) self.cycles += 1 elif addr_mode == 0xa: # log.debug("\t1010 0xa | illegal, set ea=0") ea = 0 elif addr_mode == 0xb: # log.debug("\t1011 0xb | D, R | D register offset") # D - 16 bit concatenated reg. (A + B) offset = signed16(self.accu_d.value) # FIXME: signed16() ok? self.cycles += 1 elif addr_mode == 0xc: # log.debug("\t1100 0xc | n, PCR | 8 bit offset from program counter") __, value = self.read_pc_byte() value_signed = signed8(value) ea = self.program_counter.value + value_signed # log.debug("\tea = pc($%x) + $%x = $%x (dez.: %i + %i = %i)", # self.program_counter, value_signed, ea, # self.program_counter, value_signed, ea, # ) elif addr_mode == 0xd: # log.debug("\t1101 0xd | n, PCR | 16 bit offset from program counter") __, value = self.read_pc_word() value_signed = signed16(value) ea = self.program_counter.value + value_signed self.cycles += 1 # log.debug("\tea = pc($%x) + $%x = $%x (dez.: %i + %i = %i)", # self.program_counter, value_signed, ea, # self.program_counter, value_signed, ea, # ) elif addr_mode == 0xe: # log.error("\tget_ea_indexed(): illegal address mode, use 0xffff") ea = 0xffff # illegal elif addr_mode == 0xf: # log.debug("\t1111 0xf | [n] | 16 bit address - extended indirect") __, ea = self.read_pc_word() else: raise RuntimeError("Illegal indexed addressing mode: $%x" % addr_mode) if offset is not None: ea = register_value + offset # log.debug("\t$%x + $%x = $%x (dez: %i + %i = %i)", # register_value, offset, ea, # register_value, offset, ea # ) ea = ea & 0xffff if is_bit_set(postbyte, bit=4): # bit 4 is 1 -> Indirect # log.debug("\tIndirect addressing: get new ea from $%x", ea) ea = self.memory.read_word(ea) # log.debug("\tIndirect addressing: new ea is $%x", ea) # log.debug("\tget_ea_indexed(): return ea=$%x", ea) return 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 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 traceback dump on stuck env = os.environ.copy() env["PYTHONFAULTHANDLER"] = "true" p = subprocess.Popen(cmd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, env=env) time.sleep(0.2) stdout, stderr = p.communicate() if b"already running" in stderr: raise RuntimeError("Looks like notebook_daemon is already running. Please kill it manually pkill -f notebook_daemon. Was: {}".format(stderr.decode("utf-8"))) if p.returncode != 0: logger.error("STDOUT: %s", stdout) logger.error("STDERR: %s", stderr) raise RuntimeError("Could not execute notebook command. Exit code: {} cmd: {}".format(p.returncode, " ".join(cmd))) return stdout
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 a new Notebook content folder created where all files are placed. :param context: Extra context information passed to the started Notebook. This must contain {context_hash:int} parameter used to identify the launch parameters for the notebook """
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 websocket URLs, so let them go directly through localhost or have front end server to do proxying (nginx) if "websocket_url" not in context: context["websocket_url"] = "ws://localhost:{port}".format(port=http_port) if "{port}" in context["websocket_url"]: # Do port substitution for the websocket URL context["websocket_url"] = context["websocket_url"].format(port=http_port) pid = self.get_pid(name) assert "terminated" not in context comm.set_context(pid, context) if fg: self.exec_notebook_daemon_command(name, "fg", port=http_port) else: self.exec_notebook_daemon_command(name, "start", port=http_port)
<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. :return: (context dict, created flag) """
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 over context.json file time.sleep(2.0) else: return last_context, False err_log = os.path.join(self.get_work_folder(name), "notebook.stderr.log") logger.info("Launching new Notebook named %s, context is %s", name, context) logger.info("Notebook log is %s", err_log) self.start_notebook(name, context) time.sleep(1) context = self.get_context(name) if "notebook_name" not in context: # Failed to launch within timeout raise RuntimeError("Failed to launch IPython Notebook, see {}".format(err_log)) return context, 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 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 error creating the app, it will return a dummy app that just returns the Flask error page for the exception. This works with the Flask code reloader so that if the app fails during initialization it will still monitor those files for changes and reload the app. """
@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_frame.f_code.co_filename extra_files.append(filename) tb = tb.tb_next if isinstance(exc_val, SyntaxError): extra_files.append(exc_val.filename) app = _FailSafeFlask(extra_files) app.debug = True @app.route('/') @app.route('/<path:path>') def index(path='/'): reraise(exc_type, exc_val, exc_tb) return app return wrapper
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate(cls, schema, obj): """ Validate specified JSON object obj with specified schema. :param schema: Schema to validate against :type schema: :class:`json_schema_validator.schema.Schema` :param obj: JSON object to validate :rtype: bool :returns: True on success :raises `json_schema_validator.errors.ValidationError`: if the object does not match schema. :raises `json_schema_validator.errors.SchemaError`: if the schema itself is wrong. """
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 message is used for backwards compatibility and usually contains the object (possibly very large) that failed to validate. The new message is much better as it contains just a short message on what went wrong. User code can inspect object_expr and schema_expr to see which part of the object failed to validate against which part of the schema. The schema_suffix, if provided, is appended to the schema_expr. This is quite handy to specify the bit that the validator looked at (such as the type or optional flag, etc). object_suffix serves the same purpose but is used for object expressions instead. """
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)