sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def set_value(self, instance, value): '''Set the ``value`` for this :class:`Field` in a ``instance`` of a :class:`StdModel`.''' setattr(instance, self.attname, self.to_python(value))
Set the ``value`` for this :class:`Field` in a ``instance`` of a :class:`StdModel`.
entailment
def lookup(var_name, contexts=(), start=0): """lookup the value of the var_name on the stack of contexts :var_name: TODO :contexts: TODO :returns: None if not found """ start = len(contexts) if start >=0 else start for context in reversed(contexts[:start]): try: if var_...
lookup the value of the var_name on the stack of contexts :var_name: TODO :contexts: TODO :returns: None if not found
entailment
def delimiters_to_re(delimiters): """convert delimiters to corresponding regular expressions""" # caching delimiters = tuple(delimiters) if delimiters in re_delimiters: re_tag = re_delimiters[delimiters] else: open_tag, close_tag = delimiters # escape open_tag = ''....
convert delimiters to corresponding regular expressions
entailment
def is_standalone(text, start, end): """check if the string text[start:end] is standalone by checking forwards and backwards for blankspaces :text: TODO :(start, end): TODO :returns: the start of next index after text[start:end] """ left = False start -= 1 while start >= 0 and text[...
check if the string text[start:end] is standalone by checking forwards and backwards for blankspaces :text: TODO :(start, end): TODO :returns: the start of next index after text[start:end]
entailment
def compiled(template, delimiters=DEFAULT_DELIMITERS): """Compile a template into token tree :template: TODO :delimiters: TODO :returns: the root token """ re_tag = delimiters_to_re(delimiters) # variable to save states tokens = [] index = 0 sections = [] tokens_stack = []...
Compile a template into token tree :template: TODO :delimiters: TODO :returns: the root token
entailment
def _escape(self, text): """Escape text according to self.escape""" ret = EMPTYSTRING if text is None else str(text) if self.escape: return html_escape(ret) else: return ret
Escape text according to self.escape
entailment
def _lookup(self, dot_name, contexts): """lookup value for names like 'a.b.c' and handle filters as well""" # process filters filters = [x for x in map(lambda x: x.strip(), dot_name.split('|'))] dot_name = filters[0] filters = filters[1:] # should support paths like '.....
lookup value for names like 'a.b.c' and handle filters as well
entailment
def _render_children(self, contexts, partials): """Render the children tokens""" ret = [] for child in self.children: ret.append(child._render(contexts, partials)) return EMPTYSTRING.join(ret)
Render the children tokens
entailment
def _render(self, contexts, partials): """render variable""" value = self._lookup(self.value, contexts) # lambda if callable(value): value = inner_render(str(value()), contexts, partials) return self._escape(value)
render variable
entailment
def _render(self, contexts, partials): """render section""" val = self._lookup(self.value, contexts) if not val: # false value return EMPTYSTRING # normally json has types: number/string/list/map # but python has more, so we decide that map and string sho...
render section
entailment
def _render(self, contexts, partials): """render inverted section""" val = self._lookup(self.value, contexts) if val: return EMPTYSTRING return self._render_children(contexts, partials)
render inverted section
entailment
def _render(self, contexts, partials): """render partials""" try: partial = partials[self.value] except KeyError as e: return self._escape(EMPTYSTRING) partial = re_insert_indent.sub(r'\1' + ' '*self.indent, partial) return inner_render(partial, contexts...
render partials
entailment
def Setup(): ''' Called when the code is installed. Sets up directories and downloads the K2 catalog. ''' if not os.path.exists(os.path.join(EVEREST_DAT, 'k2', 'cbv')): os.makedirs(os.path.join(EVEREST_DAT, 'k2', 'cbv')) GetK2Stars(clobber=False)
Called when the code is installed. Sets up directories and downloads the K2 catalog.
entailment
def CDPP(flux, mask=[], cadence='lc'): ''' Compute the proxy 6-hr CDPP metric. :param array_like flux: The flux array to compute the CDPP for :param array_like mask: The indices to be masked :param str cadence: The light curve cadence. Default `lc` ''' # 13 cadences is 6.5 hours rmswi...
Compute the proxy 6-hr CDPP metric. :param array_like flux: The flux array to compute the CDPP for :param array_like mask: The indices to be masked :param str cadence: The light curve cadence. Default `lc`
entailment
def GetData(EPIC, season=None, cadence='lc', clobber=False, delete_raw=False, aperture_name='k2sff_15', saturated_aperture_name='k2sff_19', max_pixels=75, download_only=False, saturation_tolerance=-0.1, bad_bits=[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17], get_hir...
Returns a :py:obj:`DataContainer` instance with the raw data for the target. :param int EPIC: The EPIC ID number :param int season: The observing season (campaign). Default :py:obj:`None` :param str cadence: The light curve cadence. Default `lc` :param bool clobber: Overwrite existing files? Defaul...
entailment
def GetNeighbors(EPIC, season=None, model=None, neighbors=10, mag_range=(11., 13.), cdpp_range=None, aperture_name='k2sff_15', cadence='lc', **kwargs): ''' Return `neighbors` random bright stars on the same module as `EPIC`. :param int EPIC: The EPIC ID nu...
Return `neighbors` random bright stars on the same module as `EPIC`. :param int EPIC: The EPIC ID number :param str model: The :py:obj:`everest` model name. Only used when \ imposing CDPP bounds. Default :py:obj:`None` :param int neighbors: Number of neighbors to return. Default 10 :param st...
entailment
def PlanetStatistics(model='nPLD', compare_to='k2sff', **kwargs): ''' Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all known K2 planets. :param str model: The :py:obj:`everest` model name :param str compare_to: The :py:obj:`everest` model name or \ ...
Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all known K2 planets. :param str model: The :py:obj:`everest` model name :param str compare_to: The :py:obj:`everest` model name or \ other K2 pipeline name
entailment
def ShortCadenceStatistics(campaign=None, clobber=False, model='nPLD', plot=True, **kwargs): ''' Computes and plots the CDPP statistics comparison between short cadence and long cadence de-trended light curves :param campaign: The campaign number or list of campaign numbers. ...
Computes and plots the CDPP statistics comparison between short cadence and long cadence de-trended light curves :param campaign: The campaign number or list of campaign numbers. \ Default is to plot all campaigns :param bool clobber: Overwrite existing files? Default :py:obj:`False` :param ...
entailment
def Statistics(season=None, clobber=False, model='nPLD', injection=False, compare_to='kepler', plot=True, cadence='lc', planets=False, **kwargs): ''' Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all long cadence light curves in a given ...
Computes and plots the CDPP statistics comparison between `model` and `compare_to` for all long cadence light curves in a given campaign :param season: The campaign number or list of campaign numbers. \ Default is to plot all campaigns :param bool clobber: Overwrite existing files? Default :py:o...
entailment
def HasShortCadence(EPIC, season=None): ''' Returns `True` if short cadence data is available for this target. :param int EPIC: The EPIC ID number :param int season: The campaign number. Default :py:obj:`None` ''' if season is None: season = Campaign(EPIC) if season is None: ...
Returns `True` if short cadence data is available for this target. :param int EPIC: The EPIC ID number :param int season: The campaign number. Default :py:obj:`None`
entailment
def InjectionStatistics(campaign=0, clobber=False, model='nPLD', plot=True, show=True, **kwargs): ''' Computes and plots the statistics for injection/recovery tests. :param int campaign: The campaign number. Default 0 :param str model: The :py:obj:`everest` model name :param...
Computes and plots the statistics for injection/recovery tests. :param int campaign: The campaign number. Default 0 :param str model: The :py:obj:`everest` model name :param bool plot: Default :py:obj:`True` :param bool show: Show the plot? Default :py:obj:`True`. \ If :py:obj:`False`, retur...
entailment
def HDUCards(headers, hdu=0): ''' Generates HDU cards for inclusion in the de-trended light curve FITS file. Used internally. ''' if headers is None: return [] if hdu == 0: # Get info from the TPF Primary HDU Header tpf_header = headers[0] entries = ['TELESCOP'...
Generates HDU cards for inclusion in the de-trended light curve FITS file. Used internally.
entailment
def TargetDirectory(ID, season, relative=False, **kwargs): ''' Returns the location of the :py:mod:`everest` data on disk for a given target. :param ID: The target ID :param int season: The target season number :param bool relative: Relative path? Default :py:obj:`False` ''' if season...
Returns the location of the :py:mod:`everest` data on disk for a given target. :param ID: The target ID :param int season: The target season number :param bool relative: Relative path? Default :py:obj:`False`
entailment
def DVSFile(ID, season, cadence='lc'): ''' Returns the name of the DVS PDF for a given target. :param ID: The target ID :param int season: The target season number :param str cadence: The cadence type. Default `lc` ''' if cadence == 'sc': strcadence = '_sc' else: strca...
Returns the name of the DVS PDF for a given target. :param ID: The target ID :param int season: The target season number :param str cadence: The cadence type. Default `lc`
entailment
def GetTargetCBVs(model): ''' Returns the design matrix of CBVs for the given target. :param model: An instance of the :py:obj:`everest` model for the target ''' # Get the info season = model.season name = model.name # We use the LC light curves as CBVs; there aren't # enough SC ...
Returns the design matrix of CBVs for the given target. :param model: An instance of the :py:obj:`everest` model for the target
entailment
def FitCBVs(model): ''' Fits the CBV design matrix to the de-trended flux of a given target. This is called internally whenever the user accesses the :py:attr:`fcor` attribute. :param model: An instance of the :py:obj:`everest` model for the target ''' # Get cbvs? if model.XCBV is Non...
Fits the CBV design matrix to the de-trended flux of a given target. This is called internally whenever the user accesses the :py:attr:`fcor` attribute. :param model: An instance of the :py:obj:`everest` model for the target
entailment
def StatsToCSV(campaign, model='nPLD'): ''' Generate the CSV file used in the search database for the documentation. ''' statsfile = os.path.join(EVEREST_SRC, 'missions', 'k2', 'tables', 'c%02d_%s.cdpp' % (campaign, model)) csvfile = os.path.join(os.path.dirname(EVEREST_...
Generate the CSV file used in the search database for the documentation.
entailment
def remove(self, item): '''Remove ``item`` for the :class:`zset` it it exists. If found it returns the score of the item removed.''' score = self._dict.pop(item, None) if score is not None: self._sl.remove(score) return score
Remove ``item`` for the :class:`zset` it it exists. If found it returns the score of the item removed.
entailment
def fields(self): '''Return a tuple of ordered fields for this :class:`ColumnTS`.''' key = self.id + ':fields' encoding = self.client.encoding return tuple(sorted((f.decode(encoding) for f in self.client.smembers(key))))
Return a tuple of ordered fields for this :class:`ColumnTS`.
entailment
def do_pending_lookups(event, sender, **kwargs): """Handle any pending relations to the sending model. Sent from class_prepared.""" key = (sender._meta.app_label, sender._meta.name) for callback in pending_lookups.pop(key, []): callback(sender)
Handle any pending relations to the sending model. Sent from class_prepared.
entailment
def Many2ManyThroughModel(field): '''Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys.''' from stdnet.odm import ModelType, StdModel, ForeignKey, CompositeIdField name_model = field.model._meta.name name_relmodel = field.relmodel....
Create a Many2Many through model with two foreign key fields and a CompositeFieldId depending on the two foreign keys.
entailment
def makeMany2ManyRelatedManager(formodel, name_relmodel, name_formodel): '''formodel is the model which the manager .''' class _Many2ManyRelatedManager(Many2ManyRelatedManager): pass _Many2ManyRelatedManager.formodel = formodel _Many2ManyRelatedManager.name_relmodel = name_relmodel ...
formodel is the model which the manager .
entailment
def session(self, session=None): '''Override :meth:`Manager.session` so that this :class:`RelatedManager` can retrieve the session from the :attr:`related_instance` if available. ''' if self.related_instance: session = self.related_instance.session # we...
Override :meth:`Manager.session` so that this :class:`RelatedManager` can retrieve the session from the :attr:`related_instance` if available.
entailment
def add(self, value, session=None, **kwargs): '''Add ``value``, an instance of :attr:`formodel` to the :attr:`through` model. This method can only be accessed by an instance of the model for which this related manager is an attribute.''' s, instance = self.session_instance('add', value, session, **k...
Add ``value``, an instance of :attr:`formodel` to the :attr:`through` model. This method can only be accessed by an instance of the model for which this related manager is an attribute.
entailment
def remove(self, value, session=None): '''Remove *value*, an instance of ``self.model`` from the set of elements contained by the field.''' s, instance = self.session_instance('remove', value, session) # update state so that the instance does look persistent instance.get_state(iid=i...
Remove *value*, an instance of ``self.model`` from the set of elements contained by the field.
entailment
def metaphone_processor(words): '''Double metaphone word processor.''' for word in words: for w in double_metaphone(word): if w: w = w.strip() if w: yield w
Double metaphone word processor.
entailment
def tolerant_metaphone_processor(words): '''Double metaphone word processor slightly modified so that when no words are returned by the algorithm, the original word is returned.''' for word in words: r = 0 for w in double_metaphone(word): if w: w = w.strip() ...
Double metaphone word processor slightly modified so that when no words are returned by the algorithm, the original word is returned.
entailment
def stemming_processor(words): '''Porter Stemmer word processor''' stem = PorterStemmer().stem for word in words: word = stem(word, 0, len(word)-1) yield word
Porter Stemmer word processor
entailment
def Pool(pool='AnyPool', **kwargs): ''' Chooses between the different pools. If ``pool == 'AnyPool'``, chooses based on availability. ''' if pool == 'MPIPool': return MPIPool(**kwargs) elif pool == 'MultiPool': return MultiPool(**kwargs) elif pool == 'SerialPool': r...
Chooses between the different pools. If ``pool == 'AnyPool'``, chooses based on availability.
entailment
def wait(self): """ If this isn't the master process, wait for instructions. """ if self.is_master(): raise RuntimeError("Master node told to await jobs.") status = MPI.Status() while True: # Event loop. # Sit here and await instruct...
If this isn't the master process, wait for instructions.
entailment
def map(self, function, tasks): """ Like the built-in :py:func:`map` function, apply a function to all of the values in a list and return the list of results. :param function: The function to apply to the list. :param tasks: The list of elements. ...
Like the built-in :py:func:`map` function, apply a function to all of the values in a list and return the list of results. :param function: The function to apply to the list. :param tasks: The list of elements.
entailment
def close(self): """ Just send a message off to all the pool members which contains the special :class:`_close_pool_message` sentinel. """ if self.is_master(): for i in range(self.size): self.comm.isend(_close_pool_message(), dest=i + 1)
Just send a message off to all the pool members which contains the special :class:`_close_pool_message` sentinel.
entailment
def commit_when_no_transaction(f): '''Decorator for committing changes when the instance session is not in a transaction.''' def _(self, *args, **kwargs): r = f(self, *args, **kwargs) return self.session.add(self) if self.session is not None else r _.__name__ = f.__name__ _.__doc_...
Decorator for committing changes when the instance session is not in a transaction.
entailment
def backend(self): '''Returns the :class:`stdnet.BackendStructure`. ''' session = self.session if session is not None: if self._field: return session.model(self._field.model).backend else: return session.model(self).backend
Returns the :class:`stdnet.BackendStructure`.
entailment
def read_backend(self): '''Returns the :class:`stdnet.BackendStructure`. ''' session = self.session if session is not None: if self._field: return session.model(self._field.model).read_backend else: return session.model(self...
Returns the :class:`stdnet.BackendStructure`.
entailment
def size(self): '''Number of elements in the :class:`Structure`.''' if self.cache.cache is None: return self.read_backend_structure().size() else: return len(self.cache.cache)
Number of elements in the :class:`Structure`.
entailment
def load_data(self, data, callback=None): '''Load ``data`` from the :class:`stdnet.BackendDataServer`.''' return self.backend.execute( self.value_pickler.load_iterable(data, self.session), callback)
Load ``data`` from the :class:`stdnet.BackendDataServer`.
entailment
def values(self): '''Iteratir over values of :class:`PairMixin`.''' if self.cache.cache is None: backend = self.read_backend return backend.execute(backend.structure(self).values(), self.load_values) else: return self....
Iteratir over values of :class:`PairMixin`.
entailment
def pair(self, pair): '''Add a *pair* to the structure.''' if len(pair) == 1: # if only one value is passed, the value must implement a # score function which retrieve the first value of the pair # (score in zset, timevalue in timeseries, field value in ...
Add a *pair* to the structure.
entailment
def remove(self, *keys): '''Remove *keys* from the key-value container.''' dumps = self.pickler.dumps self.cache.remove([dumps(v) for v in keys])
Remove *keys* from the key-value container.
entailment
def count(self, start, stop): '''Count the number of elements bewteen *start* and *stop*.''' s1 = self.pickler.dumps(start) s2 = self.pickler.dumps(stop) return self.backend_structure().count(s1, s2)
Count the number of elements bewteen *start* and *stop*.
entailment
def irange(self, start=0, end=-1, callback=None, withscores=True, **options): '''Return the range by rank between start and end.''' backend = self.read_backend res = backend.structure(self).irange(start, end, withscores=withscores,...
Return the range by rank between start and end.
entailment
def pop_range(self, start, stop, callback=None, withscores=True): '''pop a range by score from the :class:`OrderedMixin`''' s1 = self.pickler.dumps(start) s2 = self.pickler.dumps(stop) backend = self.backend res = backend.structure(self).pop_range(s1, s2, withscores=withscor...
pop a range by score from the :class:`OrderedMixin`
entailment
def ipop_range(self, start=0, stop=-1, callback=None, withscores=True): '''pop a range from the :class:`OrderedMixin`''' backend = self.backend res = backend.structure(self).ipop_range(start, stop, withscores=withscores) if not callba...
pop a range from the :class:`OrderedMixin`
entailment
def push_back(self, value): '''Appends a copy of *value* at the end of the :class:`Sequence`.''' self.cache.push_back(self.value_pickler.dumps(value)) return self
Appends a copy of *value* at the end of the :class:`Sequence`.
entailment
def pop_back(self): '''Remove the last element from the :class:`Sequence`.''' backend = self.backend return backend.execute(backend.structure(self).pop_back(), self.value_pickler.loads)
Remove the last element from the :class:`Sequence`.
entailment
def add(self, value): '''Add *value* to the set''' return self.cache.update((self.value_pickler.dumps(value),))
Add *value* to the set
entailment
def update(self, values): '''Add iterable *values* to the set''' d = self.value_pickler.dumps return self.cache.update(tuple((d(v) for v in values)))
Add iterable *values* to the set
entailment
def discard(self, value): '''Remove an element *value* from a set if it is a member.''' return self.cache.remove((self.value_pickler.dumps(value),))
Remove an element *value* from a set if it is a member.
entailment
def difference_update(self, values): '''Remove an iterable of *values* from the set.''' d = self.value_pickler.dumps return self.cache.remove(tuple((d(v) for v in values)))
Remove an iterable of *values* from the set.
entailment
def pop_front(self): '''Remove the first element from of the list.''' backend = self.backend return backend.execute(backend.structure(self).pop_front(), self.value_pickler.loads)
Remove the first element from of the list.
entailment
def block_pop_back(self, timeout=10): '''Remove the last element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.''' value = yield self.backend_structure().block_pop_back(timeout) if value is not None: yield self.value_pickler.loads(value)
Remove the last element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.
entailment
def block_pop_front(self, timeout=10): '''Remove the first element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.''' value = yield self.backend_structure().block_pop_front(timeout) if value is not None: yield self.value_pickler.loads(val...
Remove the first element from of the list. If no elements are available, blocks for at least ``timeout`` seconds.
entailment
def push_front(self, value): '''Appends a copy of ``value`` to the beginning of the list.''' self.cache.push_front(self.value_pickler.dumps(value))
Appends a copy of ``value`` to the beginning of the list.
entailment
def rank(self, value): '''The rank of a given *value*. This is the position of *value* in the :class:`OrderedMixin` container.''' value = self.value_pickler.dumps(value) return self.backend_structure().rank(value)
The rank of a given *value*. This is the position of *value* in the :class:`OrderedMixin` container.
entailment
def rank(self, dte): '''The rank of a given *dte* in the timeseries''' timestamp = self.pickler.dumps(dte) return self.backend_structure().rank(timestamp)
The rank of a given *dte* in the timeseries
entailment
def ipop(self, index): '''Pop a value at *index* from the :class:`TS`. Return ``None`` if index is not out of bound.''' backend = self.backend res = backend.structure(self).ipop(index) return backend.execute(res, lambda r: self._load_get_data(r, index...
Pop a value at *index* from the :class:`TS`. Return ``None`` if index is not out of bound.
entailment
def times(self, start, stop, callback=None, **kwargs): '''The times between times *start* and *stop*.''' s1 = self.pickler.dumps(start) s2 = self.pickler.dumps(stop) backend = self.read_backend res = backend.structure(self).times(s1, s2, **kwargs) return backend.exe...
The times between times *start* and *stop*.
entailment
def itimes(self, start=0, stop=-1, callback=None, **kwargs): '''The times between rank *start* and *stop*.''' backend = self.read_backend res = backend.structure(self).itimes(start, stop, **kwargs) return backend.execute(res, callback or self.load_keys)
The times between rank *start* and *stop*.
entailment
def get_field(self, field): '''A :class:`Q` performs a series of operations and ultimately generate of set of matched elements ``ids``. If on the other hand, a different field is required, it can be specified with the :meth:`get_field` method. For example, lets say a model has a field called ``object_id`` ...
A :class:`Q` performs a series of operations and ultimately generate of set of matched elements ``ids``. If on the other hand, a different field is required, it can be specified with the :meth:`get_field` method. For example, lets say a model has a field called ``object_id`` which contains ids of another model, we ...
entailment
def filter(self, **kwargs): '''Create a new :class:`Query` with additional clauses corresponding to ``where`` or ``limit`` in a ``SQL SELECT`` statement. :parameter kwargs: dictionary of limiting clauses. :rtype: a new :class:`Query` instance. For example:: qs = session.query(MyModel) resul...
Create a new :class:`Query` with additional clauses corresponding to ``where`` or ``limit`` in a ``SQL SELECT`` statement. :parameter kwargs: dictionary of limiting clauses. :rtype: a new :class:`Query` instance. For example:: qs = session.query(MyModel) result = qs.filter(group = 'planet')
entailment
def exclude(self, **kwargs): '''Returns a new :class:`Query` with additional clauses corresponding to ``EXCEPT`` in a ``SQL SELECT`` statement. :parameter kwargs: dictionary of limiting clauses. :rtype: a new :class:`Query` instance. Using an equivalent example to the :meth:`filter` method:: qs ...
Returns a new :class:`Query` with additional clauses corresponding to ``EXCEPT`` in a ``SQL SELECT`` statement. :parameter kwargs: dictionary of limiting clauses. :rtype: a new :class:`Query` instance. Using an equivalent example to the :meth:`filter` method:: qs = session.query(MyModel) result1 = q...
entailment
def union(self, *queries): '''Return a new :class:`Query` obtained form the union of this :class:`Query` with one or more *queries*. For example, lets say we want to have the union of two queries obtained from the :meth:`filter` method:: query = session.query(MyModel) qs = query.filter(field1 = ...
Return a new :class:`Query` obtained form the union of this :class:`Query` with one or more *queries*. For example, lets say we want to have the union of two queries obtained from the :meth:`filter` method:: query = session.query(MyModel) qs = query.filter(field1 = 'bla').union(query.filter(field2 = 'foo...
entailment
def intersect(self, *queries): '''Return a new :class:`Query` obtained form the intersection of this :class:`Query` with one or more *queries*. Workds the same way as the :meth:`union` method.''' q = self._clone() q.intersections += queries return q
Return a new :class:`Query` obtained form the intersection of this :class:`Query` with one or more *queries*. Workds the same way as the :meth:`union` method.
entailment
def sort_by(self, ordering): '''Sort the query by the given field :parameter ordering: a string indicating the class:`Field` name to sort by. If prefixed with ``-``, the sorting will be in descending order, otherwise in ascending order. :return type: a new :class:`Query` instance. ''' i...
Sort the query by the given field :parameter ordering: a string indicating the class:`Field` name to sort by. If prefixed with ``-``, the sorting will be in descending order, otherwise in ascending order. :return type: a new :class:`Query` instance.
entailment
def search(self, text, lookup=None): '''Search *text* in model. A search engine needs to be installed for this function to be available. :parameter text: a string to search. :return type: a new :class:`Query` instance. ''' q = self._clone() q.text = (text, lookup) return q
Search *text* in model. A search engine needs to be installed for this function to be available. :parameter text: a string to search. :return type: a new :class:`Query` instance.
entailment
def where(self, code, load_only=None): '''For :ref:`backend <db-index>` supporting scripting, it is possible to construct complex queries which execute the scripting *code* against each element in the query. The *coe* should reference an instance of :attr:`model` by ``this`` keyword. :parameter code: a v...
For :ref:`backend <db-index>` supporting scripting, it is possible to construct complex queries which execute the scripting *code* against each element in the query. The *coe* should reference an instance of :attr:`model` by ``this`` keyword. :parameter code: a valid expression in the scripting language of the da...
entailment
def search_queries(self, q): '''Return a new :class:`QueryElem` for *q* applying a text search.''' if self.text: searchengine = self.session.router.search_engine if searchengine: return searchengine.search_model(q, *self.text) else: ...
Return a new :class:`QueryElem` for *q* applying a text search.
entailment
def load_related(self, related, *related_fields): '''It returns a new :class:`Query` that automatically follows the foreign-key relationship ``related``. :parameter related: A field name corresponding to a :class:`ForeignKey` in :attr:`Query.model`. :parameter related_fields: optional :class:`Field` ...
It returns a new :class:`Query` that automatically follows the foreign-key relationship ``related``. :parameter related: A field name corresponding to a :class:`ForeignKey` in :attr:`Query.model`. :parameter related_fields: optional :class:`Field` names for the ``related`` model to load. If not provided,...
entailment
def load_only(self, *fields): '''This is provides a :ref:`performance boost <increase-performance>` in cases when you need to load a subset of fields of your model. The boost achieved is less than the one obtained when using :meth:`Query.load_related`, since it does not reduce the number of requests to the...
This is provides a :ref:`performance boost <increase-performance>` in cases when you need to load a subset of fields of your model. The boost achieved is less than the one obtained when using :meth:`Query.load_related`, since it does not reduce the number of requests to the database. However, it can save you lots o...
entailment
def dont_load(self, *fields): '''Works like :meth:`load_only` to provides a :ref:`performance boost <increase-performance>` in cases when you need to load all fields except a subset specified by *fields*. ''' q = self._clone() fs = unique_tuple(q.exclude_fields, fields) q.exclude_...
Works like :meth:`load_only` to provides a :ref:`performance boost <increase-performance>` in cases when you need to load all fields except a subset specified by *fields*.
entailment
def get(self, **kwargs): '''Return an instance of a model matching the query. A special case is the query on ``id`` which provides a direct access to the :attr:`session` instances. If the given primary key is present in the session, the object is returned directly without performing any query.''' r...
Return an instance of a model matching the query. A special case is the query on ``id`` which provides a direct access to the :attr:`session` instances. If the given primary key is present in the session, the object is returned directly without performing any query.
entailment
def construct(self): '''Build the :class:`QueryElement` representing this query.''' if self.__construct is None: self.__construct = self._construct() return self.__construct
Build the :class:`QueryElement` representing this query.
entailment
def backend_query(self, **kwargs): '''Build and return the :class:`stdnet.utils.async.BackendQuery`. This is a lazy method in the sense that it is evaluated once only and its result stored for future retrieval.''' q = self.construct() return q if isinstance(q, EmptyQuery) else q.backend_que...
Build and return the :class:`stdnet.utils.async.BackendQuery`. This is a lazy method in the sense that it is evaluated once only and its result stored for future retrieval.
entailment
def aggregate(self, kwargs): '''Aggregate lookup parameters.''' meta = self._meta fields = meta.dfields field_lookups = {} for name, value in iteritems(kwargs): bits = name.split(JSPLITTER) field_name = bits.pop(0) if field_name not in ...
Aggregate lookup parameters.
entailment
def models_from_model(model, include_related=False, exclude=None): '''Generator of all model in model.''' if exclude is None: exclude = set() if model and model not in exclude: exclude.add(model) if isinstance(model, ModelType) and not model._meta.abstract: yield model ...
Generator of all model in model.
entailment
def model_iterator(application, include_related=True, exclude=None): '''A generator of :class:`StdModel` classes found in *application*. :parameter application: A python dotted path or an iterable over python dotted-paths where models are defined. Only models defined in these paths are considered. For exampl...
A generator of :class:`StdModel` classes found in *application*. :parameter application: A python dotted path or an iterable over python dotted-paths where models are defined. Only models defined in these paths are considered. For example:: from stdnet.odm import model_iterator APPS = ('stdnet.contrib....
entailment
def set_search_engine(self, engine): '''Set the search ``engine`` for this :class:`Router`.''' self._search_engine = engine self._search_engine.set_router(self)
Set the search ``engine`` for this :class:`Router`.
entailment
def register(self, model, backend=None, read_backend=None, include_related=True, **params): '''Register a :class:`Model` with this :class:`Router`. If the model was already registered it does nothing. :param model: a :class:`Model` class. :param backend: a :class:`stdnet.BackendDataServer` or ...
Register a :class:`Model` with this :class:`Router`. If the model was already registered it does nothing. :param model: a :class:`Model` class. :param backend: a :class:`stdnet.BackendDataServer` or a :ref:`connection string <connection-string>`. :param read_backend: Optional :class:`stdnet.BackendDataServer` for ...
entailment
def from_uuid(self, uuid, session=None): '''Retrieve a :class:`Model` from its universally unique identifier ``uuid``. If the ``uuid`` does not match any instance an exception will raise. ''' elems = uuid.split('.') if len(elems) == 2: model = get_model_from_hash(elems[0]) ...
Retrieve a :class:`Model` from its universally unique identifier ``uuid``. If the ``uuid`` does not match any instance an exception will raise.
entailment
def flush(self, exclude=None, include=None, dryrun=False): '''Flush :attr:`registered_models`. :param exclude: optional list of model names to exclude. :param include: optional list of model names to include. :param dryrun: Doesn't remove anything, simply collect managers to...
Flush :attr:`registered_models`. :param exclude: optional list of model names to exclude. :param include: optional list of model names to include. :param dryrun: Doesn't remove anything, simply collect managers to flush. :return:
entailment
def unregister(self, model=None): '''Unregister a ``model`` if provided, otherwise it unregister all registered models. Return a list of unregistered model managers or ``None`` if no managers were removed.''' if model is not None: try: manager = self._registered_models.pop(mo...
Unregister a ``model`` if provided, otherwise it unregister all registered models. Return a list of unregistered model managers or ``None`` if no managers were removed.
entailment
def register_applications(self, applications, models=None, backends=None): '''A higher level registration functions for group of models located on application modules. It uses the :func:`model_iterator` function to iterate through all :class:`Model` models available in ``applications`` and register them using t...
A higher level registration functions for group of models located on application modules. It uses the :func:`model_iterator` function to iterate through all :class:`Model` models available in ``applications`` and register them using the :func:`register` low level method. :parameter applications: A String or a list of ...
entailment
def execute_script(self, name, keys, *args, **options): '''Execute a script. makes sure all required scripts are loaded. ''' script = get_script(name) if not script: raise redis.RedisError('No such script "%s"' % name) address = self.address() if addr...
Execute a script. makes sure all required scripts are loaded.
entailment
def register(self, model, related=None): '''Register a :class:`StdModel` with this search :class:`SearchEngine`. When registering a model, every time an instance is created, it will be indexed by the search engine. :param model: a :class:`StdModel` class. :param related: a list of related fields to inclu...
Register a :class:`StdModel` with this search :class:`SearchEngine`. When registering a model, every time an instance is created, it will be indexed by the search engine. :param model: a :class:`StdModel` class. :param related: a list of related fields to include in the index.
entailment
def words_from_text(self, text, for_search=False): '''Generator of indexable words in *text*. This functions loop through the :attr:`word_middleware` attribute to process the text. :param text: string from which to extract words. :param for_search: flag indicating if the the words will be used for search...
Generator of indexable words in *text*. This functions loop through the :attr:`word_middleware` attribute to process the text. :param text: string from which to extract words. :param for_search: flag indicating if the the words will be used for search or to index the database. This flug is used in conjunctio...
entailment
def add_word_middleware(self, middleware, for_search=True): '''Add a *middleware* function to the list of :attr:`word_middleware`, for preprocessing words to be indexed. :param middleware: a callable receving an iterable over words. :param for_search: flag indicating if the *middleware* can be used for th...
Add a *middleware* function to the list of :attr:`word_middleware`, for preprocessing words to be indexed. :param middleware: a callable receving an iterable over words. :param for_search: flag indicating if the *middleware* can be used for the text to search. Default: ``True``.
entailment
def query(self, model): '''Return a query for ``model`` when it needs to be indexed. ''' session = self.router.session() fields = tuple((f.name for f in model._meta.scalarfields if f.type == 'text')) qs = session.query(model).load_only(*fields) ...
Return a query for ``model`` when it needs to be indexed.
entailment
def get_version(version): "Returns a PEP 386-compliant version number from *version*." assert len(version) == 5 assert version[3] in ('alpha', 'beta', 'rc', 'final') parts = 2 if version[2] == 0 else 3 main = '.'.join(map(str, version[:parts])) sub = '' if version[3] == 'alpha' and ve...
Returns a PEP 386-compliant version number from *version*.
entailment
def Get_RpRs(d, **kwargs): ''' Returns the value of the planet radius over the stellar radius for a given depth :py:obj:`d`, given the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`. ''' if ps is None: raise Exception("Unable to import `pysyzygy`.") def Depth(RpRs, **kwa...
Returns the value of the planet radius over the stellar radius for a given depth :py:obj:`d`, given the :py:class:`everest.pysyzygy` transit :py:obj:`kwargs`.
entailment