Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def sg_train(**kwargs):
r
opt = tf.sg_opt(kwargs)
assert opt.loss is not None, 'loss is mandatory.'
# default training options
opt += tf.sg_opt(optim='MaxProp', lr=0.001, beta1=0.9, beta2=0.99, category='', ep_size=100000)
# get optimizer
train_... | [
"Trains the model.\n\n Args:\n **kwargs:\n optim: A name for optimizer. 'MaxProp' (default), 'AdaMax', 'Adam', 'RMSProp' or 'sgd'.\n loss: A 0-D `Tensor` containing the value to minimize.\n lr: A Python Scalar (optional). Learning rate. Default is .001.\n beta1: A Python Scalar (... |
Please provide a description of the function:def sg_init(sess):
r
# initialize variables
sess.run(tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())) | [
" Initializes session variables.\n \n Args:\n sess: Session to initialize. \n "
] |
Please provide a description of the function:def sg_print(tensor_list):
r
# to list
if type(tensor_list) is not list and type(tensor_list) is not tuple:
tensor_list = [tensor_list]
# evaluate tensor list with queue runner
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as ... | [
"Simple tensor printing function for debugging.\n Prints the value, shape, and data type of each tensor in the list.\n \n Args:\n tensor_list: A list/tuple of tensors or a single tensor.\n \n Returns:\n The value of the tensors.\n \n For example,\n \n ```python\n import s... |
Please provide a description of the function:def sg_restore(sess, save_path, category=''):
r
# to list
if not isinstance(category, (tuple, list)):
category = [category]
# make variable list to load
var_list = {}
for cat in category:
for t in tf.global_variables():
if... | [
" Restores previously saved variables.\n\n Args:\n sess: A `Session` to use to restore the parameters.\n save_path: Path where parameters were previously saved.\n category: A `String` to filter variables starts with given category.\n\n Returns:\n\n "
] |
Please provide a description of the function:def sg_optim(loss, **kwargs):
r
opt = tf.sg_opt(kwargs)
# default training options
opt += tf.sg_opt(optim='MaxProp', lr=0.001, beta1=0.9, beta2=0.99, momentum=0., category='')
# select optimizer
if opt.optim == 'MaxProp':
optim = tf.sg_optim... | [
"Applies gradients to variables.\n\n Args:\n loss: A 0-D `Tensor` containing the value to minimize. list of 0-D tensor for Multiple GPU\n kwargs:\n optim: A name for optimizer. 'MaxProp' (default), 'AdaMax', 'Adam', 'RMSProp' or 'sgd'.\n lr: A Python Scalar (optional). Learning ra... |
Please provide a description of the function:def sg_train_func(func):
r
@wraps(func)
def wrapper(**kwargs):
r
opt = tf.sg_opt(kwargs)
# default training options
opt += tf.sg_opt(lr=0.001,
save_dir='asset/train',
max_ep=1000, ... | [
" Decorates a function `func` as sg_train_func.\n\n Args:\n func: A function to decorate\n ",
" Manages arguments of `tf.sg_opt`.\n\n Args:\n **kwargs:\n lr: A Python Scalar (optional). Learning rate. Default is .001.\n\n save_dir: A string. The root path to whic... |
Please provide a description of the function:def sg_regularizer_loss(scale=1.0):
r
return scale * tf.reduce_mean(tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)) | [
" Get regularizer losss\n\n Args:\n scale: A scalar. A weight applied to regularizer loss\n "
] |
Please provide a description of the function:def sg_vgg_19(tensor, opt):
r
opt += tf.sg_opt(num_class=1000, conv_only=False, squeeze=True, act='relu')
# convolution layers
with tf.sg_context(name=opt.name, act=opt.act, bn=opt.bn, reuse=opt.reuse):
conv = (tensor
.sg_conv(dim=64,... | [
"Applies vgg 19 model.\n \n Note that the fc layers in the original architecture \n will be replaced with fully convolutional layers.\n For convenience, We still call them fc layers, though.\n \n Args:\n tensor: A `Tensor`.\n opt:\n num_class: An integer. Number of class. Defa... |
Please provide a description of the function:def sg_resnet_layer(x, opt):
r
assert opt.dim is not None, 'dim is mandatory.'
assert opt.num is not None, 'num is mandatory.'
# default stride
opt += tf.sg_opt(stride=1, act='relu')
# format convolutional layer name
def cname(index):
re... | [
"Applies basic architecture of residual net.\n \n Note that the fc layers in the original architecture \n will be replaced with fully convolutional layers.\n For convenience, We still call them fc layers, though.\n \n Args:\n x: A `Tensor`.\n opt:\n dim: An integer. Dimensio... |
Please provide a description of the function:def sg_densenet_layer(x, opt):
r
assert opt.dim is not None, 'dim is mandatory.'
assert opt.num is not None, 'num is mandatory.'
# default stride
opt += tf.sg_opt(stride=1, act='relu', trans=True)
# format convolutional layer name
def cname(inde... | [
"Applies basic architecture of densenet layer.\n\n Note that the fc layers in the original architecture\n will be replaced with fully convolutional layers.\n For convenience, We still call them fc layers, though.\n\n Args:\n x: A `Tensor`.\n opt:\n dim: An integer. Dimension for t... |
Please provide a description of the function:def _data_to_tensor(data_list, batch_size, name=None):
r
# convert to constant tensor
const_list = [tf.constant(data) for data in data_list]
# create queue from constant tensor
queue_list = tf.train.slice_input_producer(const_list, capacity=batch_size*12... | [
"Returns batch queues from the whole data. \n \n Args:\n data_list: A list of ndarrays. Every array must have the same size in the first dimension.\n batch_size: An integer.\n name: A name for the operations (optional).\n \n Returns:\n A list of tensors of `batch_size`.\n "
] |
Please provide a description of the function:def list_files(base_path, ext=None):
if not os.path.isdir(base_path):
raise ValueError("Path does not exist: %s" % base_path)
files = []
for entry in os.listdir(base_path):
if os.path.isfile(os.path.join(base_path, entry)):
_, en... | [
"Lists all of the files in the given base directory, optionally only\n including whose extension(s) match the ext string/list of strings.\n This is non-recursive.\n\n Args:\n base_path: The directory in which to search.\n ext: The extension(s) to match in the given directory. If None, this\n ... |
Please provide a description of the function:def deep_merge_dict(a, b):
if not isinstance(a, dict):
raise TypeError("a must be a dict, but found %s" % a.__class__.__name__)
if not isinstance(b, dict):
raise TypeError("b must be a dict, but found %s" % b.__class__.__name__)
_a = copy(a)... | [
"Deep merges dictionary b into dictionary a."
] |
Please provide a description of the function:def copy_file_if_modified(src_path, dest_path):
# if the destination path is a directory, delete it completely - we assume here we are
# writing a file to the filesystem
if os.path.isdir(dest_path):
shutil.rmtree(dest_path)
must_copy = False
... | [
"Only copies the file from the source path to the destination path if it doesn't exist yet or it has\n been modified. Intended to provide something of an optimisation when a project has large trees of assets."
] |
Please provide a description of the function:def copy_tree(src_path, dest_path):
files_copied = 0
if os.path.isdir(src_path):
# if the destination folder doesn't exist, create it
if not os.path.isdir(dest_path):
os.makedirs(dest_path)
for entry in os.listdir(src_path):
... | [
"Copies the entire folder tree, recursively, from the given source path\n to the given destination path. If the destination path does not exist, it\n will be created. If it does, any files/folders within it will be\n overwritten, but none will be deleted."
] |
Please provide a description of the function:def get_url_file_ext(url):
# get the last part of the path component
filename = url.split('/')[-1]
name, ext = os.path.splitext(filename)
# handle case of files with leading dot
if not ext and name and name[0] == '.':
ext = name
return ... | [
"Attempts to extract the file extension from the given URL."
] |
Please provide a description of the function:def generate_quickstart(project_path):
ensure_path_exists(project_path)
ensure_file_exists(os.path.join(project_path, "config.yml"), DEFAULT_CONFIG_CONTENT)
ensure_path_exists(os.path.join(project_path, 'models'))
ensure_path_exists(os.path.join(project_... | [
"Generates all of the basic paths for a Statik project within the given project path. If the project path\n doesn't exist, it will be created."
] |
Please provide a description of the function:def get_project_config_file(path, default_config_file_name):
_path, _config_file_path = None, None
path = os.path.abspath(path)
if os.path.isdir(path):
_path = path
# use the default config file
_config_file_path = os.path.join(_path... | [
"Attempts to extract the project config file's absolute path from the given path. If the path is a\n directory, it automatically assumes a \"config.yml\" file will be in that directory. If the path is to\n a .yml file, it assumes that that is the root configuration file for the project."
] |
Please provide a description of the function:def dict_strip(d):
_d = deepcopy(d)
for k, v in iteritems(d):
if isinstance(v, str):
_d[k] = v.strip()
elif isinstance(v, dict):
_d[k] = dict_strip(v)
return _d | [
"Strips whitespace from the string values of the given dictionary (recursively).\n\n Args:\n d: A dictionary object.\n\n Returns:\n A new dictionary object, whose string values' whitespace has been stripped out.\n "
] |
Please provide a description of the function:def strip_el_text(el, max_depth=0, cur_depth=0):
# text in front of any child elements
el_text = strip_str(el.text if el.text is not None else "")
if cur_depth < max_depth:
for child in el:
el_text += " "+strip_el_text(child, max_depth=m... | [
"Recursively strips the plain text out of the given XML etree element up to the desired depth.\n\n Args:\n el: The etree element to scan.\n max_depth: The depth to which to recursively strip text (default: 0).\n cur_depth: The current recursive depth to which we've scanned so far.\n\n Ret... |
Please provide a description of the function:def find_first_file_with_ext(base_paths, prefix, exts):
for base_path in base_paths:
for ext in exts:
filename = os.path.join(base_path, "%s%s" % (prefix, ext))
if os.path.exists(filename) and os.path.isfile(filename):
... | [
"Runs through the given list of file extensions and returns the first file with the given base\n path and extension combination that actually exists.\n\n Args:\n base_paths: The base paths in which to search for files.\n prefix: The filename prefix of the file for which to search.\n exts:... |
Please provide a description of the function:def find_duplicates_in_array(array):
duplicates = []
non_duplicates = []
if len(array) != len(set(array)):
for item in array:
if item not in non_duplicates:
non_duplicates.append(item)
elif item in non_duplica... | [
"Runs through the array and returns the elements that contain\n more than one duplicate\n\n Args:\n array: The array to check for duplicates.\n\n Returns:\n Array of the elements that are duplicates. Returns empty list if\n there are no duplicates.\n "
] |
Please provide a description of the function:def render(self, context=None):
ctx = context.render() if context else self.get_error_context().render()
return "%s: %s%s%s" % (
self.get_error_kind(),
self.get_error_message(),
(" (%s)." % ctx) if ctx else "",
... | [
"Renders the error message, optionally using the given context (which, if specified,\n will override the internal context)."
] |
Please provide a description of the function:def read_requirements(filename):
data = []
for line in read_file(filename):
line = line.strip()
if not line or line.startswith('#'):
continue
if '+' in line[:4]:
repo_link, egg_name = line.split('#egg=')
... | [
"\n Parse a requirements file.\n\n Accepts vcs+ links, and places the URL into\n `DEPENDENCY_LINKS`.\n\n :return: list of str for each package\n "
] |
Please provide a description of the function:def find_additional_rels(self, all_models):
for model_name, model in iteritems(all_models):
if model_name != self.name:
for field_name in model.field_names:
field = model.fields[field_name]
... | [
"Attempts to scan for additional relationship fields for this model based on all of the other models'\n structures and relationships.\n "
] |
Please provide a description of the function:def create_db(self, models):
# first create the table definitions
self.tables = dict(
[
(model_name, self.create_model_table(model))
for model_name, model in iteritems(models)
]
)
... | [
"Creates the in-memory SQLite database from the model\n configuration."
] |
Please provide a description of the function:def sort_models(self):
model_names = [
table.name for table in self.Base.metadata.sorted_tables if table.name in self.models
]
logger.debug("Unsorted models: %s", model_names)
model_count = len(model_names)
swappe... | [
"Sorts the database models appropriately based on their relationships so that we load our data\n in the appropriate order.\n\n Returns:\n A sorted list containing the names of the models.\n "
] |
Please provide a description of the function:def create_model_table(self, model):
try:
return db_model_factory(self.Base, model, self.models)
except Exception as exc:
raise ModelError(
model.name,
message="failed to create in-memory table.... | [
"Creates the table for the given model.\n\n Args:\n model: A StatikModel instance.\n\n Returns:\n A SQLAlchemy model instance for the table corresponding to this\n particular model.\n "
] |
Please provide a description of the function:def load_model_data(self, path, model):
if os.path.isdir(path):
# try find a model data collection
if os.path.isfile(os.path.join(path, '_all.yml')):
self.load_model_data_collection(path, model)
self.load_m... | [
"Loads the data for the specified model from the given path.\n "
] |
Please provide a description of the function:def query(self, query, additional_locals=None, safe_mode=False):
logger.debug("Attempting to execute database query: %s", query)
if safe_mode and not isinstance(query, dict):
raise SafetyViolationError(
context=self.error... | [
"Executes the given SQLAlchemy query string.\n\n Args:\n query: The SQLAlchemy ORM query (or Python code) to be executed.\n additional_locals: Any additional local variables to inject into the execution context\n when executing the query.\n safe_mode: Boolean v... |
Please provide a description of the function:def generate(input_path, output_path=None, in_memory=False, safe_mode=False, error_context=None):
project = StatikProject(input_path, safe_mode=safe_mode, error_context=error_context)
return project.generate(output_path=output_path, in_memory=in_memory) | [
"Executes the Statik site generator using the given parameters.\n "
] |
Please provide a description of the function:def generate(self, output_path=None, in_memory=False):
result = dict() if in_memory else 0
logger.info("Generating Statik build...")
try:
if output_path is None and not in_memory:
raise InternalError(
... | [
"Executes the Statik project generator.\n\n Args:\n output_path: The path to which to write output files.\n in_memory: Whether or not to generate the results in memory. If True, this will\n generate the output result as a dictionary. If False, this will write the output\n... |
Please provide a description of the function:def load_views(self):
view_path = os.path.join(self.path, StatikProject.VIEWS_DIR)
logger.debug("Loading views from: %s", view_path)
if not os.path.isdir(view_path):
raise MissingProjectFolderError(StatikProject.VIEWS_DIR)
... | [
"Loads the views for this project from the project directory\n structure."
] |
Please provide a description of the function:def load_project_context(self):
try:
# just make a copy of the project context
context = StatikContext(
initial={
"project_name": self.config.project_name,
"base_path": self.conf... | [
"Loads the project context (static and dynamic) from the database/models for common use\n amongst the project's views."
] |
Please provide a description of the function:def process_views(self):
output = {}
logger.debug("Processing %d view(s)...", len(self.views))
for view_name, view in iteritems(self.views):
try:
output = deep_merge_dict(
output,
... | [
"Processes the loaded views to generate the required output data."
] |
Please provide a description of the function:def dump_in_memory_result(self, result, output_path):
file_count = 0
logger.debug("Dumping in-memory processing results to output folder: %s", output_path)
for k, v in iteritems(result):
cur_output_path = os.path.join(output_path,... | [
"Recursively dumps the result of our processing into files within the\n given output path.\n\n Args:\n result: The in-memory result of our processing.\n output_path: Full path to the folder into which to dump the files.\n\n Returns:\n The number of files generat... |
Please provide a description of the function:def copy_assets(self, output_path):
src_paths = []
# if we have a theme
if self.config.theme is not None:
# assume it's in the folder: "themes/theme_name/assets"
src_paths.append(os.path.join(
self.pat... | [
"Copies all asset files from the source path to the destination\n path. If no such source path exists, no asset copying will be performed.\n "
] |
Please provide a description of the function:def mkdir_p(sftp, path):
try:
sftp.chdir(path)
except IOError:
dirname, basename = os.path.split(path.rstrip('/'))
mkdir_p(sftp, dirname)
sftp.mkdir(basename)
sftp.chdir(basename)
return True | [
"Create remote path including parent directories if needed\n https://stackoverflow.com/a/14819803\n "
] |
Please provide a description of the function:def rm_r(sftp, path):
files = sftp.listdir(path)
for f in files:
filepath = os.path.join(path, f)
logger.info('Deleting: %s' % (filepath))
try:
sftp.remove(filepath)
except IOError:
rm_r(sftp, filepath) | [
"Recursively delete contents of path\n https://stackoverflow.com/a/23256181\n "
] |
Please provide a description of the function:def echo_arguments(*args, **kwargs):
args_string = ', '.join(map(lambda x: str(x), args))
kwargs_string = ', '.join(map(lambda k, v: "%s=%s" % (k, v), iteritems(kwargs)))
string_lst = filter(lambda x: bool(x), [args_string, kwargs_string])
return "ditto(... | [
" Echoes all parameters back as text (for debugging)\n {% ditto 1 2 3 %} => \"ditto(1, 2, 3)\"\n "
] |
Please provide a description of the function:def autogen(project_path):
generate_quickstart(project_path)
project = StatikProject(project_path)
project.config = StatikConfig(project.config_file_path)
models = list(project.load_models().values())
logger.info('Creating view and template for ho... | [
"Autogenerates views and templates for all the models in the project."
] |
Please provide a description of the function:def generate_yaml_file(filename, contents):
with open(filename, 'w') as file:
file.write(yaml.dump(contents, default_flow_style=False)) | [
"Creates a yaml file with the given content."
] |
Please provide a description of the function:def generate_index_file(filename):
with open(filename, 'w') as file:
content = open(os.path.join(os.path.dirname(__file__), 'templates/index_page.html'), 'r').read()
file.write(content) | [
"Constructs a default home page for the project."
] |
Please provide a description of the function:def generate_model_file(filename, project, model, fields):
for field in fields:
field.type = field.__class__.__name__
content = open(os.path.join(os.path.dirname(__file__), 'templates/model_page.html'), 'r').read()
engine = StatikTemplateEngine(pro... | [
"Creates a webpage for a given instance of a model."
] |
Please provide a description of the function:def build_dynamic(self, db, extra=None, safe_mode=False):
result = dict()
for var, query in iteritems(self.dynamic):
result[var] = db.query(query, safe_mode=safe_mode, additional_locals=extra)
return result | [
"Builds the dynamic context based on our current dynamic context entity and the given\n database."
] |
Please provide a description of the function:def build_for_each(self, db, safe_mode=False, extra=None):
result = dict()
for var, query in iteritems(self.for_each):
result[var] = db.query(
query,
additional_locals=extra,
safe_mode=safe_... | [
"Builds the for-each context."
] |
Please provide a description of the function:def build(self, db=None, safe_mode=False, for_each_inst=None, extra=None):
result = copy(self.initial)
result.update(self.static)
if self.dynamic:
result.update(self.build_dynamic(db, extra=extra, safe_mode=safe_mode))
if ... | [
"Builds a dictionary that can be used as context for template rendering."
] |
Please provide a description of the function:def template_exception_handler(fn, error_context, filename=None):
error_message = None
if filename:
error_context.update(filename=filename)
try:
return fn()
except jinja2.TemplateSyntaxError as exc:
error_context.update(filename=e... | [
"Calls the given function, attempting to catch any template-related errors, and\n converts the error to a Statik TemplateError instance. Returns the result returned\n by the function itself."
] |
Please provide a description of the function:def get_provider(self, name):
if name not in self.providers:
cls = self.provider_classes[name]
# instantiate the provider
self.providers[name] = cls(self)
return self.providers[name] | [
"Allows for lazy instantiation of providers (Jinja2 templating is heavy, so only instantiate it if\n necessary)."
] |
Please provide a description of the function:def load_template(self, name):
# hopefully speeds up loading of templates a little, especially when loaded multiple times
if name in self.cached_templates:
logger.debug("Using cached template: %s", name)
return self.cached_tem... | [
"Attempts to load the relevant template from our templating system/environment.\n\n Args:\n name: The name of the template to load.\n\n Return:\n On success, a StatikTemplate object that can be used to render content.\n "
] |
Please provide a description of the function:def create_template(self, s, provider_name=None):
if provider_name is None:
provider_name = self.supported_providers[0]
return template_exception_handler(
lambda: self.get_provider(provider_name).create_template(s),
... | [
"Creates a template from the given string based on the specified provider or the provider with\n highest precedence.\n\n Args:\n s: The string to convert to a template.\n provider_name: The name of the provider to use to create the template.\n "
] |
Please provide a description of the function:def construct_field(model_name, field_name, field_type, all_models, **kwargs):
field_type_parts = field_type.split('->')
_field_type = field_type_parts[0].strip().split('[]')[0].strip()
back_populates = field_type_parts[1].strip() if len(field_type_parts) > ... | [
"Helper function to build a field from the given field name and\n type.\n\n Args:\n model_name: The name of the model for which we're building this field.\n field_name: The name of the field to build.\n field_type: A string indicator as to which field type must be built.\n all_mode... |
Please provide a description of the function:def watch(project_path, output_path, host='0.0.0.0', port=8000, min_reload_time=2.0,
open_browser=True, safe_mode=False, error_context=None):
error_context = error_context or StatikErrorContext()
project = StatikProject(project_path, safe_mode=safe_mod... | [
"Watches the given project path for filesystem changes, and automatically rebuilds the project when\n changes are detected. Also serves an HTTP server on the given host/port.\n\n Args:\n project_path: The path to the Statik project to be watched.\n output_path: The path into which to write the o... |
Please provide a description of the function:def paginate(db_query, items_per_page, offset=0, start_page=1):
return Paginator(db_query, items_per_page, offset=offset, start_page=start_page) | [
"Instantiates a Paginator instance for database queries.\n\n Args:\n db_query: The SQLAlchemy database query to paginate.\n items_per_page: The desired number of items per page.\n offset: The number of items to skip when paginating.\n start_page: The number of the first page when repo... |
Please provide a description of the function:def render_reverse(self, inst=None, context=None):
rendered = self.render(inst=inst, context=context)
parts = rendered.split('/')
# we only prettify URLs for these files
if parts[-1] in ['index.html', 'index.htm']:
return ... | [
"Renders the reverse URL for this path."
] |
Please provide a description of the function:def create(
cls,
path,
template_engine=None,
output_filename=None,
output_ext=None,
view_name=None
):
# if it's a complex view
if isinstance(path, dict):
retu... | [
"Create the relevant subclass of StatikView based on the given path variable and\n parameters."
] |
Please provide a description of the function:def render(self, context, db=None, safe_mode=False, extra_context=None):
if not db:
raise MissingParameterError(
"db",
context=self.error_context
)
rendered_views = dict()
path_instances... | [
"Renders the given context using the specified database, returning a dictionary\n containing path segments and rendered view contents."
] |
Please provide a description of the function:def render(self, db, safe_mode=False, extra_context=None):
return self.renderer.render(
self.context,
db,
safe_mode=safe_mode,
extra_context=extra_context
) | [
"Renders this view, given the specified StatikDatabase instance."
] |
Please provide a description of the function:def cleanup(self):
self.log.debug("Cleaning up %s temporary directory" % self.tmp_dir)
shutil.rmtree(self.tmp_dir, ignore_errors=True) | [
" Cleanup the temporary directory "
] |
Please provide a description of the function:def _validate_number_of_layers(self, number_of_layers):
# Only positive numbers are correct
if number_of_layers <= 0:
raise SquashError(
"Number of layers to squash cannot be less or equal 0, provided: %s" % number_of_lay... | [
"\n Makes sure that the specified number of layers to squash\n is a valid number\n "
] |
Please provide a description of the function:def _files_in_layers(self, layers, directory):
files = {}
for layer in layers:
self.log.debug("Generating list of files in layer '%s'..." % layer)
tar_file = os.path.join(directory, layer, "layer.tar")
with tarfil... | [
"\n Prepare a list of files in all layers\n "
] |
Please provide a description of the function:def _prepare_tmp_directory(self, tmp_dir):
if tmp_dir:
if os.path.exists(tmp_dir):
raise SquashError(
"The '%s' directory already exists, please remove it before you proceed" % tmp_dir)
os.makedirs... | [
" Creates temporary directory that is used to work on layers "
] |
Please provide a description of the function:def _layers_to_squash(self, layers, from_layer):
to_squash = []
to_leave = []
should_squash = True
for l in reversed(layers):
if l == from_layer:
should_squash = False
if should_squash:
... | [
" Prepares a list of layer IDs that should be squashed "
] |
Please provide a description of the function:def _save_image(self, image_id, directory):
for x in [0, 1, 2]:
self.log.info("Saving image %s to %s directory..." %
(image_id, directory))
self.log.debug("Try #%s..." % (x + 1))
try:
... | [
" Saves the image as a tar archive under specified name "
] |
Please provide a description of the function:def _unpack(self, tar_file, directory):
self.log.info("Unpacking %s tar file to %s directory" %
(tar_file, directory))
with tarfile.open(tar_file, 'r') as tar:
tar.extractall(path=directory)
self.log.info(... | [
" Unpacks tar archive to selected directory "
] |
Please provide a description of the function:def _read_layers(self, layers, image_id):
for layer in self.docker.history(image_id):
layers.append(layer['Id']) | [
" Reads the JSON metadata for specified layer / image id "
] |
Please provide a description of the function:def _parse_image_name(self, image):
if ':' in image and '/' not in image.split(':')[-1]:
image_tag = image.split(':')[-1]
image_name = image[:-(len(image_tag) + 1)]
else:
image_tag = "latest"
image_name... | [
"\n Parses the provided image name and splits it in the\n name and tag part, if possible. If no tag is provided\n 'latest' is used.\n "
] |
Please provide a description of the function:def _dump_json(self, data, new_line=False):
# We do not want any spaces between keys and values in JSON
json_data = json.dumps(data, separators=(',', ':'))
if new_line:
json_data = "%s\n" % json_data
# Generate sha256su... | [
"\n Helper function to marshal object into JSON string.\n Additionally a sha256sum of the created JSON string is generated.\n "
] |
Please provide a description of the function:def _move_layers(self, layers, src, dest):
for layer in layers:
layer_id = layer.replace('sha256:', '')
self.log.debug("Moving unmodified layer '%s'..." % layer_id)
shutil.move(os.path.join(src, layer_id), dest) | [
"\n This moves all the layers that should be copied as-is.\n In other words - all layers that are not meant to be squashed will be\n moved from the old image to the new image untouched.\n "
] |
Please provide a description of the function:def _marker_files(self, tar, members):
marker_files = {}
self.log.debug(
"Searching for marker files in '%s' archive..." % tar.name)
for member in members:
if '.wh.' in member.name:
self.log.debug("Fo... | [
"\n Searches for marker files in the specified archive.\n\n Docker marker files are files taht have the .wh. prefix in the name.\n These files mark the corresponding file to be removed (hidden) when\n we start a container from the image.\n "
] |
Please provide a description of the function:def _add_markers(self, markers, tar, files_in_layers, added_symlinks):
if markers:
self.log.debug("Marker files to add: %s" %
[o.name for o in markers.keys()])
else:
# No marker files to add
... | [
"\n This method is responsible for adding back all markers that were not\n added to the squashed layer AND files they refer to can be found in layers\n we do not squash.\n "
] |
Please provide a description of the function:def _proc_pax(self, filetar):
# Read the header information.
buf = filetar.fileobj.read(self._block(self.size))
# A pax header stores supplemental information for either
# the following file (extended) or all following files
# (global).
if self.... | [
"Process an extended or global header as described in POSIX.1-2001."
] |
Please provide a description of the function:def _create_pax_generic_header(cls, pax_headers, type=tarfile.XHDTYPE):
records = []
for keyword, value in pax_headers.iteritems():
try:
keyword = keyword.encode("utf8")
except Exception:
pass
try:
va... | [
"Return a POSIX.1-2001 extended or global header sequence\n that contains a list of keyword, value pairs. The values\n must be unicode objects.\n "
] |
Please provide a description of the function:def _read_json_file(self, json_file):
self.log.debug("Reading '%s' JSON file..." % json_file)
with open(json_file, 'r') as f:
return json.load(f, object_pairs_hook=OrderedDict) | [
" Helper function to read JSON file as OrderedDict "
] |
Please provide a description of the function:def _read_layer_paths(self, old_image_config, old_image_manifest, layers_to_move):
# In manifest.json we do not have listed all layers
# but only layers that do contain some data.
current_manifest_layer = 0
layer_paths_to_move = []
... | [
"\n In case of v2 format, layer id's are not the same as the id's\n used in the exported tar archive to name directories for layers.\n These id's can be found in the configuration files saved with\n the image - we need to read them.\n "
] |
Please provide a description of the function:def _generate_squashed_layer_path_id(self):
# Using OrderedDict, because order of JSON elements is important
v1_metadata = OrderedDict(self.old_image_config)
# Update image creation date
v1_metadata['created'] = self.date
#... | [
"\n This function generates the id used to name the directory to\n store the squashed layer content in the archive.\n\n This mimics what Docker does here: https://github.com/docker/docker/blob/v1.10.0-rc1/image/v1/imagev1.go#L42\n To make it simpler we do reuse old image metadata and\n ... |
Please provide a description of the function:def write_local_file(self, outputfile, path):
self.logger.info("Writing file to %s", path)
outputfile.seek(0)
with open(path, 'wb') as fd:
copyfileobj(outputfile, fd) | [
"Write file to the desired path."
] |
Please provide a description of the function:def _cleanup_old_backups(self, database=None, servername=None):
self.storage.clean_old_backups(encrypted=self.encrypt,
compressed=self.compress,
content_type=self.content_type,
... | [
"\n Cleanup old backups, keeping the number of backups specified by\n DBBACKUP_CLEANUP_KEEP and any backups that occur on first of the month.\n "
] |
Please provide a description of the function:def _save_new_backup(self, database):
self.logger.info("Backing Up Database: %s", database['NAME'])
# Get backup and name
filename = self.connector.generate_filename(self.servername)
outputfile = self.connector.create_dump()
#... | [
"\n Save a new backup file.\n "
] |
Please provide a description of the function:def _explore_storage(self):
path = ''
dirs = [path]
while dirs:
path = dirs.pop()
subdirs, files = self.media_storage.listdir(path)
for media_filename in files:
yield os.path.join(path, medi... | [
"Generator of all files contained in media storage."
] |
Please provide a description of the function:def _create_tar(self, name):
fileobj = utils.create_spooled_temporary_file()
mode = 'w:gz' if self.compress else 'w'
tar_file = tarfile.open(name=name, fileobj=fileobj, mode=mode)
for media_filename in self._explore_storage():
... | [
"Create TAR file."
] |
Please provide a description of the function:def backup_mediafiles(self):
# Create file name
extension = "tar%s" % ('.gz' if self.compress else '')
filename = utils.filename_generate(extension,
servername=self.servername,
... | [
"\n Create backup file and write it to storage.\n "
] |
Please provide a description of the function:def bytes_to_str(byteVal, decimals=1):
for unit, byte in BYTES:
if (byteVal >= byte):
if decimals == 0:
return '%s %s' % (int(round(byteVal / byte, 0)), unit)
return '%s %s' % (round(byteVal / byte, decimals), unit)
... | [
"\n Convert bytes to a human readable string.\n\n :param byteVal: Value to convert in bytes\n :type byteVal: int or float\n\n :param decimal: Number of decimal to display\n :type decimal: int\n\n :returns: Number of byte with the best unit of measure\n :rtype: str\n "
] |
Please provide a description of the function:def mail_admins(subject, message, fail_silently=False, connection=None,
html_message=None):
if not settings.ADMINS:
return
mail = EmailMultiAlternatives('%s%s' % (settings.EMAIL_SUBJECT_PREFIX, subject),
... | [
"Sends a message to the admins, as defined by the DBBACKUP_ADMINS setting."
] |
Please provide a description of the function:def email_uncaught_exception(func):
@wraps(func)
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except:
logger = logging.getLogger('dbbackup')
exc_type, exc_value, tb = sys.exc_info()
tb_s... | [
"\n Function decorator for send email with uncaught exceptions to admins.\n Email is sent to ``settings.DBBACKUP_FAILURE_RECIPIENTS``\n (``settings.ADMINS`` if not defined). The message contains a traceback\n of error.\n "
] |
Please provide a description of the function:def create_spooled_temporary_file(filepath=None, fileobj=None):
spooled_file = tempfile.SpooledTemporaryFile(
max_size=settings.TMP_FILE_MAX_SIZE,
dir=settings.TMP_DIR)
if filepath:
fileobj = open(filepath, 'r+b')
if fileobj is not No... | [
"\n Create a spooled temporary file. if ``filepath`` or ``fileobj`` is\n defined its content will be copied into temporary file.\n\n :param filepath: Path of input file\n :type filepath: str\n\n :param fileobj: Input file object\n :type fileobj: file\n\n :returns: Spooled temporary file\n :r... |
Please provide a description of the function:def encrypt_file(inputfile, filename):
import gnupg
tempdir = tempfile.mkdtemp(dir=settings.TMP_DIR)
try:
filename = '%s.gpg' % filename
filepath = os.path.join(tempdir, filename)
try:
inputfile.seek(0)
always_... | [
"\n Encrypt input file using GPG and remove .gpg extension to its name.\n\n :param inputfile: File to encrypt\n :type inputfile: ``file`` like object\n\n :param filename: File's name\n :type filename: ``str``\n\n :returns: Tuple with file and new file's name\n :rtype: :class:`tempfile.SpooledTe... |
Please provide a description of the function:def unencrypt_file(inputfile, filename, passphrase=None):
import gnupg
def get_passphrase(passphrase=passphrase):
return passphrase or getpass('Input Passphrase: ') or None
temp_dir = tempfile.mkdtemp(dir=settings.TMP_DIR)
try:
new_base... | [
"\n Unencrypt input file using GPG and remove .gpg extension to its name.\n\n :param inputfile: File to encrypt\n :type inputfile: ``file`` like object\n\n :param filename: File's name\n :type filename: ``str``\n\n :param passphrase: Passphrase of GPG key, if equivalent to False, it will\n ... |
Please provide a description of the function:def compress_file(inputfile, filename):
outputfile = create_spooled_temporary_file()
new_filename = filename + '.gz'
zipfile = gzip.GzipFile(filename=filename, fileobj=outputfile, mode="wb")
try:
inputfile.seek(0)
copyfileobj(inputfile, z... | [
"\n Compress input file using gzip and change its name.\n\n :param inputfile: File to compress\n :type inputfile: ``file`` like object\n\n :param filename: File's name\n :type filename: ``str``\n\n :returns: Tuple with compressed file and new file's name\n :rtype: :class:`tempfile.SpooledTempor... |
Please provide a description of the function:def uncompress_file(inputfile, filename):
zipfile = gzip.GzipFile(fileobj=inputfile, mode="rb")
try:
outputfile = create_spooled_temporary_file(fileobj=zipfile)
finally:
zipfile.close()
new_basename = os.path.basename(filename).replace('.... | [
"\n Uncompress this file using gzip and change its name.\n\n :param inputfile: File to compress\n :type inputfile: ``file`` like object\n\n :param filename: File's name\n :type filename: ``str``\n\n :returns: Tuple with file and new file's name\n :rtype: :class:`tempfile.SpooledTemporaryFile`, ... |
Please provide a description of the function:def timestamp(value):
value = value if timezone.is_naive(value) else timezone.localtime(value)
return value.strftime(settings.DATE_FORMAT) | [
"\n Return the timestamp of a datetime.datetime object.\n\n :param value: a datetime object\n :type value: datetime.datetime\n\n :return: the timestamp\n :rtype: str\n "
] |
Please provide a description of the function:def datefmt_to_regex(datefmt):
new_string = datefmt
for pat, reg in PATTERN_MATCHNG:
new_string = new_string.replace(pat, reg)
return re.compile(r'(%s)' % new_string) | [
"\n Convert a strftime format string to a regex.\n\n :param datefmt: strftime format string\n :type datefmt: ``str``\n\n :returns: Equivalent regex\n :rtype: ``re.compite``\n "
] |
Please provide a description of the function:def filename_to_date(filename, datefmt=None):
datefmt = datefmt or settings.DATE_FORMAT
datestring = filename_to_datestring(filename, datefmt)
if datestring is not None:
return datetime.strptime(datestring, datefmt) | [
"\n Return a datetime from a file name.\n\n :param datefmt: strftime format string, ``settings.DATE_FORMAT`` is used\n if is ``None``\n :type datefmt: ``str`` or ``NoneType``\n\n :returns: Date guessed or nothing if no date found\n :rtype: ``datetime.datetime`` or ``NoneType``\n ... |
Please provide a description of the function:def filename_generate(extension, database_name='', servername=None, content_type='db', wildcard=None):
if content_type == 'db':
if '/' in database_name:
database_name = os.path.basename(database_name)
if '.' in database_name:
... | [
"\n Create a new backup filename.\n\n :param extension: Extension of backup file\n :type extension: ``str``\n\n :param database_name: If it is database backup specify its name\n :type database_name: ``str``\n\n :param servername: Specify server name or by default ``settings.DBBACKUP_HOSTNAME``\n ... |
Please provide a description of the function:def get_storage(path=None, options=None):
path = path or settings.STORAGE
options = options or settings.STORAGE_OPTIONS
if not path:
raise ImproperlyConfigured('You must specify a storage class using '
'DBBACKUP_STO... | [
"\n Get the specified storage configured with options.\n\n :param path: Path in Python dot style to module containing the storage\n class. If empty settings.DBBACKUP_STORAGE will be used.\n :type path: ``str``\n\n :param options: Parameters for configure the storage, if empty\n ... |
Please provide a description of the function:def list_backups(self, encrypted=None, compressed=None, content_type=None,
database=None, servername=None):
if content_type not in ('db', 'media', None):
msg = "Bad content_type %s, must be 'db', 'media', or None" % (
... | [
"\n List stored files except given filter. If filter is None, it won't be\n used. ``content_type`` must be ``'db'`` for database backups or\n ``'media'`` for media backups.\n\n :param encrypted: Filter by encrypted or not\n :type encrypted: ``bool`` or ``None``\n\n :param c... |
Please provide a description of the function:def get_older_backup(self, encrypted=None, compressed=None,
content_type=None, database=None, servername=None):
files = self.list_backups(encrypted=encrypted, compressed=compressed,
content_type=cont... | [
"\n Return the older backup's file name.\n\n :param encrypted: Filter by encrypted or not\n :type encrypted: ``bool`` or ``None``\n\n :param compressed: Filter by compressed or not\n :type compressed: ``bool`` or ``None``\n\n :param content_type: Filter by media or database... |
Please provide a description of the function:def clean_old_backups(self, encrypted=None, compressed=None,
content_type=None, database=None, servername=None,
keep_number=None):
if keep_number is None:
keep_number = settings.CLEANUP_KEEP if ... | [
"\n Delete olders backups and hold the number defined.\n\n :param encrypted: Filter by encrypted or not\n :type encrypted: ``bool`` or ``None``\n\n :param compressed: Filter by compressed or not\n :type compressed: ``bool`` or ``None``\n\n :param content_type: Filter by med... |
Please provide a description of the function:def handle(self, *args, **options):
self.verbosity = int(options.get('verbosity'))
self.quiet = options.get('quiet')
self._set_logger_level()
try:
connection.close()
self.filename = options.get('input_filename... | [
"Django command handler."
] |
Please provide a description of the function:def _get_database(self, options):
database_name = options.get('database')
if not database_name:
if len(settings.DATABASES) > 1:
errmsg = "Because this project contains more than one database, you"\
" mu... | [
"Get the database to restore."
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.