code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
for category, commands in iteritems(command_categories): for existing_command in commands: if existing_command.match(command): existing_command.run(args)
def run_command(command, args)
Run all tasks registered in a command.
5.374506
5.151975
1.043193
subparams = getattr(subtype, "__parameters__", None) if subparams is None: return issubclass(subtype, supertype) # a non-generic actual type # It is surprisingly difficult to ignore the type variables in a # subclass check. We therefore compare __name__ (along mro) ...
def _is_possible_subclass(self, subtype, supertype)
Like issubclass(subtype, supertype) except that TypeVars are not taken into account.
11.879366
10.976909
1.082214
return namespace.is_compatible(self.typevar, type(value))
def check(self, value, namespace)
See whether the TypeVar is bound for the first time or is met with _exactly_ the same type as previously. That type must also obey the TypeVar's bound, if any. Everything else is a type error.
17.616747
10.633591
1.656707
if (not issubclass(type(value), self._cls) or len(value) != len(self._cls._fields)): return False for i, check in enumerate(self._checks): if not check(value[i], namespace): return False return True
def check(self, value, namespace)
Attribute _field_types is a dict from field name to type.
3.262504
3.198703
1.019946
for i, check in enumerate(self._checks): if check(value, namespace): return True return False
def check(self, value, namespace)
Attribute _field_types is a dict from field name to type.
4.205142
4.266255
0.985675
if db_value is not None: try: return pickle.loads(str(db_value)) except StandardError: log.exception('Failed to restore pickle') raise orb.errors.DataStoreError('Failed to restore pickle.') else: return None
def dbRestore(self, db_value, context=None)
Converts a stored database value to Python. :param py_value: <variant> :param context: <orb.Context> :return: <variant>
4.396294
4.053843
1.084476
if db_value is not None: try: return rest.unjsonify(db_value) except StandardError: log.exception('Failed to restore json') raise orb.errors.DataStoreError('Failed to restore json.') else: return db_value
def dbRestore(self, db_value, context=None)
Converts a stored database value to Python. :param py_value: <variant> :param context: <orb.Context> :return: <variant>
5.780646
5.759827
1.003615
if db_value is not None: jdata = super(QueryColumn, self).dbRestore(db_value, context=context) return orb.Query.fromJSON(jdata) else: return db_value
def dbRestore(self, db_value, context=None)
Converts a stored database value to Python. :param py_value: <variant> :param context: <orb.Context> :return: <variant>
5.745054
5.193485
1.106204
if db_value is not None: return yaml.load(projex.text.nativestring(db_value)) else: return db_value
def dbRestore(self, db_value, context=None)
Converts a stored database value to Python. :param py_value: <variant> :param context: <orb.Context> :return: <variant>
7.273026
7.793412
0.933227
maxChars = self.config.max_line_length for line in lines.splitlines(): if len(line) > maxChars: if 'http://' in line or 'https://' in line: continue self.add_message('C0301', line=i, args=(len(line), maxChars)) i += 1
def check_lines(self, lines, i)
check lines have less than a maximum number of characters. It ignored lines with long URLs.
3.838226
3.242596
1.183689
pass
def pci_lookup_name1( access: (IN, ctypes.POINTER(pci_access)), buf: (IN, ctypes.c_char_p), size: (IN, ctypes.c_int), flags: (IN, ctypes.c_int), arg1: (IN, ctypes.c_int), ) -> ctypes.c_char_p
Conversion of PCI ID's to names (according to the pci.ids file). char *pci_lookup_name( struct pci_access *a, char *buf, int size, int flags, ... ) PCI_ABI; This is a variant of pci_lookup_name() that gets called with one argument. It is required because ctypes doesn't support varadic function...
1,324,325.25
11,882.410156
111.452578
pass
def pci_lookup_name2( access: (IN, ctypes.POINTER(pci_access)), buf: (IN, ctypes.c_char_p), size: (IN, ctypes.c_int), flags: (IN, ctypes.c_int), arg1: (IN, ctypes.c_int), arg2: (IN, ctypes.c_int), ) -> ctypes.c_char_p
Conversion of PCI ID's to names (according to the pci.ids file). char *pci_lookup_name( struct pci_access *a, char *buf, int size, int flags, ... ) PCI_ABI; This is a variant of pci_lookup_name() that gets called with two arguments. It is required because ctypes doesn't support varadic functio...
1,695,859.75
12,718.202148
133.341154
pass
def pci_lookup_name4( access: (IN, ctypes.POINTER(pci_access)), buf: (IN, ctypes.c_char_p), size: (IN, ctypes.c_int), flags: (IN, ctypes.c_int), arg1: (IN, ctypes.c_int), arg2: (IN, ctypes.c_int), arg3: (IN, ctypes.c_int), arg4: (IN, ctypes.c_int), ) -> ctypes.c_char_p
Conversion of PCI ID's to names (according to the pci.ids file). char *pci_lookup_name( struct pci_access *a, char *buf, int size, int flags, ... ) PCI_ABI; This is a variant of pci_lookup_name() that gets called with four arguments. It is required because ctypes doesn't support varadic functi...
1,871,417
14,414.318359
129.83042
class LoginView(GiottoView): @renders('text/html') def html(self, result): ty = type(http_redirect) if ty == list or ty == tuple: assert len(http_redirect) == 3, "http_redirect must be three items" return Redirection(http_redirect...
def LoginView(http_redirect=None)
After logging in, redirect the user to the ``http_redirect`` program. This is a meta program, a function that returns a program. ``http_redirect`` can be either a string, or a three item tuple with M objects: http_redirect=('/blog', [m.id], {}) | http_redirect=('/blog', [], {'name': M['name']})
4.495619
4.613629
0.974421
many = isinstance(obj, collections.Iterable) \ or isinstance(obj, models.Manager) \ and not isinstance(obj, dict) assert self.serializer is not None \ and issubclass(self.serializer, serializers.ModelSerializer), ( "Bad serializer defined %s"...
def to_representation(self, obj)
Represent data for the field.
4.397346
4.331216
1.015268
if action not in ('unset', 'delete'): raise orb.errors.ValidationError('The remove action must be either "unset" or "delete"') else: self.__removeAction = action
def setRemoveAction(self, action)
Sets the remove action that should be taken when a model is removed from the collection generated by this reverse lookup. Valid actions are "unset" or "delete", any other values will raise an exception. :param action: <str>
7.164284
5.066036
1.414179
assert type(typevar) == tg.TypeVar if self.is_generic_in(typevar): self.bind_to_instance(typevar, its_type) else: self._ns[typevar] = its_type
def bind(self, typevar, its_type)
Binds typevar to the type its_type. Binding occurs on the instance if the typevar is a TypeVar of the generic type of the instance, on call level otherwise.
4.667551
3.971305
1.175319
if typevar in self._ns: return self._ns[typevar] if self._instance_ns and typevar in self._instance_ns: return self._instance_ns[typevar] return None
def binding_of(self, typevar)
Returns the type the typevar is bound to, or None.
2.726949
2.380664
1.145457
result = True binding = self.binding_of(typevar) # may or may not exist if binding is None: self.bind(typevar, its_type) # initial binding, OK elif issubclass(binding, its_type): self.bind(typevar, its_type) # rebind to supertype, OK elif not i...
def is_compatible(self, typevar, its_type)
Checks whether its_type conforms to typevar. If the typevar is not yet bound, it will be bound to its_type. The covariance/contravariance checking described in the respective section of PEP484 applies to declared types, but here we have actual types; therefore, (1) subtypes are always co...
4.271929
3.860105
1.106687
if prepend: cls._registered.insert(0, (predicate, factory)) else: cls._registered.append((predicate, factory))
def register(cls, predicate, factory, prepend=False)
Adds another type X of typecheck annotations to the framework. predicate(annot) indicates whether annot has annotation type X; factory(annot) creates the appropriate typechecker instance. The checker type is normally added after the existing ones, but 'prepend' makes it come first.
2.290604
2.434844
0.94076
is_tuplish_type = (issubclass(self._cls, tg.Tuple) or issubclass(type(values), self._cls)) if (not _is_sequence(values) or not is_tuplish_type or len(values) != len(self._checks)): return False for thischeck, thisvalue in zip(self._...
def check(self, values, namespace)
specifying a plain tuple allows arguments that are tuples or lists; specifying a specialized (subclassed) tuple allows only that type; specifying a list allows only that list type.
4.27805
4.408792
0.970345
last_pypi_url = None with open(path) as f: requires = [] pypi_urls = [] for line in f.readlines(): if not line: continue if '--' in line: match = re.match(r'--index-url\s+([\w\d:/.-]+)\s', line) if match: ...
def read_requirements_file(path)
reads requirements.txt file and handles PyPI index URLs :param path: (str) path to requirements.txt file :return: (tuple of lists)
2.580021
2.547203
1.012884
if not node.file_stream: # failed to open the module return text = node.file_stream.read() self._checkCopyright(text, node) if not isTestModule(node.name) and moduleNeedsTests: self._checkTestReference(text, node)
def visit_module(self, node)
A interface will be called when visiting a module. @param node: node of current module
9.008633
10.291776
0.875323
if not re.search(br"%s\s*\n\s*%s" % self.commentsCopyright, text): self.add_message('W9001', node=node)
def _checkCopyright(self, text, node)
Check whether the module has copyright header. @param text: codes of the module @param node: node of the module
7.821005
9.159511
0.853867
if msg.msg_id in self.messagesAllowed: super(LimitedReporter, self).handle_message(msg)
def handle_message(self, msg)
Manage message of different type and in the context of path.
11.291431
10.916223
1.034372
schemas = self.schemas().values() for schema in schemas: scope[schema.name()] = schema.model()
def init(self, scope)
Loads the models from the orb system into the inputted scope. :param scope | <dict> autoGenerate | <bool> schemas | [<orb.TableSchema>, ..] || None database | <str> || None
9.086761
8.872995
1.024092
if isinstance(obj, orb.Database): scope = self.__databases key = obj.code() elif isinstance(obj, orb.Schema): scope = self.__schemas key = obj.name() else: raise orb.errors.OrbError('Unknown object to register: {0}'.format(obj)...
def register(self, obj, force=False)
Registers a particular database. :param obj | <orb.Database> || <orb.Schema>
3.886777
3.22298
1.205957
if obj is None: self.__databases.clear() self.__schemas.clear() elif isinstance(obj, orb.Schema): self.__schemas.pop(obj.name(), None) elif isinstance(obj, orb.Database): if obj == self.__current_db: self.__current_db = Non...
def unregister(self, obj=None)
Unregisters the object from the system. If None is supplied, then all objects will be unregistered :param obj: <str> or <orb.Database> or <orb.Schema> or None
2.391234
1.918185
1.246613
size = max(0, self.context(**context).pageSize) if not size: return self.copy() else: return self.copy(page=number, pageSize=size)
def page(self, number, **context)
Returns the records for the current page, or the specified page number. If a page size is not specified, then this record sets page size will be used. :param pageno | <int> pageSize | <int> :return <orb.RecordSet>
6.601522
8.392896
0.786561
if not event.data: return context = self.context() schema = self.schema() dbname = schema.dbname() clean = {} for col, value in event.data.items(): try: model_dbname, col_name = col.split('.') except ValueErro...
def _load(self, event)
Processes a load event by setting the properties of this record to the data restored from the database. :param event: <orb.events.LoadEvent>
5.458759
5.008919
1.089808
output = {} is_record = self.isRecord() schema = self.schema() columns = [schema.column(c) for c in columns] if columns else \ schema.columns(recurse=recurse, flags=flags).values() context = self.context(inflated=inflated) with ReadLocker(self...
def changes(self, columns=None, recurse=True, flags=0, inflated=False)
Returns a dictionary of changes that have been made to the data from this record. :return { <orb.Column>: ( <variant> old, <variant> new), .. }
4.136214
3.924471
1.053955
output = orb.Context(context=self.__context) if self.__context is not None else orb.Context() output.update(context) return output
def context(self, **context)
Returns the lookup options for this record. This will track the options that were used when looking this record up from the database. :return <orb.LookupOptions>
7.011977
6.958357
1.007706
if not self.isRecord(): return 0 event = orb.events.DeleteEvent(record=self, context=self.context(**context)) if self.processEvent(event): self.onDelete(event) if event.preventDefault: return 0 if self.__delayed: self.__...
def delete(self, **context)
Removes this record from the database. If the dryRun \ flag is specified then the command will be logged and \ not executed. :note From version 0.6.0 on, this method now accepts a mutable keyword dictionary of values. You can supply any member val...
6.271844
5.726152
1.095298
# look for shortcuts (dot-noted path) if isinstance(column, (str, unicode)) and '.' in column: # create the sub context base_context = context.copy() base_context['inflated'] = True # generate the expansion to avoid unnecessary lookups ...
def get(self, column, useMethod=True, **context)
Returns the value for the column for this record. :param column | <orb.Column> || <str> default | <variant> inflated | <bool> :return <variant>
4.069268
3.920453
1.037959
schema = self.schema() columns = {schema.column(col) for col in columns} column_names = {col.name() for col in columns} with WriteLocker(self.__dataLock): for key, (old_value, new_value) in self.__values.items(): if key in column_names: ...
def markLoaded(self, *columns)
Tells the model to treat the given columns as though they had been loaded from the database. :param columns: (<str>, ..)
3.756523
3.686453
1.019008
if db is not None: same_db = db == self.context().db if db is None or same_db: col = self.schema().idColumn() with ReadLocker(self.__dataLock): return (col in self.__loaded) and (self.__values[col.name()][0] is not None) else: ...
def isRecord(self, db=None)
Returns whether or not this database table record exists in the database. :return <bool>
7.692432
8.023333
0.958758
# specify that this save call should be performed after the save of # another record, useful for chaining events if after is not None: callback = orb.events.Callback(self.save, values=values, **context) after.addCallback(orb.events.PostSaveEvent, callback, record...
def save(self, values=None, after=None, before=None, **context)
Commits the current change set information to the database, or inserts this object as a new record into the database. This method will only update the database if the record has any local changes to it, otherwise, no commit will take place. If the dryRun flag is set, then the SQL ...
3.61339
3.422013
1.055925
col = self.schema().column(column, raise_=False) if col is None: # allow setting of collections as well collector = self.schema().collector(column) if collector: my_context = self.context() for k, v in my_context.raw_values.i...
def set(self, column, value, useMethod=True, **context)
Sets the value for this record at the inputted column name. If the columnName provided doesn't exist within the schema, then the ColumnNotFound error will be raised. :param columnName | <str> value | <variant> :return <bool> changed
3.375225
3.457784
0.976124
schema = self.schema() column_updates = {} other_updates = {} for key, value in values.items(): try: column_updates[schema.column(key)] = value except orb.errors.ColumnNotFound: other_updates[key] = value # update ...
def update(self, values, **context)
Updates the model with the given dictionary of values. :param values: <dict> :param context: <orb.Context> :return: <int>
2.948978
2.648721
1.11336
schema = self.schema() if not columns: ignore_flags = orb.Column.Flags.Virtual | orb.Column.Flags.ReadOnly columns = schema.columns(flags=~ignore_flags).values() use_indexes = True else: use_indexes = False # validate the column v...
def validate(self, columns=None)
Validates the current record object to make sure it is ok to commit to the database. If the optional override dictionary is passed in, then it will use the given values vs. the one stored with this record object which can be useful to check to see if the record will be valid before it is commit...
4.25197
4.339229
0.979891
output = {} schema = self.schema() for column in columns or schema.columns(recurse=recurse, flags=flags).values(): column = column if isinstance(column, orb.Column) else schema.column(column) try: val_key = column if key == 'column' else getattr(...
def values(self, columns=None, recurse=True, flags=0, mapper=None, key='name', **get_options)
Returns a dictionary grouping the columns and their current values. If the inflated value is set to True, then you will receive any foreign keys as inflated classes (if you have any values that are already inflated in your class, then you will still get back the class and not the primar...
4.409379
4.641871
0.949914
callbacks = cls.callbacks() callbacks.setdefault(eventType, []) callbacks[eventType].append((func, record, once))
def addCallback(cls, eventType, func, record=None, once=False)
Adds a callback method to the class. When an event of the given type is triggered, any registered callback will be executed. :param eventType: <str> :param func: <callable>
3.550962
4.77819
0.74316
key = '_{0}__callbacks'.format(cls.__name__) try: callbacks = getattr(cls, key) except AttributeError: callbacks = {} setattr(cls, key, callbacks) return callbacks.get(eventType, []) if eventType is not None else callbacks
def callbacks(cls, eventType=None)
Returns a list of callback methods that can be invoked whenever an event is processed. :return: {subclass of <Event>: <list>, ..}
3.159209
3.836778
0.823402
schema = cls.schema() model = cls # check for creating inherited classes from a sub class polymorphic_columns = schema.columns(flags=orb.Column.Flags.Polymorphic) if polymorphic_columns: polymorphic_column = polymorphic_columns.values()[0] schema...
def create(cls, values, **context)
Shortcut for creating a new record for this table. :param values | <dict> :return <orb.Table>
4.265728
4.204051
1.014671
# 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 or...
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>
3.675709
3.748797
0.980504
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: remov...
def processEvent(cls, event)
Processes the given event by dispatching it to any waiting callbacks. :param event: <orb.Event>
3.190707
3.404773
0.937128
# 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: ...
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
4.163001
3.911355
1.064337
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.c...
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>
4.735386
4.689655
1.009751
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] bre...
def removeCallback(cls, eventType, func, record=None)
Removes a callback from the model's event callbacks. :param eventType: <str> :param func: <callable>
2.846996
3.215192
0.885483
rset_type = getattr(cls, 'Collection', orb.Collection) return rset_type(model=cls, **context)
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-infl...
10.564466
11.302695
0.934686
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
def jinja_template(template_name, name='data', mimetype="text/html")
Meta-renderer for rendering jinja templates
4.546123
4.47895
1.014997
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) ...
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.
3.555844
3.801388
0.935407
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
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.
5.296916
5.736712
0.923337
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: ...
def _register_renderers(self, attrs)
Go through the passed in list of attributes and register those renderers in the render map.
3.886498
3.663675
1.06082
for mime in self.render_map.keys(): if mime == '*/*': return True if partial_mimetype in mime: return True return False
def can_render(self, partial_mimetype)
Given a partial mimetype (such as 'json' or 'html'), return if the view can render that type.
3.463251
3.241635
1.068366
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: ...
def render(self, result, mimetype, errors=None)
Render a model result into `mimetype` format.
4.779863
4.756686
1.004873
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) ...
def generic_html(self, result, errors)
Try to display any object in sensible HTML.
2.910804
2.848912
1.021725
from PIL import Image ascii_chars = ['#', 'A', '@', '%', 'S', '+', '<', '*', ':', ',', '.'] def image_to_ascii(image): image_as_ascii = [] all_pixels = list(image.getdata()) for pixel_value in all_pixels: index = pixel_value / 25 # 0...
def plaintext(self, result)
Converts the image object into an ascii representation. Code taken from http://a-eter.blogspot.com/2010/04/image-to-ascii-art-in-python.html
3.033076
2.88341
1.051906
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
def install_twisted()
If twisted is available, make `emit' return a DeferredList This has been successfully tested with Twisted 14.0 and later.
3.815019
3.41248
1.117961
for callback in set(receivers[signal]): # Make a copy in case of any ninja signals _call(callback, args=args, kwargs=kwargs)
def emit(signal, *args, **kwargs)
Emits a single signal to call callbacks registered to respond to that signal. Optionally accepts args and kwargs that are passed directly to callbacks. :param signal: Signal to send
14.924563
18.527065
0.805555
errback = kwargs.pop('errback', lambda f: f) dl = [] for callback in set(receivers[signal]): # Make a copy in case of any ninja signals d = _call(callback, args=args, kwargs=kwargs) if d is not None: dl.append(d.addErrback(errback)) def simplify(results): retu...
def _emit_twisted(signal, *args, **kwargs)
Emits a single signal to call callbacks registered to respond to that signal. Optionally accepts args and kwargs that are passed directly to callbacks. :param signal: Signal to send
4.775645
5.566913
0.857862
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(callb...
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
3.721148
3.508072
1.060739
if isinstance(callback, int) or callback is None: # Decorated if isinstance(callback, int): # Here the args were passed arg-style, not kwarg-style callback, max_calls = max_calls, callback return partial(_on, signals, max_calls=max_calls) elif isinstance(call...
def on(signals, callback=None, max_calls=None)
Registers a single callback for receiving an event (or event list). Optionally, can specify a maximum number of times the callback should receive a signal. This method works as both a function and a decorator:: smokesignal.on('foo', my_callback) @smokesignal.on('foo') def my_callback()...
3.41345
3.783032
0.902305
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: ...
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_cal...
2.611899
2.9657
0.880703
# 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)
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
4.395265
4.953361
0.88733
signals = signals if signals else receivers.keys() for signal in signals: receivers[signal].clear()
def clear(*signals)
Clears all callbacks for a particular signal or signals
4.892501
4.231049
1.156333
schema = self.schema() return [schema.column(col) for col in self.__columns]
def columns(self)
Returns the list of column names that this index will be expecting as \ inputs when it is called. :return [<str>, ..]
7.83316
7.152169
1.095215
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.s...
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>
4.603857
4.303395
1.06982
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 Da...
def StaticServe(base_path='/views/static/')
Meta program for serving any file based on the path
6.279627
6.083966
1.03216
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_...
def SingleStaticServe(file_path)
Meta program for serving a single file. Useful for favicon.ico and robots.txt
5.387359
5.318523
1.012943
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)
def onSync(self, event)
Initializes the database by defining any additional structures that are required during selection.
9.488021
8.532898
1.111934
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....
def close(self)
Closes the connection to the database for this connection. :return <bool> closed
5.211394
5.931151
0.878648
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: ...
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>
5.639153
5.56293
1.013702
with self.native(writeAccess=True) as conn: if not self._closed(conn): return self._commit(conn)
def commit(self)
Commits the changes to the current database connection. :return <bool> success
13.603804
14.857013
0.915649
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: p...
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 ...
4.794574
5.001679
0.958593
# 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)
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
11.318663
13.128194
0.862164
command = command.strip() if not command: raise orb.errors.EmptyCommand() elif dryRun: print command % data raise orb.errors.DryRun() # define properties for execution data = data or {} command = command.strip() data....
def execute(self, command, data=None, returning=True, mapper=dict, writeAccess=False, dryRun=False, locale=None)
Executes the inputted command into the current \ connection cursor. :param command | <str> data | <dict> || None autoCommit | <bool> | commit database changes immediately autoClose | <bool> | closes connections immediately ...
3.466919
3.441219
1.007468
INSERT = self.statement('INSERT') sql, data = INSERT(records) if context.dryRun: print sql, data return [], 0 else: return self.execute(sql, data, writeAccess=True)
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> change...
7.476997
9.171359
0.815255
for pool in self.__pool.values(): if not pool.empty(): return True return False
def isConnected(self)
Returns whether or not this connection is currently active. :return <bool> connected
9.345231
10.029178
0.931804
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 ...
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
2.588404
2.895358
0.893984
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 p...
def open(self, writeAccess=False)
Returns the sqlite database for the current thread. :return <variant> || None
4.09006
4.250229
0.962315
with self.native(writeAccess=True) as conn: return self._rollback(conn)
def rollback(self)
Rolls back changes to this database.
18.794136
14.340646
1.31055
UPDATE = self.statement('UPDATE') sql, data = UPDATE(records) if context.dryRun: print sql, data return [], 0 else: return self.execute(sql, data, writeAccess=True)
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> :retu...
8.042114
9.372929
0.858015
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): ...
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).
2.674082
2.571351
1.039952
value = self._schema.get("properties", {}) if not isinstance(value, dict): raise SchemaError( "properties value {0!r} is not an object".format(value)) return value
def properties(self)
Schema for particular properties of the object.
4.705916
3.781013
1.244618
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
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.
5.32957
5.986868
0.89021
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
def optional(self)
Flag indicating an optional property.
4.229766
3.879265
1.090353
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
def additionalProperties(self)
Schema for all additional properties, or False.
4.805036
4.080117
1.177671
# 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)) r...
def requires(self)
Additional object or objects required by this object.
6.709873
5.827161
1.151482
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
def maximum(self)
Maximum value of the object.
3.856421
3.668844
1.051127
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 bool...
def minimumCanEqual(self)
Flag indicating if maximum value is inclusive or exclusive.
4.268668
4.042882
1.055848
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 bool...
def maximumCanEqual(self)
Flag indicating if the minimum value is inclusive or exclusive.
4.221772
4.143388
1.018918
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(v...
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 f...
3.233368
3.097
1.044032
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
def maxLength(self)
Maximum length of object.
3.611969
3.452108
1.046308
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 val...
def enum(self)
Enumeration of allowed object values. The enumeration must not contain duplicates.
2.055969
2.050518
1.002658
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
def title(self)
Title of the object. This schema element is purely informative.
3.744421
3.835696
0.976204
value = self._schema.get("format", None) if value is None: return if not isinstance(value, basestring): raise SchemaError( "format value {0!r} is not a string".format(value)) if value in [ 'date-time', 'regex', ...
def format(self)
Format of the (string) object.
3.307213
3.105607
1.064917
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...
def divisibleBy(self)
Integer that divides the object without reminder.
2.983738
2.96463
1.006445
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".forma...
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``.
2.584915
2.235128
1.156495
schema = Schema(deserializer(schema_text)) data = deserializer(data_text) return Validator.validate(schema, data)
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: ...
3.724325
5.446951
0.683745