code
stringlengths
1
18.2k
def check_lazy_load_gebouw(f): ''' Decorator function to lazy load a :class:`Gebouw`. ''' def wrapper(*args): gebouw = args[0] if ( gebouw._methode_id is None or gebouw._geometrie is None or gebouw._metadata is None ): log.debug('Lazy loading Gebouw %d', gebouw.id) gebouw.check_gateway() g = gebouw.gateway.get_gebouw_b...
def check_lazy_load_subadres(f): ''' Decorator function to lazy load a :class:`Subadres`. ''' def wrapper(*args): subadres = args[0] if ( subadres._metadata is None or subadres.aard_id is None or subadres.huisnummer_id is None ): log.debug('Lazy loading Subadres %d', subadres.id) subadres.check_gateway() s = subadres.g...
def check_lazy_load_adrespositie(f): ''' Decorator function to lazy load a :class:`Adrespositie`. ''' def wrapper(*args): adrespositie = args[0] if ( adrespositie._geometrie is None or adrespositie._aard is None or adrespositie._metadata is None ): log.debug('Lazy loading Adrespositie %d', adrespositie.id) adrespositie...
def list_gewesten(self, sort=1): ''' List all `gewesten` in Belgium. :param integer sort: What field to sort on. :rtype: A :class`list` of class: `Gewest`. ''' def creator(): res = crab_gateway_request(self.client, 'ListGewesten', sort) tmp = {} for r in res.GewestItem: if r.GewestId not in tmp: tmp[r.GewestId] = {} tm...
def get_gewest_by_id(self, id): ''' Get a `gewest` by id. :param integer id: The id of a `gewest`. :rtype: A :class:`Gewest`. ''' def creator(): nl = crab_gateway_request( self.client, 'GetGewestByGewestIdAndTaalCode', id, 'nl' ) fr = crab_gateway_request( self.client, 'GetGewestByGewestIdAndTaalCode', id, 'fr' ) de = ...
def list_provincies(self, gewest=2): ''' List all `provincies` in a `gewest`. :param gewest: The :class:`Gewest` for which the \ `provincies` are wanted. :param integer sort: What field to sort on. :rtype: A :class:`list` of :class:`Provincie`. ''' try: gewest_id = gewest.id except AttributeError: gewest_id = gewest de...
def get_provincie_by_id(self, niscode): ''' Retrieve a `provincie` by the niscode. :param integer niscode: The niscode of the provincie. :rtype: :class:`Provincie` ''' def creator(): for p in self.provincies: if p[0] == niscode: return Provincie(p[0], p[1], Gewest(p[2])) if self.caches['permanent'].is_configured: key =...
def list_gemeenten_by_provincie(self, provincie): ''' List all `gemeenten` in a `provincie`. :param provincie: The :class:`Provincie` for which the \ `gemeenten` are wanted. :rtype: A :class:`list` of :class:`Gemeente`. ''' try: gewest = provincie.gewest prov = provincie except AttributeError: prov = self.get_provincie...
def list_gemeenten(self, gewest=2, sort=1): ''' List all `gemeenten` in a `gewest`. :param gewest: The :class:`Gewest` for which the \ `gemeenten` are wanted. :param integer sort: What field to sort on. :rtype: A :class:`list` of :class:`Gemeente`. ''' try: gewest_id = gewest.id except AttributeError: gewest_id = gewes...
def get_gemeente_by_id(self, id): ''' Retrieve a `gemeente` by the crab id. :param integer id: The CRAB id of the gemeente. :rtype: :class:`Gemeente` ''' def creator(): res = crab_gateway_request( self.client, 'GetGemeenteByGemeenteId', id ) if res == None: raise GatewayResourceNotFoundException() return Gemeente( res....
def list_deelgemeenten(self, gewest=2): ''' List all `deelgemeenten` in a `gewest`. :param gewest: The :class:`Gewest` for which the \ `deelgemeenten` are wanted. Currently only Flanders is supported. :rtype: A :class:`list` of :class:`Deelgemeente`. ''' try: gewest_id = gewest.id except AttributeError: gewest_id = gew...
def list_deelgemeenten_by_gemeente(self, gemeente): ''' List all `deelgemeenten` in a `gemeente`. :param gemeente: The :class:`Gemeente` for which the \ `deelgemeenten` are wanted. Currently only Flanders is supported. :rtype: A :class:`list` of :class:`Deelgemeente`. ''' try: niscode = gemeente.niscode except Attribut...
def get_deelgemeente_by_id(self, id): ''' Retrieve a `deelgemeente` by the id. :param string id: The id of the deelgemeente. :rtype: :class:`Deelgemeente` ''' def creator(): if id in self.deelgemeenten: dg = self.deelgemeenten[id] return Deelgemeente(dg['id'], dg['naam'], dg['gemeente_niscode']) else: return None if se...
def list_straten(self, gemeente, sort=1): ''' List all `straten` in a `Gemeente`. :param gemeente: The :class:`Gemeente` for which the \ `straten` are wanted. :rtype: A :class:`list` of :class:`Straat` ''' try: id = gemeente.id except AttributeError: id = gemeente def creator(): res = crab_gateway_request( self.client,...
def get_straat_by_id(self, id): ''' Retrieve a `straat` by the Id. :param integer id: The id of the `straat`. :rtype: :class:`Straat` ''' def creator(): res = crab_gateway_request( self.client, 'GetStraatnaamWithStatusByStraatnaamId', id ) if res == None: raise GatewayResourceNotFoundException() return Straat( res.Stra...
def list_huisnummers_by_straat(self, straat, sort=1): ''' List all `huisnummers` in a `Straat`. :param straat: The :class:`Straat` for which the \ `huisnummers` are wanted. :rtype: A :class: `list` of :class:`Huisnummer` ''' try: id = straat.id except AttributeError: id = straat def creator(): res = crab_gateway_reques...
def list_huisnummers_by_perceel(self, perceel, sort=1): ''' List all `huisnummers` on a `Pereel`. Generally there will only be one, but multiples are possible. :param perceel: The :class:`Perceel` for which the \ `huisnummers` are wanted. :rtype: A :class: `list` of :class:`Huisnummer` ''' try: id = perceel.id except A...
def get_huisnummer_by_id(self, id): ''' Retrieve a `huisnummer` by the Id. :param integer id: the Id of the `huisnummer` :rtype: :class:`Huisnummer` ''' def creator(): res = crab_gateway_request( self.client, 'GetHuisnummerWithStatusByHuisnummerId', id ) if res == None: raise GatewayResourceNotFoundException() return H...
def list_postkantons_by_gemeente(self, gemeente): ''' List all `postkantons` in a :class:`Gemeente` :param gemeente: The :class:`Gemeente` for which the \ `potkantons` are wanted. :rtype: A :class:`list` of :class:`Postkanton` ''' try: id = gemeente.id except AttributeError: id = gemeente def creator(): res = crab_gate...
def get_postkanton_by_huisnummer(self, huisnummer): ''' Retrieve a `postkanton` by the Huisnummer. :param huisnummer: The :class:`Huisnummer` for which the `postkanton` \ is wanted. :rtype: :class:`Postkanton` ''' try: id = huisnummer.id except AttributeError: id = huisnummer def creator(): res = crab_gateway_request( ...
def get_wegobject_by_id(self, id): ''' Retrieve a `Wegobject` by the Id. :param integer id: the Id of the `Wegobject` :rtype: :class:`Wegobject` ''' def creator(): res = crab_gateway_request( self.client, 'GetWegobjectByIdentificatorWegobject', id ) if res == None: raise GatewayResourceNotFoundException() return Wegobj...
def list_wegobjecten_by_straat(self, straat): ''' List all `wegobjecten` in a :class:`Straat` :param straat: The :class:`Straat` for which the `wegobjecten` \ are wanted. :rtype: A :class:`list` of :class:`Wegobject` ''' try: id = straat.id except AttributeError: id = straat def creator(): res = crab_gateway_request( s...
def get_wegsegment_by_id(self, id): ''' Retrieve a `wegsegment` by the Id. :param integer id: the Id of the `wegsegment` :rtype: :class:`Wegsegment` ''' def creator(): res = crab_gateway_request( self.client, 'GetWegsegmentByIdentificatorWegsegment', id ) if res == None: raise GatewayResourceNotFoundException() return ...
def list_wegsegmenten_by_straat(self, straat): ''' List all `wegsegmenten` in a :class:`Straat` :param straat: The :class:`Straat` for which the `wegsegmenten` \ are wanted. :rtype: A :class:`list` of :class:`Wegsegment` ''' try: id = straat.id except AttributeError: id = straat def creator(): res = crab_gateway_reques...
def list_terreinobjecten_by_huisnummer(self, huisnummer): ''' List all `terreinobjecten` for a :class:`Huisnummer` :param huisnummer: The :class:`Huisnummer` for which the \ `terreinobjecten` are wanted. :rtype: A :class:`list` of :class:`Terreinobject` ''' try: id = huisnummer.id except AttributeError: id = huisnummer...
def get_terreinobject_by_id(self, id): ''' Retrieve a `Terreinobject` by the Id. :param integer id: the Id of the `Terreinobject` :rtype: :class:`Terreinobject` ''' def creator(): res = crab_gateway_request( self.client, 'GetTerreinobjectByIdentificatorTerreinobject', id ) if res == None: raise GatewayResourceNotFoundE...
def list_percelen_by_huisnummer(self, huisnummer): ''' List all `percelen` for a :class:`Huisnummer` :param huisnummer: The :class:`Huisnummer` for which the \ `percelen` are wanted. :rtype: A :class:`list` of :class:`Perceel` ''' try: id = huisnummer.id except AttributeError: id = huisnummer def creator(): res = crab_...
def get_perceel_by_id(self, id): ''' Retrieve a `Perceel` by the Id. :param string id: the Id of the `Perceel` :rtype: :class:`Perceel` ''' def creator(): res = crab_gateway_request( self.client, 'GetPerceelByIdentificatorPerceel', id ) if res == None: raise GatewayResourceNotFoundException() return Perceel( res.Identi...
def list_gebouwen_by_huisnummer(self, huisnummer): ''' List all `gebouwen` for a :class:`Huisnummer`. :param huisnummer: The :class:`Huisnummer` for which the \ `gebouwen` are wanted. :rtype: A :class:`list` of :class:`Gebouw` ''' try: id = huisnummer.id except AttributeError: id = huisnummer def creator(): res = crab_...
def get_gebouw_by_id(self, id): ''' Retrieve a `Gebouw` by the Id. :param integer id: the Id of the `Gebouw` :rtype: :class:`Gebouw` ''' def creator(): res = crab_gateway_request( self.client, 'GetGebouwByIdentificatorGebouw', id ) if res == None: raise GatewayResourceNotFoundException() return Gebouw( res.Identificato...
def list_subadressen_by_huisnummer(self, huisnummer): ''' List all `subadressen` for a :class:`Huisnummer`. :param huisnummer: The :class:`Huisnummer` for which the \ `subadressen` are wanted. OR A huisnummer id. :rtype: A :class:`list` of :class:`Gebouw` ''' try: id = huisnummer.id except AttributeError: id = huisnumm...
def get_subadres_by_id(self, id): ''' Retrieve a `Subadres` by the Id. :param integer id: the Id of the `Subadres` :rtype: :class:`Subadres` ''' def creator(): res = crab_gateway_request( self.client, 'GetSubadresWithStatusBySubadresId', id ) if res == None: raise GatewayResourceNotFoundException() return Subadres( res...
def list_adresposities_by_nummer_and_straat(self, nummer, straat): ''' List all `adresposities` for a huisnummer and a :class:`Straat`. :param nummer: A string representing a certain huisnummer. :param straat: The :class:`Straat` for which the \ `adresposities` are wanted. OR A straat id. :rtype: A :class:`list` of :cl...
def list_adresposities_by_subadres_and_huisnummer(self, subadres, huisnummer): ''' List all `adresposities` for a subadres and a :class:`Huisnummer`. :param subadres: A string representing a certain subadres. :param huisnummer: The :class:`Huisnummer` for which the \ `adresposities` are wanted. OR A huisnummer id. :rty...
def get_adrespositie_by_id(self, id): ''' Retrieve a `Adrespositie` by the Id. :param integer id: the Id of the `Adrespositie` :rtype: :class:`Adrespositie` ''' def creator(): res = crab_gateway_request( self.client, 'GetAdrespositieByAdrespositieId', id ) if res == None: raise GatewayResourceNotFoundException() return...
def get_postadres_by_huisnummer(self, huisnummer): ''' Get the `postadres` for a :class:`Huisnummer`. :param huisnummer: The :class:`Huisnummer` for which the \ `postadres` is wanted. OR A huisnummer id. :rtype: A :class:`str`. ''' try: id = huisnummer.id except AttributeError: id = huisnummer def creator(): res = crab...
def get_postadres_by_subadres(self, subadres): ''' Get the `postadres` for a :class:`Subadres`. :param subadres: The :class:`Subadres` for which the \ `postadres` is wanted. OR A subadres id. :rtype: A :class:`str`. ''' try: id = subadres.id except AttributeError: id = subadres def creator(): res = crab_gateway_request...
def set_gateway(self, gateway): ''' :param crabpy.gateway.crab.CrabGateway gateway: Gateway to use. ''' self.gateway = gateway self.gewest.gateway = gateway
def postadressen(self): ''' Returns the postadressen for this Perceel. Will only take the huisnummers with status `inGebruik` into account. :rtype: list ''' return [h.postadres for h in self.huisnummers if h.status.id == '3']
def generate_salt_cmd(target, module, args=None, kwargs=None): """ Generates a command (the arguments) for the `salt` or `salt-ssh` CLI """ args = args or [] kwargs = kwargs or {} target = target or '*' target = '"%s"' % target cmd = [target, module] for arg in args: cmd.append(arg) for key in kwargs: cmd.append('{0}={...
def salt_ssh(project, target, module, args=None, kwargs=None): """ Execute a `salt-ssh` command """ cmd = ['salt-ssh'] cmd.extend(generate_salt_cmd(target, module, args, kwargs)) cmd.append('--state-output=mixed') cmd.append('--roster-file=%s' % project.roster_path) cmd.append('--config-dir=%s' % project.salt_ssh_confi...
def salt_master(project, target, module, args=None, kwargs=None): """ Execute a `salt` command in the head node """ client = project.cluster.head.ssh_client cmd = ['salt'] cmd.extend(generate_salt_cmd(target, module, args, kwargs)) cmd.append('--timeout=300') cmd.append('--state-output=mixed') cmd = ' '.join(cmd) outpu...
def getenv(name, **kwargs): """ Retrieves environment variable by name and casts the value to desired type. If desired type is list or tuple - uses separator to split the value. """ default_value = kwargs.pop('default', None) desired_type = kwargs.pop('type', str) list_separator = kwargs.pop('separator', ',') value = o...
def generate_network(user=None, reset=False): """ Assemble the network connections for a given user """ token = collect_token() try: gh = login(token=token) root_user = gh.user(user) except Exception, e: # Failed to login using the token, github3.models.GitHubError raise e graph_nodes = [] graph_edges = [] username = u...
def import_element(self, xml_element): """ Imports the element from an lxml element and loads its content. :param lxml.etree._Element xml_element: XML element to import. """ self.xml_element = xml_element uri, tag = Element.get_namespace_and_tag(self.xml_element.tag) self.namespace = uri self.name = tag self.load_xml_a...
def as_dict(self): """ Serializes the object necessary data in a dictionary. :returns: Serialized data in a dictionary. :rtype: dict """ element_dict = dict() if hasattr(self, 'namespace'): element_dict['namespace'] = self.namespace if hasattr(self, 'name'): element_dict['name'] = self.name if hasattr(self, 'text'): el...
def load_xml_attrs(self): """ Load XML attributes as object attributes. :returns: List of parsed attributes. :rtype: list """ attrs_list = list() if hasattr(self, 'xml_element'): xml_attrs = self.xml_element.attrib for variable, value in iter(xml_attrs.items()): uri, tag = Element.get_namespace_and_tag(variable) tag = ...
def get_namespace_and_tag(name): """ Separates the namespace and tag from an element. :param str name: Tag. :returns: Namespace URI and Tag namespace. :rtype: tuple """ if isinstance(name, str): if name[0] == "{": uri, ignore, tag = name[1:].partition("}") else: uri = None tag = name else: uri = None tag = None return ...
def write_command(cls, writer, name, buffers=()): """ Write a command to the specified writer. :param writer: The writer to use. :param name: The command name. :param buffers: The buffers to writer. """ assert len(name) < 256 body_len = len(name) + 1 + sum(len(buffer) for buffer in buffers) if body_len < 256: writer.wr...
async def _expect_command(cls, reader, name): """ Expect a command. :param reader: The reader to use. :returns: The command data. """ size_type = struct.unpack('B', await reader.readexactly(1))[0] if size_type == 0x04: size = struct.unpack('!B', await reader.readexactly(1))[0] elif size_type == 0x06: size = struct.unpa...
def fit(self, X, y=None): """ Sets *self.degree* according to :func:`baart_criteria` if *degree_range* is not None, otherwise does nothing. **Parameters** X : array-like, shape = [n_samples, 1] Column vector of phases. y : array-like or None, shape = [n_samples], optional Row vector of magnitudes (default None). **Retu...
def transform(self, X, y=None, **params): """ Transforms *X* from phase-space to Fourier-space, returning the design matrix produced by :func:`Fourier.design_matrix` for input to a regressor. **Parameters** X : array-like, shape = [n_samples, 1] Column vector of phases. y : None, optional Unused argument for conformity...
def baart_criteria(self, X, y): """ Returns the optimal Fourier series degree as determined by `Baart's Criteria <http://articles.adsabs.harvard.edu/cgi-bin/nph-iarticle_query?1986A%26A...170...59P&amp;data_type=PDF_HIGH&amp;whole_paper=YES&amp;type=PRINTER&amp;filetype=.pdf>`_ [JOP]_. **Citations** .. [JOP] J. O. Pete...
def design_matrix(phases, degree): r""" Constructs an :math:`N \times 2n+1` matrix of the form: .. math:: \begin{bmatrix} 1 & \sin(1 \cdot 2\pi \cdot \phi_0) & \cos(1 \cdot 2\pi \cdot \phi_0) & \ldots & \sin(n \cdot 2\pi \cdot \phi_0) & \cos(n \cdot 2\pi \cdot \phi_0) \\ \vdots & \vdots & \vdots & \ddots & \vdots & \vd...
repeated within the # sine and cosine terms x = numpy.empty((n_samples, degree)) # the Nxn matrix now has N copies of the same row, and each row is # integer multiples of pi counting from 1 to the degree x[:,:] = i*2*numpy.pi # multiply each row of x by the phases x.T[:,:] *= phases # place 1's in the first column of t...
def phase_shifted_coefficients(amplitude_coefficients, form='cos', shift=0.0): r""" Converts Fourier coefficients from the amplitude form to the phase-shifted form, as either a sine or cosine series. Amplitude form: .. math:: m(t) = A_0 + \sum_{k=1}^n (a_k \sin(k \omega t) + b_k \cos(k \omega t)) Sine form: .. math:: m...
:math:`[ A_0, A_1, \Phi_1, \ldots, A_n, \Phi_n ]`. """ if form != 'sin' and form != 'cos': raise NotImplementedError( 'Fourier series must have form sin or cos') # separate array of coefficients into respective parts A_0 = amplitude_coefficients[0] a_k = amplitude_coefficients[1::2] b_k = amplitude_coefficients[2::2] d...
# \ | / | b_k # \ | a_k / | # A_k \ | / _| # \ | / Φ_k | | # \ | --------- # \| a_k # A_k = numpy.sqrt(a_k**2 + b_k**2) # phase coefficients are shifted to the left by optional ``shift`` if form == 'cos': Phi_k = numpy.arctan2(-a_k, b_k) + 2*pi*k*shift elif form == 'sin': Phi_k = numpy.arctan2(b_k, a_k) + 2*pi*k*shift ...
def fourier_ratios(phase_shifted_coeffs): r""" Returns the :math:`R_{j1}` and :math:`\phi_{j1}` values for the given phase-shifted coefficients. .. math:: R_{j1} = A_j / A_1 .. math:: \phi_{j1} = \phi_j - j \phi_1 **Parameters** phase_shifted_coeffs : array-like, shape = [:math:`2n+1`] Fourier sine or cosine series coe...
by zero warnings with numpy.errstate(divide="ignore"): amplitude_ratios[:] = amplitudes[1:] amplitude_ratios /= amplitudes[0] # indices for phase deltas i = numpy.arange(2, degree+1) phase_deltas[:] = phases[1:] phase_deltas -= i*phases[0] # constrain phase_deltas between 0 and 2*pi phase_deltas %= 2*pi return ratios
def _execute(self, command, stdin=None, stdout=subprocess.PIPE): """Executes the specified command relative to the repository root. Returns a tuple containing the return code and the process output. """ process = subprocess.Popen(command, shell=True, cwd=self.root_path, stdin=stdin, stdout=stdout) return (process.wait(...
def apply_patch(self, patch_path): """Applies the patch located at *patch_path*. Returns the return code of the patch command. """ # Do not create .orig backup files, and merge files in place. return self._execute('patch -p1 --no-backup-if-mismatch --merge', stdout=open(os.devnull, 'w'), stdin=open(patch_path, 'r'))[0]
def get_root_path(self, path): """See :py:meth:`~stash.repository.Repository.get_root_path`.""" # Look at the directories present in the current working directory. In # case a .svn directory is present, we know we are in the root directory # of a Subversion repository (for Subversion 1.7.x). In case no # repository spe...
def status(self): """See :py:meth:`~stash.repository.Repository.status`.""" result = set() for line in self._execute('svn stat')[1].splitlines(): if line[0] == '?': result.add((FileStatus.Added, line[2:].strip())) elif line[0] == '!': result.add((FileStatus.Removed, line[2:].strip())) return result
def choices(klass): """ Decorator to set `CHOICES` and other attributes """ _choices = [] for attr in user_attributes(klass.Meta): val = getattr(klass.Meta, attr) setattr(klass, attr, val[0]) _choices.append((val[0], val[1])) setattr(klass, 'CHOICES', tuple(_choices)) return klass
def create_db(): " Create database. " from ..ext import db db.create_all() # Evolution support from flask import current_app from flaskext.evolution import db as evolution_db evolution_db.init_app(current_app) evolution_db.create_all() print "Database created successfuly"
def drop_db(): " Drop all tables. " from ..ext import db if prompt_bool("Are you sure? You will lose all your data!"): db.drop_all() # Evolution support from flask import current_app from flaskext.evolution import db as evolution_db evolution_db.init_app(current_app) evolution_db.drop_all() print "Database clearing"
def clean_prefix(self): """ Validates the prefix """ if self.instance.fixed: return self.instance.prefix prefix = self.cleaned_data['prefix'] if not namespace.is_ncname(prefix): raise forms.ValidationError("This is an invalid prefix") return prefix
def clean_uri(self): """ Validates the URI """ if self.instance.fixed: return self.instance.uri uri = self.cleaned_data['uri'] # todo: URI validation return uri
def history(self): """Returns an SQLAlchemy query of the object's history (previous versions). If the class does not support history/versioning, returns None. """ history = self.history_class if history: return self.session.query(history).filter(history.id == self.id) else: return None
def generate_appstruct(self): """Returns a Deform compatible appstruct of the object and it's properties. Does not recurse into SQLAlchemy relationships. An example using the :class:`~drinks.models.User` class (that inherits from BaseMixin): .. code-block:: python >>> user = User(username='mcuserpants', disabled=True) ...
def _get_patch_path(cls, patch_name): """Returns the absolute path for patch *patch_name*.""" return os.path.join(cls.STASH_PATH, patch_name) if patch_name else None
def remove_patch(cls, patch_name): """Removes patch *patch_name* from the stash (in case it exists). :raises: :py:exc:`~stash.exception.StashException` in case *patch_name* does not exist. """ try: os.unlink(cls._get_patch_path(patch_name)) except: raise StashException("patch '%s' does not exist" % patch_name)
def get_patch(cls, patch_name): """Returns the contents of the specified patch *patch_name*. :raises: :py:exc:`~stash.exception.StashException` in case *patch_name* does not exist. """ try: return open(cls._get_patch_path(patch_name), 'r').read() except: raise StashException("patch '%s' does not exist" % patch_name)
def apply_patch(self, patch_name): """Applies the patch *patch_name* on to the current working directory in case the patch exists. In case applying the patch was successful, the patch is automatically removed from the stash. Returns ``True`` in case applying the patch was successful, otherwise ``False`` is returned. :r...
StashException("patch '%s' does not exist" % patch_name)
def create_patch(self, patch_name): """Creates a patch based on the changes in the current repository. In case the specified patch *patch_name* already exists, ask the user to overwrite the patch. In case creating the patch was successful, all changes in the current repository are reverted. Returns ``True`` in case a p...
Files that were added, need to be removed # again. pre_file_status = self.repository.status() self.repository.revert_all() changed_file_status = self.repository.status().difference(pre_file_status) # Remove all files that are created by the patch that is now being # stashed. for status, file_name in changed_file_status...
def as_dict(self, section='Main', **kwargs): """Return template context from configs. """ items = super(MakesiteParser, self).items(section, **kwargs) return dict(items)
def config_oauth(app): " Configure oauth support. " for name in PROVIDERS: config = app.config.get('OAUTH_%s' % name.upper()) if not config: continue if not name in oauth.remote_apps: remote_app = oauth.remote_app(name, **config) else: remote_app = oauth.remote_apps[name] client_class = CLIENTS.get(name) client_class(a...
def cached_instance(model, timeout=None, **filters): """ Auto cached model instance. """ if isinstance(model, basestring): model = _str_to_model(model) cache_key = generate_cache_key(model, **filters) return get_cached(cache_key, model.objects.select_related().get, kwargs=filters)
def cached_query(qs, timeout=None): """ Auto cached queryset and generate results. """ cache_key = generate_cache_key(qs) return get_cached(cache_key, list, args=(qs,), timeout=None)
def clean_cache(cached, **kwargs): " Generate cache key and clean cached value. " if isinstance(cached, basestring): cached = _str_to_model(cached) cache_key = generate_cache_key(cached, **kwargs) cache.delete(cache_key)
def generate_cache_key(cached, **kwargs): """ Auto generate cache key for model or queryset """ if isinstance(cached, QuerySet): key = str(cached.query) elif isinstance(cached, (Model, ModelBase)): key = '%s.%s:%s' % (cached._meta.app_label, cached._meta.module_name, ','.join('%s=%s' % item for item in kwargs.iteritems...
def clean_cache_key(key): """ Replace spaces with '-' and hash if length is greater than 250. """ cache_key = re.sub(r'\s+', '-', key) cache_key = smart_str(cache_key) if len(cache_key) > 200: cache_key = cache_key[:150] + '-' + hashlib.md5(cache_key).hexdigest() return cache_key
def collect_static_files(src_map, dst): """ Collect all static files and move them into a temporary location. This is very similar to the ``collectstatic`` command. """ for rel_src, abs_src in src_map.iteritems(): abs_dst = os.path.join(dst, rel_src) copy_file(abs_src, abs_dst)
def run_command(cmd, root, dst, input, params): """ Execute a command, and if successful write it's stdout to ``root``/``dst``. """ use_stdout = '{output}' not in cmd if not use_stdout: params['output'] = dst parsed_cmd = parse_command(cmd, input=input, params=params) ensure_dirs(os.path.join(root, dst)) logger.info("R...
def apply_preprocessors(root, src, dst, processors): """ Preprocessors operate based on the source filename, and apply to each file individually. """ matches = [(pattern, cmds) for pattern, cmds in processors.iteritems() if fnmatch(src, pattern)] if not matches: return False params = get_format_params(dst) for pattern,...
def apply_postcompilers(root, src_list, dst, processors): """ Postcompilers operate based on the destination filename. They operate on a collection of files, and are expected to take a list of 1+ inputs and generate a single output. """ dst_file = os.path.join(root, dst) matches = [(pattern, cmds) for pattern, cmds in ...
def set_model_internal_data(model, original_data, modified_data, deleted_data): """ Set internal data to model. """ model.__original_data__ = original_data list(map(model._prepare_child, model.__original_data__)) model.__modified_data__ = modified_data list(map(model._prepare_child, model.__modified_data__)) model.__de...
def recover_model_from_data(model_class, original_data, modified_data, deleted_data): """ Function to reconstruct a model from DirtyModel basic information: original data, the modified and deleted fields. Necessary for pickle an object """ model = model_class() return set_model_internal_data(model, original_data, modif...
def recover_dynamic_model_from_data(model_class, original_data, modified_data, deleted_data, structure): """ Function to reconstruct a model from DirtyModel basic information: original data, the modified and deleted fields. Necessary for pickle an object """ model = model_class() model.__structure__ = {k: d[0](**d[1]) ...
def recover_hashmap_model_from_data(model_class, original_data, modified_data, deleted_data, field_type): """ Function to reconstruct a model from DirtyModel basic information: original data, the modified and deleted fields. Necessary for pickle an object """ model = model_class(field_type=field_type[0](**field_type[1]...
def recover_fast_dynamic_model_from_data(model_class, original_data, modified_data, deleted_data, field_types): """ Function to reconstruct a model from DirtyModel basic information: original data, the modified and deleted fields. Necessary for pickle an object """ model = model_class() model.__field_types__ = {k: d[0]...
def process_base_field(cls, field, key): """ Preprocess field instances. :param field: Field object :param key: Key where field was found """ if not field.name: field.name = key elif key != field.name: if not isinstance(field.alias, list): field.alias = [key] else: field.alias.insert(0, key) setattr(cls, field.name, fi...
def set_field_value(self, name, value): """ Set the value to the field modified_data """ name = self.get_real_name(name) if not name or not self._can_write_field(name): return if name in self.__deleted_fields__: self.__deleted_fields__.remove(name) if self.__original_data__.get(name) == value: try: self.__modified_data...
def get_field_value(self, name): """ Get the field value from the modified data or the original one """ name = self.get_real_name(name) if not name or name in self.__deleted_fields__: return None modified = self.__modified_data__.get(name) if modified is not None: return modified return self.__original_data__.get(name)
def delete_field_value(self, name): """ Mark this field to be deleted """ name = self.get_real_name(name) if name and self._can_write_field(name): if name in self.__modified_data__: self.__modified_data__.pop(name) if name in self.__original_data__ and name not in self.__deleted_fields__: self.__deleted_fields__.append...
def reset_field_value(self, name): """ Resets value of a field """ name = self.get_real_name(name) if name and self._can_write_field(name): if name in self.__modified_data__: del self.__modified_data__[name] if name in self.__deleted_fields__: self.__deleted_fields__.remove(name) try: self.__original_data__[name].clear...
def is_modified_field(self, name): """ Returns whether a field is modified or not """ name = self.get_real_name(name) if name in self.__modified_data__ or name in self.__deleted_fields__: return True try: return self.get_field_value(name).is_modified() except Exception: return False