_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q37000 | BuildSourceFileAccessor.record_to_objects | train | def record_to_objects(self, preference=None):
"""Create objects from files, or merge the files into the objects. """
from ambry.orm.file import File
for f in self.list_records():
pref = preference if preference else f.record.preference
if pref == File.PREFERENCE.FILE:
... | python | {
"resource": ""
} |
q37001 | BuildSourceFileAccessor.objects_to_record | train | def objects_to_record(self, preference=None):
"""Create file records from objects. """
from ambry.orm.file import File
raise NotImplementedError("Still uses obsolete file_info_map")
for file_const, (file_name, clz) in iteritems(file_info_map):
f = self.file(file_const)
... | python | {
"resource": ""
} |
q37002 | BuildSourceFileAccessor.set_defaults | train | def set_defaults(self):
"""Add default content to any file record that is empty"""
for const_name, c in file_classes.items():
if c.multiplicity == '1':
f = self.file(const_name)
if not f.record.unpacked_contents:
f.setcontent(f.default) | python | {
"resource": ""
} |
q37003 | run | train | def run(host='127.0.0.1', port=8000):
"""
Run web server.
"""
print("Server running on {}:{}".format(host, port))
app_router = Router()
server = make_server(host, port, app_router)
server.serve_forever() | python | {
"resource": ""
} |
q37004 | main | train | def main(args=None):
"""
Create a private key and a certificate and write them to a file.
"""
if args is None:
args = sys.argv[1:]
o = Options()
try:
o.parseOptions(args)
except usage.UsageError, e:
raise SystemExit(str(e))
else:
return createSSLCertifica... | python | {
"resource": ""
} |
q37005 | Code.update | train | def update(self, f):
"""Copy another files properties into this one."""
for p in self.__mapper__.attrs:
if p.key == 'oid':
continue
try:
setattr(self, p.key, getattr(f, p.key))
except AttributeError:
# The dict() meth... | python | {
"resource": ""
} |
q37006 | TimeoutMixin.resetTimeout | train | def resetTimeout(self):
"""Reset the timeout count down"""
if self.__timeoutCall is not None and self.timeOut is not None:
self.__timeoutCall.reset(self.timeOut) | python | {
"resource": ""
} |
q37007 | TimeoutMixin.setTimeout | train | def setTimeout(self, period):
"""Change the timeout period
@type period: C{int} or C{NoneType}
@param period: The period, in seconds, to change the timeout to, or
C{None} to disable the timeout.
"""
prev = self.timeOut
self.timeOut = period
if self.__tim... | python | {
"resource": ""
} |
q37008 | Router._load_controllers | train | def _load_controllers(self):
"""
Load all controllers from folder 'controllers'.
Ignore files with leading underscore (for example: controllers/_blogs.py)
"""
for file_name in os.listdir(os.path.join(self._project_dir, 'controllers')):
# ignore disabled controllers
... | python | {
"resource": ""
} |
q37009 | Router._init_view | train | def _init_view(self):
"""
Initialize View with project settings.
"""
views_engine = get_config('rails.views.engine', 'jinja')
templates_dir = os.path.join(self._project_dir, "views", "templates")
self._view = View(views_engine, templates_dir) | python | {
"resource": ""
} |
q37010 | Router.get_action_handler | train | def get_action_handler(self, controller_name, action_name):
"""
Return action of controller as callable.
If requested controller isn't found - return 'not_found' action
of requested controller or Index controller.
"""
try_actions = [
controller_name + '/' + a... | python | {
"resource": ""
} |
q37011 | _preprocess_sqlite_index | train | def _preprocess_sqlite_index(asql_query, library, backend, connection):
""" Creates materialized view for each indexed partition found in the query.
Args:
asql_query (str): asql query
library (ambry.Library):
backend (SQLiteBackend):
connection (apsw.Connection):
Returns:
... | python | {
"resource": ""
} |
q37012 | SQLiteBackend.close | train | def close(self):
""" Closes connection to sqlite database. """
if getattr(self, '_connection', None):
logger.debug('Closing sqlite connection.')
self._connection.close()
self._connection = None | python | {
"resource": ""
} |
q37013 | SQLiteBackend._get_mpr_view | train | def _get_mpr_view(self, connection, table):
""" Finds and returns view name in the sqlite db represented by given connection.
Args:
connection: connection to sqlite db where to look for partition table.
table (orm.Table):
Raises:
MissingViewError: if databas... | python | {
"resource": ""
} |
q37014 | SQLiteBackend._get_mpr_table | train | def _get_mpr_table(self, connection, partition):
""" Returns name of the sqlite table who stores mpr data.
Args:
connection (apsw.Connection): connection to sqlite database who stores mpr data.
partition (orm.Partition):
Returns:
str:
Raises:
... | python | {
"resource": ""
} |
q37015 | SQLiteBackend._get_create_query | train | def _get_create_query(partition, tablename, include=None):
""" Creates and returns `CREATE TABLE ...` sql statement for given mprows.
Args:
partition (orm.Partition):
tablename (str): name of the table in the return create query.
include (list of str, optional): list... | python | {
"resource": ""
} |
q37016 | SQLiteBackend._get_connection | train | def _get_connection(self):
""" Returns connection to sqlite db.
Returns:
connection to the sqlite db who stores mpr data.
"""
if getattr(self, '_connection', None):
logger.debug('Connection to sqlite db already exists. Using existing one.')
else:
... | python | {
"resource": ""
} |
q37017 | SQLiteBackend._add_partition | train | def _add_partition(self, connection, partition):
""" Creates sqlite virtual table for mpr file of the given partition.
Args:
connection: connection to the sqlite db who stores mpr data.
partition (orm.Partition):
"""
logger.debug('Creating virtual table for part... | python | {
"resource": ""
} |
q37018 | SQLiteBackend._execute | train | def _execute(self, connection, query, fetch=True):
""" Executes given query using given connection.
Args:
connection (apsw.Connection): connection to the sqlite db who stores mpr data.
query (str): sql query
fetch (boolean, optional): if True, fetch query result and ... | python | {
"resource": ""
} |
q37019 | list_milestones | train | def list_milestones(page_size=200, page_index=0, q="", sort=""):
"""
List all ProductMilestones
"""
data = list_milestones_raw(page_size, page_index, sort, q)
if data:
return utils.format_json_list(data) | python | {
"resource": ""
} |
q37020 | update_milestone | train | def update_milestone(id, **kwargs):
"""
Update a ProductMilestone
"""
data = update_milestone_raw(id, **kwargs)
if data:
return utils.format_json(data) | python | {
"resource": ""
} |
q37021 | close_milestone | train | def close_milestone(id, **kwargs):
"""
Close a milestone. This triggers its release process.
The user can optionally specify the release-date, otherwise today's date is
used.
If the wait parameter is specified and set to True, upon closing the milestone,
we'll periodically check that the relea... | python | {
"resource": ""
} |
q37022 | HtPasswdAuth.init_app | train | def init_app(self, app):
"""
Find and configure the user database from specified file
"""
app.config.setdefault('FLASK_AUTH_ALL', False)
app.config.setdefault('FLASK_AUTH_REALM', 'Login Required')
# Default set to bad file to trigger IOError
app.config.setdefault(... | python | {
"resource": ""
} |
q37023 | HtPasswdAuth.get_hashhash | train | def get_hashhash(self, username):
"""
Generate a digest of the htpasswd hash
"""
return hashlib.sha256(
self.users.get_hash(username)
).hexdigest() | python | {
"resource": ""
} |
q37024 | HtPasswdAuth.generate_token | train | def generate_token(self, username):
"""
assumes user exists in htpasswd file.
Return the token for the given user by signing a token of
the username and a hash of the htpasswd string.
"""
serializer = self.get_signature()
return serializer.dumps(
{
... | python | {
"resource": ""
} |
q37025 | HtPasswdAuth.check_token_auth | train | def check_token_auth(self, token):
"""
Check to see who this is and if their token gets
them into the system.
"""
serializer = self.get_signature()
try:
data = serializer.loads(token)
except BadSignature:
log.warning('Received bad token si... | python | {
"resource": ""
} |
q37026 | HtPasswdAuth.authenticate | train | def authenticate(self):
"""Authenticate user by any means and return either true or false.
Args:
Returns:
tuple (is_valid, username): True is valid user, False if not
"""
basic_auth = request.authorization
is_valid = False
user = None
if basi... | python | {
"resource": ""
} |
q37027 | HtPasswdAuth.required | train | def required(self, func):
"""
Decorator function with basic and token authentication handler
"""
@wraps(func)
def decorated(*args, **kwargs):
"""
Actual wrapper to run the auth checks.
"""
is_valid, user = self.authenticate()
... | python | {
"resource": ""
} |
q37028 | Name.source_path | train | def source_path(self):
"""The name in a form suitable for use in a filesystem.
Excludes the revision
"""
# Need to do this to ensure the function produces the
# bundle path when called from subclasses
names = [k for k, _, _ in self._name_parts]
parts = [self.so... | python | {
"resource": ""
} |
q37029 | Name.cache_key | train | def cache_key(self):
"""The name in a form suitable for use as a cache-key"""
try:
return self.path
except TypeError:
raise TypeError("self.path is invalild: '{}', '{}'".format(str(self.path), type(self.path))) | python | {
"resource": ""
} |
q37030 | Name.ver | train | def ver(self, revision):
"""Clone and change the version."""
c = self.clone()
c.version = self._parse_version(self.version)
return c | python | {
"resource": ""
} |
q37031 | Name.as_partition | train | def as_partition(self, **kwargs):
"""Return a PartitionName based on this name."""
return PartitionName(**dict(list(self.dict.items()) + list(kwargs.items()))) | python | {
"resource": ""
} |
q37032 | PartialPartitionName.promote | train | def promote(self, name):
"""Promote to a PartitionName by combining with a bundle Name."""
return PartitionName(**dict(list(name.dict.items()) + list(self.dict.items()))) | python | {
"resource": ""
} |
q37033 | PartitionName.path | train | def path(self):
"""The path of the bundle source.
Includes the revision.
"""
# Need to do this to ensure the function produces the
# bundle path when called from subclasses
names = [k for k, _, _ in Name._name_parts]
return os.path.join(self.source,
... | python | {
"resource": ""
} |
q37034 | PartitionName.sub_path | train | def sub_path(self):
"""The path of the partition source, excluding the bundle path parts.
Includes the revision.
"""
try:
return os.path.join(*(self._local_parts()))
except TypeError as e:
raise TypeError(
"Path failed for partition {} :... | python | {
"resource": ""
} |
q37035 | PartitionName.partital_dict | train | def partital_dict(self, with_name=True):
"""Returns the name as a dict, but with only the items that are
particular to a PartitionName."""
d = self._dict(with_name=False)
d = {k: d.get(k) for k, _, _ in PartialPartitionName._name_parts if d.get(k, False)}
if 'format' in d and ... | python | {
"resource": ""
} |
q37036 | ObjectNumber.base62_encode | train | def base62_encode(cls, num):
"""Encode a number in Base X.
`num`: The number to encode
`alphabet`: The alphabet to use for encoding
Stolen from: http://stackoverflow.com/a/1119769/1144479
"""
alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
... | python | {
"resource": ""
} |
q37037 | ObjectNumber.base62_decode | train | def base62_decode(cls, string):
"""Decode a Base X encoded string into the number.
Arguments:
- `string`: The encoded string
- `alphabet`: The alphabet to use for encoding
Stolen from: http://stackoverflow.com/a/1119769/1144479
"""
alphabet = "0123456789abcdefg... | python | {
"resource": ""
} |
q37038 | ObjectNumber.increment | train | def increment(cls, v):
"""Increment the version number of an object number of object number string"""
if not isinstance(v, ObjectNumber):
v = ObjectNumber.parse(v)
return v.rev(v.revision+1) | python | {
"resource": ""
} |
q37039 | ObjectNumber.rev | train | def rev(self, i):
"""Return a clone with a different revision."""
on = copy(self)
on.revision = i
return on | python | {
"resource": ""
} |
q37040 | TopNumber.from_hex | train | def from_hex(cls, h, space, assignment_class='self'):
"""Produce a TopNumber, with a length to match the given assignment
class, based on an input hex string.
This can be used to create TopNumbers from a hash of a string.
"""
from math import log
# Use the ln(N)/ln(ba... | python | {
"resource": ""
} |
q37041 | TopNumber.from_string | train | def from_string(cls, s, space):
"""Produce a TopNumber by hashing a string."""
import hashlib
hs = hashlib.sha1(s).hexdigest()
return cls.from_hex(hs, space) | python | {
"resource": ""
} |
q37042 | Identity.classify | train | def classify(cls, o):
"""Break an Identity name into parts, or describe the type of other
forms.
Break a name or object number into parts and classify them. Returns a named tuple
that indicates which parts of input string are name components, object number and
version number. Do... | python | {
"resource": ""
} |
q37043 | Identity.to_meta | train | def to_meta(self, md5=None, file=None):
"""Return a dictionary of metadata, for use in the Remote api."""
# from collections import OrderedDict
if not md5:
if not file:
raise ValueError('Must specify either file or md5')
md5 = md5_for_file(file)
... | python | {
"resource": ""
} |
q37044 | Identity.names_dict | train | def names_dict(self):
"""A dictionary with only the generated names, name, vname and fqname."""
INCLUDE_KEYS = ['name', 'vname', 'vid']
d = {k: v for k, v in iteritems(self.dict) if k in INCLUDE_KEYS}
d['fqname'] = self.fqname
return d | python | {
"resource": ""
} |
q37045 | Identity.ident_dict | train | def ident_dict(self):
"""A dictionary with only the items required to specify the identy,
excluding the generated names, name, vname and fqname."""
SKIP_KEYS = ['name','vname','fqname','vid','cache_key']
return {k: v for k, v in iteritems(self.dict) if k not in SKIP_KEYS} | python | {
"resource": ""
} |
q37046 | Identity.as_partition | train | def as_partition(self, partition=0, **kwargs):
"""Return a new PartitionIdentity based on this Identity.
:param partition: Integer partition number for PartitionObjectNumber
:param kwargs:
"""
assert isinstance(self._name, Name), "Wrong type: {}".format(type(self._name))
... | python | {
"resource": ""
} |
q37047 | Identity.partition | train | def partition(self):
"""Convenience function for accessing the first partition in the
partitions list, when there is only one."""
if not self.partitions:
return None
if len(self.partitions) > 1:
raise ValueError(
"Can't use this method when there... | python | {
"resource": ""
} |
q37048 | Identity.rev | train | def rev(self, rev):
"""Return a new identity with the given revision"""
d = self.dict
d['revision'] = rev
return self.from_dict(d) | python | {
"resource": ""
} |
q37049 | Identity._info | train | def _info(self):
"""Returns an OrderedDict of information, for human display."""
d = OrderedDict()
d['vid'] = self.vid
d['sname'] = self.sname
d['vname'] = self.vname
return d | python | {
"resource": ""
} |
q37050 | PartitionIdentity.from_dict | train | def from_dict(cls, d):
"""Like Identity.from_dict, but will cast the class type based on the
format. i.e. if the format is hdf, return an HdfPartitionIdentity.
:param d:
:return:
"""
name = PartitionIdentity._name_class(**d)
if 'id' in d and 'revision' in d:
... | python | {
"resource": ""
} |
q37051 | PartitionIdentity.as_dataset | train | def as_dataset(self):
"""Convert this identity to the identity of the corresponding
dataset."""
on = self.on.dataset
on.revision = self.on.revision
name = Name(**self.name.dict)
return Identity(name, on) | python | {
"resource": ""
} |
q37052 | NumberServer.sleep | train | def sleep(self):
"""Wait for the sleep time of the last response, to avoid being rate
limited."""
if self.next_time and time.time() < self.next_time:
time.sleep(self.next_time - time.time()) | python | {
"resource": ""
} |
q37053 | root_sync | train | def root_sync(args, l, config):
"""Sync with the remote. For more options, use library sync
"""
from requests.exceptions import ConnectionError
all_remote_names = [ r.short_name for r in l.remotes ]
if args.all:
remotes = all_remote_names
else:
remotes = args.refs
prt("Syn... | python | {
"resource": ""
} |
q37054 | _CaptureException | train | def _CaptureException(f, *args, **kwargs):
"""Decorator implementation for capturing exceptions."""
from ambry.dbexceptions import LoggedException
b = args[0] # The 'self' argument
try:
return f(*args, **kwargs)
except Exception as e:
raise
try:
b.set_error_sta... | python | {
"resource": ""
} |
q37055 | Bundle.clear_file_systems | train | def clear_file_systems(self):
"""Remove references to build and source file systems, reverting to the defaults"""
self._source_url = None
self.dataset.config.library.source.url = None
self._source_fs = None
self._build_url = None
self.dataset.config.library.build.url = ... | python | {
"resource": ""
} |
q37056 | Bundle.cast_to_subclass | train | def cast_to_subclass(self):
"""
Load the bundle file from the database to get the derived bundle class,
then return a new bundle built on that class
:return:
"""
self.import_lib()
self.load_requirements()
try:
self.commit() # To ensure the r... | python | {
"resource": ""
} |
q37057 | Bundle.load_requirements | train | def load_requirements(self):
"""If there are python library requirements set, append the python dir
to the path."""
for module_name, pip_name in iteritems(self.metadata.requirements):
extant = self.dataset.config.requirements[module_name].url
force = (extant and extant ... | python | {
"resource": ""
} |
q37058 | Bundle.dep | train | def dep(self, source_name):
"""Return a bundle dependency from the sources list
:param source_name: Source name. The URL field must be a bundle or partition reference
:return:
"""
from ambry.orm.exc import NotFoundError
from ambry.dbexceptions import ConfigurationError
... | python | {
"resource": ""
} |
q37059 | Bundle.documentation | train | def documentation(self):
"""Return the documentation, from the documentation.md file, with template substitutions"""
# Return the documentation as a scalar term, which has .text() and .html methods to do
# metadata substitution using Jinja
s = ''
rc = self.build_source_files.d... | python | {
"resource": ""
} |
q37060 | Bundle.progress | train | def progress(self):
"""Returned a cached ProcessLogger to record build progress """
if not self._progress:
# If won't be building, only use one connection
new_connection = False if self._library.read_only else True
self._progress = ProcessLogger(self.dataset, self.... | python | {
"resource": ""
} |
q37061 | Bundle.partition | train | def partition(self, ref=None, **kwargs):
"""Return a partition in this bundle for a vid reference or name parts"""
from ambry.orm.exc import NotFoundError
from sqlalchemy.orm.exc import NoResultFound
if not ref and not kwargs:
return None
if ref:
for p i... | python | {
"resource": ""
} |
q37062 | Bundle.partition_by_vid | train | def partition_by_vid(self, ref):
"""A much faster way to get partitions, by vid only"""
from ambry.orm import Partition
p = self.session.query(Partition).filter(Partition.vid == str(ref)).first()
if p:
return self.wrap_partition(p)
else:
return None | python | {
"resource": ""
} |
q37063 | Bundle.sources | train | def sources(self):
"""Iterate over downloadable sources"""
def set_bundle(s):
s._bundle = self
return s
return list(set_bundle(s) for s in self.dataset.sources) | python | {
"resource": ""
} |
q37064 | Bundle._resolve_sources | train | def _resolve_sources(self, sources, tables, stage=None, predicate=None):
"""
Determine what sources to run from an input of sources and tables
:param sources: A collection of source objects, source names, or source vids
:param tables: A collection of table names
:param stage: I... | python | {
"resource": ""
} |
q37065 | Bundle.build_source_files | train | def build_source_files(self):
"""Return acessors to the build files"""
from .files import BuildSourceFileAccessor
return BuildSourceFileAccessor(self, self.dataset, self.source_fs) | python | {
"resource": ""
} |
q37066 | Bundle.build_partition_fs | train | def build_partition_fs(self):
"""Return a pyfilesystem subdirectory for the build directory for the bundle. This the sub-directory
of the build FS that holds the compiled SQLite file and the partition data files"""
base_path = os.path.dirname(self.identity.cache_key)
if not self.build_... | python | {
"resource": ""
} |
q37067 | Bundle.build_ingest_fs | train | def build_ingest_fs(self):
"""Return a pyfilesystem subdirectory for the ingested source files"""
base_path = 'ingest'
if not self.build_fs.exists(base_path):
self.build_fs.makedir(base_path, recursive=True, allow_recreate=True)
return self.build_fs.opendir(base_path) | python | {
"resource": ""
} |
q37068 | Bundle.logger | train | def logger(self):
"""The bundle logger."""
if not self._logger:
ident = self.identity
if self.multi:
template = '%(levelname)s %(process)d {} %(message)s'.format(ident.vid)
else:
template = '%(levelname)s {} %(message)s'.format(ident... | python | {
"resource": ""
} |
q37069 | Bundle.log_to_file | train | def log_to_file(self, message):
"""Write a log message only to the file"""
with self.build_fs.open(self.log_file, 'a+') as f:
f.write(unicode(message + '\n')) | python | {
"resource": ""
} |
q37070 | Bundle.logged_exception | train | def logged_exception(self, e):
"""Record the exception, but don't log it; it's already been logged
:param e: Exception to log.
"""
if str(e) not in self._errors:
self._errors.append(str(e))
self.set_error_state()
self.buildstate.state.exception_type = str(... | python | {
"resource": ""
} |
q37071 | Bundle.fatal | train | def fatal(self, message):
"""Log a fatal messsage and exit.
:param message: Log message.
"""
self.logger.fatal(message)
sys.stderr.flush()
if self.exit_on_fatal:
sys.exit(1)
else:
raise FatalError(message) | python | {
"resource": ""
} |
q37072 | Bundle.log_pipeline | train | def log_pipeline(self, pl):
"""Write a report of the pipeline out to a file """
from datetime import datetime
from ambry.etl.pipeline import CastColumns
self.build_fs.makedir('pipeline', allow_recreate=True)
try:
ccp = pl[CastColumns]
caster_code = ccp.p... | python | {
"resource": ""
} |
q37073 | Bundle.pipeline | train | def pipeline(self, source=None, phase='build', ps=None):
"""
Construct the ETL pipeline for all phases. Segments that are not used for the current phase
are filtered out later.
:param source: A source object, or a source string name
:return: an etl Pipeline
"""
f... | python | {
"resource": ""
} |
q37074 | Bundle.field_row | train | def field_row(self, fields):
"""
Return a list of values to match the fields values. This is used when listing bundles to
produce a table of information about the bundle.
:param fields: A list of names of data items.
:return: A list of values, in the same order as the fields inp... | python | {
"resource": ""
} |
q37075 | Bundle.source_pipe | train | def source_pipe(self, source, ps=None):
"""Create a source pipe for a source, giving it access to download files to the local cache"""
if isinstance(source, string_types):
source = self.source(source)
source.dataset = self.dataset
source._bundle = self
iter_source,... | python | {
"resource": ""
} |
q37076 | Bundle.error_state | train | def error_state(self):
"""Set the error condition"""
self.buildstate.state.lasttime = time()
self.buildstate.commit()
return self.buildstate.state.error | python | {
"resource": ""
} |
q37077 | Bundle.state | train | def state(self, state):
"""Set the current build state and record the time to maintain history.
Note! This is different from the dataset state. Setting the build set is commiteed to the
progress table/database immediately. The dstate is also set, but is not committed until the
bundle is... | python | {
"resource": ""
} |
q37078 | Bundle.record_stage_state | train | def record_stage_state(self, phase, stage):
"""Record the completion times of phases and stages"""
key = '{}-{}'.format(phase, stage if stage else 1)
self.buildstate.state[key] = time() | python | {
"resource": ""
} |
q37079 | Bundle.set_last_access | train | def set_last_access(self, tag):
"""Mark the time that this bundle was last accessed"""
import time
# time defeats check that value didn't change
self.buildstate.access.last = '{}-{}'.format(tag, time.time())
self.buildstate.commit() | python | {
"resource": ""
} |
q37080 | Bundle.sync_in | train | def sync_in(self, force=False):
"""Synchronize from files to records, and records to objects"""
self.log('---- Sync In ----')
self.dstate = self.STATES.BUILDING
for path_name in self.source_fs.listdir():
f = self.build_source_files.instance_from_name(path_name)
... | python | {
"resource": ""
} |
q37081 | Bundle.sync_out | train | def sync_out(self, file_name=None, force=False):
"""Synchronize from objects to records"""
self.log('---- Sync Out ----')
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
for f in self.build_source_files.list_records():
if (f.sync_d... | python | {
"resource": ""
} |
q37082 | Bundle.sync_objects_in | train | def sync_objects_in(self):
"""Synchronize from records to objects"""
self.dstate = self.STATES.BUILDING
self.build_source_files.record_to_objects() | python | {
"resource": ""
} |
q37083 | Bundle.sync_objects_out | train | def sync_objects_out(self, force=False):
"""Synchronize from objects to records, and records to files"""
self.log('---- Sync Objects Out ----')
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
for f in self.build_source_files.list_records():
... | python | {
"resource": ""
} |
q37084 | Bundle.sync_sources | train | def sync_sources(self, force=False):
"""Sync in only the sources.csv file"""
from ambry.orm.file import File
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.SOURCES]:
bsf = self.build_source_files.file(fc)
if bsf.fs_is_newer or forc... | python | {
"resource": ""
} |
q37085 | Bundle.update_schema | train | def update_schema(self):
"""Propagate schema object changes to file records"""
self.commit()
self.build_source_files.schema.objects_to_record()
self.commit() | python | {
"resource": ""
} |
q37086 | Bundle.clean | train | def clean(self, force=False):
"""Clean generated objects from the dataset, but only if there are File contents
to regenerate them"""
if self.is_finalized and not force:
self.warn("Can't clean; bundle is finalized")
return False
self.log('---- Cleaning ----')
... | python | {
"resource": ""
} |
q37087 | Bundle.clean_except_files | train | def clean_except_files(self):
"""Clean everything except the build source files"""
if self.is_finalized:
self.warn("Can't clean; bundle is finalized")
return False
self.log('---- Cleaning ----')
self.state = self.STATES.CLEANING
self.commit()
s... | python | {
"resource": ""
} |
q37088 | Bundle.clean_sources | train | def clean_sources(self):
"""Like clean, but also clears out files. """
for src in self.dataset.sources:
src.st_id = None
src.t_id = None
self.dataset.sources[:] = []
self.dataset.source_tables[:] = []
self.dataset.st_sequence_id = 1 | python | {
"resource": ""
} |
q37089 | Bundle.clean_partitions | train | def clean_partitions(self):
"""Delete partition records and any built partition files. """
import shutil
from ambry.orm import ColumnStat
# FIXME. There is a problem with the cascades for ColumnStats that prevents them from
# being deleted with the partitions. Probably, they ar... | python | {
"resource": ""
} |
q37090 | Bundle.clean_build | train | def clean_build(self):
"""Delete the build directory and all ingested files """
import shutil
if self.build_fs.exists:
try:
shutil.rmtree(self.build_fs.getsyspath('/'))
except NoSysPathError:
pass | python | {
"resource": ""
} |
q37091 | Bundle.clean_ingested | train | def clean_ingested(self):
""""Clean ingested files"""
for s in self.sources:
df = s.datafile
if df.exists and not s.is_partition:
df.remove()
s.state = s.STATES.NEW
self.commit() | python | {
"resource": ""
} |
q37092 | Bundle.clean_process_meta | train | def clean_process_meta(self):
"""Remove all process and build metadata"""
ds = self.dataset
ds.config.build.clean()
ds.config.process.clean()
ds.commit()
self.state = self.STATES.CLEANED | python | {
"resource": ""
} |
q37093 | Bundle.clean_source_files | train | def clean_source_files(self):
"""Remove the schema.csv and source_schema.csv files"""
self.build_source_files.file(File.BSFILE.SOURCESCHEMA).remove()
self.build_source_files.file(File.BSFILE.SCHEMA).remove()
self.commit() | python | {
"resource": ""
} |
q37094 | Bundle.ingest | train | def ingest(self, sources=None, tables=None, stage=None, force=False, load_meta=False):
"""Ingest a set of sources, specified as source objects, source names, or destination tables.
If no stage is specified, execute the sources in groups by stage.
Note, however, that when this is called from run... | python | {
"resource": ""
} |
q37095 | Bundle._ingest_sources | train | def _ingest_sources(self, sources, stage, force=False):
"""Ingest a set of sources, usually for one stage"""
from concurrent import ingest_mp
self.state = self.STATES.INGESTING
downloadable_sources = [s for s in sources if force or
(s.is_processable and ... | python | {
"resource": ""
} |
q37096 | Bundle.source_schema | train | def source_schema(self, sources=None, tables=None, clean=False):
"""Process a collection of ingested sources to make source tables. """
sources = self._resolve_sources(sources, tables, None,
predicate=lambda s: s.is_processable)
for source in sources:
... | python | {
"resource": ""
} |
q37097 | Bundle.schema | train | def schema(self, sources=None, tables=None, clean=False, force=False, use_pipeline=False):
"""
Generate destination schemas.
:param sources: If specified, build only destination tables for these sources
:param tables: If specified, build only these tables
:param clean: Delete ta... | python | {
"resource": ""
} |
q37098 | Bundle._reset_build | train | def _reset_build(self, sources):
"""Remove partition datafiles and reset the datafiles to the INGESTED state"""
from ambry.orm.exc import NotFoundError
for p in self.dataset.partitions:
if p.type == p.TYPE.SEGMENT:
self.log("Removing old segment partition: {}".format... | python | {
"resource": ""
} |
q37099 | Bundle.build_table | train | def build_table(self, table, force=False):
"""Build all of the sources for a table """
sources = self._resolve_sources(None, [table])
for source in sources:
self.build_source(None, source, force=force)
self.unify_partitions() | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.