INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
This function returns the conventional form of the actions. | def serialize_action(action_type, payload, **extra_fields):
"""
This function returns the conventional form of the actions.
"""
action_dict = dict(
action_type=action_type,
payload=payload,
**extra_fields
)
# return a serializable version
return json.dumps(action... |
This function returns the fields for a schema that matches the provided nautilus model. | def fields_for_model(model):
"""
This function returns the fields for a schema that matches the provided
nautilus model.
Args:
model (nautilus.model.BaseModel): The model to base the field list on
Returns:
(dict<field_name: str, graphqlType>): A mapping of f... |
Create an SQL Alchemy table that connects the provides services | def create_connection_model(service):
""" Create an SQL Alchemy table that connects the provides services """
# the services connected
services = service._services
# the mixins / base for the model
bases = (BaseModel,)
# the fields of the derived
attributes = {model_service_name(service): f... |
This factory returns an action handler that creates a new instance of the specified model when a create action is recieved assuming the action follows nautilus convetions. | def create_handler(Model, name=None, **kwds):
"""
This factory returns an action handler that creates a new instance of
the specified model when a create action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to c... |
Equality checks are overwitten to perform the actual check in a semantic way. | async def _has_id(self, *args, **kwds):
"""
Equality checks are overwitten to perform the actual check in a
semantic way.
"""
# if there is only one positional argument
if len(args) == 1:
# parse the appropriate query
result = await parse_s... |
This method performs a depth - first search for the given uid in the dictionary of results. | def _find_id(self, result, uid):
"""
This method performs a depth-first search for the given uid in the dictionary of results.
"""
# if the result is a list
if isinstance(result, list):
# if the list has a valid entry
if any([self._find_id(value, uid) ... |
Returns a builder inserting a new block before the current block | def add_before(self):
"""Returns a builder inserting a new block before the current block"""
idx = self._container.structure.index(self)
return BlockBuilder(self._container, idx) |
Returns a builder inserting a new block after the current block | def add_after(self):
"""Returns a builder inserting a new block after the current block"""
idx = self._container.structure.index(self)
return BlockBuilder(self._container, idx+1) |
Creates a comment block | def comment(self, text, comment_prefix='#'):
"""Creates a comment block
Args:
text (str): content of comment without #
comment_prefix (str): character indicating start of comment
Returns:
self for chaining
"""
comment = Comment(self._containe... |
Creates a section block | def section(self, section):
"""Creates a section block
Args:
section (str or :class:`Section`): name of section or object
Returns:
self for chaining
"""
if not isinstance(self._container, ConfigUpdater):
raise ValueError("Sections can only be... |
Creates a vertical space of newlines | def space(self, newlines=1):
"""Creates a vertical space of newlines
Args:
newlines (int): number of empty lines
Returns:
self for chaining
"""
space = Space()
for line in range(newlines):
space.add_line('\n')
self._container.... |
Creates a new option inside a section | def option(self, key, value=None, **kwargs):
"""Creates a new option inside a section
Args:
key (str): key of the option
value (str or None): value of the option
**kwargs: are passed to the constructor of :class:`Option`
Returns:
self for chainin... |
Add a Comment object to the section | def add_comment(self, line):
"""Add a Comment object to the section
Used during initial parsing mainly
Args:
line (str): one line in the comment
"""
if not isinstance(self.last_item, Comment):
comment = Comment(self._structure)
self._structur... |
Add a Space object to the section | def add_space(self, line):
"""Add a Space object to the section
Used during initial parsing mainly
Args:
line (str): one line that defines the space, maybe whitespaces
"""
if not isinstance(self.last_item, Space):
space = Space(self._structure)
... |
Transform to dictionary | def to_dict(self):
"""Transform to dictionary
Returns:
dict: dictionary with same content
"""
return {key: self.__getitem__(key).value for key in self.options()} |
Set an option for chaining. | def set(self, option, value=None):
"""Set an option for chaining.
Args:
option (str): option name
value (str): value, default None
"""
option = self._container.optionxform(option)
if option in self.options():
self.__getitem__(option).value = v... |
Sets the value to a given list of options e. g. multi - line values | def set_values(self, values, separator='\n', indent=4*' '):
"""Sets the value to a given list of options, e.g. multi-line values
Args:
values (list): list of values
separator (str): separator for values, default: line separator
indent (str): indentation depth in case... |
Read and parse a filename. | def read(self, filename, encoding=None):
"""Read and parse a filename.
Args:
filename (str): path to file
encoding (str): encoding of file, default None
"""
with open(filename, encoding=encoding) as fp:
self._read(fp, filename)
self._filename ... |
Update the read - in configuration file. | def update_file(self):
"""Update the read-in configuration file.
"""
if self._filename is None:
raise NoConfigFileReadError()
with open(self._filename, 'w') as fb:
self.write(fb) |
Call ConfigParser to validate config | def validate_format(self, **kwargs):
"""Call ConfigParser to validate config
Args:
kwargs: are passed to :class:`configparser.ConfigParser`
"""
args = dict(
dict_type=self._dict,
allow_no_value=self._allow_no_value,
inline_comment_prefixes... |
Create a new section in the configuration. | def add_section(self, section):
"""Create a new section in the configuration.
Raise DuplicateSectionError if a section by the specified name
already exists. Raise ValueError if name is DEFAULT.
Args:
section (str or :class:`Section`): name or Section type
"""
... |
Returns list of configuration options for the named section. | def options(self, section):
"""Returns list of configuration options for the named section.
Args:
section (str): name of section
Returns:
list: list of option names
"""
if not self.has_section(section):
raise NoSectionError(section) from None... |
Gets an option value for a given section. | def get(self, section, option):
"""Gets an option value for a given section.
Args:
section (str): section name
option (str): option name
Returns:
:class:`Option`: Option object holding key/value pair
"""
if not self.has_section(section):
... |
Return a list of ( name value ) tuples for options or sections. | def items(self, section=_UNSET):
"""Return a list of (name, value) tuples for options or sections.
If section is given, return a list of tuples with (name, value) for
each option in the section. Otherwise, return a list of tuples with
(section_name, section_type) for each section.
... |
Checks for the existence of a given option in a given section. | def has_option(self, section, option):
"""Checks for the existence of a given option in a given section.
Args:
section (str): name of section
option (str): name of option
Returns:
bool: whether the option exists in the given section
"""
if se... |
Set an option. | def set(self, section, option, value=None):
"""Set an option.
Args:
section (str): section name
option (str): option name
value (str): value, default None
"""
try:
section = self.__getitem__(section)
except KeyError:
ra... |
Remove an option. | def remove_option(self, section, option):
"""Remove an option.
Args:
section (str): section name
option (str): option name
Returns:
bool: whether the option was actually removed
"""
try:
section = self.__getitem__(section)
... |
Remove a file section. | def remove_section(self, name):
"""Remove a file section.
Args:
name: name of the section
Returns:
bool: whether the section was actually removed
"""
existed = self.has_section(name)
if existed:
idx = self._get_section_idx(name)
... |
Transform to dictionary | def to_dict(self):
"""Transform to dictionary
Returns:
dict: dictionary with same content
"""
return {sect: self.__getitem__(sect).to_dict()
for sect in self.sections()} |
This function renders the template desginated by the argument to the designated directory using the given context. | def render_template(template, out_dir='.', context=None):
'''
This function renders the template desginated by the argument to the
designated directory using the given context.
Args:
template (string) : the source template to use (relative to ./templates)
out_dir (st... |
Publish a message with the specified action_type and payload over the event system. Useful for debugging. | def publish(type, payload):
"""
Publish a message with the specified action_type and payload over the
event system. Useful for debugging.
"""
async def _produce():
# fire an action with the given values
await producer.send(action_type=type, payload=payload)
# notify t... |
This factory returns an action handler that deletes a new instance of the specified model when a delete action is recieved assuming the action follows nautilus convetions. | def delete_handler(Model, name=None, **kwds):
"""
This factory returns an action handler that deletes a new instance of
the specified model when a delete action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to d... |
This factory returns an action handler that responds to read requests by resolving the payload as a graphql query against the internal schema. | def read_handler(Model, name=None, **kwds):
"""
This factory returns an action handler that responds to read requests
by resolving the payload as a graphql query against the internal schema.
Args:
Model (nautilus.BaseModel): The model to delete when the action
r... |
This action handler factory reaturns an action handler that responds to actions with CRUD types ( following nautilus conventions ) and performs the necessary mutation on the model s database. | def crud_handler(Model, name=None, **kwds):
"""
This action handler factory reaturns an action handler that
responds to actions with CRUD types (following nautilus conventions)
and performs the necessary mutation on the model's database.
Args:
Model (nautilus.BaseModel):... |
Publish a message with the specified action_type and payload over the event system. Useful for debugging. | def ask(type, payload):
"""
Publish a message with the specified action_type and payload over the
event system. Useful for debugging.
"""
async def _produce():
# notify the user that we were successful
print("Dispatching action with type {}...".format(type))
# fire an... |
This method converts a type into a dict. | def _from_type(self, config):
"""
This method converts a type into a dict.
"""
def is_user_attribute(attr):
return (
not attr.startswith('__') and
not isinstance(getattr(config, attr), collections.abc.Callable)
)
return... |
This function traverses a query and collects the corresponding information in a dictionary. | async def walk_query(obj, object_resolver, connection_resolver, errors, current_user=None, __naut_name=None, obey_auth=True, **filters):
"""
This function traverses a query and collects the corresponding
information in a dictionary.
"""
# if the object has no selection set
if not hasattr... |
This action handler interprets the payload as a query to be executed by the api gateway service. | async def query_handler(service, action_type, payload, props, **kwds):
"""
This action handler interprets the payload as a query to be executed
by the api gateway service.
"""
# check that the action type indicates a query
if action_type == query_action_type():
print('encountered... |
This function returns the standard summary for mutations inputs and outputs | def summarize_mutation_io(name, type, required=False):
"""
This function returns the standard summary for mutations inputs
and outputs
"""
return dict(
name=name,
type=type,
required=required
) |
This function returns the name of a mutation that performs the specified crud action on the given model service | def crud_mutation_name(action, model):
"""
This function returns the name of a mutation that performs the specified
crud action on the given model service
"""
model_string = get_model_string(model)
# make sure the mutation name is correctly camelcases
model_string = model_string[0].u... |
Args: service: The service being created by the mutation Returns: ( list ): a list of all of the fields availible for the service with the required ones respected. | def create_mutation_inputs(service):
"""
Args:
service : The service being created by the mutation
Returns:
(list) : a list of all of the fields availible for the service,
with the required ones respected.
"""
# grab the default list of field summaries... |
Args: service: The service being updated by the mutation Returns: ( list ): a list of all of the fields availible for the service. Pk is a required field in order to filter the results | def update_mutation_inputs(service):
"""
Args:
service : The service being updated by the mutation
Returns:
(list) : a list of all of the fields availible for the service. Pk
is a required field in order to filter the results
"""
# grab the default lis... |
Args: service: The service being deleted by the mutation Returns: ( [ str ] ): the only input for delete is the pk of the service. | def delete_mutation_inputs(service):
"""
Args:
service : The service being deleted by the mutation
Returns:
([str]): the only input for delete is the pk of the service.
"""
from nautilus.api.util import summarize_mutation_io
# the only input for delete events is... |
This function create the actual mutation io summary corresponding to the model | def _summarize_o_mutation_type(model):
"""
This function create the actual mutation io summary corresponding to the model
"""
from nautilus.api.util import summarize_mutation_io
# compute the appropriate name for the object
object_type_name = get_model_string(model)
# return a mutation ... |
This function returns the summary for a given model | def _summarize_object_type(model):
"""
This function returns the summary for a given model
"""
# the fields for the service's model
model_fields = {field.name: field for field in list(model.fields())}
# summarize the model
return {
'fields': [{
'name': key,
... |
This function combines the given action handlers into a single function which will call all of them. | def combine_action_handlers(*handlers):
"""
This function combines the given action handlers into a single function
which will call all of them.
"""
# make sure each of the given handlers is callable
for handler in handlers:
# if the handler is not a function
if not (isco... |
This factory returns an action handler that updates a new instance of the specified model when a update action is recieved assuming the action follows nautilus convetions. | def update_handler(Model, name=None, **kwds):
"""
This factory returns an action handler that updates a new instance of
the specified model when a update action is recieved, assuming the
action follows nautilus convetions.
Args:
Model (nautilus.BaseModel): The model to u... |
This function returns a graphql mutation corresponding to the provided summary. | def graphql_mutation_from_summary(summary):
"""
This function returns a graphql mutation corresponding to the provided
summary.
"""
# get the name of the mutation from the summary
mutation_name = summary['name']
# print(summary)
# the treat the "type" string as a gra
input_... |
This function takes a series of ditionaries and creates an argument string for a graphql query | def arg_string_from_dict(arg_dict, **kwds):
"""
This function takes a series of ditionaries and creates an argument
string for a graphql query
"""
# the filters dictionary
filters = {
**arg_dict,
**kwds,
}
# return the correctly formed string
return ", ".join(... |
This function creates a graphql schema that provides a single model | def create_model_schema(target_model):
""" This function creates a graphql schema that provides a single model """
from nautilus.database import db
# create the schema instance
schema = graphene.Schema(auto_camelcase=False)
# grab the primary key from the model
primary_key = target_model.prim... |
the name of a service that manages the connection between services | def connection_service_name(service, *args):
''' the name of a service that manages the connection between services '''
# if the service is a string
if isinstance(service, str):
return service
return normalize_string(type(service).__name__) |
This function verifies the token using the secret key and returns its contents. | def read_session_token(secret_key, token):
"""
This function verifies the token using the secret key and returns its
contents.
"""
return jwt.decode(token.encode('utf-8'), secret_key,
algorithms=[token_encryption_algorithm()]
) |
The default action Handler has no action. | async def handle_action(self, action_type, payload, **kwds):
"""
The default action Handler has no action.
"""
# if there is a service attached to the action handler
if hasattr(self, 'service'):
# handle roll calls
await roll_call_handler(self.service,... |
This method is used to announce the existence of the service | async def announce(self):
"""
This method is used to announce the existence of the service
"""
# send a serialized event
await self.event_broker.send(
action_type=intialize_service_action(),
payload=json.dumps(self.summarize())
) |
This function starts the service s network intefaces. | def run(self, host="localhost", port=8000, shutdown_timeout=60.0, **kwargs):
"""
This function starts the service's network intefaces.
Args:
port (int): The port for the http server.
"""
print("Running service on http://localhost:%i. " % port + \
... |
This function is called when the service has finished running regardless of intentionally or not. | def cleanup(self):
"""
This function is called when the service has finished running
regardless of intentionally or not.
"""
# if an event broker has been created for this service
if self.event_broker:
# stop the event broker
self.event_br... |
This method provides a programatic way of added invidual routes to the http server. | def add_http_endpoint(self, url, request_handler):
"""
This method provides a programatic way of added invidual routes
to the http server.
Args:
url (str): the url to be handled by the request_handler
request_handler (nautilus.network.RequestH... |
This method provides a decorator for adding endpoints to the http server. | def route(cls, route, config=None):
"""
This method provides a decorator for adding endpoints to the
http server.
Args:
route (str): The url to be handled by the RequestHandled
config (dict): Configuration for the request handler
... |
This function generates a session token signed by the secret key which can be used to extract the user credentials in a verifiable way. | def generate_session_token(secret_key, **payload):
"""
This function generates a session token signed by the secret key which
can be used to extract the user credentials in a verifiable way.
"""
return jwt.encode(payload, secret_key, algorithm=token_encryption_algorithm()).decode('utf-8') |
This function provides a standard representation of mutations to be used when services announce themselves | def summarize_mutation(mutation_name, event, inputs, outputs, isAsync=False):
"""
This function provides a standard representation of mutations to be
used when services announce themselves
"""
return dict(
name=mutation_name,
event=event,
isAsync=isAsync,
inpu... |
Creates a PasswordHash from the given password. | def new(cls, password, rounds):
"""Creates a PasswordHash from the given password."""
if isinstance(password, str):
password = password.encode('utf-8')
return cls(cls._new(password, rounds)) |
Ensure that loaded values are PasswordHashes. | def coerce(cls, key, value):
"""Ensure that loaded values are PasswordHashes."""
if isinstance(value, PasswordHash):
return value
return super(PasswordHash, cls).coerce(key, value) |
Recreates the internal hash. | def rehash(self, password):
"""Recreates the internal hash."""
self.hash = self._new(password, self.desired_rounds)
self.rounds = self.desired_rounds |
This function configures the database used for models to make the configuration parameters. | def init_db(self):
"""
This function configures the database used for models to make
the configuration parameters.
"""
# get the database url from the configuration
db_url = self.config.get('database_url', 'sqlite:///nautilus.db')
# configure the nautilus ... |
This attribute provides the mapping of services to their auth requirement | def auth_criteria(self):
"""
This attribute provides the mapping of services to their auth requirement
Returns:
(dict) : the mapping from services to their auth requirements.
"""
# the dictionary we will return
auth = {}
# go over each at... |
This function handles the registration of the given user credentials in the database | async def login_user(self, password, **kwds):
"""
This function handles the registration of the given user credentials in the database
"""
# find the matching user with the given email
user_data = (await self._get_matching_user(fields=list(kwds.keys()), **kwds))['data']
... |
This function is used to provide a sessionToken for later requests. | async def register_user(self, password, **kwds):
"""
This function is used to provide a sessionToken for later requests.
Args:
uid (str): The
"""
# so make one
user = await self._create_remote_user(password=password, **kwds)
# if there is ... |
This function resolves a given object in the remote backend services | async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters):
"""
This function resolves a given object in the remote backend services
"""
try:
# check if an object with that name has been registered
registered = [model ... |
the default behavior for mutations is to look up the event publish the correct event type with the args as the body and return the fields contained in the result | async def mutation_resolver(self, mutation_name, args, fields):
"""
the default behavior for mutations is to look up the event,
publish the correct event type with the args as the body,
and return the fields contained in the result
"""
try:
# make... |
This function checks if there is a user with the same uid in the remote user service Args: ** kwds: the filters of the user to check for Returns: ( bool ): wether or not there is a matching user | async def _check_for_matching_user(self, **user_filters):
"""
This function checks if there is a user with the same uid in the
remote user service
Args:
**kwds : the filters of the user to check for
Returns:
(bool): wether or not th... |
This method creates a service record in the remote user service with the given email. Args: uid ( str ): the user identifier to create Returns: ( dict ): a summary of the user that was created | async def _create_remote_user(self, **payload):
"""
This method creates a service record in the remote user service
with the given email.
Args:
uid (str): the user identifier to create
Returns:
(dict): a summary of the user that was... |
Calculation of WER with Levenshtein distance. Works only for iterables up to 254 elements ( uint8 ). O ( nm ) time and space complexity. | def calculate_wer(reference, hypothesis):
"""
Calculation of WER with Levenshtein distance.
Works only for iterables up to 254 elements (uint8).
O(nm) time and space complexity.
>>> calculate_wer("who is there".split(), "is there".split())
1
>>> calculate_wer("who is... |
Get a parser object | def get_parser():
"""Get a parser object"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
parser = ArgumentParser(description=__doc__,
formatter_class=ArgumentDefaultsHelpFormatter)
parser.add_argument("-s1", dest="s1", help="sequence 1")
parser.add_a... |
Perform a GET web request and return a bs4 parser | async def _async_request_soup(url):
'''
Perform a GET web request and return a bs4 parser
'''
from bs4 import BeautifulSoup
import aiohttp
_LOGGER.debug('GET %s', url)
async with aiohttp.ClientSession() as session:
resp = await session.get(url)
text = await resp.text()
... |
Check whether the current channel is correct. If not try to determine it using fuzzywuzzy | async def async_determine_channel(channel):
'''
Check whether the current channel is correct. If not try to determine it
using fuzzywuzzy
'''
from fuzzywuzzy import process
channel_data = await async_get_channels()
if not channel_data:
_LOGGER.error('No channel data. Cannot determine... |
Get channel list and corresponding urls | async def async_get_channels(no_cache=False, refresh_interval=4):
'''
Get channel list and corresponding urls
'''
# Check cache
now = datetime.datetime.now()
max_cache_age = datetime.timedelta(hours=refresh_interval)
if not no_cache and 'channels' in _CACHE:
cache = _CACHE.get('chann... |
Resize a program s thumbnail to the desired dimension | def resize_program_image(img_url, img_size=300):
'''
Resize a program's thumbnail to the desired dimension
'''
match = re.match(r'.+/(\d+)x(\d+)/.+', img_url)
if not match:
_LOGGER.warning('Could not compute current image resolution of %s',
img_url)
return img... |
Get the current progress of the program in % | def get_current_program_progress(program):
'''
Get the current progress of the program in %
'''
now = datetime.datetime.now()
program_duration = get_program_duration(program)
if not program_duration:
return
progress = now - program.get('start_time')
return progress.seconds * 100 ... |
Get a program s duration in seconds | def get_program_duration(program):
'''
Get a program's duration in seconds
'''
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could not determine program start and/or end times.')
_LOGGER.deb... |
Get the remaining time in seconds of a program that is currently on. | def get_remaining_time(program):
'''
Get the remaining time in seconds of a program that is currently on.
'''
now = datetime.datetime.now()
program_start = program.get('start_time')
program_end = program.get('end_time')
if not program_start or not program_end:
_LOGGER.error('Could no... |
Extract the summary data from a program s detail page | def extract_program_summary(data):
'''
Extract the summary data from a program's detail page
'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(data, 'html.parser')
try:
return soup.find(
'div', {'class': 'episode-synopsis'}
).find_all('div')[-1].text.strip()
... |
Set a program s summary | async def async_set_summary(program):
'''
Set a program's summary
'''
import aiohttp
async with aiohttp.ClientSession() as session:
resp = await session.get(program.get('url'))
text = await resp.text()
summary = extract_program_summary(text)
program['summary'] = summa... |
Get the program data for a channel | async def async_get_program_guide(channel, no_cache=False, refresh_interval=4):
'''
Get the program data for a channel
'''
chan = await async_determine_channel(channel)
now = datetime.datetime.now()
max_cache_age = datetime.timedelta(hours=refresh_interval)
if not no_cache and 'guide' in _CA... |
Get the current program info | async def async_get_current_program(channel, no_cache=False):
'''
Get the current program info
'''
chan = await async_determine_channel(channel)
guide = await async_get_program_guide(chan, no_cache)
if not guide:
_LOGGER.warning('Could not retrieve TV program for %s', channel)
re... |
Get or create publish | def publish(self, distribution, storage=""):
"""
Get or create publish
"""
try:
return self._publishes[distribution]
except KeyError:
self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or self.stor... |
Add mirror or repo to publish | def add(self, snapshot, distributions, component='main', storage=""):
""" Add mirror or repo to publish """
for dist in distributions:
self.publish(dist, storage=storage).add(snapshot, component) |
Check if publish name matches list of names or regex patterns | def _publish_match(self, publish, names=False, name_only=False):
"""
Check if publish name matches list of names or regex patterns
"""
if names:
for name in names:
if not name_only and isinstance(name, re._pattern_type):
if re.match(name, p... |
fill two dictionnaries: one containing all the packages for every repository and the second one associating to every component of every publish its repository | def get_repo_information(config, client, fill_repo=False, components=[]):
""" fill two dictionnaries : one containing all the packages for every repository
and the second one associating to every component of every publish its repository"""
repo_dict = {}
publish_dict = {}
f... |
Compare two publishes It expects that other publish is same or older than this one | def compare(self, other, components=[]):
"""
Compare two publishes
It expects that other publish is same or older than this one
Return tuple (diff, equal) of dict {'component': ['snapshot']}
"""
lg.debug("Comparing publish %s (%s) and %s (%s)" % (self.name, self.storage ... |
Find this publish on remote | def _get_publish(self):
"""
Find this publish on remote
"""
publishes = self._get_publishes(self.client)
for publish in publishes:
if publish['Distribution'] == self.distribution and \
publish['Prefix'].replace("/", "_") == (self.prefix or '.') and... |
Serialize publish in YAML | def save_publish(self, save_path):
"""
Serialize publish in YAML
"""
timestamp = time.strftime("%Y%m%d%H%M%S")
yaml_dict = {}
yaml_dict["publish"] = self.name
yaml_dict["name"] = timestamp
yaml_dict["components"] = []
yaml_dict["storage"] = self.s... |
Restore publish from config file | def restore_publish(self, config, components, recreate=False):
"""
Restore publish from config file
"""
if "all" in components:
components = []
try:
self.load()
publish = True
except NoSuchPublish:
publish = False
... |
Load publish info from remote | def load(self):
"""
Load publish info from remote
"""
publish = self._get_publish()
self.architectures = publish['Architectures']
for source in publish['Sources']:
component = source['Component']
snapshot = source['Name']
self.publish_s... |
Return package refs for given components | def get_packages(self, component=None, components=[], packages=None):
"""
Return package refs for given components
"""
if component:
components = [component]
package_refs = []
for snapshot in self.publish_snapshots:
if component and snapshot['Comp... |
Return tuple of architecture package_name version id | def parse_package_ref(self, ref):
"""
Return tuple of architecture, package_name, version, id
"""
if not ref:
return None
parsed = re.match('(.*)\ (.*)\ (.*)\ (.*)', ref)
return parsed.groups() |
Add snapshot of component to publish | def add(self, snapshot, component='main'):
"""
Add snapshot of component to publish
"""
try:
self.components[component].append(snapshot)
except KeyError:
self.components[component] = [snapshot] |
Find snapshot on remote by name or regular expression | def _find_snapshot(self, name):
"""
Find snapshot on remote by name or regular expression
"""
remote_snapshots = self._get_snapshots(self.client)
for remote in reversed(remote_snapshots):
if remote["Name"] == name or \
re.match(name, remote["Name"]... |
Get list of source snapshot names of given snapshot | def _get_source_snapshots(self, snapshot, fallback_self=False):
"""
Get list of source snapshot names of given snapshot
TODO: we have to decide by description at the moment
"""
if not snapshot:
return []
source_snapshots = re.findall(r"'([\w\d\.-]+)'", snaps... |
Create component snapshots by merging other snapshots of same component | def merge_snapshots(self):
"""
Create component snapshots by merging other snapshots of same component
"""
self.publish_snapshots = []
for component, snapshots in self.components.items():
if len(snapshots) <= 1:
# Only one snapshot, no need to merge
... |
Prints the time func takes to execute. | def timing_decorator(func):
"""Prints the time func takes to execute."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
"""
Wrapper for printing execution time.
Parameters
----------
print_time: bool, optional
whether or not to print time function t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.