_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q37100 | Bundle.build_source | train | def build_source(self, stage, source, ps, force=False):
"""Build a single source"""
from ambry.bundle.process import call_interval
assert source.is_processable, source.name
if source.state == self.STATES.BUILT and not force:
ps.update(message='Source {} already built'.forma... | python | {
"resource": ""
} |
q37101 | Bundle.collect_segment_partitions | train | def collect_segment_partitions(self):
"""Return a dict of segments partitions, keyed on the name of the parent partition
"""
from collections import defaultdict
# Group the segments by their parent partition name, which is the
# same name, but without the segment.
partit... | python | {
"resource": ""
} |
q37102 | Bundle.unify_partitions | train | def unify_partitions(self):
"""For all of the segments for a partition, create the parent partition, combine the
children into the parent, and delete the children. """
partitions = self.collect_segment_partitions()
# For each group, copy the segment partitions to the parent partitions,... | python | {
"resource": ""
} |
q37103 | Bundle.exec_context | train | def exec_context(self, **kwargs):
"""Base environment for evals, the stuff that is the same for all evals. Primarily used in the
Caster pipe"""
import inspect
import dateutil.parser
import datetime
import random
from functools import partial
from ambry.val... | python | {
"resource": ""
} |
q37104 | Bundle.post_build_time_coverage | train | def post_build_time_coverage(self):
"""Collect all of the time coverage for the bundle."""
from ambry.util.datestimes import expand_to_years
years = set()
# From the bundle about
if self.metadata.about.time:
for year in expand_to_years(self.metadata.about.time):
... | python | {
"resource": ""
} |
q37105 | Bundle.post_build_geo_coverage | train | def post_build_geo_coverage(self):
"""Collect all of the geocoverage for the bundle."""
spaces = set()
grains = set()
def resolve(term):
places = list(self.library.search.search_identifiers(term))
if not places:
raise BuildError(
... | python | {
"resource": ""
} |
q37106 | Bundle._run_events | train | def _run_events(self, tag, stage=None):
"""Run tests marked with a particular tag and stage"""
self._run_event_methods(tag, stage)
self._run_tests(tag, stage) | python | {
"resource": ""
} |
q37107 | Bundle._run_event_methods | train | def _run_event_methods(self, tag, stage=None):
"""Run code in the bundle that is marked with events. """
import inspect
from ambry.bundle.events import _runable_for_event
funcs = []
for func_name, f in inspect.getmembers(self, predicate=inspect.ismethod):
if _runabl... | python | {
"resource": ""
} |
q37108 | include | train | def include(prop):
'''Replicate property that is normally not replicated. Right now it's
meaningful for one-to-many relations only.'''
if isinstance(prop, QueryableAttribute):
prop = prop.property
assert isinstance(prop, (Column, ColumnProperty, RelationshipProperty))
#assert isinstance(prop... | python | {
"resource": ""
} |
q37109 | reflect | train | def reflect(source, model, cache=None):
'''Finds an object of class `model` with the same identifier as the
`source` object'''
if source is None:
return None
if cache and source in cache:
return cache[source]
db = object_session(source)
ident = identity_key(instance=source)[1]
... | python | {
"resource": ""
} |
q37110 | replicate_attributes | train | def replicate_attributes(source, target, cache=None):
'''Replicates common SQLAlchemy attributes from the `source` object to the
`target` object.'''
target_manager = manager_of_class(type(target))
column_attrs = set()
relationship_attrs = set()
relationship_columns = set()
for attr in manage... | python | {
"resource": ""
} |
q37111 | replicate_filter | train | def replicate_filter(sources, model, cache=None):
'''Replicates the list of objects to other class and returns their
reflections'''
targets = [replicate_no_merge(source, model, cache=cache)
for source in sources]
# Some objects may not be available in target DB (not published), so we
... | python | {
"resource": ""
} |
q37112 | reflect_filter | train | def reflect_filter(sources, model, cache=None):
'''Returns the list of reflections of objects in the `source` list to other
class. Objects that are not found in target table are silently discarded.
'''
targets = [reflect(source, model, cache=cache) for source in sources]
# Some objects may not be av... | python | {
"resource": ""
} |
q37113 | Column.valuetype_class | train | def valuetype_class(self):
"""Return the valuetype class, if one is defined, or a built-in type if it isn't"""
from ambry.valuetype import resolve_value_type
if self.valuetype:
return resolve_value_type(self.valuetype)
else:
return resolve_value_type(self.datat... | python | {
"resource": ""
} |
q37114 | Column.python_type | train | def python_type(self):
"""Return the python type for the row, possibly getting it from a valuetype reference """
from ambry.valuetype import resolve_value_type
if self.valuetype and resolve_value_type(self.valuetype):
return resolve_value_type(self.valuetype)._pythontype
e... | python | {
"resource": ""
} |
q37115 | Column.role | train | def role(self):
'''Return the code for the role, measure, dimension or error'''
from ambry.valuetype.core import ROLE
if not self.valuetype_class:
return ''
role = self.valuetype_class.role
if role == ROLE.UNKNOWN:
vt_code = self.valuetype_class.vt_code... | python | {
"resource": ""
} |
q37116 | Column.children | train | def children(self):
""""Return the table's other column that have this column as a parent, excluding labels"""
for c in self.table.columns:
if c.parent == self.name and not c.valuetype_class.is_label():
yield c | python | {
"resource": ""
} |
q37117 | Column.label | train | def label(self):
""""Return first child of the column that is marked as a label. Returns self if the column is a label"""
if self.valuetype_class.is_label():
return self
for c in self.table.columns:
if c.parent == self.name and c.valuetype_class.is_label():
... | python | {
"resource": ""
} |
q37118 | Column.geoid | train | def geoid(self):
""""Return first child of the column, or self that is marked as a geographic identifier"""
if self.valuetype_class.is_geoid():
return self
for c in self.table.columns:
if c.parent == self.name and c.valuetype_class.is_geoid():
return c | python | {
"resource": ""
} |
q37119 | Column.python_cast | train | def python_cast(self, v):
"""Cast a value to the type of the column.
Primarily used to check that a value is valid; it will throw an
exception otherwise
"""
if self.type_is_time():
dt = dateutil.parser.parse(v)
if self.datatype == Column.DATATYPE_TIME:... | python | {
"resource": ""
} |
q37120 | Column.convert_numpy_type | train | def convert_numpy_type(cls, dtype):
"""Convert a numpy dtype into a Column datatype. Only handles common
types.
Implemented as a function to decouple from numpy
"""
m = {
'int64': cls.DATATYPE_INTEGER64,
'float64': cls.DATATYPE_FLOAT,
'objec... | python | {
"resource": ""
} |
q37121 | Column.nonull_dict | train | def nonull_dict(self):
"""Like dict, but does not hold any null values.
:return:
"""
return {k: v for k, v in six.iteritems(self.dict) if v and k != '_codes'} | python | {
"resource": ""
} |
q37122 | Column.mangle_name | train | def mangle_name(name):
"""Mangles a column name to a standard form, remoing illegal
characters.
:param name:
:return:
"""
import re
try:
return re.sub('_+', '_', re.sub('[^\w_]', '_', name).lower()).rstrip('_')
except TypeError:
r... | python | {
"resource": ""
} |
q37123 | Column.expanded_transform | train | def expanded_transform(self):
"""Expands the transform string into segments """
segments = self._expand_transform(self.transform)
if segments:
segments[0]['datatype'] = self.valuetype_class
for s in segments:
s['column'] = self
else:
... | python | {
"resource": ""
} |
q37124 | Column.before_insert | train | def before_insert(mapper, conn, target):
"""event.listen method for Sqlalchemy to set the seqience_id for this
object and create an ObjectNumber value for the id_"""
# from identity import ObjectNumber
# assert not target.fk_vid or not ObjectNumber.parse(target.fk_vid).revision
... | python | {
"resource": ""
} |
q37125 | Column.before_update | train | def before_update(mapper, conn, target):
"""Set the column id number based on the table number and the sequence
id for the column."""
assert target.datatype or target.valuetype
target.name = Column.mangle_name(target.name)
Column.update_number(target) | python | {
"resource": ""
} |
q37126 | spawnProcess | train | def spawnProcess(processProtocol, executable, args=(), env={},
path=None, uid=None, gid=None, usePTY=0,
packages=()):
"""Launch a process with a particular Python environment.
All arguments as to reactor.spawnProcess(), except for the
addition of an optional packages itera... | python | {
"resource": ""
} |
q37127 | spawnPythonProcess | train | def spawnPythonProcess(processProtocol, args=(), env={},
path=None, uid=None, gid=None, usePTY=0,
packages=()):
"""Launch a Python process
All arguments as to spawnProcess(), except the executable
argument is omitted.
"""
return spawnProcess(processProt... | python | {
"resource": ""
} |
q37128 | _runable_for_event | train | def _runable_for_event(f, tag, stage):
"""Loot at the event property for a function to see if it should be run at this stage. """
if not hasattr(f, '__ambry_event__'):
return False
f_tag, f_stage = f.__ambry_event__
if stage is None:
stage = 0
if tag != f_tag or stage != f_stage:... | python | {
"resource": ""
} |
q37129 | load_obj_from_path | train | def load_obj_from_path(import_path, prefix=None, ld=dict()):
"""
import a python object from an import path
`import_path` - a python import path. For instance:
mypackage.module.func
or
mypackage.module.class
`prefix` (str) - a value to prepend to the import path
... | python | {
"resource": ""
} |
q37130 | ArtifactRest.artifact_quality | train | def artifact_quality(self, artifact_quality):
"""
Sets the artifact_quality of this ArtifactRest.
:param artifact_quality: The artifact_quality of this ArtifactRest.
:type: str
"""
allowed_values = ["NEW", "VERIFIED", "TESTED", "DEPRECATED", "BLACKLISTED", "DELETED", "TE... | python | {
"resource": ""
} |
q37131 | _get_sqlite_columns | train | def _get_sqlite_columns(connection, table):
""" Returns list of tuple containg columns of the table.
Args:
connection: sqlalchemy connection to sqlite database.
table (str): name of the table
Returns:
list of (name, datatype, position): where name is column name, datatype is
... | python | {
"resource": ""
} |
q37132 | DataSourceBase.partition | train | def partition(self):
"""For partition urltypes, return the partition specified by the ref """
if self.urltype != 'partition':
return None
return self._bundle.library.partition(self.url) | python | {
"resource": ""
} |
q37133 | DataSourceBase.spec | train | def spec(self):
"""Return a SourceSpec to describe this source"""
from ambry_sources.sources import SourceSpec
d = self.dict
d['url'] = self.url
# Will get the URL twice; once as ref and once as URL, but the ref is ignored
return SourceSpec(**d) | python | {
"resource": ""
} |
q37134 | DataSourceBase.account | train | def account(self):
"""Return an account record, based on the host in the url"""
from ambry.util import parse_url_to_dict
d = parse_url_to_dict(self.url)
return self._bundle.library.account(d['netloc']) | python | {
"resource": ""
} |
q37135 | DataSourceBase.update_table | train | def update_table(self, unknown_type='str'):
"""Update the source table from the datafile"""
from ambry_sources.intuit import TypeIntuiter
st = self.source_table
if self.reftype == 'partition':
for c in self.partition.table.columns:
st.add_column(c.sequence_i... | python | {
"resource": ""
} |
q37136 | DataSourceBase.update_spec | train | def update_spec(self):
"""Update the source specification with information from the row intuiter, but only if the spec values
are not already set. """
if self.datafile.exists:
with self.datafile.reader as r:
self.header_lines = r.info['header_rows']
... | python | {
"resource": ""
} |
q37137 | get_runconfig | train | def get_runconfig(path=None, root=None, db=None):
"""Load the main configuration files and accounts file.
Debprecated. Use load()
"""
return load(path, root=root, db=db) | python | {
"resource": ""
} |
q37138 | load | train | def load(path=None, root=None, db=None, load_user=True):
"Load all of the config files. "
config = load_config(path, load_user=load_user)
remotes = load_remotes(path, load_user=load_user)
# The external file overwrites the main config
if remotes:
if not 'remotes' in config:
co... | python | {
"resource": ""
} |
q37139 | load_accounts | train | def load_accounts(extra_path=None, load_user=True):
"""Load the yaml account files
:param load_user:
:return: An `AttrDict`
"""
from os.path import getmtime
try:
accts_file = find_config_file(ACCOUNTS_FILE, extra_path=extra_path, load_user=load_user)
except ConfigurationError:
... | python | {
"resource": ""
} |
q37140 | load_remotes | train | def load_remotes(extra_path=None, load_user=True):
"""Load the YAML remotes file, which sort of combines the Accounts file with part of the
remotes sections from the main config
:return: An `AttrDict`
"""
from os.path import getmtime
try:
remotes_file = find_config_file(REMOTES_FILE, ... | python | {
"resource": ""
} |
q37141 | normalize_dsn_or_dict | train | def normalize_dsn_or_dict(d):
"""Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version"""
if isinstance(d, dict):
try:
# Convert from an AttrDict to a real dict
d = d.to_dict()
except AttributeError:
pass # Alread... | python | {
"resource": ""
} |
q37142 | execute_command | train | def execute_command(cmd, execute, echo=True):
"""Execute a command in shell or just print it if execute is False"""
if execute:
if echo:
print("Executing: " + cmd)
return os.system(cmd)
else:
print(cmd)
return 0 | python | {
"resource": ""
} |
q37143 | set_log_level | train | def set_log_level(level):
"""Sets the desired log level."""
lLevel = level.lower()
unrecognized = False
if (lLevel == 'debug-all'):
loglevel = logging.DEBUG
elif (lLevel == 'debug'):
loglevel = logging.DEBUG
elif (lLevel == 'info'):
loglevel = logging.INFO
elif (lLeve... | python | {
"resource": ""
} |
q37144 | required | train | def required(field):
"""Decorator that checks if return value is set, if not, raises exception.
"""
def wrap(f):
def wrappedf(*args):
result = f(*args)
if result is None or result == "":
raise Exception(
"Config option '%s' is required." %... | python | {
"resource": ""
} |
q37145 | JinjaView.render | train | def render(self, template_name, variables=None):
"""
Render a template with the passed variables.
"""
if variables is None:
variables = {}
template = self._engine.get_template(template_name)
return template.render(**variables) | python | {
"resource": ""
} |
q37146 | JinjaView.render_source | train | def render_source(self, source, variables=None):
"""
Render a source with the passed variables.
"""
if variables is None:
variables = {}
template = self._engine.from_string(source)
return template.render(**variables) | python | {
"resource": ""
} |
q37147 | construct_re | train | def construct_re(url_template, match_whole_str=False, converters=None,
default_converter='string', anonymous=False):
'''
url_template - str or unicode representing template
Constructed pattern expects urlencoded string!
returns (compiled re pattern,
dict {url param nam... | python | {
"resource": ""
} |
q37148 | export | train | def export(bundle, force=False, force_restricted=False):
""" Exports bundle to ckan instance.
Args:
bundle (ambry.bundle.Bundle):
force (bool, optional): if True, ignore existance error and continue to export.
force_restricted (bool, optional): if True, then export restricted bundles as... | python | {
"resource": ""
} |
q37149 | is_exported | train | def is_exported(bundle):
""" Returns True if dataset is already exported to CKAN. Otherwise returns False. """
if not ckan:
raise EnvironmentError(MISSING_CREDENTIALS_MSG)
params = {'q': 'name:{}'.format(bundle.dataset.vid.lower())}
resp = ckan.action.package_search(**params)
return len(resp... | python | {
"resource": ""
} |
q37150 | _convert_bundle | train | def _convert_bundle(bundle):
""" Converts ambry bundle to dict ready to send to CKAN API.
Args:
bundle (ambry.bundle.Bundle): bundle to convert.
Returns:
dict: dict to send to CKAN to create dataset.
See http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.package_creat... | python | {
"resource": ""
} |
q37151 | _convert_partition | train | def _convert_partition(partition):
""" Converts partition to resource dict ready to save to CKAN. """
# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create
# convert bundle to csv.
csvfile = six.StringIO()
writer = unicodecsv.writer(csvfile)
headers = partition.datafile... | python | {
"resource": ""
} |
q37152 | _convert_schema | train | def _convert_schema(bundle):
""" Converts schema of the dataset to resource dict ready to save to CKAN. """
# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create
schema_csv = None
for f in bundle.dataset.files:
if f.path.endswith('schema.csv'):
contents = f.u... | python | {
"resource": ""
} |
q37153 | _convert_external | train | def _convert_external(bundle, name, external):
""" Converts external documentation to resource dict ready to save to CKAN. """
# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create
ret = {
'package_id': bundle.dataset.vid.lower(),
'url': external.url,
'descri... | python | {
"resource": ""
} |
q37154 | wait_for_repo_creation | train | def wait_for_repo_creation(task_id, retry=30):
"""
Using polling check if the task finished
"""
success_event_types = ("RC_CREATION_SUCCESS", )
error_event_types = ("RC_REPO_CREATION_ERROR", "RC_REPO_CLONE_ERROR", "RC_CREATION_ERROR")
while retry > 0:
bpm_task = get_bpm_task_by_id(task_... | python | {
"resource": ""
} |
q37155 | M_.count | train | def count(self):
'''
A count based on `count_field` and `format_args`.
'''
args = self.format_args
if args is None or \
(isinstance(args, dict) and self.count_field not in args):
raise TypeError("count is required")
return args[self.count_field... | python | {
"resource": ""
} |
q37156 | generate_sources_zip | train | def generate_sources_zip(milestone_id=None, output=None):
"""
Generate a sources archive for given milestone id.
"""
if not is_input_valid(milestone_id, output):
logging.error("invalid input")
return 1
create_work_dir(output)
download_sources_artifacts(milestone_id, output)
... | python | {
"resource": ""
} |
q37157 | get_repository_configuration | train | def get_repository_configuration(id):
"""
Retrieve a specific RepositoryConfiguration
"""
response = utils.checked_api_call(pnc_api.repositories, 'get_specific', id=id)
if response:
return response.content | python | {
"resource": ""
} |
q37158 | update_repository_configuration | train | def update_repository_configuration(id, external_repository=None, prebuild_sync=None):
"""
Update an existing RepositoryConfiguration with new information
"""
to_update_id = id
rc_to_update = pnc_api.repositories.get_specific(id=to_update_id).content
if external_repository is None:
ext... | python | {
"resource": ""
} |
q37159 | list_repository_configurations | train | def list_repository_configurations(page_size=200, page_index=0, sort="", q=""):
"""
List all RepositoryConfigurations
"""
response = utils.checked_api_call(pnc_api.repositories, 'get_all', page_size=page_size, page_index=page_index, sort=sort, q=q)
if response:
return utils.format_json_list(... | python | {
"resource": ""
} |
q37160 | match_repository_configuration | train | def match_repository_configuration(url, page_size=10, page_index=0, sort=""):
"""
Search for Repository Configurations based on internal or external url with exact match
"""
content = match_repository_configuration_raw(url, page_size, page_index, sort)
if content:
return utils.format_json_li... | python | {
"resource": ""
} |
q37161 | Form.render | train | def render(self):
'''Proxy method to form's environment render method'''
return self.env.template.render(self.template, form=self) | python | {
"resource": ""
} |
q37162 | Form.accept | train | def accept(self, data):
'''
Try to accpet MultiDict-like object and return if it is valid.
'''
self.raw_data = MultiDict(data)
self.errors = {}
for field in self.fields:
if field.writable:
self.python_data.update(field.accept())
els... | python | {
"resource": ""
} |
q37163 | pluginPackagePaths | train | def pluginPackagePaths(name):
"""
Return a list of additional directories which should be searched for
modules to be included as part of the named plugin package.
@type name: C{str}
@param name: The fully-qualified Python name of a plugin package, eg
C{'twisted.plugins'}.
@rtype: C{lis... | python | {
"resource": ""
} |
q37164 | storage_method | train | def storage_method(func):
'''Calls decorated method with VersionedStorage as self'''
def wrap(self, *args, **kwargs):
return func(self._root_storage, *args, **kwargs)
return wrap | python | {
"resource": ""
} |
q37165 | TemplateEngine.render | train | def render(self, template_name, **kw):
'Interface method called from `Template.render`'
return self.env.get_template(template_name).render(**kw) | python | {
"resource": ""
} |
q37166 | Library.ctor_args | train | def ctor_args(self):
"""Return arguments for constructing a copy"""
return dict(
config=self._config,
search=self._search,
echo=self._echo,
read_only=self.read_only
) | python | {
"resource": ""
} |
q37167 | Library.sync_config | train | def sync_config(self, force=False):
"""Sync the file config into the library proxy data in the root dataset """
from ambry.library.config import LibraryConfigSyncProxy
lcsp = LibraryConfigSyncProxy(self)
lcsp.sync(force=force) | python | {
"resource": ""
} |
q37168 | Library.init_debug | train | def init_debug(self):
"""Initialize debugging features, such as a handler for USR2 to print a trace"""
import signal
def debug_trace(sig, frame):
"""Interrupt running process, and provide a python prompt for interactive
debugging."""
self.log('Trace signal r... | python | {
"resource": ""
} |
q37169 | Library.resolve_object_number | train | def resolve_object_number(self, ref):
"""Resolve a variety of object numebrs to a dataset number"""
if not isinstance(ref, ObjectNumber):
on = ObjectNumber.parse(ref)
else:
on = ref
ds_on = on.as_dataset
return ds_on | python | {
"resource": ""
} |
q37170 | Library.new_bundle | train | def new_bundle(self, assignment_class=None, **kwargs):
"""
Create a new bundle, with the same arguments as creating a new dataset
:param assignment_class: String. assignment class to use for fetching a number, if one
is not specified in kwargs
:param kwargs:
:return:
... | python | {
"resource": ""
} |
q37171 | Library.new_from_bundle_config | train | def new_from_bundle_config(self, config):
"""
Create a new bundle, or link to an existing one, based on the identity in config data.
:param config: A Dict form of a bundle.yaml file
:return:
"""
identity = Identity.from_dict(config['identity'])
ds = self._db.dat... | python | {
"resource": ""
} |
q37172 | Library.bundle | train | def bundle(self, ref, capture_exceptions=False):
"""Return a bundle build on a dataset, with the given vid or id reference"""
from ..orm.exc import NotFoundError
if isinstance(ref, Dataset):
ds = ref
else:
try:
ds = self._db.dataset(ref)
... | python | {
"resource": ""
} |
q37173 | Library.partition | train | def partition(self, ref, localize=False):
""" Finds partition by ref and converts to bundle partition.
:param ref: A partition reference
:param localize: If True, copy a remote partition to local filesystem. Defaults to False
:raises: NotFoundError: if partition with given ref not found... | python | {
"resource": ""
} |
q37174 | Library.table | train | def table(self, ref):
""" Finds table by ref and returns it.
Args:
ref (str): id, vid (versioned id) or name of the table
Raises:
NotFoundError: if table with given ref not found.
Returns:
orm.Table
"""
try:
obj_number ... | python | {
"resource": ""
} |
q37175 | Library.remove | train | def remove(self, bundle):
""" Removes a bundle from the library and deletes the configuration for
it from the library database."""
from six import string_types
if isinstance(bundle, string_types):
bundle = self.bundle(bundle)
self.database.remove_dataset(bundle.data... | python | {
"resource": ""
} |
q37176 | Library.duplicate | train | def duplicate(self, b):
"""Duplicate a bundle, with a higher version number.
This only copies the files, under the theory that the bundle can be rebuilt from them.
"""
on = b.identity.on
on.revision = on.revision + 1
try:
extant = self.bundle(str(on))
... | python | {
"resource": ""
} |
q37177 | Library.checkin_bundle | train | def checkin_bundle(self, db_path, replace=True, cb=None):
"""Add a bundle, as a Sqlite file, to this library"""
from ambry.orm.exc import NotFoundError
db = Database('sqlite:///{}'.format(db_path))
db.open()
if len(db.datasets) == 0:
raise NotFoundError("Did not get... | python | {
"resource": ""
} |
q37178 | Library.checkin_remote_bundle | train | def checkin_remote_bundle(self, ref, remote=None):
""" Checkin a remote bundle to this library.
:param ref: Any bundle reference
:param remote: If specified, use this remote. If not, search for the reference
in cached directory listings
:param cb: A one argument progress cal... | python | {
"resource": ""
} |
q37179 | Library.remotes | train | def remotes(self):
"""Return the names and URLs of the remotes"""
from ambry.orm import Remote
for r in self.database.session.query(Remote).all():
if not r.short_name:
continue
yield self.remote(r.short_name) | python | {
"resource": ""
} |
q37180 | Library._remote | train | def _remote(self, name):
"""Return a remote for which 'name' matches the short_name or url """
from ambry.orm import Remote
from sqlalchemy import or_
from ambry.orm.exc import NotFoundError
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
if not name.s... | python | {
"resource": ""
} |
q37181 | Library.number | train | def number(self, assignment_class=None, namespace='d'):
"""
Return a new number.
:param assignment_class: Determines the length of the number. Possible values are 'authority' (3 characters) ,
'registered' (5) , 'unregistered' (7) and 'self' (9). Self assigned numbers are random and... | python | {
"resource": ""
} |
q37182 | Library.edit_history | train | def edit_history(self):
"""Return config record information about the most recent bundle accesses and operations"""
ret = self._db.session\
.query(Config)\
.filter(Config.type == 'buildstate')\
.filter(Config.group == 'access')\
.filter(Config.key == 'las... | python | {
"resource": ""
} |
q37183 | Library.import_bundles | train | def import_bundles(self, dir, detach=False, force=False):
"""
Import bundles from a directory
:param dir:
:return:
"""
import yaml
fs = fsopendir(dir)
bundles = []
for f in fs.walkfiles(wildcard='bundle.yaml'):
self.logger.info('V... | python | {
"resource": ""
} |
q37184 | Library.process_pool | train | def process_pool(self, limited_run=False):
"""Return a pool for multiprocess operations, sized either to the number of CPUS, or a configured value"""
from multiprocessing import cpu_count
from ambry.bundle.concurrent import Pool, init_library
if self.processes:
cpus = self.... | python | {
"resource": ""
} |
q37185 | file_loc | train | def file_loc():
"""Return file and line number"""
import sys
import inspect
try:
raise Exception
except:
file_ = '.../' + '/'.join((inspect.currentframe().f_code.co_filename.split('/'))[-3:])
line_ = sys.exc_info()[2].tb_frame.f_back.f_lineno
return "{}:{}".format(fil... | python | {
"resource": ""
} |
q37186 | calling_code | train | def calling_code(f, f_name=None, raise_for_missing=True):
"""Return the code string for calling a function. """
import inspect
from ambry.dbexceptions import ConfigurationError
if inspect.isclass(f):
try:
args = inspect.getargspec(f.__init__).args
except TypeError as e:
... | python | {
"resource": ""
} |
q37187 | PriorityQueue.push | train | def push(self, el):
""" Put a new element in the queue. """
count = next(self.counter)
heapq.heappush(self._queue, (el, count)) | python | {
"resource": ""
} |
q37188 | PartitionDisplay.geo_description | train | def geo_description(self):
"""Return a description of the geographic extents, using the largest scale
space and grain coverages"""
sc = self._p.space_coverage
gc = self._p.grain_coverage
if sc and gc:
if parse_to_gvid(gc[0]).level == 'state' and parse_to_gvid(sc[0])... | python | {
"resource": ""
} |
q37189 | PartitionDisplay.time_description | train | def time_description(self):
"""String description of the year or year range"""
tc = [t for t in self._p.time_coverage if t]
if not tc:
return ''
mn = min(tc)
mx = max(tc)
if not mn and not mx:
return ''
elif mn == mx:
return... | python | {
"resource": ""
} |
q37190 | PartitionDisplay.sub_description | train | def sub_description(self):
"""Time and space dscription"""
gd = self.geo_description
td = self.time_description
if gd and td:
return '{}, {}. {} Rows.'.format(gd, td, self._p.count)
elif gd:
return '{}. {} Rows.'.format(gd, self._p.count)
elif td:... | python | {
"resource": ""
} |
q37191 | Partition.identity | train | def identity(self):
"""Return this partition information as a PartitionId."""
if self.dataset is None:
# The relationship will be null until the object is committed
s = object_session(self)
ds = s.query(Dataset).filter(Dataset.id_ == self.d_id).one()
else:
... | python | {
"resource": ""
} |
q37192 | Partition.detail_dict | train | def detail_dict(self):
"""A more detailed dict that includes the descriptions, sub descriptions, table
and columns."""
d = self.dict
def aug_col(c):
d = c.dict
d['stats'] = [s.dict for s in c.stats]
return d
d['table'] = self.table.dict
... | python | {
"resource": ""
} |
q37193 | Partition.local_datafile | train | def local_datafile(self):
"""Return the datafile for this partition, from the build directory, the remote, or the warehouse"""
from ambry_sources import MPRowsFile
from fs.errors import ResourceNotFoundError
from ambry.orm.exc import NotFoundError
try:
return MPRowsF... | python | {
"resource": ""
} |
q37194 | Partition.remote | train | def remote(self):
"""
Return the remote for this partition
:return:
"""
from ambry.exc import NotFoundError
ds = self.dataset
if 'remote_name' not in ds.data:
raise NotFoundError('Could not determine remote for partition: {}'.format(self.identity.f... | python | {
"resource": ""
} |
q37195 | Partition.is_local | train | def is_local(self):
"""Return true is the partition file is local"""
from ambry.orm.exc import NotFoundError
try:
if self.local_datafile.exists:
return True
except NotFoundError:
pass
return False | python | {
"resource": ""
} |
q37196 | Partition.localize | train | def localize(self, ps=None):
"""Copy a non-local partition file to the local build directory"""
from filelock import FileLock
from ambry.util import ensure_dir_exists
from ambry_sources import MPRowsFile
from fs.errors import ResourceNotFoundError
if self.is_local:
... | python | {
"resource": ""
} |
q37197 | Partition.reader | train | def reader(self):
from ambry.orm.exc import NotFoundError
from fs.errors import ResourceNotFoundError
"""The reader for the datafile"""
try:
return self.datafile.reader
except ResourceNotFoundError:
raise NotFoundError("Failed to find partition file, '{}'... | python | {
"resource": ""
} |
q37198 | Partition.analysis | train | def analysis(self):
"""Return an AnalysisPartition proxy, which wraps this partition to provide acess to
dataframes, shapely shapes and other analysis services"""
if isinstance(self, PartitionProxy):
return AnalysisPartition(self._obj)
else:
return AnalysisPartiti... | python | {
"resource": ""
} |
q37199 | Partition.measuredim | train | def measuredim(self):
"""Return a MeasureDimension proxy, which wraps the partition to provide access to
columns in terms of measures and dimensions"""
if isinstance(self, PartitionProxy):
return MeasureDimensionPartition(self._obj)
else:
return MeasureDimensionP... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.