signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def parse_port_pin(name_str): | if len(name_str) < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if name_str[<NUM_LIT:0>] != '<STR_LIT:P>':<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if name_str[<NUM_LIT:1>] < '<STR_LIT:A>' or name_str[<NUM_LIT:1>] > '<STR_LIT>':<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>po... | Parses a string and returns a (port-num, pin-num) tuple. | f7029:m0 |
def ptr(self): | if self.fn_num is None:<EOL><INDENT>return self.func<EOL><DEDENT>return '<STR_LIT>'.format(self.func, self.fn_num)<EOL> | Returns the numbered function (i.e. USART6) for this AF. | f7029:c0:m2 |
def print(self): | cond_var = None<EOL>if self.supported:<EOL><INDENT>cond_var = conditional_var('<STR_LIT>'.format(self.func, self.fn_num))<EOL>print_conditional_if(cond_var)<EOL>print('<STR_LIT>', end='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>', end='<STR_LIT>')<EOL><DEDENT>fn_num = self.fn_num<EOL>if fn_num is None:<... | Prints the C representation of this AF. | f7029:c0:m4 |
def parse_port_pin(name_str): | if len(name_str) < <NUM_LIT:3>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if name_str[:<NUM_LIT:2>] != '<STR_LIT>':<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not name_str[<NUM_LIT:2>:].isdigit():<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>port = int(int(name_str[<NUM_LIT:2>:]) / <N... | Parses a string and returns a (port, gpio_bit) tuple. | f7037:m0 |
def parse_port_pin(name_str): | if len(name_str) < <NUM_LIT:4>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if name_str[<NUM_LIT:0>:<NUM_LIT:2>] != '<STR_LIT>':<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if name_str[<NUM_LIT:2>] not in ('<STR_LIT:A>', '<STR_LIT:B>', '<STR_LIT:C>', '<STR_LIT:D>', '<STR_LIT:E>', '<STR_LIT>'):<EOL><... | Parses a string and returns a (port-num, pin-num) tuple. | f7057:m0 |
def ptr(self): | if self.fn_num is None:<EOL><INDENT>return self.func<EOL><DEDENT>return '<STR_LIT>'.format(self.func, self.fn_num)<EOL> | Returns the numbered function (i.e. USART6) for this AF. | f7057:c0:m2 |
def print(self): | if self.supported:<EOL><INDENT>print('<STR_LIT>', end='<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>', end='<STR_LIT>')<EOL><DEDENT>fn_num = self.fn_num<EOL>if fn_num is None:<EOL><INDENT>fn_num = <NUM_LIT:0><EOL><DEDENT>print('<STR_LIT>'.format(self.idx,<EOL>self.func, fn_num, self.pin_type, self.ptr(), ... | Prints the C representation of this AF. | f7057:c0:m4 |
def get_product_metadata_path(product_name): | string_date = product_name.split('<STR_LIT:_>')[-<NUM_LIT:1>]<EOL>date = datetime.datetime.strptime(string_date, '<STR_LIT>')<EOL>path = '<STR_LIT>'.format(date.year, date.month, date.day, product_name)<EOL>return {<EOL>product_name: {<EOL>'<STR_LIT>': '<STR_LIT>'.format(path, '<STR_LIT>'),<EOL>'<STR_LIT>': get_tile_me... | gets a single products metadata | f7078:m1 |
def get_products_metadata_path(year, month, day): | products = {}<EOL>path = '<STR_LIT>'.format(year, month, day)<EOL>for key in bucket.objects.filter(Prefix=path):<EOL><INDENT>product_path = key.key.replace(path, '<STR_LIT>').split('<STR_LIT:/>')<EOL>name = product_path[<NUM_LIT:0>]<EOL>if name not in products:<EOL><INDENT>products[name] = {}<EOL><DEDENT>if product_pat... | Get paths to multiple products metadata | f7078:m2 |
def product_metadata(product, dst_folder, counter=None, writers=[file_writer], geometry_check=None): | if not counter:<EOL><INDENT>counter = {<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': []<EOL>}<EOL><DEDENT>s3_url = '<STR_LIT>'<EOL>product_meta_link = '<STR_LIT>'.format(s3_url, product['<STR_LIT>'])<EOL>product_info = requests.get(product_meta_link, stream=... | Extract metadata for a specific product | f7079:m3 |
def daily_metadata(year, month, day, dst_folder, writers=[file_writer], geometry_check=None,<EOL>num_worker_threads=<NUM_LIT:1>): | threaded = False<EOL>counter = {<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>': []<EOL>}<EOL>if num_worker_threads > <NUM_LIT:1>:<EOL><INDENT>threaded = True<EOL>queue = Queue()<EOL><DEDENT>year_dir = os.path.join(dst_folder, str(year))<EOL>month_dir = os.path... | Extra metadata for all products in a specific date | f7079:m5 |
def range_metadata(start, end, dst_folder, num_worker_threads=<NUM_LIT:0>, writers=[file_writer], geometry_check=None): | assert isinstance(start, date)<EOL>assert isinstance(end, date)<EOL>delta = end - start<EOL>dates = []<EOL>for i in range(delta.days + <NUM_LIT:1>):<EOL><INDENT>dates.append(start + timedelta(days=i))<EOL><DEDENT>days = len(dates)<EOL>total_counter = {<EOL>'<STR_LIT>': days,<EOL>'<STR_LIT>': <NUM_LIT:0>,<EOL>'<STR_LIT>... | Extra metadata for all products in a date range | f7079:m6 |
def epsg_code(geojson): | if isinstance(geojson, dict):<EOL><INDENT>if '<STR_LIT>' in geojson:<EOL><INDENT>urn = geojson['<STR_LIT>']['<STR_LIT>']['<STR_LIT:name>'].split('<STR_LIT::>')<EOL>if '<STR_LIT>' in urn:<EOL><INDENT>try:<EOL><INDENT>return int(urn[-<NUM_LIT:1>])<EOL><DEDENT>except (TypeError, ValueError):<EOL><INDENT>return None<EOL><D... | get the espg code from the crs system | f7081:m0 |
def convert_coordinates(coords, origin, wgs84, wrapped): | if isinstance(coords, list) or isinstance(coords, tuple):<EOL><INDENT>try:<EOL><INDENT>if isinstance(coords[<NUM_LIT:0>], list) or isinstance(coords[<NUM_LIT:0>], tuple):<EOL><INDENT>return [convert_coordinates(list(c), origin, wgs84, wrapped) for c in coords]<EOL><DEDENT>elif isinstance(coords[<NUM_LIT:0>], float):<EO... | Convert coordinates from one crs to another | f7081:m2 |
def to_latlon(geojson, origin_espg=None): | if isinstance(geojson, dict):<EOL><INDENT>if origin_espg:<EOL><INDENT>code = origin_espg<EOL><DEDENT>else:<EOL><INDENT>code = epsg_code(geojson)<EOL><DEDENT>if code:<EOL><INDENT>origin = Proj(init='<STR_LIT>' % code)<EOL>wgs84 = Proj(init='<STR_LIT>')<EOL>wrapped = test_wrap_coordinates(geojson['<STR_LIT>'], origin, wg... | Convert a given geojson to wgs84. The original epsg must be included insde the crs
tag of geojson | f7081:m3 |
def camelcase_underscore(name): | s1 = re.sub('<STR_LIT>', r'<STR_LIT>', name)<EOL>return re.sub('<STR_LIT>', r'<STR_LIT>', s1).lower()<EOL> | Convert camelcase names to underscore | f7081:m4 |
def get_tiles_list(element): | tiles = {}<EOL>for el in element:<EOL><INDENT>g = (el.findall('<STR_LIT>') or el.findall('<STR_LIT>'))[<NUM_LIT:0>]<EOL>name = g.attrib['<STR_LIT>']<EOL>name_parts = name.split('<STR_LIT:_>')<EOL>mgs = name_parts[-<NUM_LIT:2>]<EOL>tiles[mgs] = name<EOL><DEDENT>return tiles<EOL> | Returns the list of all tile names from Product_Organisation element
in metadata.xml | f7081:m5 |
def metadata_to_dict(metadata): | tree = etree.parse(metadata)<EOL>root = tree.getroot()<EOL>meta = OrderedDict()<EOL>keys = [<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>]<EOL>for key in keys:<EOL><INDENT>try:<EOL><INDENT>meta[key.lower()] ... | Looks at metadata.xml file of sentinel product and extract useful keys
Returns a python dict | f7081:m6 |
def get_tile_geometry(path, origin_espg, tolerance=<NUM_LIT>): | with rasterio.open(path) as src:<EOL><INDENT>b = src.bounds<EOL>tile_shape = Polygon([(b[<NUM_LIT:0>], b[<NUM_LIT:1>]), (b[<NUM_LIT:2>], b[<NUM_LIT:1>]), (b[<NUM_LIT:2>], b[<NUM_LIT:3>]), (b[<NUM_LIT:0>], b[<NUM_LIT:3>]), (b[<NUM_LIT:0>], b[<NUM_LIT:1>])])<EOL>tile_geojson = mapping(tile_shape)<EOL>image = src.read(<NU... | Calculate the data and tile geometry for sentinel-2 tiles | f7081:m7 |
def tile_metadata(tile, product, geometry_check=None): | grid = '<STR_LIT>'.format(pad(tile['<STR_LIT>'], <NUM_LIT:2>), tile['<STR_LIT>'], tile['<STR_LIT>'])<EOL>meta = OrderedDict({<EOL>'<STR_LIT>': product['<STR_LIT>'][grid]<EOL>})<EOL>logger.info('<STR_LIT>' % (threading.current_thread().name, tile['<STR_LIT:path>']))<EOL>meta['<STR_LIT:date>'] = tile['<STR_LIT>'].split('... | Generate metadata for a given tile
- geometry_check is a function the determines whether to calculate the geometry by downloading
B01 and override provided geometry in tilejson. The meta object is passed to this function.
The function return a True or False response. | f7081:m9 |
def __init__(self,<EOL>session: sa_orm.Session,<EOL>models: Union[List[type], Dict[str, type]],<EOL>date_factory: Optional[FunctionType] = None,<EOL>datetime_factory: Optional[FunctionType] = None): | super().__init__()<EOL>self.session = session<EOL>self.models = (models if isinstance(models, dict)<EOL>else {model.__name__: model for model in models})<EOL>self.model_instances = {}<EOL>self.datetime_factory = datetime_factory or utils.datetime_factory<EOL>self.date_factory = date_factory or utils.date_factory<EOL> | :param session: the sqlalchemy session
:param models: list of model classes, or dictionary of models by name
:param date_factory: function used to generate dates (takes one
parameter, the text value to convert)
:param datetime_factory: function used to generate datetimes (takes one
parameter, the text value to ... | f7086:c0:m0 |
def create_or_update(self,<EOL>identifier: Identifier,<EOL>data: Dict[str, Any],<EOL>) -> Tuple[object, bool]: | raise NotImplementedError<EOL> | Create or update a model.
:param identifier: An object with :attr:`class_name` and :attr:`key`
attributes
:param data: A dictionary keyed by column name, with values being the
converted values to set on the model instance
:return: A two-tuple of model instance and whether or not it was ... | f7088:c0:m1 |
def get_relationships(self, class_name: str) -> Set[str]: | raise NotImplementedError<EOL> | Return a list of model attribute names that could have relationships for
the given model class name.
:param class_name: The name of the class name to discover relationships for.
:return: A set of model attribute names. | f7088:c0:m2 |
def maybe_convert_values(self,<EOL>identifier: Identifier,<EOL>data: Dict[str, Any],<EOL>) -> Dict[str, Any]: | raise NotImplementedError<EOL> | Takes a dictionary of raw values for a specific identifier, as parsed
from the YAML file, and depending upon the type of db column the data
is meant for, decides what to do with the value (eg leave it alone,
convert a string to a date/time instance, or convert identifiers to
model instances by calling :meth:`self.loade... | f7088:c0:m3 |
def commit(self): | pass<EOL> | If your ORM implements the data mapper pattern instead of active
record, then you can implement this method to commit the session after
all the models have been added to it. | f7088:c0:m4 |
def create_all(self, progress_callback: Optional[callable] = None) -> Dict[str, object]: | if not self._loaded:<EOL><INDENT>self._load_data()<EOL><DEDENT>dag = nx.DiGraph()<EOL>for model_class_name, dependencies in self.relationships.items():<EOL><INDENT>dag.add_node(model_class_name)<EOL>for dep in dependencies:<EOL><INDENT>dag.add_edge(model_class_name, dep)<EOL><DEDENT><DEDENT>try:<EOL><INDENT>creation_or... | Creates all the models discovered from fixture files in :attr:`fixtures_dir`.
:param progress_callback: An optional function to track progress. It must take three
parameters:
- an :class:`Identifier`
- the model instance
- a... | f7099:c0:m1 |
def convert_identifiers(self, identifiers: Union[Identifier, List[Identifier]]): | if not identifiers:<EOL><INDENT>return identifiers<EOL><DEDENT>def _create_or_update(identifier):<EOL><INDENT>data = self._cache[identifier.key]<EOL>return self.factory.create_or_update(identifier, data)[<NUM_LIT:0>]<EOL><DEDENT>if isinstance(identifiers, Identifier):<EOL><INDENT>return _create_or_update(identifiers)<E... | Convert an individual :class:`Identifier` to a model instance,
or a list of Identifiers to a list of model instances. | f7099:c0:m2 |
def _load_data(self): | filenames = []<EOL>model_identifiers = defaultdict(list)<EOL>for fixtures_dir in self.fixture_dirs:<EOL><INDENT>for filename in os.listdir(fixtures_dir):<EOL><INDENT>path = os.path.join(fixtures_dir, filename)<EOL>file_ext = filename[filename.find('<STR_LIT:.>')+<NUM_LIT:1>:]<EOL>if os.path.isfile(path) and file_ext in... | Load all fixtures from :attr:`fixtures_dir` | f7099:c0:m3 |
def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]): | class_name = filename[:filename.rfind('<STR_LIT:.>')]<EOL>rendered_yaml = self.env.get_template(filename).render(<EOL>model_identifiers=model_identifiers)<EOL>fixture_data, self.relationships[class_name] = self._post_process_yaml_data(<EOL>yaml.load(rendered_yaml),<EOL>self.factory.get_relationships(class_name))<EOL>fo... | Load fixtures from the given filename | f7099:c0:m4 |
def _post_process_yaml_data(self,<EOL>fixture_data: Dict[str, Dict[str, Any]],<EOL>relationship_columns: Set[str],<EOL>) -> Tuple[Dict[str, Dict[str, Any]], List[str]]: | rv = {}<EOL>relationships = set()<EOL>if not fixture_data:<EOL><INDENT>return rv, relationships<EOL><DEDENT>for identifier_id, data in fixture_data.items():<EOL><INDENT>new_data = {}<EOL>for col_name, value in data.items():<EOL><INDENT>if col_name not in relationship_columns:<EOL><INDENT>new_data[col_name] = value<EOL>... | Convert and normalize identifier strings to Identifiers, as well as determine
class relationships. | f7099:c0:m5 |
def _ensure_env(self, env: Union[jinja2.Environment, None]): | if not env:<EOL><INDENT>env = jinja2.Environment()<EOL><DEDENT>if not env.loader:<EOL><INDENT>env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename])<EOL><DEDENT>if '<STR_LIT>' not in env.globals:<EOL><INDENT>faker = Faker()<EOL>faker.seed(<NUM_LIT>)<EOL>env.globals['<STR_LIT>'] = faker<EOL><DEDENT>i... | Make sure the jinja environment is minimally configured. | f7099:c0:m6 |
@contextlib.contextmanager<EOL><INDENT>def _preloading_env(self):<DEDENT> | ctx = self.env.globals<EOL>try:<EOL><INDENT>ctx['<STR_LIT>'] = lambda *a, **kw: None<EOL>ctx['<STR_LIT>'] = lambda *a, **kw: None<EOL>yield self.env<EOL><DEDENT>finally:<EOL><INDENT>ctx['<STR_LIT>'] = jinja2.contextfunction(random_model)<EOL>ctx['<STR_LIT>'] = jinja2.contextfunction(random_models)<EOL><DEDENT> | A "stripped" jinja environment. | f7099:c0:m7 |
def random_model(ctx, model_class_name): | model_identifiers = ctx['<STR_LIT>'][model_class_name]<EOL>if not model_identifiers:<EOL><INDENT>return '<STR_LIT:None>'<EOL><DEDENT>idx = random.randrange(<NUM_LIT:0>, len(model_identifiers))<EOL>return '<STR_LIT>' % (model_class_name, model_identifiers[idx])<EOL> | Get a random model identifier by class name. For example::
# db/fixtures/Category.yml
{% for i in range(0, 10) %}
category{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
category: {{ random_model('Category') }}
Will render to something like t... | f7100:m2 |
def random_models(ctx, model_class_name, min_count=<NUM_LIT:0>, max_count=<NUM_LIT:3>): | model_identifiers = ctx['<STR_LIT>'][model_class_name]<EOL>num_models = random.randint(min_count, min(max_count, len(model_identifiers)))<EOL>if num_models == <NUM_LIT:0>:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>added = set()<EOL>while len(added) < num_models:<EOL><INDENT>idx = random.randrange(<NUM_LIT:0>, len(mode... | Get a random model identifier by class name. Example usage::
# db/fixtures/Tag.yml
{% for i in range(0, 10) %}
tag{{ i }}:
name: {{ faker.name() }}
{% endfor %}
# db/fixtures/Post.yml
a_blog_post:
tags: {{ random_models('Tag') }}
Will render to something like the following::
... | f7100:m3 |
@task<EOL>def install_gitflow(): | if not run('<STR_LIT>', hide=True, warn=True).ok:<EOL><INDENT>run('<STR_LIT>')<EOL>run('<STR_LIT>')<EOL>run('<STR_LIT>')<EOL><DEDENT> | Install git-flow if not found | f7104:m0 |
@task<EOL>def next_release(major=False, minor=False, patch=True): | import semantic_version<EOL>prev = run('<STR_LIT>', warn=True, hide=True).stdout or '<STR_LIT>'<EOL>ver = semantic_version.Version.coerce(prev.strip())<EOL>if major:<EOL><INDENT>return ver.next_major()<EOL><DEDENT>if minor:<EOL><INDENT>return ver.next_minor()<EOL><DEDENT>if patch:<EOL><INDENT>return ver.next_patch()<EO... | Get next release version (by major, minor or patch) | f7104:m1 |
@task(install_gitflow)<EOL>def start_rel_branch(relver): | print('<STR_LIT>', relver)<EOL>run('<STR_LIT>'.format(relver), hide=True)<EOL> | Start release branch | f7104:m2 |
@task(install_gitflow)<EOL>def finish_rel_branch(relver): | print('<STR_LIT>', relver)<EOL>run('<STR_LIT>'.format(ver=relver), hide=True)<EOL> | Finish release branch | f7104:m3 |
@task<EOL>def package(): | print('<STR_LIT>')<EOL>run('<STR_LIT>', hide=True)<EOL> | Package application for release | f7104:m4 |
def _iter_changelog(changelog): | first_line = True<EOL>current_release = None<EOL>prev_msg = None<EOL>yield current_release, '<STR_LIT>'<EOL>for hash, tags, msg in changelog:<EOL><INDENT>if prev_msg is None:<EOL><INDENT>prev_msg = msg<EOL><DEDENT>else:<EOL><INDENT>if prev_msg.lower() == msg.lower():<EOL><INDENT>continue<EOL><DEDENT>else:<EOL><INDENT>p... | Convert a oneline log iterator to formatted strings.
:param changelog: An iterator of one line log entries like
that given by _iter_log_oneline.
:return: An iterator over (release, formatted changelog) tuples. | f7104:m5 |
def _iter_log_inner(debug): | if debug:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>changelog = run('<STR_LIT>', hide=True).stdout.strip().decode('<STR_LIT:utf-8>', '<STR_LIT:replace>')<EOL>for line in changelog.split('<STR_LIT:\n>'):<EOL><INDENT>line_parts = line.split()<EOL>if len(line_parts) < <NUM_LIT:2>:<EOL><INDENT>continue<EOL><DEDENT>if line... | Iterate over --oneline log entries.
This parses the output intro a structured form but does not apply
presentation logic to the output - making it suitable for different
uses.
:return: An iterator of (hash, tags_set, 1st_line) tuples. | f7104:m6 |
def _iter_log_oneline(debug): | return _iter_log_inner(debug)<EOL> | Iterate over --oneline log entries if possible.
This parses the output into a structured form but does not apply
presentation logic to the output - making it suitable for different
uses. | f7104:m7 |
@task<EOL>def write_changelog(debug=False): | changelog = _iter_log_oneline(debug)<EOL>if changelog:<EOL><INDENT>changelog = _iter_changelog(changelog)<EOL><DEDENT>if not changelog:<EOL><INDENT>return<EOL><DEDENT>if debug:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>new_changelog = os.path.join(os.path.curdir, '<STR_LIT>')<EOL>if (os.path.exists(new_changelog)<EOL>... | Write a changelog based on the git changelog. | f7104:m8 |
@task<EOL>def prepare_release(ver=None): | write_changelog(True)<EOL>if ver is None:<EOL><INDENT>ver = next_release()<EOL><DEDENT>print('<STR_LIT>')<EOL>run('<STR_LIT>'.format(ver), hide=True)<EOL>sha = run('<STR_LIT>', hide=True).stdout<EOL>run('<STR_LIT>'.format(ver=ver, sha=sha), hide=True)<EOL>package()<EOL>write_changelog()<EOL>run('<STR_LIT>'.format(ver),... | Prepare release artifacts | f7104:m9 |
@task<EOL>def publish(idx=None): | if idx is None:<EOL><INDENT>idx = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>idx = '<STR_LIT>' + idx<EOL><DEDENT>run('<STR_LIT>'.format(idx))<EOL>run('<STR_LIT>'.format(idx))<EOL> | Publish packaged distributions to pypi index | f7104:m10 |
@task<EOL>def release(major=False, minor=False, patch=True, pypi_index=None): | relver = next_release(major, minor, patch)<EOL>start_rel_branch(relver)<EOL>prepare_release(relver)<EOL>finish_rel_branch(relver)<EOL>publish(pypi_index)<EOL> | Overall process flow for performing a release | f7104:m11 |
@task<EOL>def clean(all=False, docs=False, dist=False, extra=None): | run('<STR_LIT>')<EOL>run('<STR_LIT>')<EOL>patterns = ['<STR_LIT>', '<STR_LIT>']<EOL>if all or docs:<EOL><INDENT>patterns.append('<STR_LIT>')<EOL><DEDENT>if all or dist:<EOL><INDENT>patterns.append('<STR_LIT>')<EOL><DEDENT>if extra:<EOL><INDENT>patterns.append(extra)<EOL><DEDENT>for pattern in patterns:<EOL><INDENT>run(... | Clean up build files | f7104:m12 |
def _make_opt_list(opts, group): | import copy<EOL>import itertools<EOL>_opts = [(group, list(itertools.chain(*opts)))]<EOL>return [(g, copy.deepcopy(o)) for g, o in _opts]<EOL> | Generate a list of tuple containing group, options
:param opts: option lists associated with a group
:type opts: list
:param group: name of an option group
:type group: str
:return: a list of (group_name, opts) tuples
:rtype: list | f7111:m0 |
def list_opts(): | return _make_opt_list([OPTS], '<STR_LIT>')<EOL> | Returns a list of oslo_config options available in the library.
The returned list includes all oslo_config options which may be registered
at runtime by the library.
Each element of the list is a tuple. The first element is the name of the
group under which the list of elements in the second element wi... | f7111:m1 |
def utcnow(): | return datetime.datetime.utcnow()<EOL> | Gets current time.
:returns: current time from utc
:rtype: :py:obj:`datetime.datetime` | f7112:m0 |
def is_older_than(before, delta): | return utcnow() - before > delta<EOL> | Checks if a datetime is older than delta
:param datetime before: a datetime to check
:param timedelta delta: period of time to compare against
:returns: ``True`` if before is older than time period else ``False``
:rtype: bool | f7112:m1 |
def is_newer_than(after, delta): | return after - utcnow() > delta<EOL> | Checks if a datetime is newer than delta
:param datetime after: a datetime to check
:param timedelta delta: period of time to compare against
:returns: ``True`` if before is newer than time period else ``False``
:rtype: bool | f7112:m2 |
def get_client(config_file=None, apikey=None, username=None, userpass=None,<EOL>service_url=None, verify_ssl_certs=None, select_first=None): | from oslo_config import cfg<EOL>from tvdbapi_client import api<EOL>if config_file is not None:<EOL><INDENT>cfg.CONF([], default_config_files=[config_file])<EOL><DEDENT>else:<EOL><INDENT>if apikey is not None:<EOL><INDENT>cfg.CONF.set_override('<STR_LIT>', apikey, '<STR_LIT>')<EOL><DEDENT>if username is not None:<EOL><I... | Configure the API service and creates a new instance of client.
:param str config_file: absolute path to configuration file
:param str apikey: apikey from thetvdb
:param str username: username used on thetvdb
:param str userpass: password used on thetvdb
:param str service_url: the url for thetvdb ... | f7113:m0 |
def requires_auth(func): | @six.wraps(func)<EOL>def wrapper(self, *args, **kwargs):<EOL><INDENT>if self.token_expired:<EOL><INDENT>self.authenticate()<EOL><DEDENT>return func(self, *args, **kwargs)<EOL><DEDENT>return wrapper<EOL> | Handle authentication checks.
.. py:decorator:: requires_auth
Checks if the token has expired and performs authentication if needed. | f7114:m0 |
def __init__(self, apikey=None, username=None, userpass=None): | self.__apikey = apikey or cfg.CONF.tvdb.apikey<EOL>self.__username = username or cfg.CONF.tvdb.username<EOL>self.__userpass = userpass or cfg.CONF.tvdb.userpass<EOL>self.__token = None<EOL>self._token_timer = None<EOL>self._session = None<EOL>self._headers = DEFAULT_HEADERS<EOL>self._language = '<STR_LIT>'<EOL> | Create new instance of API client.
:param str apikey: apikey from thetvdb
:param str username: username used on thetvdb
:param str userpass: password used on thetvdb | f7114:c0:m0 |
@property<EOL><INDENT>def headers(self):<DEDENT> | self._headers.update(**{'<STR_LIT>': self.language})<EOL>if self.__token:<EOL><INDENT>self._headers.update(<EOL>**{'<STR_LIT>': '<STR_LIT>' % self.__token})<EOL><DEDENT>return self._headers<EOL> | Provide access to updated headers. | f7114:c0:m1 |
@property<EOL><INDENT>def language(self):<DEDENT> | return self._language<EOL> | Provide access to current language. | f7114:c0:m2 |
@language.setter<EOL><INDENT>def language(self, abbr):<DEDENT> | self._language = abbr<EOL> | Provide access to update language. | f7114:c0:m3 |
@property<EOL><INDENT>def token_expired(self):<DEDENT> | if self._token_timer is None:<EOL><INDENT>return True<EOL><DEDENT>return timeutil.is_newer_than(self._token_timer, timeutil.ONE_HOUR)<EOL> | Provide access to flag indicating if token has expired. | f7114:c0:m4 |
@property<EOL><INDENT>def session(self):<DEDENT> | if self._session is None:<EOL><INDENT>self._session = cachecontrol.CacheControl(<EOL>requests.Session(),<EOL>cache=caches.FileCache('<STR_LIT>'))<EOL><DEDENT>return self._session<EOL> | Provide access to request session with local cache enabled. | f7114:c0:m5 |
@exceptions.error_map<EOL><INDENT>def _exec_request(self, service, method=None, path_args=None, data=None,<EOL>params=None):<DEDENT> | if path_args is None:<EOL><INDENT>path_args = []<EOL><DEDENT>req = {<EOL>'<STR_LIT>': method or '<STR_LIT>',<EOL>'<STR_LIT:url>': '<STR_LIT:/>'.join(str(a).strip('<STR_LIT:/>') for a in [<EOL>cfg.CONF.tvdb.service_url, service] + path_args),<EOL>'<STR_LIT:data>': json.dumps(data) if data else None,<EOL>'<STR_LIT>': sel... | Execute request. | f7114:c0:m6 |
def authenticate(self): | if self.__token:<EOL><INDENT>try:<EOL><INDENT>resp = self._refresh_token()<EOL><DEDENT>except exceptions.TVDBRequestException as err:<EOL><INDENT>if getattr(err.response, '<STR_LIT>', <NUM_LIT:0>) == <NUM_LIT>:<EOL><INDENT>resp = self._login()<EOL><DEDENT>else:<EOL><INDENT>raise<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><I... | Aquire authorization token for using thetvdb apis. | f7114:c0:m9 |
@requires_auth<EOL><INDENT>def search_series(self, **kwargs):<DEDENT> | params = {}<EOL>for arg, val in six.iteritems(kwargs):<EOL><INDENT>if arg in SERIES_BY:<EOL><INDENT>params[arg] = val<EOL><DEDENT><DEDENT>resp = self._exec_request(<EOL>'<STR_LIT>', path_args=['<STR_LIT>'], params=params)<EOL>if cfg.CONF.tvdb.select_first:<EOL><INDENT>return resp['<STR_LIT:data>'][<NUM_LIT:0>]<EOL><DED... | Provide the ability to search for a series.
.. warning::
authorization token required
The following search arguments currently supported:
* name
* imdbId
* zap2itId
:param kwargs: keyword arguments to search for series
:returns: series... | f7114:c0:m10 |
@requires_auth<EOL><INDENT>def get_series(self, series_id):<DEDENT> | return self._exec_request('<STR_LIT>', path_args=[series_id])['<STR_LIT:data>']<EOL> | Retrieve series record.
.. warning::
authorization token required
:param str series_id: id of series as found on thetvdb
:returns: series record
:rtype: dict | f7114:c0:m11 |
@requires_auth<EOL><INDENT>def get_episodes(self, series_id, **kwargs):<DEDENT> | params = {'<STR_LIT>': <NUM_LIT:1>}<EOL>for arg, val in six.iteritems(kwargs):<EOL><INDENT>if arg in EPISODES_BY:<EOL><INDENT>params[arg] = val<EOL><DEDENT><DEDENT>return self._exec_request(<EOL>'<STR_LIT>',<EOL>path_args=[series_id, '<STR_LIT>', '<STR_LIT>'], params=params)['<STR_LIT:data>']<EOL> | All episodes for a given series.
Paginated with 100 results per page.
.. warning::
authorization token required
The following search arguments currently supported:
* airedSeason
* airedEpisode
* imdbId
* dvdSeason
* dvd... | f7114:c0:m12 |
@requires_auth<EOL><INDENT>def get_episodes_summary(self, series_id):<DEDENT> | return self._exec_request(<EOL>'<STR_LIT>', path_args=[series_id, '<STR_LIT>', '<STR_LIT>'])['<STR_LIT:data>']<EOL> | Return a summary of the episodes and seasons for the series.
.. warning::
authorization token required
.. note::
Season "0" is for all episodes that are considered to be specials.
:param str series_id: id of series as found on thetvdb
:returns: summary of the... | f7114:c0:m13 |
@requires_auth<EOL><INDENT>def get_series_image_info(self, series_id):<DEDENT> | return self._exec_request(<EOL>'<STR_LIT>', path_args=[series_id, '<STR_LIT>'])['<STR_LIT:data>']<EOL> | Return a summary of the images for a particular series.
.. warning::
authorization token required
:param str series_id: id of series as found on thetvdb
:returns: summary of the images for the series
:rtype: dict | f7114:c0:m14 |
@requires_auth<EOL><INDENT>def get_episode(self, episode_id):<DEDENT> | return self._exec_request('<STR_LIT>', path_args=[episode_id])['<STR_LIT:data>']<EOL> | Return the full information for a given episode id.
.. warning::
authorization token required
:param str episode_id: id of episode as found on thetvdb
:returns: episode record
:rtype: dict | f7114:c0:m15 |
def error_map(func): | @six.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>except exceptions.RequestException as err:<EOL><INDENT>raise TVDBRequestException(<EOL>err,<EOL>response=getattr(err, '<STR_LIT>', None),<EOL>request=getattr(err, '<STR_LIT>', None))<EOL><DEDENT><DED... | Wrap exceptions raised by requests.
.. py:decorator:: error_map | f7115:m0 |
def construct(self): | def _any(thing, fields=None):<EOL><INDENT>"""<STR_LIT>"""<EOL>ret = None<EOL>if isinstance(thing, QuerySet):<EOL><INDENT>ret = _qs(thing, fields)<EOL><DEDENT>elif isinstance(thing, (tuple, list, set)):<EOL><INDENT>ret = _list(thing, fields)<EOL><DEDENT>elif isinstance(thing, dict):<EOL><INDENT>ret = _dict(thing, fields... | Recursively serialize a lot of types, and
in cases where it doesn't recognize the type,
it will fall back to Django's `smart_unicode`.
Returns `dict`. | f7123:c0:m2 |
def render(self): | raise NotImplementedError("<STR_LIT>")<EOL> | This super emitter does not implement `render`,
this is a job for the specific emitter below. | f7123:c0:m4 |
def stream_render(self, request, stream=True): | yield self.render(request)<EOL> | Tells our patched middleware not to look
at the contents, and returns a generator
rather than the buffered string. Should be
more memory friendly for large datasets. | f7123:c0:m5 |
@classmethod<EOL><INDENT>def get(cls, format):<DEDENT> | if format in cls.EMITTERS:<EOL><INDENT>return cls.EMITTERS.get(format)<EOL><DEDENT>raise ValueError("<STR_LIT>" % format)<EOL> | Gets an emitter, returns the class and a content-type. | f7123:c0:m6 |
@classmethod<EOL><INDENT>def register(cls, name, klass, content_type='<STR_LIT>'):<DEDENT> | cls.EMITTERS[name] = (klass, content_type)<EOL> | Register an emitter.
Parameters::
- `name`: The name of the emitter ('json', 'xml', 'yaml', ...)
- `klass`: The emitter class.
- `content_type`: The content type to serve response as. | f7123:c0:m7 |
@classmethod<EOL><INDENT>def unregister(cls, name):<DEDENT> | return cls.EMITTERS.pop(name, None)<EOL> | Remove an emitter from the registry. Useful if you don't
want to provide output in one of the built-in emitters. | f7123:c0:m8 |
def determine_emitter(self, request, *args, **kwargs): | em = kwargs.pop('<STR_LIT>', None)<EOL>if not em:<EOL><INDENT>em = request.GET.get('<STR_LIT>', '<STR_LIT>')<EOL><DEDENT>return em<EOL> | Function for determening which emitter to use
for output. It lives here so you can easily subclass
`Resource` in order to change how emission is detected.
You could also check for the `Accept` HTTP header here,
since that pretty much makes sense. Refer to `Mimer` for
that as well. | f7123:c3:m1 |
def form_validation_response(self, e): | resp = rc.BAD_REQUEST<EOL>resp.write('<STR_LIT:U+0020>'+str(e.form.errors))<EOL>return resp<EOL> | Method to return form validation error information.
You will probably want to override this in your own
`Resource` subclass. | f7123:c3:m2 |
@property<EOL><INDENT>def anonymous(self):<DEDENT> | if hasattr(self.handler, '<STR_LIT>'):<EOL><INDENT>anon = self.handler.anonymous<EOL>if callable(anon):<EOL><INDENT>return anon<EOL><DEDENT>for klass in list(typemapper.keys()):<EOL><INDENT>if anon == klass.__name__:<EOL><INDENT>return klass<EOL><DEDENT><DEDENT><DEDENT>return None<EOL> | Gets the anonymous handler. Also tries to grab a class
if the `anonymous` value is a string, so that we can define
anonymous handlers that aren't defined yet (like, when
you're subclassing your basehandler into an anonymous one.) | f7123:c3:m3 |
@vary_on_headers('<STR_LIT>')<EOL><INDENT>def __call__(self, request, *args, **kwargs):<DEDENT> | rm = request.method.upper()<EOL>if rm == "<STR_LIT>":<EOL><INDENT>coerce_put_post(request)<EOL><DEDENT>actor, anonymous = self.authenticate(request, rm)<EOL>if anonymous is CHALLENGE:<EOL><INDENT>return actor()<EOL><DEDENT>else:<EOL><INDENT>handler = actor<EOL><DEDENT>if rm in ('<STR_LIT:POST>', '<STR_LIT>'):<EOL><INDE... | NB: Sends a `Vary` header so we don't cache requests
that are different (OAuth stuff in `Authorization` header.) | f7123:c3:m5 |
@staticmethod<EOL><INDENT>def cleanup_request(request):<DEDENT> | for method_type in ('<STR_LIT:GET>', '<STR_LIT>', '<STR_LIT:POST>', '<STR_LIT>'):<EOL><INDENT>block = getattr(request, method_type, { })<EOL>if True in [ k.startswith("<STR_LIT>") for k in list(block.keys()) ]:<EOL><INDENT>sanitized = block.copy()<EOL>for k in list(sanitized.keys()):<EOL><INDENT>if k.startswith("<STR_L... | Removes `oauth_` keys from various dicts on the
request object, and returns the sanitized version. | f7123:c3:m6 |
def error_handler(self, e, request, meth, em_format): | if isinstance(e, FormValidationError):<EOL><INDENT>return self.form_validation_response(e)<EOL><DEDENT>elif isinstance(e, TypeError):<EOL><INDENT>result = rc.BAD_REQUEST<EOL>hm = HandlerMethod(meth)<EOL>sig = hm.signature<EOL>msg = '<STR_LIT>'<EOL>if sig:<EOL><INDENT>msg += '<STR_LIT>' % sig<EOL><DEDENT>else:<EOL><INDE... | Override this method to add handling of errors customized for your
needs | f7123:c3:m8 |
def address_inline(request, prefix="<STR_LIT>", country_code=None, template_name="<STR_LIT>"): | country_prefix = "<STR_LIT>"<EOL>prefix = request.POST.get('<STR_LIT>', prefix)<EOL>if prefix:<EOL><INDENT>country_prefix = prefix + '<STR_LIT>'<EOL><DEDENT>country_code = request.POST.get(country_prefix, country_code)<EOL>form_class = form_factory(country_code=country_code)<EOL>if request.method == "<STR_LIT:POST>":<E... | Displays postal address with localized fields | f7124:m0 |
def coerce_put_post(request): | if request.method == "<STR_LIT>":<EOL><INDENT>if hasattr(request, '<STR_LIT>'):<EOL><INDENT>del request._post<EOL>del request._files<EOL><DEDENT>try:<EOL><INDENT>request.method = "<STR_LIT:POST>"<EOL>request._load_post_and_files()<EOL>request.method = "<STR_LIT>"<EOL><DEDENT>except AttributeError:<EOL><INDENT>request.M... | Django doesn't particularly understand REST.
In case we send data over PUT, Django won't
actually look at the data and load it. We need
to twist its arm here.
The try/except abominiation here is due to a bug
in mod_python. This should fix it. | f7143:m1 |
def __getattr__(self, attr): | try:<EOL><INDENT>(r, c) = self.CODES.get(attr)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise AttributeError(attr)<EOL><DEDENT>class HttpResponseWrapper(HttpResponse):<EOL><INDENT>"""<STR_LIT>"""<EOL>def _set_content(self, content):<EOL><INDENT>"""<STR_LIT>"""<EOL>if not isinstance(content, basestring) and hasattr(con... | Returns a fresh `HttpResponse` when getting
an "attribute". This is backwards compatible
with 0.2, which is important. | f7143:c0:m0 |
def loader_for_type(self, ctype): | for loadee, mimes in Mimer.TYPES.iteritems():<EOL><INDENT>for mime in mimes:<EOL><INDENT>if ctype.startswith(mime):<EOL><INDENT>return loadee<EOL><DEDENT><DEDENT><DEDENT> | Gets a function ref to deserialize content
for a certain mimetype. | f7143:c4:m2 |
def content_type(self): | type_formencoded = "<STR_LIT>"<EOL>ctype = self.request.META.get('<STR_LIT>', type_formencoded)<EOL>if type_formencoded in ctype:<EOL><INDENT>return None<EOL><DEDENT>return ctype<EOL> | Returns the content type of the request in all cases where it is
different than a submitted form - application/x-www-form-urlencoded | f7143:c4:m3 |
def translate(self): | ctype = self.content_type()<EOL>self.request.content_type = ctype<EOL>if not self.is_multipart() and ctype:<EOL><INDENT>loadee = self.loader_for_type(ctype)<EOL>if loadee:<EOL><INDENT>try:<EOL><INDENT>self.request.data = loadee(self.request.raw_post_data)<EOL>self.request.POST = self.request.PUT = dict()<EOL><DEDENT>ex... | Will look at the `Content-type` sent by the client, and maybe
deserialize the contents into the format they sent. This will
work for JSON, YAML, XML and Pickle. Since the data is not just
key-value (and maybe just a list), the data will be placed on
`request.data` instead, and the handler will have to read from
there.
... | f7143:c4:m4 |
def service_factory(prefix, base): | name = prefix.title() + base.__name__<EOL>cls = type(name, (base,), {'<STR_LIT:name>': prefix})<EOL>return cls<EOL> | Test utility to create subclasses of the above ServiceHandler classes
based on a prefix and base. The prefix is set as the ``name`` attribute
on the resulting type.
e.g. ``service_factory("foo", ServicePoolHandler)`` returns a type
called ``FooServicePoolHandler`` that inherits from ``ServicePoolHandle... | f7150:m4 |
@rpc<EOL><INDENT>def proxy(self, method, *args):<DEDENT> | getattr(self.rpcproxy, method)(*args)<EOL> | Proxies RPC calls to ``method`` on itself, so we can test handling
of errors in remote services. | f7164:c1:m3 |
def iter_extensions(extension): | for _, ext in inspect.getmembers(extension, is_extension):<EOL><INDENT>for item in iter_extensions(ext):<EOL><INDENT>yield item<EOL><DEDENT>yield ext<EOL><DEDENT> | Depth-first iterator over sub-extensions on `extension`. | f7192:m4 |
def setup(self): | Called on bound Extensions before the container starts.
Extensions should do any required initialisation here. | f7192:c0:m1 | |
def start(self): | Called on bound Extensions when the container has successfully
started.
This is only called after all other Extensions have successfully
returned from :meth:`Extension.setup`. If the Extension reacts
to external events, it should now start acting upon them. | f7192:c0:m2 | |
def stop(self): | Called when the service container begins to shut down.
Extensions should do any graceful shutdown here. | f7192:c0:m3 | |
def kill(self): | Called to stop this extension without grace.
Extensions should urgently shut down here. This means
stopping as soon as possible by omitting cleanup.
This may be distinct from ``stop()`` for certain dependencies.
For example, :class:`~messaging.QueueConsumer` tracks messages being
... | f7192:c0:m4 | |
def bind(self, container): | def clone(prototype):<EOL><INDENT>if prototype.is_bound():<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>cls = type(prototype)<EOL>args, kwargs = prototype.__params<EOL>instance = cls(*args, **kwargs)<EOL>instance.container = weakref.proxy(container)<EOL>return instance<EOL><DEDENT>instance = clone(self)<EOL>... | Get an instance of this Extension to bind to `container`. | f7192:c0:m5 |
def bind(self, container): | <EOL>shared = container.shared_extensions.get(self.sharing_key)<EOL>if shared:<EOL><INDENT>return shared<EOL><DEDENT>instance = super(SharedExtension, self).bind(container)<EOL>container.shared_extensions[self.sharing_key] = instance<EOL>return instance<EOL> | Bind implementation that supports sharing. | f7192:c1:m1 |
def bind(self, container, attr_name): | instance = super(DependencyProvider, self).bind(container)<EOL>instance.attr_name = attr_name<EOL>self.attr_name = attr_name<EOL>return instance<EOL> | Get an instance of this Dependency to bind to `container` with
`attr_name`. | f7192:c2:m0 |
def get_dependency(self, worker_ctx): | Called before worker execution. A DependencyProvider should return
an object to be injected into the worker instance by the container. | f7192:c2:m1 | |
def worker_result(self, worker_ctx, result=None, exc_info=None): | Called with the result of a service worker execution.
Dependencies that need to process the result should do it here.
This method is called for all `Dependency` instances on completion
of any worker.
Example: a database session dependency may flush the transaction
:Parameters:... | f7192:c2:m2 | |
def worker_setup(self, worker_ctx): | Called before a service worker executes a task.
Dependencies should do any pre-processing here, raising exceptions
in the event of failure.
Example: ...
:Parameters:
worker_ctx : WorkerContext
See ``nameko.containers.ServiceContainer.spawn_worker`` | f7192:c2:m3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.