repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
heigeo/climata
climata/huc8/__init__.py
get_huc8
python
def get_huc8(prefix): if not prefix.isdigit(): # Look up hucs by name name = prefix prefix = None for row in hucs: if row.basin.lower() == name.lower(): # Use most general huc if two have the same name if prefix is None or len(row.huc) < le...
Return all HUC8s matching the given prefix (e.g. 1801) or basin name (e.g. Klamath)
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/huc8/__init__.py#L23-L46
null
from wq.io import NetLoader, TupleMapper, BaseIO from climata.parsers import RdbParser class HucIO(NetLoader, RdbParser, TupleMapper, BaseIO): url = "http://water.usgs.gov/GIS/new_huc_rdb.txt" def parse(self): super(HucIO, self).parse() # FIXME: new_huc_rdb.txt isn't a valid RDB file; remove...
heigeo/climata
climata/acis/__init__.py
StationMetaIO.parse
python
def parse(self): super(AcisIO, self).parse() # This is more of a "mapping" step than a "parsing" step, but mappers # only allow one-to-one mapping from input fields to output fields. for row in self.data: if 'meta' in row: row = row['meta'] if 'll...
Convert ACIS 'll' value into separate latitude and longitude.
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L80-L93
null
class StationMetaIO(AcisIO): """ Retrieves metadata about the climate stations in a region. See http://data.rcc-acis.org/doc/#title8 """ namespace = "meta" # For wq.io.parsers.text.JsonParser path = "StnMeta" # These options are not required for StationMetaIO start_date = DateOpt(url_...
heigeo/climata
climata/acis/__init__.py
StationMetaIO.map_value
python
def map_value(self, field, value): if field == 'sids': # Site identifiers are returned as "[id] [auth_id]"; # Map to auth name for easier usability ids = {} for idinfo in value: id, auth = idinfo.split(' ') auth = AUTHORITY_BY_ID[a...
Clean up some values returned from the web service. (overrides wq.io.mappers.BaseMapper)
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L95-L124
null
class StationMetaIO(AcisIO): """ Retrieves metadata about the climate stations in a region. See http://data.rcc-acis.org/doc/#title8 """ namespace = "meta" # For wq.io.parsers.text.JsonParser path = "StnMeta" # These options are not required for StationMetaIO start_date = DateOpt(url_...
heigeo/climata
climata/acis/__init__.py
StationDataIO.get_field_names
python
def get_field_names(self): field_names = super(StationDataIO, self).get_field_names() if set(field_names) == set(['meta', 'data']): meta_fields = list(self.data[0]['meta'].keys()) if set(meta_fields) < set(self.getvalue('meta')): meta_fields = self.getvalue('meta'...
ACIS web service returns "meta" and "data" for each station; Use meta attributes as field names
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L147-L158
null
class StationDataIO(StationMetaIO): """ Retrieve daily time series data from the climate stations in a region. See http://data.rcc-acis.org/doc/#title19 """ nested = True namespace = "data" # For wq.io.parsers.text.JsonParser path = "MultiStnData" # Specify ACIS-defined URL parameter...
heigeo/climata
climata/acis/__init__.py
StationDataIO.usable_item
python
def usable_item(self, data): # Use metadata as item item = data['meta'] # Add nested IO for data elems, elems_is_complex = self.getlist('parameter') if elems_is_complex: elems = [elem['name'] for elem in elems] add, add_is_complex = self.getlist('add') ...
ACIS web service returns "meta" and "data" for each station; use meta attributes as item values, and add an IO for iterating over "data"
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L175-L199
null
class StationDataIO(StationMetaIO): """ Retrieve daily time series data from the climate stations in a region. See http://data.rcc-acis.org/doc/#title19 """ nested = True namespace = "data" # For wq.io.parsers.text.JsonParser path = "MultiStnData" # Specify ACIS-defined URL parameter...
heigeo/climata
climata/acis/__init__.py
DataIO.load_data
python
def load_data(self, data): dates = fill_date_range(self.start_date, self.end_date) for row, date in zip(data, dates): data = {'date': date} if self.add: # If self.add is set, results will contain additional # attributes (e.g. flags). In that case,...
MultiStnData data results are arrays without explicit dates; Infer time series based on start date.
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L216-L243
[ "def fill_date_range(start_date, end_date, date_format=None):\n \"\"\"\n Function accepts start date, end date, and format (if dates are strings)\n and returns a list of Python dates.\n \"\"\"\n\n if date_format:\n start_date = datetime.strptime(start_date, date_format).date()\n end_dat...
class DataIO(TimeSeriesMapper, BaseIO): """ IO for iterating over ACIS time series data. Created internally by StationDataIO; not meant to be used directly. """ # Inherited from parent parameter = [] add = [] start_date = None end_date = None date_formats = [] # For TimeSeries...
heigeo/climata
climata/acis/__init__.py
DataIO.get_field_names
python
def get_field_names(self): if self.add: return ['date', 'elem', 'value'] + [flag for flag in self.add] else: field_names = ['date'] for elem in self.parameter: # namedtuple doesn't like numeric field names if elem.isdigit(): ...
Different field names depending on self.add setting (see load_data) For BaseIO
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/acis/__init__.py#L250-L264
null
class DataIO(TimeSeriesMapper, BaseIO): """ IO for iterating over ACIS time series data. Created internally by StationDataIO; not meant to be used directly. """ # Inherited from parent parameter = [] add = [] start_date = None end_date = None date_formats = [] # For TimeSeries...
heigeo/climata
climata/base.py
fill_date_range
python
def fill_date_range(start_date, end_date, date_format=None): if date_format: start_date = datetime.strptime(start_date, date_format).date() end_date = datetime.strptime(end_date, date_format).date() date_list = [] while start_date <= end_date: date_list.append(start_date) st...
Function accepts start date, end date, and format (if dates are strings) and returns a list of Python dates.
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L252-L265
null
from warnings import warn from .version import VERSION from datetime import datetime, timedelta from wq.io import make_date_mapper, NetLoader, Zipper parse_date = make_date_mapper('%Y-%m-%d') class FilterOpt(object): """ Base class for describing a filter option """ name = None # Option name as def...
heigeo/climata
climata/base.py
FilterOpt.parse
python
def parse(self, value): if self.required and value is None: raise ValueError("%s is required!" % self.name) elif self.ignored and value is not None: warn("%s is ignored for this class!" % self.name) elif not self.multi and isinstance(value, (list, tuple)): if ...
Enforce rules and return parsed value
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L32-L49
null
class FilterOpt(object): """ Base class for describing a filter option """ name = None # Option name as defined on IO class url_param = None # Actual URL parameter to use (defaults to name) required = False # Whether option is equired for valid request multi = False # Whether multiple v...
heigeo/climata
climata/base.py
DateOpt.parse
python
def parse(self, value): value = super(DateOpt, self).parse(value) if value is None: return None if isinstance(value, str): value = self.parse_date(value) if isinstance(value, datetime) and self.date_only: value = value.date() return value
Parse date
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L58-L69
[ "def parse(self, value):\n \"\"\"\n Enforce rules and return parsed value\n \"\"\"\n if self.required and value is None:\n raise ValueError(\"%s is required!\" % self.name)\n elif self.ignored and value is not None:\n warn(\"%s is ignored for this class!\" % self.name)\n elif not sel...
class DateOpt(FilterOpt): date_only = True def parse_date(self, value): return parse_date(value)
heigeo/climata
climata/base.py
WebserviceLoader.get_filter_options
python
def get_filter_options(cls): attr = '_filter_options_%s' % id(cls) options = getattr(cls, attr, {}) if options: return options for key in dir(cls): val = getattr(cls, key) if isinstance(val, FilterOpt): options[key] = val set...
List all filter options defined on class (and superclasses)
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L135-L151
null
class WebserviceLoader(NetLoader): """ NetLoader subclass with enhanced functionality for enumerating and validating URL arguments. """ # Default filter options, common to most web services for climate data. # Every climata IO class is assumed to support at least these options; if # any are...
heigeo/climata
climata/base.py
WebserviceLoader.getlist
python
def getlist(self, name): value = self.getvalue(name) complex = {} def str_value(val): # TODO: nonlocal complex if isinstance(val, dict): complex['complex'] = True return val else: return str(val) if val...
Retrieve given property from class/instance, ensuring it is a list. Also determine whether the list contains simple text/numeric values or nested dictionaries (a "complex" list)
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L163-L185
[ "def as_list(value):\n if isinstance(value, (list, tuple)):\n return value\n else:\n return [value]\n" ]
class WebserviceLoader(NetLoader): """ NetLoader subclass with enhanced functionality for enumerating and validating URL arguments. """ # Default filter options, common to most web services for climate data. # Every climata IO class is assumed to support at least these options; if # any are...
heigeo/climata
climata/base.py
WebserviceLoader.set_param
python
def set_param(self, into, name): value, complex = self.getlist(name) if value is not None: into[name] = value return complex
Set parameter key, noting whether list value is "complex"
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L187-L194
null
class WebserviceLoader(NetLoader): """ NetLoader subclass with enhanced functionality for enumerating and validating URL arguments. """ # Default filter options, common to most web services for climate data. # Every climata IO class is assumed to support at least these options; if # any are...
heigeo/climata
climata/base.py
WebserviceLoader.get_params
python
def get_params(self): params = {} complex = False for name, opt in self.filter_options.items(): if opt.ignored: continue if self.set_param(params, name): complex = True return params, complex
Get parameters for web service, noting whether any are "complex"
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L196-L208
null
class WebserviceLoader(NetLoader): """ NetLoader subclass with enhanced functionality for enumerating and validating URL arguments. """ # Default filter options, common to most web services for climate data. # Every climata IO class is assumed to support at least these options; if # any are...
heigeo/climata
climata/base.py
WebserviceLoader.params
python
def params(self): params, complex = self.get_params() url_params = self.default_params.copy() url_params.update(self.serialize_params(params, complex)) return url_params
URL parameters for wq.io.loaders.NetLoader
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L211-L218
null
class WebserviceLoader(NetLoader): """ NetLoader subclass with enhanced functionality for enumerating and validating URL arguments. """ # Default filter options, common to most web services for climate data. # Every climata IO class is assumed to support at least these options; if # any are...
heigeo/climata
climata/base.py
WebserviceLoader.serialize_params
python
def serialize_params(self, params, complex=False): if complex: # See climata.acis for an example implementation raise NotImplementedError("Cannot serialize %s!" % params) else: # Simpler queries can use traditional URL parameters return { s...
Serialize parameter names and values to a dict ready for urlencode()
train
https://github.com/heigeo/climata/blob/2028bdbd40e1c8985b0b62f7cb969ce7dfa8f1bd/climata/base.py#L220-L232
null
class WebserviceLoader(NetLoader): """ NetLoader subclass with enhanced functionality for enumerating and validating URL arguments. """ # Default filter options, common to most web services for climate data. # Every climata IO class is assumed to support at least these options; if # any are...
cpburnz/python-path-specification
pathspec/pathspec.py
PathSpec.from_lines
python
def from_lines(cls, pattern_factory, lines): if isinstance(pattern_factory, string_types): pattern_factory = util.lookup_pattern(pattern_factory) if not callable(pattern_factory): raise TypeError("pattern_factory:{!r} is not callable.".format(pattern_factory)) if isinstance(lines, (bytes, unicode)): rai...
Compiles the pattern lines. *pattern_factory* can be either the name of a registered pattern factory (:class:`str`), or a :class:`~collections.abc.Callable` used to compile patterns. It must accept an uncompiled pattern (:class:`str`) and return the compiled pattern (:class:`.Pattern`). *lines* (:class:`~co...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/pathspec.py#L50-L75
[ "def lookup_pattern(name):\n\t\"\"\"\n\tLookups a registered pattern factory by name.\n\n\t*name* (:class:`str`) is the name of the pattern factory.\n\n\tReturns the registered pattern factory (:class:`~collections.abc.Callable`).\n\tIf no pattern factory is registered, raises :exc:`KeyError`.\n\t\"\"\"\n\treturn _...
class PathSpec(object): """ The :class:`PathSpec` class is a wrapper around a list of compiled :class:`.Pattern` instances. """ def __init__(self, patterns): """ Initializes the :class:`PathSpec` instance. *patterns* (:class:`~collections.abc.Collection` or :class:`~collections.abc.Iterable`) yields each...
cpburnz/python-path-specification
pathspec/pathspec.py
PathSpec.match_file
python
def match_file(self, file, separators=None): norm_file = util.normalize_file(file, separators=separators) return util.match_file(self.patterns, norm_file)
Matches the file to this path-spec. *file* (:class:`str`) is the file path to be matched against :attr:`self.patterns <PathSpec.patterns>`. *separators* (:class:`~collections.abc.Collection` of :class:`str`) optionally contains the path separators to normalize. See :func:`~pathspec.util.normalize_file` for ...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/pathspec.py#L77-L91
[ "def match_file(patterns, file):\n\t\"\"\"\n\tMatches the file to the patterns.\n\n\t*patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`)\n\tcontains the patterns to use.\n\n\t*file* (:class:`str`) is the normalized file path to be matched\n\tagainst *patterns*.\n\n\tReturns :data:`...
class PathSpec(object): """ The :class:`PathSpec` class is a wrapper around a list of compiled :class:`.Pattern` instances. """ def __init__(self, patterns): """ Initializes the :class:`PathSpec` instance. *patterns* (:class:`~collections.abc.Collection` or :class:`~collections.abc.Iterable`) yields each...
cpburnz/python-path-specification
pathspec/pathspec.py
PathSpec.match_files
python
def match_files(self, files, separators=None): if isinstance(files, (bytes, unicode)): raise TypeError("files:{!r} is not an iterable.".format(files)) file_map = util.normalize_files(files, separators=separators) matched_files = util.match_files(self.patterns, iterkeys(file_map)) for path in matched_files: ...
Matches the files to this path-spec. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains the file paths to be matched against :attr:`self.patterns <PathSpec.patterns>`. *separators* (:class:`~collections.abc.Collection` of :class:`str`; or :data:`None`) optionally contains the path separat...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/pathspec.py#L93-L115
[ "def match_files(patterns, files):\n\t\"\"\"\n\tMatches the files to the patterns.\n\n\t*patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`)\n\tcontains the patterns to use.\n\n\t*files* (:class:`~collections.abc.Iterable` of :class:`str`) contains\n\tthe normalized file paths to be...
class PathSpec(object): """ The :class:`PathSpec` class is a wrapper around a list of compiled :class:`.Pattern` instances. """ def __init__(self, patterns): """ Initializes the :class:`PathSpec` instance. *patterns* (:class:`~collections.abc.Collection` or :class:`~collections.abc.Iterable`) yields each...
cpburnz/python-path-specification
pathspec/pathspec.py
PathSpec.match_tree
python
def match_tree(self, root, on_error=None, follow_links=None): files = util.iter_tree(root, on_error=on_error, follow_links=follow_links) return self.match_files(files)
Walks the specified root path for all files and matches them to this path-spec. *root* (:class:`str`) is the root directory to search for files. *on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is the error handler for file-system exceptions. See :func:`~pathspec.util.iter_tree` fo...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/pathspec.py#L117-L137
[ "def iter_tree(root, on_error=None, follow_links=None):\n\t\"\"\"\n\tWalks the specified directory for all files.\n\n\t*root* (:class:`str`) is the root directory to search for files.\n\n\t*on_error* (:class:`~collections.abc.Callable` or :data:`None`)\n\toptionally is the error handler for file-system exceptions. ...
class PathSpec(object): """ The :class:`PathSpec` class is a wrapper around a list of compiled :class:`.Pattern` instances. """ def __init__(self, patterns): """ Initializes the :class:`PathSpec` instance. *patterns* (:class:`~collections.abc.Collection` or :class:`~collections.abc.Iterable`) yields each...
cpburnz/python-path-specification
pathspec/patterns/gitwildmatch.py
GitWildMatchPattern.pattern_to_regex
python
def pattern_to_regex(cls, pattern): if isinstance(pattern, unicode): return_type = unicode elif isinstance(pattern, bytes): return_type = bytes pattern = pattern.decode(_BYTES_ENCODING) else: raise TypeError("pattern:{!r} is not a unicode or byte string.".format(pattern)) pattern = pattern.strip() ...
Convert the pattern into a regular expression. *pattern* (:class:`unicode` or :class:`bytes`) is the pattern to convert into a regular expression. Returns the uncompiled regular expression (:class:`unicode`, :class:`bytes`, or :data:`None`), and whether matched files should be included (:data:`True`), exclu...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/patterns/gitwildmatch.py#L30-L174
null
class GitWildMatchPattern(RegexPattern): """ The :class:`GitWildMatchPattern` class represents a compiled Git wildmatch pattern. """ # Keep the dict-less class hierarchy. __slots__ = () @classmethod @staticmethod def _translate_segment_glob(pattern): """ Translates the glob pattern to a regular express...
cpburnz/python-path-specification
pathspec/patterns/gitwildmatch.py
GitWildMatchPattern._translate_segment_glob
python
def _translate_segment_glob(pattern): # NOTE: This is derived from `fnmatch.translate()` and is similar to # the POSIX function `fnmatch()` with the `FNM_PATHNAME` flag set. escape = False regex = '' i, end = 0, len(pattern) while i < end: # Get next character. char = pattern[i] i += 1 if esca...
Translates the glob pattern to a regular expression. This is used in the constructor to translate a path segment glob pattern to its corresponding regular expression. *pattern* (:class:`str`) is the glob pattern. Returns the regular expression (:class:`str`).
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/patterns/gitwildmatch.py#L177-L280
null
class GitWildMatchPattern(RegexPattern): """ The :class:`GitWildMatchPattern` class represents a compiled Git wildmatch pattern. """ # Keep the dict-less class hierarchy. __slots__ = () @classmethod def pattern_to_regex(cls, pattern): """ Convert the pattern into a regular expression. *pattern* (:class...
cpburnz/python-path-specification
pathspec/patterns/gitwildmatch.py
GitIgnorePattern.pattern_to_regex
python
def pattern_to_regex(cls, *args, **kw): cls._deprecated() return super(GitIgnorePattern, cls).pattern_to_regex(*args, **kw)
Warn about deprecation.
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/patterns/gitwildmatch.py#L306-L311
null
class GitIgnorePattern(GitWildMatchPattern): """ The :class:`GitIgnorePattern` class is deprecated by :class:`GitWildMatchPattern`. This class only exists to maintain compatibility with v0.4. """ def __init__(self, *args, **kw): """ Warn about deprecation. """ self._deprecated() return super(GitIgnorePa...
cpburnz/python-path-specification
pathspec/util.py
iter_tree
python
def iter_tree(root, on_error=None, follow_links=None): if on_error is not None and not callable(on_error): raise TypeError("on_error:{!r} is not callable.".format(on_error)) if follow_links is None: follow_links = True for file_rel in _iter_tree_next(os.path.abspath(root), '', {}, on_error, follow_links): yi...
Walks the specified directory for all files. *root* (:class:`str`) is the root directory to search for files. *on_error* (:class:`~collections.abc.Callable` or :data:`None`) optionally is the error handler for file-system exceptions. It will be called with the exception (:exc:`OSError`). Reraise the exception to ...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L27-L55
[ "def _iter_tree_next(root_full, dir_rel, memo, on_error, follow_links):\n\t\"\"\"\n\tScan the directory for all descendant files.\n\n\t*root_full* (:class:`str`) the absolute path to the root directory.\n\n\t*dir_rel* (:class:`str`) the path to the directory to scan relative to\n\t*root_full*.\n\n\t*memo* (:class:`...
# encoding: utf-8 """ This module provides utility methods for dealing with path-specs. """ import os import os.path import posixpath import stat from .compat import collection_type, string_types NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep] """ *NORMALIZE_PATH_SEPS* (:cl...
cpburnz/python-path-specification
pathspec/util.py
_iter_tree_next
python
def _iter_tree_next(root_full, dir_rel, memo, on_error, follow_links): dir_full = os.path.join(root_full, dir_rel) dir_real = os.path.realpath(dir_full) # Remember each encountered ancestor directory and its canonical # (real) path. If a canonical path is encountered more than once, # recursion has occurred. if ...
Scan the directory for all descendant files. *root_full* (:class:`str`) the absolute path to the root directory. *dir_rel* (:class:`str`) the path to the directory to scan relative to *root_full*. *memo* (:class:`dict`) keeps track of ancestor directories encountered. Maps each ancestor real path (:class:`str``...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L57-L126
null
# encoding: utf-8 """ This module provides utility methods for dealing with path-specs. """ import os import os.path import posixpath import stat from .compat import collection_type, string_types NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep] """ *NORMALIZE_PATH_SEPS* (:cl...
cpburnz/python-path-specification
pathspec/util.py
match_file
python
def match_file(patterns, file): matched = False for pattern in patterns: if pattern.include is not None: if file in pattern.match((file,)): matched = pattern.include return matched
Matches the file to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *file* (:class:`str`) is the normalized file path to be matched against *patterns*. Returns :data:`True` if *file* matched; otherwise, :data:`False`.
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L139-L156
null
# encoding: utf-8 """ This module provides utility methods for dealing with path-specs. """ import os import os.path import posixpath import stat from .compat import collection_type, string_types NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep] """ *NORMALIZE_PATH_SEPS* (:cl...
cpburnz/python-path-specification
pathspec/util.py
match_files
python
def match_files(patterns, files): all_files = files if isinstance(files, collection_type) else list(files) return_files = set() for pattern in patterns: if pattern.include is not None: result_files = pattern.match(all_files) if pattern.include: return_files.update(result_files) else: return_files....
Matches the files to the patterns. *patterns* (:class:`~collections.abc.Iterable` of :class:`~pathspec.pattern.Pattern`) contains the patterns to use. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains the normalized file paths to be matched against *patterns*. Returns the matched files (:cla...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L158-L179
null
# encoding: utf-8 """ This module provides utility methods for dealing with path-specs. """ import os import os.path import posixpath import stat from .compat import collection_type, string_types NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep] """ *NORMALIZE_PATH_SEPS* (:cl...
cpburnz/python-path-specification
pathspec/util.py
normalize_file
python
def normalize_file(file, separators=None): # Normalize path separators. if separators is None: separators = NORMALIZE_PATH_SEPS norm_file = file for sep in separators: norm_file = norm_file.replace(sep, posixpath.sep) # Remove current directory prefix. if norm_file.startswith('./'): norm_file = norm_file[2...
Normalizes the file path to use the POSIX path separator (i.e., ``'/'``). *file* (:class:`str`) is the file path. *separators* (:class:`~collections.abc.Collection` of :class:`str`; or :data:`None`) optionally contains the path separators to normalize. This does not need to include the POSIX path separator (``'/'...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L181-L207
null
# encoding: utf-8 """ This module provides utility methods for dealing with path-specs. """ import os import os.path import posixpath import stat from .compat import collection_type, string_types NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep] """ *NORMALIZE_PATH_SEPS* (:cl...
cpburnz/python-path-specification
pathspec/util.py
normalize_files
python
def normalize_files(files, separators=None): norm_files = {} for path in files: norm_files[normalize_file(path, separators=separators)] = path return norm_files
Normalizes the file paths to use the POSIX path separator. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains the file paths to be normalized. *separators* (:class:`~collections.abc.Collection` of :class:`str`; or :data:`None`) optionally contains the path separators to normalize. See :func:`n...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L209-L226
[ "def normalize_file(file, separators=None):\n\t\"\"\"\n\tNormalizes the file path to use the POSIX path separator (i.e., ``'/'``).\n\n\t*file* (:class:`str`) is the file path.\n\n\t*separators* (:class:`~collections.abc.Collection` of :class:`str`; or\n\t:data:`None`) optionally contains the path separators to norm...
# encoding: utf-8 """ This module provides utility methods for dealing with path-specs. """ import os import os.path import posixpath import stat from .compat import collection_type, string_types NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep] """ *NORMALIZE_PATH_SEPS* (:cl...
cpburnz/python-path-specification
pathspec/util.py
register_pattern
python
def register_pattern(name, pattern_factory, override=None): if not isinstance(name, string_types): raise TypeError("name:{!r} is not a string.".format(name)) if not callable(pattern_factory): raise TypeError("pattern_factory:{!r} is not callable.".format(pattern_factory)) if name in _registered_patterns and not ...
Registers the specified pattern factory. *name* (:class:`str`) is the name to register the pattern factory under. *pattern_factory* (:class:`~collections.abc.Callable`) is used to compile patterns. It must accept an uncompiled pattern (:class:`str`) and return the compiled pattern (:class:`.Pattern`). *overrid...
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L228-L250
null
# encoding: utf-8 """ This module provides utility methods for dealing with path-specs. """ import os import os.path import posixpath import stat from .compat import collection_type, string_types NORMALIZE_PATH_SEPS = [sep for sep in [os.sep, os.altsep] if sep and sep != posixpath.sep] """ *NORMALIZE_PATH_SEPS* (:cl...
cpburnz/python-path-specification
pathspec/util.py
RecursionError.message
python
def message(self): return "Real path {real!r} was encountered at {first!r} and then {second!r}.".format( real=self.real_path, first=self.first_path, second=self.second_path, )
*message* (:class:`str`) is the error message.
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/util.py#L326-L334
null
class RecursionError(Exception): """ The :exc:`RecursionError` exception is raised when recursion is detected. """ def __init__(self, real_path, first_path, second_path): """ Initializes the :exc:`RecursionError` instance. *real_path* (:class:`str`) is the real path that recursion was encountered on. ...
cpburnz/python-path-specification
pathspec/pattern.py
Pattern.match
python
def match(self, files): raise NotImplementedError("{}.{} must override match().".format(self.__class__.__module__, self.__class__.__name__))
Matches this pattern against the specified files. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains each file relative to the root directory (e.g., ``"relative/path/to/file"``). Returns an :class:`~collections.abc.Iterable` yielding each matched file path (:class:`str`).
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/pattern.py#L35-L45
null
class Pattern(object): """ The :class:`Pattern` class is the abstract definition of a pattern. """ # Make the class dict-less. __slots__ = ('include',) def __init__(self, include): """ Initializes the :class:`Pattern` instance. *include* (:class:`bool` or :data:`None`) is whether the matched files shou...
cpburnz/python-path-specification
pathspec/pattern.py
RegexPattern.match
python
def match(self, files): if self.include is not None: for path in files: if self.regex.match(path) is not None: yield path
Matches this pattern against the specified files. *files* (:class:`~collections.abc.Iterable` of :class:`str`) contains each file relative to the root directory (e.g., "relative/path/to/file"). Returns an :class:`~collections.abc.Iterable` yielding each matched file path (:class:`str`).
train
https://github.com/cpburnz/python-path-specification/blob/6fc7567a58cb68ec7d72cc287e7fb97dbe22c017/pathspec/pattern.py#L116-L129
null
class RegexPattern(Pattern): """ The :class:`RegexPattern` class is an implementation of a pattern using regular expressions. """ # Make the class dict-less. __slots__ = ('regex',) def __init__(self, pattern, include=None): """ Initializes the :class:`RegexPattern` instance. *pattern* (:class:`unicode`,...
willkg/socorro-siggen
siggen/siglists_utils.py
_get_file_content
python
def _get_file_content(source): filepath = os.path.join('siglists', source + '.txt') lines = [] with resource_stream(__name__, filepath) as f: for i, line in enumerate(f): line = line.decode('utf-8', 'strict').strip() if not line or line.startswith('#'): conti...
Return a tuple, each value being a line of the source file. Remove empty lines and comments (lines starting with a '#').
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/siglists_utils.py#L30-L61
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import os import re from pkg_resources import resource_stream # This is a hack because sentinels can be a tuple, with...
willkg/socorro-siggen
siggen/cmd_signify.py
main
python
def main(): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( '-v', '--verbose', help='increase output verbosity', action='store_true' ) args = parser.parse_args() generator = SignatureGenerator(debug=args.verbose) crash_data = json.loads(sys.stdin.read()) ...
Takes crash data via stdin and generates a Socorro signature
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/cmd_signify.py#L19-L33
[ "def generate(self, signature_data):\n \"\"\"Takes data and returns a signature\n\n :arg dict signature_data: data to use to generate a signature\n\n :returns: ``Result`` instance\n\n \"\"\"\n result = Result()\n\n for rule in self.pipeline:\n rule_name = rule.__class__.__name__\n\n ...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import print_function import argparse import json import sys from .generator import SignatureGenerator...
willkg/socorro-siggen
siggen/utils.py
convert_to_crash_data
python
def convert_to_crash_data(raw_crash, processed_crash): # We want to generate fresh signatures, so we remove the "normalized" field # from stack frames from the processed crash because this is essentially # cached data from previous processing for thread in glom(processed_crash, 'json_dump.threads', defa...
Takes a raw crash and a processed crash (these are Socorro-centric data structures) and converts them to a crash data structure used by signature generation. :arg raw_crash: raw crash data from Socorro :arg processed_crash: processed crash data from Socorro :returns: crash data structure that conf...
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L16-L84
[ "def int_or_none(data):\n try:\n return int(data)\n except (TypeError, ValueError):\n return None\n" ]
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from glom import glom def int_or_none(data): try: return int(data) except (TypeError, ValueError): ...
willkg/socorro-siggen
siggen/utils.py
drop_bad_characters
python
def drop_bad_characters(text): # Strip all non-ascii and non-printable characters text = ''.join([c for c in text if c in ALLOWED_CHARS]) return text
Takes a text and drops all non-printable and non-ascii characters and also any whitespace characters that aren't space. :arg str text: the text to fix :returns: text with all bad characters dropped
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L91-L102
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from glom import glom def int_or_none(data): try: return int(data) except (TypeError, ValueError): ...
willkg/socorro-siggen
siggen/utils.py
parse_source_file
python
def parse_source_file(source_file): if not source_file: return None vcsinfo = source_file.split(':') if len(vcsinfo) == 4: # These are repositories or cloud file systems (e.g. hg, git, s3) vcstype, root, vcs_source_file, revision = vcsinfo return vcs_source_file if len(...
Parses a source file thing and returns the file name Example: >>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06') 'js/src/jit/MIR.h' :arg str source_file: the source file ("file") from a stack frame :returns: the filename or ``None`` if it couldn't determine ...
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L105-L138
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from glom import glom def int_or_none(data): try: return int(data) except (TypeError, ValueError): ...
willkg/socorro-siggen
siggen/utils.py
_is_exception
python
def _is_exception(exceptions, before_token, after_token, token): if not exceptions: return False for s in exceptions: if before_token.endswith(s): return True if s in token: return True return False
Predicate for whether the open token is in an exception context :arg exceptions: list of strings or None :arg before_token: the text of the function up to the token delimiter :arg after_token: the text of the function after the token delimiter :arg token: the token (only if we're looking at a close del...
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L141-L159
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from glom import glom def int_or_none(data): try: return int(data) except (TypeError, ValueError): ...
willkg/socorro-siggen
siggen/utils.py
collapse
python
def collapse( function, open_string, close_string, replacement='', exceptions=None, ): collapsed = [] open_count = 0 open_token = [] for i, char in enumerate(function): if not open_count: if char == open_string and not _is_exception(exceptions, function[:i], func...
Collapses the text between two delimiters in a frame function value This collapses the text between two delimiters and either removes the text altogether or replaces it with a replacement string. There are certain contexts in which we might not want to collapse the text between two delimiters. These a...
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L162-L239
[ "def _is_exception(exceptions, before_token, after_token, token):\n \"\"\"Predicate for whether the open token is in an exception context\n\n :arg exceptions: list of strings or None\n :arg before_token: the text of the function up to the token delimiter\n :arg after_token: the text of the function afte...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from glom import glom def int_or_none(data): try: return int(data) except (TypeError, ValueError): ...
willkg/socorro-siggen
siggen/utils.py
drop_prefix_and_return_type
python
def drop_prefix_and_return_type(function): DELIMITERS = { '(': ')', '{': '}', '[': ']', '<': '>', '`': "'" } OPEN = DELIMITERS.keys() CLOSE = DELIMITERS.values() # The list of tokens accumulated so far tokens = [] # Keeps track of open delimiters so ...
Takes the function value from a frame and drops prefix and return type For example:: static void * Allocator<MozJemallocBase>::malloc(unsigned __int64) ^ ^^^^^^ return type prefix This gets changes to this:: Allocator<MozJemallocBase>::malloc(unsigned __int64) This ...
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/utils.py#L242-L324
null
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from glom import glom def int_or_none(data): try: return int(data) except (TypeError, ValueError): ...
willkg/socorro-siggen
siggen/cmd_signature.py
main
python
def main(argv=None): parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG) parser.add_argument( '-v', '--verbose', help='increase output verbosity', action='store_true' ) parser.add_argument( '--format', help='specify output format: csv, text (default)' ) parse...
Takes crash data via args and generates a Socorro signature
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/cmd_signature.py#L111-L209
[ "def convert_to_crash_data(raw_crash, processed_crash):\n \"\"\"\n Takes a raw crash and a processed crash (these are Socorro-centric\n data structures) and converts them to a crash data structure used\n by signature generation.\n\n :arg raw_crash: raw crash data from Socorro\n :arg processed_cras...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import argparse import csv import os import sys import requests from .generator import SignatureGenerator from .utils ...
willkg/socorro-siggen
siggen/cmd_fetch_data.py
main
python
def main(): parser = argparse.ArgumentParser( formatter_class=WrappedTextHelpFormatter, description=DESCRIPTION ) parser.add_argument( '-v', '--verbose', help='increase output verbosity', action='store_true' ) parser.add_argument( 'crashid', help='crash id to generate...
Takes a crash id, pulls down data from Socorro, generates signature data
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/cmd_fetch_data.py#L73-L136
[ "def convert_to_crash_data(raw_crash, processed_crash):\n \"\"\"\n Takes a raw crash and a processed crash (these are Socorro-centric\n data structures) and converts them to a crash data structure used\n by signature generation.\n\n :arg raw_crash: raw crash data from Socorro\n :arg processed_cras...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import print_function import argparse import json import os import sys import requests from .utils im...
willkg/socorro-siggen
siggen/cmd_fetch_data.py
WrappedTextHelpFormatter._fill_text
python
def _fill_text(self, text, width, indent): parts = text.split('\n\n') for i, part in enumerate(parts): # Check to see if it's a bulleted list--if so, then fill each line if part.startswith('* '): subparts = part.split('\n') for j, subpart in enumer...
Wraps text like HelpFormatter, but doesn't squash lines This makes it easier to do lists and paragraphs.
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/cmd_fetch_data.py#L20-L39
null
class WrappedTextHelpFormatter(argparse.HelpFormatter): """Subclass that wraps description and epilog text taking paragraphs into account"""
willkg/socorro-siggen
siggen/generator.py
SignatureGenerator.generate
python
def generate(self, signature_data): result = Result() for rule in self.pipeline: rule_name = rule.__class__.__name__ try: if rule.predicate(signature_data, result): rule.action(signature_data, result) except Exception as exc: ...
Takes data and returns a signature :arg dict signature_data: data to use to generate a signature :returns: ``Result`` instance
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/generator.py#L74-L100
[ "def info(self, rule, msg, *args):\n if args:\n msg = msg % args\n self.notes.append('%s: %s' % (rule, msg))\n" ]
class SignatureGenerator: def __init__(self, pipeline=None, error_handler=None): """ :arg pipeline: list of rules to use for signature generation :arg error_handler: error handling function with signature ``fun(signature_data, exc_info, extra)`` """ self.pipeline...
willkg/socorro-siggen
siggen/cmd_doc.py
main
python
def main(argv=None): parser = argparse.ArgumentParser(description=DESCRIPTION) parser.add_argument( 'pipeline', help='Python dotted path to rules pipeline to document' ) parser.add_argument('output', help='output file') if argv is None: args = parser.parse_args() else: ...
Generates documentation for signature generation pipeline
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/cmd_doc.py#L68-L107
[ "def indent(text, prefix):\n text = text.replace('\\n', '\\n' + prefix)\n return text.strip()\n", "def import_rules(rules):\n module_path, attr = rules.rsplit('.', 1)\n module = importlib.import_module(module_path)\n return getattr(module, attr)\n", "def get_doc(cls):\n return 'Rule: %s\\n\\n%...
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import argparse import importlib import re import sys DESCRIPTION = """ Generates documentation for the specified sign...
willkg/socorro-siggen
siggen/rules.py
CSignatureTool.normalize_rust_function
python
def normalize_rust_function(self, function, line): # Drop the prefix and return type if there is any function = drop_prefix_and_return_type(function) # Collapse types function = collapse( function, open_string='<', close_string='>', replac...
Normalizes a single rust frame with a function
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/rules.py#L121-L156
[ "def collapse(\n function,\n open_string,\n close_string,\n replacement='',\n exceptions=None,\n):\n \"\"\"Collapses the text between two delimiters in a frame function value\n\n This collapses the text between two delimiters and either removes the text\n altogether or replaces it with a rep...
class CSignatureTool(SignatureTool): """Generates signature from C/C++/Rust stacks. This is the class for signature generation tools that work on breakpad C/C++ stacks. It normalizes frames and then runs them through the siglists to determine which frames should be part of the signature. """ ...
willkg/socorro-siggen
siggen/rules.py
CSignatureTool.normalize_cpp_function
python
def normalize_cpp_function(self, function, line): # Drop member function cv/ref qualifiers like const, const&, &, and && for ref in ('const', 'const&', '&&', '&'): if function.endswith(ref): function = function[:-len(ref)].strip() # Drop the prefix and return type if...
Normalizes a single cpp frame with a function
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/rules.py#L158-L208
[ "def collapse(\n function,\n open_string,\n close_string,\n replacement='',\n exceptions=None,\n):\n \"\"\"Collapses the text between two delimiters in a frame function value\n\n This collapses the text between two delimiters and either removes the text\n altogether or replaces it with a rep...
class CSignatureTool(SignatureTool): """Generates signature from C/C++/Rust stacks. This is the class for signature generation tools that work on breakpad C/C++ stacks. It normalizes frames and then runs them through the siglists to determine which frames should be part of the signature. """ ...
willkg/socorro-siggen
siggen/rules.py
CSignatureTool.normalize_frame
python
def normalize_frame( self, module=None, function=None, file=None, line=None, module_offset=None, offset=None, normalized=None, **kwargs # eat any extra kwargs passed in ): # If there's a cached normalized value, use that so we don't sp...
Normalizes a single frame Returns a structured conglomeration of the input parameters to serve as a signature. The parameter names of this function reflect the exact names of the fields from the jsonMDSW frame output. This allows this function to be invoked by passing a frame as ``**a_f...
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/rules.py#L210-L266
[ "def parse_source_file(source_file):\n \"\"\"Parses a source file thing and returns the file name\n\n Example:\n\n >>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')\n 'js/src/jit/MIR.h'\n\n :arg str source_file: the source file (\"file\") from a stack frame\n\n ...
class CSignatureTool(SignatureTool): """Generates signature from C/C++/Rust stacks. This is the class for signature generation tools that work on breakpad C/C++ stacks. It normalizes frames and then runs them through the siglists to determine which frames should be part of the signature. """ ...
willkg/socorro-siggen
siggen/rules.py
CSignatureTool._do_generate
python
def _do_generate(self, source_list, hang_type, crashed_thread, delimiter=' | '): notes = [] debug_notes = [] # shorten source_list to the first signatureSentinel sentinel_locations = [] for a_sentinel in self.signature_sentinels: if type(a_sentinel) == tuple: ...
each element of signatureList names a frame in the crash stack; and is: - a prefix of a relevant frame: Append this element to the signature - a relevant frame: Append this element and stop looking - irrelevant: Append this element only after seeing a prefix frame The signature is ...
train
https://github.com/willkg/socorro-siggen/blob/db7e3233e665a458a961c48da22e93a69b1d08d6/siggen/rules.py#L268-L351
null
class CSignatureTool(SignatureTool): """Generates signature from C/C++/Rust stacks. This is the class for signature generation tools that work on breakpad C/C++ stacks. It normalizes frames and then runs them through the siglists to determine which frames should be part of the signature. """ ...
inveniosoftware/invenio-db
invenio_db/ext.py
InvenioDB.init_app
python
def init_app(self, app, **kwargs): self.init_db(app, **kwargs) app.config.setdefault('ALEMBIC', { 'script_location': pkg_resources.resource_filename( 'invenio_db', 'alembic' ), 'version_locations': [ (base_entry.name, pkg_resources.res...
Initialize application object.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/ext.py#L34-L53
[ "def init_db(self, app, entry_point_group='invenio_db.models', **kwargs):\n \"\"\"Initialize Flask-SQLAlchemy extension.\"\"\"\n # Setup SQLAlchemy\n app.config.setdefault(\n 'SQLALCHEMY_DATABASE_URI',\n 'sqlite:///' + os.path.join(app.instance_path, app.name + '.db')\n )\n app.config.s...
class InvenioDB(object): """Invenio database extension.""" def __init__(self, app=None, **kwargs): """Extension initialization.""" self.alembic = Alembic(run_mkdir=False, command_name='alembic') if app: self.init_app(app, **kwargs) def init_db(self, app, entry_point_gr...
inveniosoftware/invenio-db
invenio_db/ext.py
InvenioDB.init_db
python
def init_db(self, app, entry_point_group='invenio_db.models', **kwargs): # Setup SQLAlchemy app.config.setdefault( 'SQLALCHEMY_DATABASE_URI', 'sqlite:///' + os.path.join(app.instance_path, app.name + '.db') ) app.config.setdefault('SQLALCHEMY_ECHO', False) ...
Initialize Flask-SQLAlchemy extension.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/ext.py#L55-L88
[ "def versioning_models_registered(manager, base):\n \"\"\"Return True if all versioning models have been registered.\"\"\"\n declared_models = base._decl_class_registry.keys()\n return all(versioning_model_classname(manager, c) in declared_models\n for c in manager.pending_classes)\n", "def...
class InvenioDB(object): """Invenio database extension.""" def __init__(self, app=None, **kwargs): """Extension initialization.""" self.alembic = Alembic(run_mkdir=False, command_name='alembic') if app: self.init_app(app, **kwargs) def init_app(self, app, **kwargs): ...
inveniosoftware/invenio-db
invenio_db/ext.py
InvenioDB.init_versioning
python
def init_versioning(self, app, database, versioning_manager=None): try: pkg_resources.get_distribution('sqlalchemy_continuum') except pkg_resources.DistributionNotFound: # pragma: no cover default_versioning = False else: default_versioning = True ap...
Initialize the versioning support using SQLAlchemy-Continuum.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/ext.py#L90-L142
null
class InvenioDB(object): """Invenio database extension.""" def __init__(self, app=None, **kwargs): """Extension initialization.""" self.alembic = Alembic(run_mkdir=False, command_name='alembic') if app: self.init_app(app, **kwargs) def init_app(self, app, **kwargs): ...
inveniosoftware/invenio-db
invenio_db/shared.py
do_sqlite_connect
python
def do_sqlite_connect(dbapi_connection, connection_record): # Enable foreign key constraint checking cursor = dbapi_connection.cursor() cursor.execute('PRAGMA foreign_keys=ON') cursor.close()
Ensure SQLite checks foreign key constraints. For further details see "Foreign key support" sections on https://docs.sqlalchemy.org/en/latest/dialects/sqlite.html#foreign-key-support
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/shared.py#L82-L91
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Shared database object for Invenio.""" from flask_sqlalchemy import SQLAlchemy as...
inveniosoftware/invenio-db
invenio_db/shared.py
SQLAlchemy.apply_driver_hacks
python
def apply_driver_hacks(self, app, info, options): # Don't forget to apply hacks defined on parent object. super(SQLAlchemy, self).apply_driver_hacks(app, info, options) if info.drivername == 'sqlite': connect_args = options.setdefault('connect_args', {}) if 'isolation_l...
Call before engine creation.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/shared.py#L32-L79
null
class SQLAlchemy(FlaskSQLAlchemy): """Implement or overide extension methods."""
inveniosoftware/invenio-db
invenio_db/cli.py
create
python
def create(verbose): click.secho('Creating all tables!', fg='yellow', bold=True) with click.progressbar(_db.metadata.sorted_tables) as bar: for table in bar: if verbose: click.echo(' Creating table {0}'.format(table)) table.create(bind=_db.engine, checkfirst=True)...
Create tables.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/cli.py#L49-L58
[ "def create_alembic_version_table():\n \"\"\"Create alembic_version table.\"\"\"\n alembic = current_app.extensions['invenio-db'].alembic\n if not alembic.migration_context._has_version_table():\n alembic.migration_context._ensure_version_table()\n for head in alembic.script_directory.revisio...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line interface for database management.""" from __future__ import a...
inveniosoftware/invenio-db
invenio_db/cli.py
drop
python
def drop(verbose): click.secho('Dropping all tables!', fg='red', bold=True) with click.progressbar(reversed(_db.metadata.sorted_tables)) as bar: for table in bar: if verbose: click.echo(' Dropping table {0}'.format(table)) table.drop(bind=_db.engine, checkfirst=Tr...
Drop tables.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/cli.py#L67-L76
[ "def drop_alembic_version_table():\n \"\"\"Drop alembic_version table.\"\"\"\n if _db.engine.dialect.has_table(_db.engine, 'alembic_version'):\n alembic_version = _db.Table('alembic_version', _db.metadata,\n autoload_with=_db.engine)\n alembic_version.drop(bind...
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line interface for database management.""" from __future__ import a...
inveniosoftware/invenio-db
invenio_db/cli.py
init
python
def init(): click.secho('Creating database {0}'.format(_db.engine.url), fg='green') if not database_exists(str(_db.engine.url)): create_database(str(_db.engine.url))
Create database.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/cli.py#L81-L86
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line interface for database management.""" from __future__ import a...
inveniosoftware/invenio-db
invenio_db/cli.py
destroy
python
def destroy(): click.secho('Destroying database {0}'.format(_db.engine.url), fg='red', bold=True) if _db.engine.name == 'sqlite': try: drop_database(_db.engine.url) except FileNotFoundError as e: click.secho('Sqlite database has not been initialised', ...
Drop database.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/cli.py#L94-L105
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2015-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Click command-line interface for database management.""" from __future__ import a...
inveniosoftware/invenio-db
invenio_db/utils.py
rebuild_encrypted_properties
python
def rebuild_encrypted_properties(old_key, model, properties): inspector = reflection.Inspector.from_engine(db.engine) primary_key_names = inspector.get_primary_keys(model.__tablename__) new_secret_key = current_app.secret_key db.session.expunge_all() try: with db.session.begin_nested(): ...
Rebuild a model's EncryptedType properties when the SECRET_KEY is changed. :param old_key: old SECRET_KEY. :param model: the affected db model. :param properties: list of properties to rebuild.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/utils.py#L21-L58
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # from .signals import secret_key_changed """Invenio-DB utility functions.""" from f...
inveniosoftware/invenio-db
invenio_db/utils.py
create_alembic_version_table
python
def create_alembic_version_table(): alembic = current_app.extensions['invenio-db'].alembic if not alembic.migration_context._has_version_table(): alembic.migration_context._ensure_version_table() for head in alembic.script_directory.revision_map._real_heads: alembic.migration_context...
Create alembic_version table.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/utils.py#L61-L67
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # from .signals import secret_key_changed """Invenio-DB utility functions.""" from f...
inveniosoftware/invenio-db
invenio_db/utils.py
drop_alembic_version_table
python
def drop_alembic_version_table(): if _db.engine.dialect.has_table(_db.engine, 'alembic_version'): alembic_version = _db.Table('alembic_version', _db.metadata, autoload_with=_db.engine) alembic_version.drop(bind=_db.engine)
Drop alembic_version table.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/utils.py#L70-L75
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # from .signals import secret_key_changed """Invenio-DB utility functions.""" from f...
inveniosoftware/invenio-db
invenio_db/utils.py
versioning_model_classname
python
def versioning_model_classname(manager, model): if manager.options.get('use_module_name', True): return '%s%sVersion' % ( model.__module__.title().replace('.', ''), model.__name__) else: return '%sVersion' % (model.__name__,)
Get the name of the versioned model class.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/utils.py#L78-L84
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # from .signals import secret_key_changed """Invenio-DB utility functions.""" from f...
inveniosoftware/invenio-db
invenio_db/utils.py
versioning_models_registered
python
def versioning_models_registered(manager, base): declared_models = base._decl_class_registry.keys() return all(versioning_model_classname(manager, c) in declared_models for c in manager.pending_classes)
Return True if all versioning models have been registered.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/utils.py#L87-L91
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2017-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # from .signals import secret_key_changed """Invenio-DB utility functions.""" from f...
inveniosoftware/invenio-db
invenio_db/alembic/35c1075e6360_force_naming_convention.py
upgrade
python
def upgrade(): op.execute('COMMIT') # See https://bitbucket.org/zzzeek/alembic/issue/123 ctx = op.get_context() metadata = ctx.opts['target_metadata'] metadata.naming_convention = NAMING_CONVENTION metadata.bind = ctx.connection.engine insp = Inspector.from_engine(ctx.connection.engine) fo...
Upgrade database.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/alembic/35c1075e6360_force_naming_convention.py#L31-L98
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Force naming convention.""" import sqlalchemy as sa from alembic import op, util ...
inveniosoftware/invenio-db
invenio_db/alembic/dbdbc1b19cf2_create_transaction_table.py
upgrade
python
def upgrade(): op.create_table( 'transaction', sa.Column('issued_at', sa.DateTime(), nullable=True), sa.Column('id', sa.BigInteger(), nullable=False), sa.Column('remote_addr', sa.String(length=50), nullable=True), ) op.create_primary_key('pk_transaction', 'transaction', ['id'...
Update database.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/alembic/dbdbc1b19cf2_create_transaction_table.py#L23-L33
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create transaction table.""" import sqlalchemy as sa from alembic import op from ...
inveniosoftware/invenio-db
invenio_db/alembic/dbdbc1b19cf2_create_transaction_table.py
downgrade
python
def downgrade(): op.drop_table('transaction') if op._proxy.migration_context.dialect.supports_sequences: op.execute(DropSequence(Sequence('transaction_id_seq')))
Downgrade database.
train
https://github.com/inveniosoftware/invenio-db/blob/9009a4cf79574083e129909cf3d2656568550184/invenio_db/alembic/dbdbc1b19cf2_create_transaction_table.py#L36-L40
null
# -*- coding: utf-8 -*- # # This file is part of Invenio. # Copyright (C) 2016-2018 CERN. # # Invenio is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. """Create transaction table.""" import sqlalchemy as sa from alembic import op from ...
klen/flask-pw
flask_pw/models.py
Signal.connect
python
def connect(self, receiver): if not callable(receiver): raise ValueError('Invalid receiver: %s' % receiver) self.receivers.append(receiver)
Append receiver.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/models.py#L56-L60
null
class Signal: """Simplest signals implementation. :: @Model.post_save def example(instance, created=False): pass """ __slots__ = 'receivers' def __init__(self): """Initialize the signal.""" self.receivers = [] def __call__(self, receiver): ...
klen/flask-pw
flask_pw/models.py
Signal.disconnect
python
def disconnect(self, receiver): try: self.receivers.remove(receiver) except ValueError: raise ValueError('Unknown receiver: %s' % receiver)
Remove receiver.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/models.py#L67-L72
null
class Signal: """Simplest signals implementation. :: @Model.post_save def example(instance, created=False): pass """ __slots__ = 'receivers' def __init__(self): """Initialize the signal.""" self.receivers = [] def connect(self, receiver): ...
klen/flask-pw
flask_pw/models.py
Signal.send
python
def send(self, instance, *args, **kwargs): for receiver in self.receivers: receiver(instance, *args, **kwargs)
Send signal.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/models.py#L74-L77
null
class Signal: """Simplest signals implementation. :: @Model.post_save def example(instance, created=False): pass """ __slots__ = 'receivers' def __init__(self): """Initialize the signal.""" self.receivers = [] def connect(self, receiver): ...
klen/flask-pw
flask_pw/models.py
Model.select
python
def select(cls, *args, **kwargs): query = super(Model, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query
Support read slaves.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/models.py#L105-L109
null
class Model(with_metaclass(BaseSignalModel, pw.Model)): @classmethod @classmethod def raw(cls, *args, **kwargs): query = super(Model, cls).raw(*args, **kwargs) if query._sql.lower().startswith('select'): query.database = cls._get_read_database() return query @prop...
klen/flask-pw
flask_pw/models.py
Model.save
python
def save(self, force_insert=False, **kwargs): created = force_insert or not bool(self.pk) self.pre_save.send(self, created=created) super(Model, self).save(force_insert=force_insert, **kwargs) self.post_save.send(self, created=created)
Send signals.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/models.py#L130-L135
null
class Model(with_metaclass(BaseSignalModel, pw.Model)): @classmethod def select(cls, *args, **kwargs): """Support read slaves.""" query = super(Model, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query @classmethod def raw(cls, *args, **...
klen/flask-pw
flask_pw/models.py
Model.delete_instance
python
def delete_instance(self, *args, **kwargs): self.pre_delete.send(self) super(Model, self).delete_instance(*args, **kwargs) self.post_delete.send(self)
Send signals.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/models.py#L137-L141
null
class Model(with_metaclass(BaseSignalModel, pw.Model)): @classmethod def select(cls, *args, **kwargs): """Support read slaves.""" query = super(Model, cls).select(*args, **kwargs) query.database = cls._get_read_database() return query @classmethod def raw(cls, *args, **...
klen/flask-pw
flask_pw/__init__.py
get_database
python
def get_database(obj, **params): if isinstance(obj, string_types): return connect(obj, **params) return obj
Get database from given URI/Object.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L244-L248
null
import logging import os from importlib import import_module import peewee as pw from cached_property import cached_property from flask._compat import string_types from peewee_migrate.router import Router from playhouse.db_url import connect from .models import Model, BaseSignalModel, Choices # noqa __license__ = "...
klen/flask-pw
flask_pw/__init__.py
Peewee.init_app
python
def init_app(self, app, database=None): # Register application if not app: raise RuntimeError('Invalid application.') self.app = app if not hasattr(app, 'extensions'): app.extensions = {} app.extensions['peewee'] = self app.config.setdefault('PEE...
Initialize application.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L30-L70
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def connect(self): """Initialize connection to databse.""" LOGGER.info('Connecting [%s]...
klen/flask-pw
flask_pw/__init__.py
Peewee.close
python
def close(self, response): LOGGER.info('Closing [%s]', os.getpid()) if not self.database.is_closed(): self.database.close() return response
Close connection to database.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L77-L82
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
klen/flask-pw
flask_pw/__init__.py
Peewee.Model
python
def Model(self): Model_ = self.app.config['PEEWEE_MODELS_CLASS'] meta_params = {'database': self.database} if self.slaves and self.app.config['PEEWEE_USE_READ_SLAVES']: meta_params['read_slaves'] = self.slaves Meta = type('Meta', (), meta_params) return type('Model',...
Bind model to self database.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L85-L93
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
klen/flask-pw
flask_pw/__init__.py
Peewee.models
python
def models(self): Model_ = self.app.config['PEEWEE_MODELS_CLASS'] ignore = self.app.config['PEEWEE_MODELS_IGNORE'] models = [] if Model_ is not Model: try: mod = import_module(self.app.config['PEEWEE_MODELS_MODULE']) for model in dir(mod): ...
Return self.application models.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L96-L115
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
klen/flask-pw
flask_pw/__init__.py
Peewee.cmd_create
python
def cmd_create(self, name, auto=False): LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIGRATE_TABLE']) if auto: ...
Create a new migration.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L117-L130
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
klen/flask-pw
flask_pw/__init__.py
Peewee.cmd_migrate
python
def cmd_migrate(self, name=None, fake=False): from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=se...
Run migrations.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L132-L145
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
klen/flask-pw
flask_pw/__init__.py
Peewee.cmd_rollback
python
def cmd_rollback(self, name): from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('INFO') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['P...
Rollback migrations.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L147-L158
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
klen/flask-pw
flask_pw/__init__.py
Peewee.cmd_list
python
def cmd_list(self): from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('DEBUG') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MIG...
List migrations.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L160-L175
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
klen/flask-pw
flask_pw/__init__.py
Peewee.cmd_merge
python
def cmd_merge(self): from peewee_migrate.router import Router, LOGGER LOGGER.setLevel('DEBUG') LOGGER.propagate = 0 router = Router(self.database, migrate_dir=self.app.config['PEEWEE_MIGRATE_DIR'], migrate_table=self.app.config['PEEWEE_MI...
Merge migrations.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L177-L188
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
klen/flask-pw
flask_pw/__init__.py
Peewee.manager
python
def manager(self): from flask_script import Manager, Command manager = Manager(usage="Migrate database.") manager.add_command('create', Command(self.cmd_create)) manager.add_command('migrate', Command(self.cmd_migrate)) manager.add_command('rollback', Command(self.cmd_rollback))...
Integrate a Flask-Script.
train
https://github.com/klen/flask-pw/blob/04d7846f0c89f2b2331b238b1c8223368c2a40a7/flask_pw/__init__.py#L191-L202
null
class Peewee(object): def __init__(self, app=None): """Initialize the plugin.""" self.app = app self.database = pw.Proxy() if app is not None: self.init_app(app) def init_app(self, app, database=None): """Initialize application.""" # Register applic...
xolox/python-rotate-backups
rotate_backups/cli.py
main
python
def main(): coloredlogs.install(syslog=True) # Command line option defaults. rotation_scheme = {} kw = dict(include_list=[], exclude_list=[]) parallel = False use_sudo = False # Internal state. selected_locations = [] # Parse the command line arguments. try: options, argu...
Command line interface for the ``rotate-backups`` program.
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/cli.py#L205-L303
[ "def coerce_retention_period(value):\n \"\"\"\n Coerce a retention period to a Python value.\n\n :param value: A string containing the text 'always', a number or\n an expression that can be evaluated to a number.\n :returns: A number or the string 'always'.\n :raises: :exc:`~exceptio...
# rotate-backups: Simple command line interface for backup rotation. # # Author: Peter Odding <peter@peterodding.com> # Last Change: August 2, 2018 # URL: https://github.com/xolox/python-rotate-backups """ Usage: rotate-backups [OPTIONS] [DIRECTORY, ..] Easy rotation of backups based on the Python package by the same...
xolox/python-rotate-backups
rotate_backups/__init__.py
coerce_location
python
def coerce_location(value, **options): # Location objects pass through untouched. if not isinstance(value, Location): # Other values are expected to be strings. if not isinstance(value, string_types): msg = "Expected Location object or string, got %s instead!" raise Value...
Coerce a string to a :class:`Location` object. :param value: The value to coerce (a string or :class:`Location` object). :param options: Any keyword arguments are passed on to :func:`~executor.contexts.create_context()`. :returns: A :class:`Location` object.
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L93-L119
null
# rotate-backups: Simple command line interface for backup rotation. # # Author: Peter Odding <peter@peterodding.com> # Last Change: August 3, 2018 # URL: https://github.com/xolox/python-rotate-backups """ Simple to use Python API for rotation of backups. The :mod:`rotate_backups` module contains the Python API of th...
xolox/python-rotate-backups
rotate_backups/__init__.py
coerce_retention_period
python
def coerce_retention_period(value): # Numbers pass through untouched. if not isinstance(value, numbers.Number): # Other values are expected to be strings. if not isinstance(value, string_types): msg = "Expected string, got %s instead!" raise ValueError(msg % type(value)) ...
Coerce a retention period to a Python value. :param value: A string containing the text 'always', a number or an expression that can be evaluated to a number. :returns: A number or the string 'always'. :raises: :exc:`~exceptions.ValueError` when the string can't be coerced.
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L122-L147
null
# rotate-backups: Simple command line interface for backup rotation. # # Author: Peter Odding <peter@peterodding.com> # Last Change: August 3, 2018 # URL: https://github.com/xolox/python-rotate-backups """ Simple to use Python API for rotation of backups. The :mod:`rotate_backups` module contains the Python API of th...
xolox/python-rotate-backups
rotate_backups/__init__.py
load_config_file
python
def load_config_file(configuration_file=None, expand=True): expand_notice_given = False if configuration_file: loader = ConfigLoader(available_files=[configuration_file], strict=True) else: loader = ConfigLoader(program_name='rotate-backups', strict=False) for section in loader.section_n...
Load a configuration file with backup directories and rotation schemes. :param configuration_file: Override the pathname of the configuration file to load (a string or :data:`None`). :param expand: :data:`True` to expand filename patterns to their matches, :dat...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L150-L220
[ "def coerce_location(value, **options):\n \"\"\"\n Coerce a string to a :class:`Location` object.\n\n :param value: The value to coerce (a string or :class:`Location` object).\n :param options: Any keyword arguments are passed on to\n :func:`~executor.contexts.create_context()`.\n ...
# rotate-backups: Simple command line interface for backup rotation. # # Author: Peter Odding <peter@peterodding.com> # Last Change: August 3, 2018 # URL: https://github.com/xolox/python-rotate-backups """ Simple to use Python API for rotation of backups. The :mod:`rotate_backups` module contains the Python API of th...
xolox/python-rotate-backups
rotate_backups/__init__.py
rotate_backups
python
def rotate_backups(directory, rotation_scheme, **options): program = RotateBackups(rotation_scheme=rotation_scheme, **options) program.rotate_backups(directory)
Rotate the backups in a directory according to a flexible rotation scheme. .. note:: This function exists to preserve backwards compatibility with older versions of the `rotate-backups` package where all of the logic was exposed as a single function. Please refer to the do...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L223-L235
null
# rotate-backups: Simple command line interface for backup rotation. # # Author: Peter Odding <peter@peterodding.com> # Last Change: August 3, 2018 # URL: https://github.com/xolox/python-rotate-backups """ Simple to use Python API for rotation of backups. The :mod:`rotate_backups` module contains the Python API of th...
xolox/python-rotate-backups
rotate_backups/__init__.py
RotateBackups.rotate_concurrent
python
def rotate_concurrent(self, *locations, **kw): timer = Timer() pool = CommandPool(concurrency=10) logger.info("Scanning %s ..", pluralize(len(locations), "backup location")) for location in locations: for cmd in self.rotate_backups(location, prepare=True, **kw): ...
Rotate the backups in the given locations concurrently. :param locations: One or more values accepted by :func:`coerce_location()`. :param kw: Any keyword arguments are passed on to :func:`rotate_backups()`. This function uses :func:`rotate_backups()` to prepare rotation commands for t...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L403-L431
null
class RotateBackups(PropertyManager): """Python API for the ``rotate-backups`` program.""" def __init__(self, rotation_scheme, **options): """ Initialize a :class:`RotateBackups` object. :param rotation_scheme: Used to set :attr:`rotation_scheme`. :param options: Any keyword a...
xolox/python-rotate-backups
rotate_backups/__init__.py
RotateBackups.rotate_backups
python
def rotate_backups(self, location, load_config=True, prepare=False): rotation_commands = [] location = coerce_location(location) # Load configuration overrides by user? if load_config: location = self.load_config_file(location) # Collect the backups in the given direc...
Rotate the backups in a directory according to a flexible rotation scheme. :param location: Any value accepted by :func:`coerce_location()`. :param load_config: If :data:`True` (so by default) the rotation scheme and other options can be customized by the user in ...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L433-L512
[ "def coerce_location(value, **options):\n \"\"\"\n Coerce a string to a :class:`Location` object.\n\n :param value: The value to coerce (a string or :class:`Location` object).\n :param options: Any keyword arguments are passed on to\n :func:`~executor.contexts.create_context()`.\n ...
class RotateBackups(PropertyManager): """Python API for the ``rotate-backups`` program.""" def __init__(self, rotation_scheme, **options): """ Initialize a :class:`RotateBackups` object. :param rotation_scheme: Used to set :attr:`rotation_scheme`. :param options: Any keyword a...
xolox/python-rotate-backups
rotate_backups/__init__.py
RotateBackups.load_config_file
python
def load_config_file(self, location): location = coerce_location(location) for configured_location, rotation_scheme, options in load_config_file(self.config_file, expand=False): if configured_location.match(location): logger.verbose("Loading configuration for %s ..", location...
Load a rotation scheme and other options from a configuration file. :param location: Any value accepted by :func:`coerce_location()`. :returns: The configured or given :class:`Location` object.
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L514-L544
[ "def coerce_location(value, **options):\n \"\"\"\n Coerce a string to a :class:`Location` object.\n\n :param value: The value to coerce (a string or :class:`Location` object).\n :param options: Any keyword arguments are passed on to\n :func:`~executor.contexts.create_context()`.\n ...
class RotateBackups(PropertyManager): """Python API for the ``rotate-backups`` program.""" def __init__(self, rotation_scheme, **options): """ Initialize a :class:`RotateBackups` object. :param rotation_scheme: Used to set :attr:`rotation_scheme`. :param options: Any keyword a...
xolox/python-rotate-backups
rotate_backups/__init__.py
RotateBackups.collect_backups
python
def collect_backups(self, location): backups = [] location = coerce_location(location) logger.info("Scanning %s for backups ..", location) location.ensure_readable() for entry in natsort(location.context.list_entries(location.directory)): match = TIMESTAMP_PATTERN.sea...
Collect the backups at the given location. :param location: Any value accepted by :func:`coerce_location()`. :returns: A sorted :class:`list` of :class:`Backup` objects (the backups are sorted by their date). :raises: :exc:`~exceptions.ValueError` when the given directory does...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L546-L579
[ "def coerce_location(value, **options):\n \"\"\"\n Coerce a string to a :class:`Location` object.\n\n :param value: The value to coerce (a string or :class:`Location` object).\n :param options: Any keyword arguments are passed on to\n :func:`~executor.contexts.create_context()`.\n ...
class RotateBackups(PropertyManager): """Python API for the ``rotate-backups`` program.""" def __init__(self, rotation_scheme, **options): """ Initialize a :class:`RotateBackups` object. :param rotation_scheme: Used to set :attr:`rotation_scheme`. :param options: Any keyword a...
xolox/python-rotate-backups
rotate_backups/__init__.py
RotateBackups.group_backups
python
def group_backups(self, backups): backups_by_frequency = dict((frequency, collections.defaultdict(list)) for frequency in SUPPORTED_FREQUENCIES) for b in backups: backups_by_frequency['minutely'][(b.year, b.month, b.day, b.hour, b.minute)].append(b) backups_by_frequency['hourly']...
Group backups collected by :func:`collect_backups()` by rotation frequencies. :param backups: A :class:`set` of :class:`Backup` objects. :returns: A :class:`dict` whose keys are the names of rotation frequencies ('hourly', 'daily', etc.) and whose values are dictiona...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L581-L601
null
class RotateBackups(PropertyManager): """Python API for the ``rotate-backups`` program.""" def __init__(self, rotation_scheme, **options): """ Initialize a :class:`RotateBackups` object. :param rotation_scheme: Used to set :attr:`rotation_scheme`. :param options: Any keyword a...
xolox/python-rotate-backups
rotate_backups/__init__.py
RotateBackups.apply_rotation_scheme
python
def apply_rotation_scheme(self, backups_by_frequency, most_recent_backup): if not self.rotation_scheme: raise ValueError("Refusing to use empty rotation scheme! (all backups would be deleted)") for frequency, backups in backups_by_frequency.items(): # Ignore frequencies not speci...
Apply the user defined rotation scheme to the result of :func:`group_backups()`. :param backups_by_frequency: A :class:`dict` in the format generated by :func:`group_backups()`. :param most_recent_backup: The :class:`~datetime.datetime` of the most ...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L603-L649
null
class RotateBackups(PropertyManager): """Python API for the ``rotate-backups`` program.""" def __init__(self, rotation_scheme, **options): """ Initialize a :class:`RotateBackups` object. :param rotation_scheme: Used to set :attr:`rotation_scheme`. :param options: Any keyword a...
xolox/python-rotate-backups
rotate_backups/__init__.py
RotateBackups.find_preservation_criteria
python
def find_preservation_criteria(self, backups_by_frequency): backups_to_preserve = collections.defaultdict(list) for frequency, delta in ORDERED_FREQUENCIES: for period in backups_by_frequency[frequency].values(): for backup in period: backups_to_preserve[b...
Collect the criteria used to decide which backups to preserve. :param backups_by_frequency: A :class:`dict` in the format generated by :func:`group_backups()` which has been processed by :func:`apply_rotation_scheme()`. :returns:...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L651-L667
null
class RotateBackups(PropertyManager): """Python API for the ``rotate-backups`` program.""" def __init__(self, rotation_scheme, **options): """ Initialize a :class:`RotateBackups` object. :param rotation_scheme: Used to set :attr:`rotation_scheme`. :param options: Any keyword a...
xolox/python-rotate-backups
rotate_backups/__init__.py
Location.mount_point
python
def mount_point(self): try: return self.context.capture('stat', '--format=%m', self.directory, silent=True) except ExternalCommandFailed: return None
The pathname of the mount point of :attr:`directory` (a string or :data:`None`). If the ``stat --format=%m ...`` command that is used to determine the mount point fails, the value of this property defaults to :data:`None`. This enables graceful degradation on e.g. Mac OS X whose ``stat`` ...
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L693-L705
null
class Location(PropertyManager): """:class:`Location` objects represent a root directory containing backups.""" @required_property def context(self): """An execution context created using :mod:`executor.contexts`.""" @required_property def directory(self): """The pathname of a dir...
xolox/python-rotate-backups
rotate_backups/__init__.py
Location.ensure_exists
python
def ensure_exists(self): if not self.context.is_directory(self.directory): # This can also happen when we don't have permission to one of the # parent directories so we'll point that out in the error message # when it seems applicable (so as not to confuse users). ...
Make sure the location exists.
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L729-L744
null
class Location(PropertyManager): """:class:`Location` objects represent a root directory containing backups.""" @required_property def context(self): """An execution context created using :mod:`executor.contexts`.""" @required_property def directory(self): """The pathname of a dir...
xolox/python-rotate-backups
rotate_backups/__init__.py
Location.ensure_readable
python
def ensure_readable(self): self.ensure_exists() if not self.context.is_readable(self.directory): if self.context.have_superuser_privileges: msg = "The directory %s isn't readable!" raise ValueError(msg % self) else: raise ValueError...
Make sure the location exists and is readable.
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L746-L758
null
class Location(PropertyManager): """:class:`Location` objects represent a root directory containing backups.""" @required_property def context(self): """An execution context created using :mod:`executor.contexts`.""" @required_property def directory(self): """The pathname of a dir...
xolox/python-rotate-backups
rotate_backups/__init__.py
Location.ensure_writable
python
def ensure_writable(self): self.ensure_exists() if not self.context.is_writable(self.directory): if self.context.have_superuser_privileges: msg = "The directory %s isn't writable!" raise ValueError(msg % self) else: raise ValueError...
Make sure the directory exists and is writable.
train
https://github.com/xolox/python-rotate-backups/blob/611c72b2806952bf2bb84c38a4b5f856ea334707/rotate_backups/__init__.py#L760-L771
null
class Location(PropertyManager): """:class:`Location` objects represent a root directory containing backups.""" @required_property def context(self): """An execution context created using :mod:`executor.contexts`.""" @required_property def directory(self): """The pathname of a dir...