repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.sync_objects_in | def sync_objects_in(self):
"""Synchronize from records to objects"""
self.dstate = self.STATES.BUILDING
self.build_source_files.record_to_objects() | python | def sync_objects_in(self):
"""Synchronize from records to objects"""
self.dstate = self.STATES.BUILDING
self.build_source_files.record_to_objects() | [
"def",
"sync_objects_in",
"(",
"self",
")",
":",
"self",
".",
"dstate",
"=",
"self",
".",
"STATES",
".",
"BUILDING",
"self",
".",
"build_source_files",
".",
"record_to_objects",
"(",
")"
] | Synchronize from records to objects | [
"Synchronize",
"from",
"records",
"to",
"objects"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1487-L1490 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.sync_objects_out | 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():
self.log('Sync: {}'.format(f.record.path))
f.objects_to_record()
self.commit() | python | 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():
self.log('Sync: {}'.format(f.record.path))
f.objects_to_record()
self.commit() | [
"def",
"sync_objects_out",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"log",
"(",
"'---- Sync Objects Out ----'",
")",
"from",
"ambry",
".",
"bundle",
".",
"files",
"import",
"BuildSourceFile",
"self",
".",
"dstate",
"=",
"self",
".",
... | Synchronize from objects to records, and records to files | [
"Synchronize",
"from",
"objects",
"to",
"records",
"and",
"records",
"to",
"files"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1492-L1504 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.sync_code | def sync_code(self):
"""Sync in code files and the meta file, avoiding syncing the larger files"""
from ambry.orm.file import File
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.BUILD, File.BSFILE.META, File.BSFILE.LIB, File.BSFILE.TEST, File.BSFILE.DOC]:
bsf = self.build_source_files.file(fc)
if bsf.fs_is_newer:
self.log('Syncing {}'.format(bsf.file_name))
bsf.sync(BuildSourceFile.SYNC_DIR.FILE_TO_RECORD)
synced += 1
# Only the metadata needs to be driven to the objects, since the other files are used as code,
# directly from the file record.
self.build_source_files.file(File.BSFILE.META).record_to_objects()
return synced | python | def sync_code(self):
"""Sync in code files and the meta file, avoiding syncing the larger files"""
from ambry.orm.file import File
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.BUILD, File.BSFILE.META, File.BSFILE.LIB, File.BSFILE.TEST, File.BSFILE.DOC]:
bsf = self.build_source_files.file(fc)
if bsf.fs_is_newer:
self.log('Syncing {}'.format(bsf.file_name))
bsf.sync(BuildSourceFile.SYNC_DIR.FILE_TO_RECORD)
synced += 1
# Only the metadata needs to be driven to the objects, since the other files are used as code,
# directly from the file record.
self.build_source_files.file(File.BSFILE.META).record_to_objects()
return synced | [
"def",
"sync_code",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"file",
"import",
"File",
"from",
"ambry",
".",
"bundle",
".",
"files",
"import",
"BuildSourceFile",
"self",
".",
"dstate",
"=",
"self",
".",
"STATES",
".",
"BUILDING",
"synced"... | Sync in code files and the meta file, avoiding syncing the larger files | [
"Sync",
"in",
"code",
"files",
"and",
"the",
"meta",
"file",
"avoiding",
"syncing",
"the",
"larger",
"files"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1511-L1531 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.sync_sources | 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 force:
self.log('Syncing {}'.format(bsf.file_name))
bsf.fs_to_objects()
synced += 1
return synced | python | 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 force:
self.log('Syncing {}'.format(bsf.file_name))
bsf.fs_to_objects()
synced += 1
return synced | [
"def",
"sync_sources",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"file",
"import",
"File",
"self",
".",
"dstate",
"=",
"self",
".",
"STATES",
".",
"BUILDING",
"synced",
"=",
"0",
"for",
"fc",
"in",
"[",
"F... | Sync in only the sources.csv file | [
"Sync",
"in",
"only",
"the",
"sources",
".",
"csv",
"file"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1533-L1548 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.sync_schema | def sync_schema(self):
"""Sync in code files and the meta file, avoiding syncing the larger files"""
from ambry.orm.file import File
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.SCHEMA, File.BSFILE.SOURCESCHEMA]:
bsf = self.build_source_files.file(fc)
if bsf.fs_is_newer:
self.log('Syncing {}'.format(bsf.file_name))
bsf.sync(BuildSourceFile.SYNC_DIR.FILE_TO_RECORD)
synced += 1
return synced | python | def sync_schema(self):
"""Sync in code files and the meta file, avoiding syncing the larger files"""
from ambry.orm.file import File
from ambry.bundle.files import BuildSourceFile
self.dstate = self.STATES.BUILDING
synced = 0
for fc in [File.BSFILE.SCHEMA, File.BSFILE.SOURCESCHEMA]:
bsf = self.build_source_files.file(fc)
if bsf.fs_is_newer:
self.log('Syncing {}'.format(bsf.file_name))
bsf.sync(BuildSourceFile.SYNC_DIR.FILE_TO_RECORD)
synced += 1
return synced | [
"def",
"sync_schema",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"file",
"import",
"File",
"from",
"ambry",
".",
"bundle",
".",
"files",
"import",
"BuildSourceFile",
"self",
".",
"dstate",
"=",
"self",
".",
"STATES",
".",
"BUILDING",
"synce... | Sync in code files and the meta file, avoiding syncing the larger files | [
"Sync",
"in",
"code",
"files",
"and",
"the",
"meta",
"file",
"avoiding",
"syncing",
"the",
"larger",
"files"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1550-L1565 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.update_schema | def update_schema(self):
"""Propagate schema object changes to file records"""
self.commit()
self.build_source_files.schema.objects_to_record()
self.commit() | python | def update_schema(self):
"""Propagate schema object changes to file records"""
self.commit()
self.build_source_files.schema.objects_to_record()
self.commit() | [
"def",
"update_schema",
"(",
"self",
")",
":",
"self",
".",
"commit",
"(",
")",
"self",
".",
"build_source_files",
".",
"schema",
".",
"objects_to_record",
"(",
")",
"self",
".",
"commit",
"(",
")"
] | Propagate schema object changes to file records | [
"Propagate",
"schema",
"object",
"changes",
"to",
"file",
"records"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1567-L1572 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.clean | 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 ----')
self.state = self.STATES.CLEANING
self.dstate = self.STATES.BUILDING
self.commit()
self.clean_sources()
self.clean_tables()
self.clean_partitions()
self.clean_build()
self.clean_files()
self.clean_ingested()
self.clean_build_state()
self.clean_progress()
self.state = self.STATES.CLEANED
self.commit()
return True | python | 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 ----')
self.state = self.STATES.CLEANING
self.dstate = self.STATES.BUILDING
self.commit()
self.clean_sources()
self.clean_tables()
self.clean_partitions()
self.clean_build()
self.clean_files()
self.clean_ingested()
self.clean_build_state()
self.clean_progress()
self.state = self.STATES.CLEANED
self.commit()
return True | [
"def",
"clean",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"self",
".",
"is_finalized",
"and",
"not",
"force",
":",
"self",
".",
"warn",
"(",
"\"Can't clean; bundle is finalized\"",
")",
"return",
"False",
"self",
".",
"log",
"(",
"'---- Clea... | Clean generated objects from the dataset, but only if there are File contents
to regenerate them | [
"Clean",
"generated",
"objects",
"from",
"the",
"dataset",
"but",
"only",
"if",
"there",
"are",
"File",
"contents",
"to",
"regenerate",
"them"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1582-L1609 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.clean_except_files | 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()
self.clean_sources()
self.clean_tables()
self.clean_partitions()
self.clean_build()
self.clean_ingested()
self.clean_build_state()
self.state = self.STATES.CLEANED
self.commit()
self.log('---- Done Cleaning ----')
return True | python | 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()
self.clean_sources()
self.clean_tables()
self.clean_partitions()
self.clean_build()
self.clean_ingested()
self.clean_build_state()
self.state = self.STATES.CLEANED
self.commit()
self.log('---- Done Cleaning ----')
return True | [
"def",
"clean_except_files",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_finalized",
":",
"self",
".",
"warn",
"(",
"\"Can't clean; bundle is finalized\"",
")",
"return",
"False",
"self",
".",
"log",
"(",
"'---- Cleaning ----'",
")",
"self",
".",
"state",
"=... | Clean everything except the build source files | [
"Clean",
"everything",
"except",
"the",
"build",
"source",
"files"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1611-L1636 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.clean_sources | 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 | 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 | [
"def",
"clean_sources",
"(",
"self",
")",
":",
"for",
"src",
"in",
"self",
".",
"dataset",
".",
"sources",
":",
"src",
".",
"st_id",
"=",
"None",
"src",
".",
"t_id",
"=",
"None",
"self",
".",
"dataset",
".",
"sources",
"[",
":",
"]",
"=",
"[",
"]... | Like clean, but also clears out files. | [
"Like",
"clean",
"but",
"also",
"clears",
"out",
"files",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1638-L1647 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.clean_partitions | 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 are seen to be owed by the columns instead.
self.session.query(ColumnStat).filter(ColumnStat.d_vid == self.dataset.vid).delete()
self.dataset.delete_partitions()
for s in self.sources:
s.state = None
if self.build_partition_fs.exists:
try:
shutil.rmtree(self.build_partition_fs.getsyspath('/'))
except NoSysPathError:
pass | python | 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 are seen to be owed by the columns instead.
self.session.query(ColumnStat).filter(ColumnStat.d_vid == self.dataset.vid).delete()
self.dataset.delete_partitions()
for s in self.sources:
s.state = None
if self.build_partition_fs.exists:
try:
shutil.rmtree(self.build_partition_fs.getsyspath('/'))
except NoSysPathError:
pass | [
"def",
"clean_partitions",
"(",
"self",
")",
":",
"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 are seen to be owed ... | Delete partition records and any built partition files. | [
"Delete",
"partition",
"records",
"and",
"any",
"built",
"partition",
"files",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1657-L1675 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.clean_build | 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 | 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 | [
"def",
"clean_build",
"(",
"self",
")",
":",
"import",
"shutil",
"if",
"self",
".",
"build_fs",
".",
"exists",
":",
"try",
":",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"build_fs",
".",
"getsyspath",
"(",
"'/'",
")",
")",
"except",
"NoSysPathError",
... | Delete the build directory and all ingested files | [
"Delete",
"the",
"build",
"directory",
"and",
"all",
"ingested",
"files"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1677-L1685 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.clean_ingested | 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 | 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() | [
"def",
"clean_ingested",
"(",
"self",
")",
":",
"for",
"s",
"in",
"self",
".",
"sources",
":",
"df",
"=",
"s",
".",
"datafile",
"if",
"df",
".",
"exists",
"and",
"not",
"s",
".",
"is_partition",
":",
"df",
".",
"remove",
"(",
")",
"s",
".",
"stat... | Clean ingested files | [
"Clean",
"ingested",
"files"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1693-L1701 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.clean_process_meta | 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 | 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 | [
"def",
"clean_process_meta",
"(",
"self",
")",
":",
"ds",
"=",
"self",
".",
"dataset",
"ds",
".",
"config",
".",
"build",
".",
"clean",
"(",
")",
"ds",
".",
"config",
".",
"process",
".",
"clean",
"(",
")",
"ds",
".",
"commit",
"(",
")",
"self",
... | Remove all process and build metadata | [
"Remove",
"all",
"process",
"and",
"build",
"metadata"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1708-L1714 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.clean_source_files | 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 | 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() | [
"def",
"clean_source_files",
"(",
"self",
")",
":",
"self",
".",
"build_source_files",
".",
"file",
"(",
"File",
".",
"BSFILE",
".",
"SOURCESCHEMA",
")",
".",
"remove",
"(",
")",
"self",
".",
"build_source_files",
".",
"file",
"(",
"File",
".",
"BSFILE",
... | Remove the schema.csv and source_schema.csv files | [
"Remove",
"the",
"schema",
".",
"csv",
"and",
"source_schema",
".",
"csv",
"files"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1716-L1721 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.ingest | 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_stage, all of the sources have the same stage, so they
get grouped together. The result it that the stage in the inner loop is the same as the stage being
run buy run_stage.
"""
from itertools import groupby
from ambry.bundle.events import TAG
from fs.errors import ResourceNotFoundError
import zlib
self.log('---- Ingesting ----')
self.dstate = self.STATES.BUILDING
self.commit() # WTF? Without this, postgres blocks between table query, and update seq id in source tables.
key = lambda s: s.stage if s.stage else 1
def not_final_or_delete(s):
import zlib
if force:
return True
try:
return s.is_processable and not s.is_ingested and not s.is_built
except (IOError, zlib.error):
s.local_datafile.remove()
return True
sources = sorted(self._resolve_sources(sources, tables, stage, predicate=not_final_or_delete),
key=key)
if not sources:
self.log('No sources left to ingest')
return
self.state = self.STATES.INGESTING
count = 0
errors = 0
self._run_events(TAG.BEFORE_INGEST, 0)
# Clear out all ingested files that are malformed
for s in self.sources:
if s.is_downloadable:
df = s.datafile
try:
info = df.info
df.close()
except (ResourceNotFoundError, zlib.error, IOError):
df.remove()
for stage, g in groupby(sources, key):
sources = [s for s in g if not_final_or_delete(s)]
if not len(sources):
continue
self._run_events(TAG.BEFORE_INGEST, stage)
stage_errors = self._ingest_sources(sources, stage, force=force)
errors += stage_errors
count += len(sources) - stage_errors
self._run_events(TAG.AFTER_INGEST, stage)
self.record_stage_state(self.STATES.INGESTING, stage)
self.state = self.STATES.INGESTED
try:
pass
finally:
self._run_events(TAG.AFTER_INGEST, 0)
self.log('Ingested {} sources'.format(count))
if load_meta:
if len(sources) == 1:
iterable_source, source_pipe = self.source_pipe(sources[0])
try:
meta = iterable_source.meta
if meta:
self.metadata.about.title = meta['title']
self.metadata.about.summary = meta['summary']
self.build_source_files.bundle_meta.objects_to_record()
except AttributeError as e:
self.warn("Failed to set metadata: {}".format(e))
pass
else:
self.warn("Didn't not load meta from source. Must have exactly one soruce, got {}".format(len(sources)))
self.commit()
if errors == 0:
return True
else:
return False | python | 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_stage, all of the sources have the same stage, so they
get grouped together. The result it that the stage in the inner loop is the same as the stage being
run buy run_stage.
"""
from itertools import groupby
from ambry.bundle.events import TAG
from fs.errors import ResourceNotFoundError
import zlib
self.log('---- Ingesting ----')
self.dstate = self.STATES.BUILDING
self.commit() # WTF? Without this, postgres blocks between table query, and update seq id in source tables.
key = lambda s: s.stage if s.stage else 1
def not_final_or_delete(s):
import zlib
if force:
return True
try:
return s.is_processable and not s.is_ingested and not s.is_built
except (IOError, zlib.error):
s.local_datafile.remove()
return True
sources = sorted(self._resolve_sources(sources, tables, stage, predicate=not_final_or_delete),
key=key)
if not sources:
self.log('No sources left to ingest')
return
self.state = self.STATES.INGESTING
count = 0
errors = 0
self._run_events(TAG.BEFORE_INGEST, 0)
# Clear out all ingested files that are malformed
for s in self.sources:
if s.is_downloadable:
df = s.datafile
try:
info = df.info
df.close()
except (ResourceNotFoundError, zlib.error, IOError):
df.remove()
for stage, g in groupby(sources, key):
sources = [s for s in g if not_final_or_delete(s)]
if not len(sources):
continue
self._run_events(TAG.BEFORE_INGEST, stage)
stage_errors = self._ingest_sources(sources, stage, force=force)
errors += stage_errors
count += len(sources) - stage_errors
self._run_events(TAG.AFTER_INGEST, stage)
self.record_stage_state(self.STATES.INGESTING, stage)
self.state = self.STATES.INGESTED
try:
pass
finally:
self._run_events(TAG.AFTER_INGEST, 0)
self.log('Ingested {} sources'.format(count))
if load_meta:
if len(sources) == 1:
iterable_source, source_pipe = self.source_pipe(sources[0])
try:
meta = iterable_source.meta
if meta:
self.metadata.about.title = meta['title']
self.metadata.about.summary = meta['summary']
self.build_source_files.bundle_meta.objects_to_record()
except AttributeError as e:
self.warn("Failed to set metadata: {}".format(e))
pass
else:
self.warn("Didn't not load meta from source. Must have exactly one soruce, got {}".format(len(sources)))
self.commit()
if errors == 0:
return True
else:
return False | [
"def",
"ingest",
"(",
"self",
",",
"sources",
"=",
"None",
",",
"tables",
"=",
"None",
",",
"stage",
"=",
"None",
",",
"force",
"=",
"False",
",",
"load_meta",
"=",
"False",
")",
":",
"from",
"itertools",
"import",
"groupby",
"from",
"ambry",
".",
"b... | 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_stage, all of the sources have the same stage, so they
get grouped together. The result it that the stage in the inner loop is the same as the stage being
run buy run_stage. | [
"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",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1737-L1842 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle._ingest_sources | 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 not s.is_ingested and not s.is_built)]
errors = 0
with self.progress.start('ingest', stage,
message='Ingesting ' + ('MP' if self.multi else 'SP'),
item_total=len(sources), item_type='source',
item_count=len(downloadable_sources)
) as ps:
# Create all of the source tables first, so we can't get contention for creating them
# in MP.
for source in sources:
_ = source.source_table
if self.multi:
args = [(self.identity.vid, stage, source.vid, force) for source in downloadable_sources]
pool = self.library.process_pool(limited_run=self.limited_run)
try:
# The '1' for chunksize ensures that the subprocess only gets one
# source to build. Combined with maxchildspertask = 1 in the pool,
# each process will only handle one source before exiting.
result = pool.map_async(ingest_mp, args, 1)
pool.close()
pool.join()
except KeyboardInterrupt:
self.log('Got keyboard interrrupt; terminating workers')
pool.terminate()
raise
else:
for i, source in enumerate(downloadable_sources, 1):
ps.add(
message='Ingesting source #{}, {}'.format(i, source.name),
source=source, state='running')
r = self._ingest_source(source, ps, force)
if not r:
errors += 1
if errors > 0:
from ambry.dbexceptions import IngestionError
raise IngestionError('Failed to ingest {} sources'.format(errors))
return errors | python | 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 not s.is_ingested and not s.is_built)]
errors = 0
with self.progress.start('ingest', stage,
message='Ingesting ' + ('MP' if self.multi else 'SP'),
item_total=len(sources), item_type='source',
item_count=len(downloadable_sources)
) as ps:
# Create all of the source tables first, so we can't get contention for creating them
# in MP.
for source in sources:
_ = source.source_table
if self.multi:
args = [(self.identity.vid, stage, source.vid, force) for source in downloadable_sources]
pool = self.library.process_pool(limited_run=self.limited_run)
try:
# The '1' for chunksize ensures that the subprocess only gets one
# source to build. Combined with maxchildspertask = 1 in the pool,
# each process will only handle one source before exiting.
result = pool.map_async(ingest_mp, args, 1)
pool.close()
pool.join()
except KeyboardInterrupt:
self.log('Got keyboard interrrupt; terminating workers')
pool.terminate()
raise
else:
for i, source in enumerate(downloadable_sources, 1):
ps.add(
message='Ingesting source #{}, {}'.format(i, source.name),
source=source, state='running')
r = self._ingest_source(source, ps, force)
if not r:
errors += 1
if errors > 0:
from ambry.dbexceptions import IngestionError
raise IngestionError('Failed to ingest {} sources'.format(errors))
return errors | [
"def",
"_ingest_sources",
"(",
"self",
",",
"sources",
",",
"stage",
",",
"force",
"=",
"False",
")",
":",
"from",
"concurrent",
"import",
"ingest_mp",
"self",
".",
"state",
"=",
"self",
".",
"STATES",
".",
"INGESTING",
"downloadable_sources",
"=",
"[",
"s... | Ingest a set of sources, usually for one stage | [
"Ingest",
"a",
"set",
"of",
"sources",
"usually",
"for",
"one",
"stage"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1844-L1898 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle._ingest_source | def _ingest_source(self, source, ps, force=None):
"""Ingest a single source"""
from ambry.bundle.process import call_interval
try:
from ambry.orm.exc import NotFoundError
if not source.is_partition and source.datafile.exists:
if not source.datafile.is_finalized:
source.datafile.remove()
elif force:
source.datafile.remove()
else:
ps.update(
message='Source {} already ingested, skipping'.format(source.name),
state='skipped')
return True
if source.is_partition:
# Check if the partition exists
try:
self.library.partition(source.ref)
except NotFoundError:
# Maybe it is an internal reference, in which case we can just delay
# until the partition is built
ps.update(message="Not Ingesting {}: referenced partition '{}' does not exist"
.format(source.name, source.ref), state='skipped')
return True
source.state = source.STATES.INGESTING
iterable_source, source_pipe = self.source_pipe(source, ps)
if not source.is_ingestible:
ps.update(message='Not an ingestiable source: {}'.format(source.name),
state='skipped', source=source)
source.state = source.STATES.NOTINGESTABLE
return True
ps.update('Ingesting {} from {}'.format(source.spec.name, source.url or source.generator),
item_type='rows', item_count=0)
@call_interval(5)
def ingest_progress_f(i):
(desc, n_records, total, rate) = source.datafile.report_progress()
ps.update(
message='Ingesting {}: rate: {}'.format(source.spec.name, rate), item_count=n_records)
source.datafile.load_rows(iterable_source,
callback=ingest_progress_f,
limit=500 if self.limited_run else None,
intuit_type=True, run_stats=False)
if source.datafile.meta['warnings']:
for w in source.datafile.meta['warnings']:
self.error("Ingestion error: {}".format(w))
ps.update(message='Ingested to {}'.format(source.datafile.syspath))
ps.update(message='Updating tables and specs for {}'.format(source.name))
# source.update_table() # Generate the source tables.
source.update_spec() # Update header_lines, start_line, etc.
if self.limited_run:
source.end_line = None # Otherwize, it will be 500
self.build_source_files.sources.objects_to_record()
ps.update(message='Ingested {}'.format(source.datafile.path), state='done')
source.state = source.STATES.INGESTED
self.commit()
return True
except Exception as e:
import traceback
from ambry.util import qualified_class_name
ps.update(
message='Source {} failed with exception: {}'.format(source.name, e),
exception_class=qualified_class_name(e),
exception_trace=str(traceback.format_exc()),
state='error'
)
source.state = source.STATES.INGESTING + '_error'
self.commit()
return False | python | def _ingest_source(self, source, ps, force=None):
"""Ingest a single source"""
from ambry.bundle.process import call_interval
try:
from ambry.orm.exc import NotFoundError
if not source.is_partition and source.datafile.exists:
if not source.datafile.is_finalized:
source.datafile.remove()
elif force:
source.datafile.remove()
else:
ps.update(
message='Source {} already ingested, skipping'.format(source.name),
state='skipped')
return True
if source.is_partition:
# Check if the partition exists
try:
self.library.partition(source.ref)
except NotFoundError:
# Maybe it is an internal reference, in which case we can just delay
# until the partition is built
ps.update(message="Not Ingesting {}: referenced partition '{}' does not exist"
.format(source.name, source.ref), state='skipped')
return True
source.state = source.STATES.INGESTING
iterable_source, source_pipe = self.source_pipe(source, ps)
if not source.is_ingestible:
ps.update(message='Not an ingestiable source: {}'.format(source.name),
state='skipped', source=source)
source.state = source.STATES.NOTINGESTABLE
return True
ps.update('Ingesting {} from {}'.format(source.spec.name, source.url or source.generator),
item_type='rows', item_count=0)
@call_interval(5)
def ingest_progress_f(i):
(desc, n_records, total, rate) = source.datafile.report_progress()
ps.update(
message='Ingesting {}: rate: {}'.format(source.spec.name, rate), item_count=n_records)
source.datafile.load_rows(iterable_source,
callback=ingest_progress_f,
limit=500 if self.limited_run else None,
intuit_type=True, run_stats=False)
if source.datafile.meta['warnings']:
for w in source.datafile.meta['warnings']:
self.error("Ingestion error: {}".format(w))
ps.update(message='Ingested to {}'.format(source.datafile.syspath))
ps.update(message='Updating tables and specs for {}'.format(source.name))
# source.update_table() # Generate the source tables.
source.update_spec() # Update header_lines, start_line, etc.
if self.limited_run:
source.end_line = None # Otherwize, it will be 500
self.build_source_files.sources.objects_to_record()
ps.update(message='Ingested {}'.format(source.datafile.path), state='done')
source.state = source.STATES.INGESTED
self.commit()
return True
except Exception as e:
import traceback
from ambry.util import qualified_class_name
ps.update(
message='Source {} failed with exception: {}'.format(source.name, e),
exception_class=qualified_class_name(e),
exception_trace=str(traceback.format_exc()),
state='error'
)
source.state = source.STATES.INGESTING + '_error'
self.commit()
return False | [
"def",
"_ingest_source",
"(",
"self",
",",
"source",
",",
"ps",
",",
"force",
"=",
"None",
")",
":",
"from",
"ambry",
".",
"bundle",
".",
"process",
"import",
"call_interval",
"try",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError"... | Ingest a single source | [
"Ingest",
"a",
"single",
"source"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L1900-L1992 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.source_schema | 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:
source.update_table()
self.log("Creating source schema for '{}': Table {}, {} columns"
.format(source.name, source.source_table.name, len(source.source_table.columns)))
self.commit() | python | 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:
source.update_table()
self.log("Creating source schema for '{}': Table {}, {} columns"
.format(source.name, source.source_table.name, len(source.source_table.columns)))
self.commit() | [
"def",
"source_schema",
"(",
"self",
",",
"sources",
"=",
"None",
",",
"tables",
"=",
"None",
",",
"clean",
"=",
"False",
")",
":",
"sources",
"=",
"self",
".",
"_resolve_sources",
"(",
"sources",
",",
"tables",
",",
"None",
",",
"predicate",
"=",
"lam... | Process a collection of ingested sources to make source tables. | [
"Process",
"a",
"collection",
"of",
"ingested",
"sources",
"to",
"make",
"source",
"tables",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2010-L2021 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.schema | 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 tables and partitions first
:param force: Population tables even if the table isn't empty
:param use_pipeline: If True, use the build pipeline to determine columns. If False,
:return: True on success.
"""
from itertools import groupby
from operator import attrgetter
from ambry.etl import Collect, Head
from ambry.orm.exc import NotFoundError
self.dstate = self.STATES.BUILDING
self.commit() # Workaround for https://github.com/CivicKnowledge/ambry/issues/171
self.log('---- Schema ----')
resolved_sources = self._resolve_sources(sources, tables, predicate=lambda s: s.is_processable)
if clean:
self.dataset.delete_tables_partitions()
self.commit()
# Group the sources by the destination table name
keyfunc = attrgetter('dest_table')
for t, table_sources in groupby(sorted(resolved_sources, key=keyfunc), keyfunc):
if use_pipeline:
for source in table_sources:
pl = self.pipeline(source)
pl.cast = [ambry.etl.CastSourceColumns]
pl.select_partition = []
pl.write = [Head, Collect]
pl.final = []
self.log_pipeline(pl)
pl.run()
pl.phase = 'build_schema'
self.log_pipeline(pl)
for h, c in zip(pl.write[Collect].headers, pl.write[Collect].rows[1]):
c = t.add_column(name=h, datatype=type(c).__name__ if c is not None else 'str',
update_existing=True)
self.log("Populated destination table '{}' from pipeline '{}'"
.format(t.name, pl.name))
else:
# Get all of the header names, for each source, associating the header position in the table
# with the header, then sort on the postition. This will produce a stream of header names
# that may have duplicates, but which is generally in the order the headers appear in the
# sources. The duplicates are properly handled when we add the columns in add_column()
self.commit()
def source_cols(source):
if source.is_partition and not source.source_table_exists:
return enumerate(source.partition.table.columns)
else:
return enumerate(source.source_table.columns)
columns = sorted(set([(i, col.dest_header, col.datatype, col.description, col.has_codes)
for source in table_sources for i, col in source_cols(source)]))
initial_count = len(t.columns)
for pos, name, datatype, desc, has_codes in columns:
kwds = dict(
name=name,
datatype=datatype,
description=desc,
update_existing=True
)
try:
extant = t.column(name)
except NotFoundError:
extant = None
if extant is None or not extant.description:
kwds['description'] = desc
c = t.add_column(**kwds)
final_count = len(t.columns)
if final_count > initial_count:
diff = final_count - initial_count
self.log("Populated destination table '{}' from source table '{}' with {} columns"
.format(t.name, source.source_table.name, diff))
self.commit()
return True | python | 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 tables and partitions first
:param force: Population tables even if the table isn't empty
:param use_pipeline: If True, use the build pipeline to determine columns. If False,
:return: True on success.
"""
from itertools import groupby
from operator import attrgetter
from ambry.etl import Collect, Head
from ambry.orm.exc import NotFoundError
self.dstate = self.STATES.BUILDING
self.commit() # Workaround for https://github.com/CivicKnowledge/ambry/issues/171
self.log('---- Schema ----')
resolved_sources = self._resolve_sources(sources, tables, predicate=lambda s: s.is_processable)
if clean:
self.dataset.delete_tables_partitions()
self.commit()
# Group the sources by the destination table name
keyfunc = attrgetter('dest_table')
for t, table_sources in groupby(sorted(resolved_sources, key=keyfunc), keyfunc):
if use_pipeline:
for source in table_sources:
pl = self.pipeline(source)
pl.cast = [ambry.etl.CastSourceColumns]
pl.select_partition = []
pl.write = [Head, Collect]
pl.final = []
self.log_pipeline(pl)
pl.run()
pl.phase = 'build_schema'
self.log_pipeline(pl)
for h, c in zip(pl.write[Collect].headers, pl.write[Collect].rows[1]):
c = t.add_column(name=h, datatype=type(c).__name__ if c is not None else 'str',
update_existing=True)
self.log("Populated destination table '{}' from pipeline '{}'"
.format(t.name, pl.name))
else:
# Get all of the header names, for each source, associating the header position in the table
# with the header, then sort on the postition. This will produce a stream of header names
# that may have duplicates, but which is generally in the order the headers appear in the
# sources. The duplicates are properly handled when we add the columns in add_column()
self.commit()
def source_cols(source):
if source.is_partition and not source.source_table_exists:
return enumerate(source.partition.table.columns)
else:
return enumerate(source.source_table.columns)
columns = sorted(set([(i, col.dest_header, col.datatype, col.description, col.has_codes)
for source in table_sources for i, col in source_cols(source)]))
initial_count = len(t.columns)
for pos, name, datatype, desc, has_codes in columns:
kwds = dict(
name=name,
datatype=datatype,
description=desc,
update_existing=True
)
try:
extant = t.column(name)
except NotFoundError:
extant = None
if extant is None or not extant.description:
kwds['description'] = desc
c = t.add_column(**kwds)
final_count = len(t.columns)
if final_count > initial_count:
diff = final_count - initial_count
self.log("Populated destination table '{}' from source table '{}' with {} columns"
.format(t.name, source.source_table.name, diff))
self.commit()
return True | [
"def",
"schema",
"(",
"self",
",",
"sources",
"=",
"None",
",",
"tables",
"=",
"None",
",",
"clean",
"=",
"False",
",",
"force",
"=",
"False",
",",
"use_pipeline",
"=",
"False",
")",
":",
"from",
"itertools",
"import",
"groupby",
"from",
"operator",
"i... | 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 tables and partitions first
:param force: Population tables even if the table isn't empty
:param use_pipeline: If True, use the build pipeline to determine columns. If False,
:return: True on success. | [
"Generate",
"destination",
"schemas",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2024-L2129 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle._reset_build | 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(p.identity.name))
try:
self.wrap_partition(p).local_datafile.remove()
self.session.delete(p)
except NotFoundError:
pass
for s in sources:
# Don't delete partitions fro mother bundles!
if s.reftype == 'partition':
continue
p = s.partition
if p:
try:
self.wrap_partition(p).local_datafile.remove()
self.session.delete(p)
except NotFoundError:
pass
if s.state in (self.STATES.BUILDING, self.STATES.BUILT):
s.state = self.STATES.INGESTED
self.commit() | python | 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(p.identity.name))
try:
self.wrap_partition(p).local_datafile.remove()
self.session.delete(p)
except NotFoundError:
pass
for s in sources:
# Don't delete partitions fro mother bundles!
if s.reftype == 'partition':
continue
p = s.partition
if p:
try:
self.wrap_partition(p).local_datafile.remove()
self.session.delete(p)
except NotFoundError:
pass
if s.state in (self.STATES.BUILDING, self.STATES.BUILT):
s.state = self.STATES.INGESTED
self.commit() | [
"def",
"_reset_build",
"(",
"self",
",",
"sources",
")",
":",
"from",
"ambry",
".",
"orm",
".",
"exc",
"import",
"NotFoundError",
"for",
"p",
"in",
"self",
".",
"dataset",
".",
"partitions",
":",
"if",
"p",
".",
"type",
"==",
"p",
".",
"TYPE",
".",
... | Remove partition datafiles and reset the datafiles to the INGESTED state | [
"Remove",
"partition",
"datafiles",
"and",
"reset",
"the",
"datafiles",
"to",
"the",
"INGESTED",
"state"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2161-L2191 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.build | def build(self, sources=None, tables=None, stage=None, force=False):
"""
:param phase:
:param stage:
:param sources: Source names or destination table names.
:return:
"""
from operator import attrgetter
from itertools import groupby
from .concurrent import build_mp, unify_mp
from ambry.bundle.events import TAG
self.log('==== Building ====')
self.state = self.STATES.BUILDING
self.commit()
class SourceSet(object):
"""Container for sources that can reload them after they get expired from the session"""
def __init__(self, bundle, v):
self.bundle = bundle
self.sources = v
self._s_vids = [s.vid for s in self.sources]
def reload(self):
self.sources = [self.bundle.source(vid) for vid in self._s_vids]
def __iter__(self):
for s in self.sources:
yield s
def __len__(self):
return len(self._s_vids)
self._run_events(TAG.BEFORE_BUILD, 0)
resolved_sources = SourceSet(self, self._resolve_sources(sources, tables, stage=stage,
predicate=lambda s: s.is_processable))
with self.progress.start('build', stage, item_total=len(resolved_sources)) as ps:
if len(resolved_sources) == 0:
ps.update(message='No sources', state='skipped')
self.log('No processable sources, skipping build stage {}'.format(stage))
return True
if not self.pre_build(force):
ps.update(message='Pre-build failed', state='skipped')
return False
if force:
self._reset_build(resolved_sources)
resolved_sources.reload()
e = [
(stage, SourceSet(self, list(stage_sources)))
for stage, stage_sources in groupby(sorted(resolved_sources, key=attrgetter('stage')),
attrgetter('stage'))
]
for stage, stage_sources in e:
stage_sources.reload()
for s in stage_sources:
s.state = self.STATES.WAITING
self.commit()
stage_sources.reload()
self.log('Processing {} sources, stage {} ; first 10: {}'
.format(len(stage_sources), stage, [x.name for x in stage_sources.sources[:10]]))
self._run_events(TAG.BEFORE_BUILD, stage)
if self.multi:
try:
# The '1' for chunksize ensures that the subprocess only gets one
# source to build. Combined with maxchildspertask = 1 in the pool,
# each process will only handle one source before exiting.
args = [(self.identity.vid, stage, source.vid, force) for source in stage_sources]
pool = self.library.process_pool(limited_run=self.limited_run)
r = pool.map_async(build_mp, args, 1)
completed_sources = r.get()
ps.add('Finished MP building {} sources. Starting MP coalescing'
.format(len(completed_sources)))
partition_names = [(self.identity.vid, k) for k, v
in self.collect_segment_partitions().items()]
r = pool.map_async(unify_mp, partition_names, 1)
completed_partitions = r.get()
ps.add('Finished MP coalescing {} partitions'.format(len(completed_partitions)))
pool.close()
pool.join()
except KeyboardInterrupt:
self.log('Got keyboard interrrupt; terminating workers')
pool.terminate()
else:
for i, source in enumerate(stage_sources):
id_ = ps.add(message='Running source {}'.format(source.name),
source=source, item_count=i, state='running')
self.build_source(stage, source, ps, force=force)
ps.update(message='Finished processing source', state='done')
# This bit seems to solve a problem where the records from the ps.add above
# never gets closed out.
ps.get(id_).state = 'done'
self.progress.commit()
self.unify_partitions()
self._run_events(TAG.AFTER_BUILD, stage)
self.state = self.STATES.BUILT
self.commit()
self._run_events(TAG.AFTER_BUILD, 0)
self.close_session()
self.log('==== Done Building ====')
self.buildstate.commit()
self.state = self.STATES.BUILT
self.commit()
return True | python | def build(self, sources=None, tables=None, stage=None, force=False):
"""
:param phase:
:param stage:
:param sources: Source names or destination table names.
:return:
"""
from operator import attrgetter
from itertools import groupby
from .concurrent import build_mp, unify_mp
from ambry.bundle.events import TAG
self.log('==== Building ====')
self.state = self.STATES.BUILDING
self.commit()
class SourceSet(object):
"""Container for sources that can reload them after they get expired from the session"""
def __init__(self, bundle, v):
self.bundle = bundle
self.sources = v
self._s_vids = [s.vid for s in self.sources]
def reload(self):
self.sources = [self.bundle.source(vid) for vid in self._s_vids]
def __iter__(self):
for s in self.sources:
yield s
def __len__(self):
return len(self._s_vids)
self._run_events(TAG.BEFORE_BUILD, 0)
resolved_sources = SourceSet(self, self._resolve_sources(sources, tables, stage=stage,
predicate=lambda s: s.is_processable))
with self.progress.start('build', stage, item_total=len(resolved_sources)) as ps:
if len(resolved_sources) == 0:
ps.update(message='No sources', state='skipped')
self.log('No processable sources, skipping build stage {}'.format(stage))
return True
if not self.pre_build(force):
ps.update(message='Pre-build failed', state='skipped')
return False
if force:
self._reset_build(resolved_sources)
resolved_sources.reload()
e = [
(stage, SourceSet(self, list(stage_sources)))
for stage, stage_sources in groupby(sorted(resolved_sources, key=attrgetter('stage')),
attrgetter('stage'))
]
for stage, stage_sources in e:
stage_sources.reload()
for s in stage_sources:
s.state = self.STATES.WAITING
self.commit()
stage_sources.reload()
self.log('Processing {} sources, stage {} ; first 10: {}'
.format(len(stage_sources), stage, [x.name for x in stage_sources.sources[:10]]))
self._run_events(TAG.BEFORE_BUILD, stage)
if self.multi:
try:
# The '1' for chunksize ensures that the subprocess only gets one
# source to build. Combined with maxchildspertask = 1 in the pool,
# each process will only handle one source before exiting.
args = [(self.identity.vid, stage, source.vid, force) for source in stage_sources]
pool = self.library.process_pool(limited_run=self.limited_run)
r = pool.map_async(build_mp, args, 1)
completed_sources = r.get()
ps.add('Finished MP building {} sources. Starting MP coalescing'
.format(len(completed_sources)))
partition_names = [(self.identity.vid, k) for k, v
in self.collect_segment_partitions().items()]
r = pool.map_async(unify_mp, partition_names, 1)
completed_partitions = r.get()
ps.add('Finished MP coalescing {} partitions'.format(len(completed_partitions)))
pool.close()
pool.join()
except KeyboardInterrupt:
self.log('Got keyboard interrrupt; terminating workers')
pool.terminate()
else:
for i, source in enumerate(stage_sources):
id_ = ps.add(message='Running source {}'.format(source.name),
source=source, item_count=i, state='running')
self.build_source(stage, source, ps, force=force)
ps.update(message='Finished processing source', state='done')
# This bit seems to solve a problem where the records from the ps.add above
# never gets closed out.
ps.get(id_).state = 'done'
self.progress.commit()
self.unify_partitions()
self._run_events(TAG.AFTER_BUILD, stage)
self.state = self.STATES.BUILT
self.commit()
self._run_events(TAG.AFTER_BUILD, 0)
self.close_session()
self.log('==== Done Building ====')
self.buildstate.commit()
self.state = self.STATES.BUILT
self.commit()
return True | [
"def",
"build",
"(",
"self",
",",
"sources",
"=",
"None",
",",
"tables",
"=",
"None",
",",
"stage",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"from",
"operator",
"import",
"attrgetter",
"from",
"itertools",
"import",
"groupby",
"from",
".",
"c... | :param phase:
:param stage:
:param sources: Source names or destination table names.
:return: | [
":",
"param",
"phase",
":",
":",
"param",
"stage",
":",
":",
"param",
"sources",
":",
"Source",
"names",
"or",
"destination",
"table",
"names",
".",
":",
"return",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2194-L2330 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.build_table | 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 | 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() | [
"def",
"build_table",
"(",
"self",
",",
"table",
",",
"force",
"=",
"False",
")",
":",
"sources",
"=",
"self",
".",
"_resolve_sources",
"(",
"None",
",",
"[",
"table",
"]",
")",
"for",
"source",
"in",
"sources",
":",
"self",
".",
"build_source",
"(",
... | Build all of the sources for a table | [
"Build",
"all",
"of",
"the",
"sources",
"for",
"a",
"table"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2332-L2340 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.build_source | 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'.format(source.name), state='skipped')
return
pl = self.pipeline(source, ps=ps)
source.state = self.STATES.BUILDING
# Doing this before hand to get at least some information about the pipline,
# in case there is an error during the run. It will get overwritten with more information
# after successful run
self.log_pipeline(pl)
try:
source_name = source.name # In case the source drops out of the session, which is does.
s_vid = source.vid
ps.update(message='Running pipeline {}'.format(pl.name), s_vid=s_vid, item_type='rows', item_count=0)
@call_interval(5)
def run_progress_f(sink_pipe, rows):
(n_records, rate) = sink_pipe.report_progress()
if n_records > 0:
ps.update(message='Running pipeline {}: rate: {}'
.format(pl.name, rate),
s_vid=s_vid, item_type='rows', item_count=n_records)
pl.run(callback=run_progress_f)
# Run the final routines at the end of the pipelin
for f in pl.final:
ps.update(message='Run final routine: {}'.format(f.__name__))
f(pl)
ps.update(message='Finished building source')
except:
self.log_pipeline(pl)
raise
self.commit()
try:
partitions = list(pl[ambry.etl.PartitionWriter].partitions)
ps.update(message='Finalizing segment partition',
item_type='partitions', item_total=len(partitions), item_count=0)
for i, p in enumerate(partitions):
ps.update(message='Finalizing segment partition {}'.format(p.name), item_count=i, p_vid=p.vid)
try:
p.finalize()
except AttributeError:
print(self.table(p.table_name))
raise
# FIXME Shouldn't need to do this commit, but without it, some stats get added multiple
# times, causing an error later. Probably could be avoided by adding the stats to the
# collection in the dataset
self.commit()
except IndexError:
self.error("Pipeline didn't have a PartitionWriters, won't try to finalize")
self.log_pipeline(pl)
source.state = self.STATES.BUILT
self.commit()
return source.name | python | 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'.format(source.name), state='skipped')
return
pl = self.pipeline(source, ps=ps)
source.state = self.STATES.BUILDING
# Doing this before hand to get at least some information about the pipline,
# in case there is an error during the run. It will get overwritten with more information
# after successful run
self.log_pipeline(pl)
try:
source_name = source.name # In case the source drops out of the session, which is does.
s_vid = source.vid
ps.update(message='Running pipeline {}'.format(pl.name), s_vid=s_vid, item_type='rows', item_count=0)
@call_interval(5)
def run_progress_f(sink_pipe, rows):
(n_records, rate) = sink_pipe.report_progress()
if n_records > 0:
ps.update(message='Running pipeline {}: rate: {}'
.format(pl.name, rate),
s_vid=s_vid, item_type='rows', item_count=n_records)
pl.run(callback=run_progress_f)
# Run the final routines at the end of the pipelin
for f in pl.final:
ps.update(message='Run final routine: {}'.format(f.__name__))
f(pl)
ps.update(message='Finished building source')
except:
self.log_pipeline(pl)
raise
self.commit()
try:
partitions = list(pl[ambry.etl.PartitionWriter].partitions)
ps.update(message='Finalizing segment partition',
item_type='partitions', item_total=len(partitions), item_count=0)
for i, p in enumerate(partitions):
ps.update(message='Finalizing segment partition {}'.format(p.name), item_count=i, p_vid=p.vid)
try:
p.finalize()
except AttributeError:
print(self.table(p.table_name))
raise
# FIXME Shouldn't need to do this commit, but without it, some stats get added multiple
# times, causing an error later. Probably could be avoided by adding the stats to the
# collection in the dataset
self.commit()
except IndexError:
self.error("Pipeline didn't have a PartitionWriters, won't try to finalize")
self.log_pipeline(pl)
source.state = self.STATES.BUILT
self.commit()
return source.name | [
"def",
"build_source",
"(",
"self",
",",
"stage",
",",
"source",
",",
"ps",
",",
"force",
"=",
"False",
")",
":",
"from",
"ambry",
".",
"bundle",
".",
"process",
"import",
"call_interval",
"assert",
"source",
".",
"is_processable",
",",
"source",
".",
"n... | Build a single source | [
"Build",
"a",
"single",
"source"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2342-L2420 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.collect_segment_partitions | 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.
partitions = defaultdict(set)
for p in self.dataset.partitions:
if p.type == p.TYPE.SEGMENT:
name = p.identity.name
name.segment = None
partitions[name].add(p)
return partitions | python | 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.
partitions = defaultdict(set)
for p in self.dataset.partitions:
if p.type == p.TYPE.SEGMENT:
name = p.identity.name
name.segment = None
partitions[name].add(p)
return partitions | [
"def",
"collect_segment_partitions",
"(",
"self",
")",
":",
"from",
"collections",
"import",
"defaultdict",
"# Group the segments by their parent partition name, which is the",
"# same name, but without the segment.",
"partitions",
"=",
"defaultdict",
"(",
"set",
")",
"for",
"p... | Return a dict of segments partitions, keyed on the name of the parent partition | [
"Return",
"a",
"dict",
"of",
"segments",
"partitions",
"keyed",
"on",
"the",
"name",
"of",
"the",
"parent",
"partition"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2422-L2436 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.unify_partitions | 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, then
# delete the segment partitions.
with self.progress.start('coalesce', 0, message='Coalescing partition segments') as ps:
for name, segments in iteritems(partitions):
ps.add(item_type='partitions', item_count=len(segments),
message='Colescing partition {}'.format(name))
self.unify_partition(name, segments, ps) | python | 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, then
# delete the segment partitions.
with self.progress.start('coalesce', 0, message='Coalescing partition segments') as ps:
for name, segments in iteritems(partitions):
ps.add(item_type='partitions', item_count=len(segments),
message='Colescing partition {}'.format(name))
self.unify_partition(name, segments, ps) | [
"def",
"unify_partitions",
"(",
"self",
")",
":",
"partitions",
"=",
"self",
".",
"collect_segment_partitions",
"(",
")",
"# For each group, copy the segment partitions to the parent partitions, then",
"# delete the segment partitions.",
"with",
"self",
".",
"progress",
".",
... | For all of the segments for a partition, create the parent partition, combine the
children into the parent, and delete the children. | [
"For",
"all",
"of",
"the",
"segments",
"for",
"a",
"partition",
"create",
"the",
"parent",
"partition",
"combine",
"the",
"children",
"into",
"the",
"parent",
"and",
"delete",
"the",
"children",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2438-L2452 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.exec_context | 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.valuetype.types import parse_date, parse_time, parse_datetime
import ambry.valuetype.types
import ambry.valuetype.exceptions
import ambry.valuetype.test
import ambry.valuetype
def set_from(f, frm):
try:
try:
f.ambry_from = frm
except AttributeError: # for instance methods
f.im_func.ambry_from = frm
except (TypeError, AttributeError): # Builtins, non python code
pass
return f
test_env = dict(
parse_date=parse_date,
parse_time=parse_time,
parse_datetime=parse_datetime,
partial=partial,
bundle=self
)
test_env.update(kwargs)
test_env.update(dateutil.parser.__dict__)
test_env.update(datetime.__dict__)
test_env.update(random.__dict__)
test_env.update(ambry.valuetype.core.__dict__)
test_env.update(ambry.valuetype.types.__dict__)
test_env.update(ambry.valuetype.exceptions.__dict__)
test_env.update(ambry.valuetype.test.__dict__)
test_env.update(ambry.valuetype.__dict__)
localvars = {}
for f_name, func in test_env.items():
if not isinstance(func, (str, tuple)):
localvars[f_name] = set_from(func, 'env')
# The 'b' parameter of randint is assumed to be a bundle, but
# replacing it with a lambda prevents the param assignment
localvars['randint'] = lambda a, b: random.randint(a, b)
if self != Bundle:
# Functions from the bundle
base = set(inspect.getmembers(Bundle, predicate=inspect.isfunction))
mine = set(inspect.getmembers(self.__class__, predicate=inspect.isfunction))
localvars.update({f_name: set_from(func, 'bundle') for f_name, func in mine - base})
# Bound methods. In python 2, these must be called referenced from the bundle, since
# there is a difference between bound and unbound methods. In Python 3, there is no differnce,
# so the lambda functions may not be necessary.
base = set(inspect.getmembers(Bundle, predicate=inspect.ismethod))
mine = set(inspect.getmembers(self.__class__, predicate=inspect.ismethod))
# Functions are descriptors, and the __get__ call binds the function to its object to make a bound method
localvars.update({f_name: set_from(func.__get__(self), 'bundle') for f_name, func in (mine - base)})
# Bundle module functions
module_entries = inspect.getmembers(sys.modules['ambry.build'], predicate=inspect.isfunction)
localvars.update({f_name: set_from(func, 'module') for f_name, func in module_entries})
return localvars | python | 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.valuetype.types import parse_date, parse_time, parse_datetime
import ambry.valuetype.types
import ambry.valuetype.exceptions
import ambry.valuetype.test
import ambry.valuetype
def set_from(f, frm):
try:
try:
f.ambry_from = frm
except AttributeError: # for instance methods
f.im_func.ambry_from = frm
except (TypeError, AttributeError): # Builtins, non python code
pass
return f
test_env = dict(
parse_date=parse_date,
parse_time=parse_time,
parse_datetime=parse_datetime,
partial=partial,
bundle=self
)
test_env.update(kwargs)
test_env.update(dateutil.parser.__dict__)
test_env.update(datetime.__dict__)
test_env.update(random.__dict__)
test_env.update(ambry.valuetype.core.__dict__)
test_env.update(ambry.valuetype.types.__dict__)
test_env.update(ambry.valuetype.exceptions.__dict__)
test_env.update(ambry.valuetype.test.__dict__)
test_env.update(ambry.valuetype.__dict__)
localvars = {}
for f_name, func in test_env.items():
if not isinstance(func, (str, tuple)):
localvars[f_name] = set_from(func, 'env')
# The 'b' parameter of randint is assumed to be a bundle, but
# replacing it with a lambda prevents the param assignment
localvars['randint'] = lambda a, b: random.randint(a, b)
if self != Bundle:
# Functions from the bundle
base = set(inspect.getmembers(Bundle, predicate=inspect.isfunction))
mine = set(inspect.getmembers(self.__class__, predicate=inspect.isfunction))
localvars.update({f_name: set_from(func, 'bundle') for f_name, func in mine - base})
# Bound methods. In python 2, these must be called referenced from the bundle, since
# there is a difference between bound and unbound methods. In Python 3, there is no differnce,
# so the lambda functions may not be necessary.
base = set(inspect.getmembers(Bundle, predicate=inspect.ismethod))
mine = set(inspect.getmembers(self.__class__, predicate=inspect.ismethod))
# Functions are descriptors, and the __get__ call binds the function to its object to make a bound method
localvars.update({f_name: set_from(func.__get__(self), 'bundle') for f_name, func in (mine - base)})
# Bundle module functions
module_entries = inspect.getmembers(sys.modules['ambry.build'], predicate=inspect.isfunction)
localvars.update({f_name: set_from(func, 'module') for f_name, func in module_entries})
return localvars | [
"def",
"exec_context",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"inspect",
"import",
"dateutil",
".",
"parser",
"import",
"datetime",
"import",
"random",
"from",
"functools",
"import",
"partial",
"from",
"ambry",
".",
"valuetype",
".",
"type... | Base environment for evals, the stuff that is the same for all evals. Primarily used in the
Caster pipe | [
"Base",
"environment",
"for",
"evals",
"the",
"stuff",
"that",
"is",
"the",
"same",
"for",
"all",
"evals",
".",
"Primarily",
"used",
"in",
"the",
"Caster",
"pipe"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2534-L2611 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.post_build_time_coverage | 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):
years.add(year)
# From the bundle name
if self.identity.btime:
for year in expand_to_years(self.identity.btime):
years.add(year)
# From all of the partitions
for p in self.partitions:
years |= set(p.time_coverage) | python | 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):
years.add(year)
# From the bundle name
if self.identity.btime:
for year in expand_to_years(self.identity.btime):
years.add(year)
# From all of the partitions
for p in self.partitions:
years |= set(p.time_coverage) | [
"def",
"post_build_time_coverage",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"util",
".",
"datestimes",
"import",
"expand_to_years",
"years",
"=",
"set",
"(",
")",
"# From the bundle about",
"if",
"self",
".",
"metadata",
".",
"about",
".",
"time",
":",
"... | Collect all of the time coverage for the bundle. | [
"Collect",
"all",
"of",
"the",
"time",
"coverage",
"for",
"the",
"bundle",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2664-L2682 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.post_build_geo_coverage | 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(
"Failed to find space identifier '{}' in full text identifier search".format(term))
return places[0].vid
if self.metadata.about.space: # From the bundle metadata
spaces.add(resolve(self.metadata.about.space))
if self.metadata.about.grain: # From the bundle metadata
grains.add(self.metadata.about.grain)
if self.identity.bspace: # And from the bundle name
spaces.add(resolve(self.identity.bspace))
# From all of the partitions
for p in self.partitions.all:
if 'geo_coverage' in p.record.data:
for space in p.record.data['geo_coverage']:
spaces.add(space)
if 'geo_grain' in p.record.data:
for grain in p.record.data['geo_grain']:
grains.add(grain)
def conv_grain(g):
"""Some grain are expressed as summary level names, not gvids."""
try:
c = GVid.get_class(g)
return b(c().summarize())
except NotASummaryName:
return g
self.metadata.coverage.geo = sorted(spaces)
self.metadata.coverage.grain = sorted(conv_grain(g) for g in grains)
self.metadata.write_to_dir() | python | 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(
"Failed to find space identifier '{}' in full text identifier search".format(term))
return places[0].vid
if self.metadata.about.space: # From the bundle metadata
spaces.add(resolve(self.metadata.about.space))
if self.metadata.about.grain: # From the bundle metadata
grains.add(self.metadata.about.grain)
if self.identity.bspace: # And from the bundle name
spaces.add(resolve(self.identity.bspace))
# From all of the partitions
for p in self.partitions.all:
if 'geo_coverage' in p.record.data:
for space in p.record.data['geo_coverage']:
spaces.add(space)
if 'geo_grain' in p.record.data:
for grain in p.record.data['geo_grain']:
grains.add(grain)
def conv_grain(g):
"""Some grain are expressed as summary level names, not gvids."""
try:
c = GVid.get_class(g)
return b(c().summarize())
except NotASummaryName:
return g
self.metadata.coverage.geo = sorted(spaces)
self.metadata.coverage.grain = sorted(conv_grain(g) for g in grains)
self.metadata.write_to_dir() | [
"def",
"post_build_geo_coverage",
"(",
"self",
")",
":",
"spaces",
"=",
"set",
"(",
")",
"grains",
"=",
"set",
"(",
")",
"def",
"resolve",
"(",
"term",
")",
":",
"places",
"=",
"list",
"(",
"self",
".",
"library",
".",
"search",
".",
"search_identifier... | Collect all of the geocoverage for the bundle. | [
"Collect",
"all",
"of",
"the",
"geocoverage",
"for",
"the",
"bundle",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2684-L2729 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.is_finalized | def is_finalized(self):
"""Return True if the bundle is installed."""
return self.state == self.STATES.FINALIZED or self.state == self.STATES.INSTALLED | python | def is_finalized(self):
"""Return True if the bundle is installed."""
return self.state == self.STATES.FINALIZED or self.state == self.STATES.INSTALLED | [
"def",
"is_finalized",
"(",
"self",
")",
":",
"return",
"self",
".",
"state",
"==",
"self",
".",
"STATES",
".",
"FINALIZED",
"or",
"self",
".",
"state",
"==",
"self",
".",
"STATES",
".",
"INSTALLED"
] | Return True if the bundle is installed. | [
"Return",
"True",
"if",
"the",
"bundle",
"is",
"installed",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2736-L2739 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle._run_events | 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 | 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) | [
"def",
"_run_events",
"(",
"self",
",",
"tag",
",",
"stage",
"=",
"None",
")",
":",
"self",
".",
"_run_event_methods",
"(",
"tag",
",",
"stage",
")",
"self",
".",
"_run_tests",
"(",
"tag",
",",
"stage",
")"
] | Run tests marked with a particular tag and stage | [
"Run",
"tests",
"marked",
"with",
"a",
"particular",
"tag",
"and",
"stage"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2792-L2796 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle._run_event_methods | 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 _runable_for_event(f, tag, stage):
funcs.append(f)
for func in funcs:
func() | python | 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 _runable_for_event(f, tag, stage):
funcs.append(f)
for func in funcs:
func() | [
"def",
"_run_event_methods",
"(",
"self",
",",
"tag",
",",
"stage",
"=",
"None",
")",
":",
"import",
"inspect",
"from",
"ambry",
".",
"bundle",
".",
"events",
"import",
"_runable_for_event",
"funcs",
"=",
"[",
"]",
"for",
"func_name",
",",
"f",
"in",
"in... | Run code in the bundle that is marked with events. | [
"Run",
"code",
"in",
"the",
"bundle",
"that",
"is",
"marked",
"with",
"events",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L2798-L2810 |
CivicSpleen/ambry | ambry/bundle/bundle.py | Bundle.is_installed | def is_installed(self):
"""Return True if the bundle is installed."""
r = self.library.resolve(self.identity.vid)
return r is not None | python | def is_installed(self):
"""Return True if the bundle is installed."""
r = self.library.resolve(self.identity.vid)
return r is not None | [
"def",
"is_installed",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"library",
".",
"resolve",
"(",
"self",
".",
"identity",
".",
"vid",
")",
"return",
"r",
"is",
"not",
"None"
] | Return True if the bundle is installed. | [
"Return",
"True",
"if",
"the",
"bundle",
"is",
"installed",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/bundle.py#L3029-L3034 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/replication.py | include | 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, RelationshipProperty)
_included.add(prop) | python | 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, RelationshipProperty)
_included.add(prop) | [
"def",
"include",
"(",
"prop",
")",
":",
"if",
"isinstance",
"(",
"prop",
",",
"QueryableAttribute",
")",
":",
"prop",
"=",
"prop",
".",
"property",
"assert",
"isinstance",
"(",
"prop",
",",
"(",
"Column",
",",
"ColumnProperty",
",",
"RelationshipProperty",
... | Replicate property that is normally not replicated. Right now it's
meaningful for one-to-many relations only. | [
"Replicate",
"property",
"that",
"is",
"normally",
"not",
"replicated",
".",
"Right",
"now",
"it",
"s",
"meaningful",
"for",
"one",
"-",
"to",
"-",
"many",
"relations",
"only",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/replication.py#L33-L40 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/replication.py | exclude | def exclude(prop):
'''Don't replicate property that is normally replicated: ordering column,
many-to-one relation that is marked for replication from other side.'''
if isinstance(prop, QueryableAttribute):
prop = prop.property
assert isinstance(prop, (Column, ColumnProperty, RelationshipProperty))
_excluded.add(prop)
if isinstance(prop, RelationshipProperty):
# Also exclude columns that participate in this relationship
for local in prop.local_columns:
_excluded.add(local) | python | def exclude(prop):
'''Don't replicate property that is normally replicated: ordering column,
many-to-one relation that is marked for replication from other side.'''
if isinstance(prop, QueryableAttribute):
prop = prop.property
assert isinstance(prop, (Column, ColumnProperty, RelationshipProperty))
_excluded.add(prop)
if isinstance(prop, RelationshipProperty):
# Also exclude columns that participate in this relationship
for local in prop.local_columns:
_excluded.add(local) | [
"def",
"exclude",
"(",
"prop",
")",
":",
"if",
"isinstance",
"(",
"prop",
",",
"QueryableAttribute",
")",
":",
"prop",
"=",
"prop",
".",
"property",
"assert",
"isinstance",
"(",
"prop",
",",
"(",
"Column",
",",
"ColumnProperty",
",",
"RelationshipProperty",
... | Don't replicate property that is normally replicated: ordering column,
many-to-one relation that is marked for replication from other side. | [
"Don",
"t",
"replicate",
"property",
"that",
"is",
"normally",
"replicated",
":",
"ordering",
"column",
"many",
"-",
"to",
"-",
"one",
"relation",
"that",
"is",
"marked",
"for",
"replication",
"from",
"other",
"side",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/replication.py#L42-L52 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/replication.py | reflect | 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]
assert ident is not None
return db.query(model).get(ident) | python | 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]
assert ident is not None
return db.query(model).get(ident) | [
"def",
"reflect",
"(",
"source",
",",
"model",
",",
"cache",
"=",
"None",
")",
":",
"if",
"source",
"is",
"None",
":",
"return",
"None",
"if",
"cache",
"and",
"source",
"in",
"cache",
":",
"return",
"cache",
"[",
"source",
"]",
"db",
"=",
"object_ses... | Finds an object of class `model` with the same identifier as the
`source` object | [
"Finds",
"an",
"object",
"of",
"class",
"model",
"with",
"the",
"same",
"identifier",
"as",
"the",
"source",
"object"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/replication.py#L55-L65 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/replication.py | replicate_attributes | 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 manager_of_class(type(source)).attributes:
if attr.key not in target_manager:
# It's not common attribute
continue
target_attr = target_manager[attr.key]
if isinstance(attr.property, ColumnProperty):
assert isinstance(target_attr.property, ColumnProperty)
column_attrs.add(attr)
elif isinstance(attr.property, RelationshipProperty):
assert isinstance(target_attr.property, RelationshipProperty)
relationship_attrs.add(attr)
if attr.property.direction is MANYTOONE:
relationship_columns.update(attr.property.local_columns)
for attr in column_attrs:
if _column_property_in_registry(attr.property, _excluded):
continue
elif (not _column_property_in_registry(attr.property, _included) and
all(column in relationship_columns
for column in attr.property.columns)):
continue
setattr(target, attr.key, getattr(source, attr.key))
for attr in relationship_attrs:
target_attr_model = target_manager[attr.key].property.argument
if not is_relation_replicatable(attr):
continue
replicate_relation(source, target, attr, target_manager[attr.key],
cache=cache) | python | 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 manager_of_class(type(source)).attributes:
if attr.key not in target_manager:
# It's not common attribute
continue
target_attr = target_manager[attr.key]
if isinstance(attr.property, ColumnProperty):
assert isinstance(target_attr.property, ColumnProperty)
column_attrs.add(attr)
elif isinstance(attr.property, RelationshipProperty):
assert isinstance(target_attr.property, RelationshipProperty)
relationship_attrs.add(attr)
if attr.property.direction is MANYTOONE:
relationship_columns.update(attr.property.local_columns)
for attr in column_attrs:
if _column_property_in_registry(attr.property, _excluded):
continue
elif (not _column_property_in_registry(attr.property, _included) and
all(column in relationship_columns
for column in attr.property.columns)):
continue
setattr(target, attr.key, getattr(source, attr.key))
for attr in relationship_attrs:
target_attr_model = target_manager[attr.key].property.argument
if not is_relation_replicatable(attr):
continue
replicate_relation(source, target, attr, target_manager[attr.key],
cache=cache) | [
"def",
"replicate_attributes",
"(",
"source",
",",
"target",
",",
"cache",
"=",
"None",
")",
":",
"target_manager",
"=",
"manager_of_class",
"(",
"type",
"(",
"target",
")",
")",
"column_attrs",
"=",
"set",
"(",
")",
"relationship_attrs",
"=",
"set",
"(",
... | Replicates common SQLAlchemy attributes from the `source` object to the
`target` object. | [
"Replicates",
"common",
"SQLAlchemy",
"attributes",
"from",
"the",
"source",
"object",
"to",
"the",
"target",
"object",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/replication.py#L144-L177 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/replication.py | replicate_no_merge | def replicate_no_merge(source, model, cache=None):
'''Replicates the `source` object to `model` class and returns its
reflection.'''
# `cache` is used to break circular dependency: we need to replicate
# attributes before merging target into the session, but replication of
# some attributes may require target to be in session to avoid infinite
# loop.
if source is None:
return None
if cache is None:
cache = {}
elif source in cache:
return cache[source]
db = object_session(source)
cls, ident = identity_key(instance=source)
target = db.query(model).get(ident)
if target is None:
target = model()
cache[source] = target
try:
replicate_attributes(source, target, cache=cache)
except _PrimaryKeyIsNull:
return None
else:
return target | python | def replicate_no_merge(source, model, cache=None):
'''Replicates the `source` object to `model` class and returns its
reflection.'''
# `cache` is used to break circular dependency: we need to replicate
# attributes before merging target into the session, but replication of
# some attributes may require target to be in session to avoid infinite
# loop.
if source is None:
return None
if cache is None:
cache = {}
elif source in cache:
return cache[source]
db = object_session(source)
cls, ident = identity_key(instance=source)
target = db.query(model).get(ident)
if target is None:
target = model()
cache[source] = target
try:
replicate_attributes(source, target, cache=cache)
except _PrimaryKeyIsNull:
return None
else:
return target | [
"def",
"replicate_no_merge",
"(",
"source",
",",
"model",
",",
"cache",
"=",
"None",
")",
":",
"# `cache` is used to break circular dependency: we need to replicate",
"# attributes before merging target into the session, but replication of",
"# some attributes may require target to be in... | Replicates the `source` object to `model` class and returns its
reflection. | [
"Replicates",
"the",
"source",
"object",
"to",
"model",
"class",
"and",
"returns",
"its",
"reflection",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/replication.py#L180-L204 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/replication.py | replicate | def replicate(source, model, cache=None):
'''Replicates the `source` object to `model` class and returns its
reflection.'''
target = replicate_no_merge(source, model, cache=cache)
if target is not None:
db = object_session(source)
target = db.merge(target)
return target | python | def replicate(source, model, cache=None):
'''Replicates the `source` object to `model` class and returns its
reflection.'''
target = replicate_no_merge(source, model, cache=cache)
if target is not None:
db = object_session(source)
target = db.merge(target)
return target | [
"def",
"replicate",
"(",
"source",
",",
"model",
",",
"cache",
"=",
"None",
")",
":",
"target",
"=",
"replicate_no_merge",
"(",
"source",
",",
"model",
",",
"cache",
"=",
"cache",
")",
"if",
"target",
"is",
"not",
"None",
":",
"db",
"=",
"object_sessio... | Replicates the `source` object to `model` class and returns its
reflection. | [
"Replicates",
"the",
"source",
"object",
"to",
"model",
"class",
"and",
"returns",
"its",
"reflection",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/replication.py#L207-L214 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/replication.py | replicate_filter | 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
# have to exclude None from the list.
return [target for target in targets if target is not None] | python | 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
# have to exclude None from the list.
return [target for target in targets if target is not None] | [
"def",
"replicate_filter",
"(",
"sources",
",",
"model",
",",
"cache",
"=",
"None",
")",
":",
"targets",
"=",
"[",
"replicate_no_merge",
"(",
"source",
",",
"model",
",",
"cache",
"=",
"cache",
")",
"for",
"source",
"in",
"sources",
"]",
"# Some objects ma... | Replicates the list of objects to other class and returns their
reflections | [
"Replicates",
"the",
"list",
"of",
"objects",
"to",
"other",
"class",
"and",
"returns",
"their",
"reflections"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/replication.py#L217-L224 |
SmartTeleMax/iktomi | iktomi/unstable/db/sqla/replication.py | reflect_filter | 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 available in target DB (not published), so we
# have to exclude None from the list.
return [target for target in targets if target is not None] | python | 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 available in target DB (not published), so we
# have to exclude None from the list.
return [target for target in targets if target is not None] | [
"def",
"reflect_filter",
"(",
"sources",
",",
"model",
",",
"cache",
"=",
"None",
")",
":",
"targets",
"=",
"[",
"reflect",
"(",
"source",
",",
"model",
",",
"cache",
"=",
"cache",
")",
"for",
"source",
"in",
"sources",
"]",
"# Some objects may not be avai... | 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. | [
"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",
"."
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/unstable/db/sqla/replication.py#L227-L234 |
CivicSpleen/ambry | ambry/orm/column.py | Column.valuetype_class | 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.datatype) | python | 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.datatype) | [
"def",
"valuetype_class",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
"import",
"resolve_value_type",
"if",
"self",
".",
"valuetype",
":",
"return",
"resolve_value_type",
"(",
"self",
".",
"valuetype",
")",
"else",
":",
"return",
"resolve_value_typ... | Return the valuetype class, if one is defined, or a built-in type if it isn't | [
"Return",
"the",
"valuetype",
"class",
"if",
"one",
"is",
"defined",
"or",
"a",
"built",
"-",
"in",
"type",
"if",
"it",
"isn",
"t"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L185-L194 |
CivicSpleen/ambry | ambry/orm/column.py | Column.python_type | 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
elif self.datatype:
try:
return self.types[self.datatype][1]
except KeyError:
return resolve_value_type(self.datatype)._pythontype
else:
from ambry.exc import ConfigurationError
raise ConfigurationError("Can't get python_type: neither datatype of valuetype is defined") | python | 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
elif self.datatype:
try:
return self.types[self.datatype][1]
except KeyError:
return resolve_value_type(self.datatype)._pythontype
else:
from ambry.exc import ConfigurationError
raise ConfigurationError("Can't get python_type: neither datatype of valuetype is defined") | [
"def",
"python_type",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
"import",
"resolve_value_type",
"if",
"self",
".",
"valuetype",
"and",
"resolve_value_type",
"(",
"self",
".",
"valuetype",
")",
":",
"return",
"resolve_value_type",
"(",
"self",
"... | Return the python type for the row, possibly getting it from a valuetype reference | [
"Return",
"the",
"python",
"type",
"for",
"the",
"row",
"possibly",
"getting",
"it",
"from",
"a",
"valuetype",
"reference"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L205-L221 |
CivicSpleen/ambry | ambry/orm/column.py | Column.role | 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
if len(vt_code) == 1 or vt_code[1] == '/':
return vt_code[0]
else:
return ''
return role | python | 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
if len(vt_code) == 1 or vt_code[1] == '/':
return vt_code[0]
else:
return ''
return role | [
"def",
"role",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"if",
"not",
"self",
".",
"valuetype_class",
":",
"return",
"''",
"role",
"=",
"self",
".",
"valuetype_class",
".",
"role",
"if",
"role",
"==",
"ROL... | Return the code for the role, measure, dimension or error | [
"Return",
"the",
"code",
"for",
"the",
"role",
"measure",
"dimension",
"or",
"error"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L224-L240 |
CivicSpleen/ambry | ambry/orm/column.py | Column.is_dimension | def is_dimension(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.DIMENSION | python | def is_dimension(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.DIMENSION | [
"def",
"is_dimension",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"return",
"self",
".",
"role",
"==",
"ROLE",
".",
"DIMENSION"
] | Return true if the colum is a dimension | [
"Return",
"true",
"if",
"the",
"colum",
"is",
"a",
"dimension"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L243-L246 |
CivicSpleen/ambry | ambry/orm/column.py | Column.is_measure | def is_measure(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.MEASURE | python | def is_measure(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.MEASURE | [
"def",
"is_measure",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"return",
"self",
".",
"role",
"==",
"ROLE",
".",
"MEASURE"
] | Return true if the colum is a dimension | [
"Return",
"true",
"if",
"the",
"colum",
"is",
"a",
"dimension"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L249-L252 |
CivicSpleen/ambry | ambry/orm/column.py | Column.is_label | def is_label(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.LABEL | python | def is_label(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.LABEL | [
"def",
"is_label",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"return",
"self",
".",
"role",
"==",
"ROLE",
".",
"LABEL"
] | Return true if the colum is a dimension | [
"Return",
"true",
"if",
"the",
"colum",
"is",
"a",
"dimension"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L255-L258 |
CivicSpleen/ambry | ambry/orm/column.py | Column.is_error | def is_error(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.ERROR | python | def is_error(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.ERROR | [
"def",
"is_error",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"return",
"self",
".",
"role",
"==",
"ROLE",
".",
"ERROR"
] | Return true if the colum is a dimension | [
"Return",
"true",
"if",
"the",
"colum",
"is",
"a",
"dimension"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L261-L264 |
CivicSpleen/ambry | ambry/orm/column.py | Column.children | 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 | 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 | [
"def",
"children",
"(",
"self",
")",
":",
"for",
"c",
"in",
"self",
".",
"table",
".",
"columns",
":",
"if",
"c",
".",
"parent",
"==",
"self",
".",
"name",
"and",
"not",
"c",
".",
"valuetype_class",
".",
"is_label",
"(",
")",
":",
"yield",
"c"
] | Return the table's other column that have this column as a parent, excluding labels | [
"Return",
"the",
"table",
"s",
"other",
"column",
"that",
"have",
"this",
"column",
"as",
"a",
"parent",
"excluding",
"labels"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L278-L282 |
CivicSpleen/ambry | ambry/orm/column.py | Column.label | 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():
return c
return None | python | 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():
return c
return None | [
"def",
"label",
"(",
"self",
")",
":",
"if",
"self",
".",
"valuetype_class",
".",
"is_label",
"(",
")",
":",
"return",
"self",
"for",
"c",
"in",
"self",
".",
"table",
".",
"columns",
":",
"if",
"c",
".",
"parent",
"==",
"self",
".",
"name",
"and",
... | Return first child of the column that is marked as a label. Returns self if the column is a label | [
"Return",
"first",
"child",
"of",
"the",
"column",
"that",
"is",
"marked",
"as",
"a",
"label",
".",
"Returns",
"self",
"if",
"the",
"column",
"is",
"a",
"label"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L285-L295 |
CivicSpleen/ambry | ambry/orm/column.py | Column.geoid | 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 | 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 | [
"def",
"geoid",
"(",
"self",
")",
":",
"if",
"self",
".",
"valuetype_class",
".",
"is_geoid",
"(",
")",
":",
"return",
"self",
"for",
"c",
"in",
"self",
".",
"table",
".",
"columns",
":",
"if",
"c",
".",
"parent",
"==",
"self",
".",
"name",
"and",
... | Return first child of the column, or self that is marked as a geographic identifier | [
"Return",
"first",
"child",
"of",
"the",
"column",
"or",
"self",
"that",
"is",
"marked",
"as",
"a",
"geographic",
"identifier"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L308-L316 |
CivicSpleen/ambry | ambry/orm/column.py | Column.python_cast | 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:
dt = dt.time()
if not isinstance(dt, self.python_type):
raise TypeError('{} was parsed to {}, expected {}'.format(v, type(dt), self.python_type))
return dt
else:
# This isn't calling the python_type method -- it's getting a python type, then instantialting it,
# such as "int(v)"
return self.python_type(v) | python | 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:
dt = dt.time()
if not isinstance(dt, self.python_type):
raise TypeError('{} was parsed to {}, expected {}'.format(v, type(dt), self.python_type))
return dt
else:
# This isn't calling the python_type method -- it's getting a python type, then instantialting it,
# such as "int(v)"
return self.python_type(v) | [
"def",
"python_cast",
"(",
"self",
",",
"v",
")",
":",
"if",
"self",
".",
"type_is_time",
"(",
")",
":",
"dt",
"=",
"dateutil",
".",
"parser",
".",
"parse",
"(",
"v",
")",
"if",
"self",
".",
"datatype",
"==",
"Column",
".",
"DATATYPE_TIME",
":",
"d... | Cast a value to the type of the column.
Primarily used to check that a value is valid; it will throw an
exception otherwise | [
"Cast",
"a",
"value",
"to",
"the",
"type",
"of",
"the",
"column",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L318-L338 |
CivicSpleen/ambry | ambry/orm/column.py | Column.convert_numpy_type | 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,
'object': cls.DATATYPE_TEXT # Hack. Pandas makes strings into object.
}
t = m.get(dtype.name, None)
if not t:
raise TypeError(
"Failed to convert numpy type: '{}' ".format(
dtype.name))
return t | python | 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,
'object': cls.DATATYPE_TEXT # Hack. Pandas makes strings into object.
}
t = m.get(dtype.name, None)
if not t:
raise TypeError(
"Failed to convert numpy type: '{}' ".format(
dtype.name))
return t | [
"def",
"convert_numpy_type",
"(",
"cls",
",",
"dtype",
")",
":",
"m",
"=",
"{",
"'int64'",
":",
"cls",
".",
"DATATYPE_INTEGER64",
",",
"'float64'",
":",
"cls",
".",
"DATATYPE_FLOAT",
",",
"'object'",
":",
"cls",
".",
"DATATYPE_TEXT",
"# Hack. Pandas makes stri... | Convert a numpy dtype into a Column datatype. Only handles common
types.
Implemented as a function to decouple from numpy | [
"Convert",
"a",
"numpy",
"dtype",
"into",
"a",
"Column",
"datatype",
".",
"Only",
"handles",
"common",
"types",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L352-L373 |
CivicSpleen/ambry | ambry/orm/column.py | Column.dict | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs
if p.key not in ('table', 'stats', '_codes', 'data')}
if not d:
raise Exception(self.__dict__)
d['schema_type'] = self.schema_type
if self.data:
# Copy data fields into top level dict, but don't overwrite existind values.
for k, v in six.iteritems(self.data):
if k not in d and k not in ('table', 'stats', '_codes', 'data'):
d[k] = v
return d | python | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
d = {p.key: getattr(self, p.key) for p in self.__mapper__.attrs
if p.key not in ('table', 'stats', '_codes', 'data')}
if not d:
raise Exception(self.__dict__)
d['schema_type'] = self.schema_type
if self.data:
# Copy data fields into top level dict, but don't overwrite existind values.
for k, v in six.iteritems(self.data):
if k not in d and k not in ('table', 'stats', '_codes', 'data'):
d[k] = v
return d | [
"def",
"dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"p",
".",
"key",
":",
"getattr",
"(",
"self",
",",
"p",
".",
"key",
")",
"for",
"p",
"in",
"self",
".",
"__mapper__",
".",
"attrs",
"if",
"p",
".",
"key",
"not",
"in",
"(",
"'table'",
",",
... | A dict that holds key/values for all of the properties in the
object.
:return: | [
"A",
"dict",
"that",
"holds",
"key",
"/",
"values",
"for",
"all",
"of",
"the",
"properties",
"in",
"the",
"object",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L411-L432 |
CivicSpleen/ambry | ambry/orm/column.py | Column.nonull_dict | 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 | 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'} | [
"def",
"nonull_dict",
"(",
"self",
")",
":",
"return",
"{",
"k",
":",
"v",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"self",
".",
"dict",
")",
"if",
"v",
"and",
"k",
"!=",
"'_codes'",
"}"
] | Like dict, but does not hold any null values.
:return: | [
"Like",
"dict",
"but",
"does",
"not",
"hold",
"any",
"null",
"values",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L435-L441 |
CivicSpleen/ambry | ambry/orm/column.py | Column.mangle_name | 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:
raise TypeError(
'Trying to mangle name with invalid type of: ' + str(type(name))) | python | 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:
raise TypeError(
'Trying to mangle name with invalid type of: ' + str(type(name))) | [
"def",
"mangle_name",
"(",
"name",
")",
":",
"import",
"re",
"try",
":",
"return",
"re",
".",
"sub",
"(",
"'_+'",
",",
"'_'",
",",
"re",
".",
"sub",
"(",
"'[^\\w_]'",
",",
"'_'",
",",
"name",
")",
".",
"lower",
"(",
")",
")",
".",
"rstrip",
"("... | Mangles a column name to a standard form, remoing illegal
characters.
:param name:
:return: | [
"Mangles",
"a",
"column",
"name",
"to",
"a",
"standard",
"form",
"remoing",
"illegal",
"characters",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L444-L457 |
CivicSpleen/ambry | ambry/orm/column.py | Column.reverse_code_map | def reverse_code_map(self):
"""Return a map from a code ( usually a string ) to the shorter numeric value"""
return {c.value: (c.ikey if c.ikey else c.key) for c in self.codes} | python | def reverse_code_map(self):
"""Return a map from a code ( usually a string ) to the shorter numeric value"""
return {c.value: (c.ikey if c.ikey else c.key) for c in self.codes} | [
"def",
"reverse_code_map",
"(",
"self",
")",
":",
"return",
"{",
"c",
".",
"value",
":",
"(",
"c",
".",
"ikey",
"if",
"c",
".",
"ikey",
"else",
"c",
".",
"key",
")",
"for",
"c",
"in",
"self",
".",
"codes",
"}"
] | Return a map from a code ( usually a string ) to the shorter numeric value | [
"Return",
"a",
"map",
"from",
"a",
"code",
"(",
"usually",
"a",
"string",
")",
"to",
"the",
"shorter",
"numeric",
"value"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L461-L464 |
CivicSpleen/ambry | ambry/orm/column.py | Column.expanded_transform | 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:
segments = [self.make_xform_seg(datatype=self.valuetype_class, column=self)]
# If we want to add the find datatype cast to a transform.
#segments.append(self.make_xform_seg(transforms=["cast_"+self.datatype], column=self))
return segments | python | 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:
segments = [self.make_xform_seg(datatype=self.valuetype_class, column=self)]
# If we want to add the find datatype cast to a transform.
#segments.append(self.make_xform_seg(transforms=["cast_"+self.datatype], column=self))
return segments | [
"def",
"expanded_transform",
"(",
"self",
")",
":",
"segments",
"=",
"self",
".",
"_expand_transform",
"(",
"self",
".",
"transform",
")",
"if",
"segments",
":",
"segments",
"[",
"0",
"]",
"[",
"'datatype'",
"]",
"=",
"self",
".",
"valuetype_class",
"for",... | Expands the transform string into segments | [
"Expands",
"the",
"transform",
"string",
"into",
"segments"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L567-L586 |
CivicSpleen/ambry | ambry/orm/column.py | Column.before_insert | 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
if target.sequence_id is None:
from ambry.orm.exc import DatabaseError
raise DatabaseError('Must have sequence_id before insertion')
# Check that the id column is always sequence id 1
assert (target.name == 'id') == (target.sequence_id == 1), (target.name, target.sequence_id)
Column.before_update(mapper, conn, target) | python | 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
if target.sequence_id is None:
from ambry.orm.exc import DatabaseError
raise DatabaseError('Must have sequence_id before insertion')
# Check that the id column is always sequence id 1
assert (target.name == 'id') == (target.sequence_id == 1), (target.name, target.sequence_id)
Column.before_update(mapper, conn, target) | [
"def",
"before_insert",
"(",
"mapper",
",",
"conn",
",",
"target",
")",
":",
"# from identity import ObjectNumber",
"# assert not target.fk_vid or not ObjectNumber.parse(target.fk_vid).revision",
"if",
"target",
".",
"sequence_id",
"is",
"None",
":",
"from",
"ambry",
".",
... | event.listen method for Sqlalchemy to set the seqience_id for this
object and create an ObjectNumber value for the id_ | [
"event",
".",
"listen",
"method",
"for",
"Sqlalchemy",
"to",
"set",
"the",
"seqience_id",
"for",
"this",
"object",
"and",
"create",
"an",
"ObjectNumber",
"value",
"for",
"the",
"id_"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L653-L667 |
CivicSpleen/ambry | ambry/orm/column.py | Column.before_update | 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 | 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) | [
"def",
"before_update",
"(",
"mapper",
",",
"conn",
",",
"target",
")",
":",
"assert",
"target",
".",
"datatype",
"or",
"target",
".",
"valuetype",
"target",
".",
"name",
"=",
"Column",
".",
"mangle_name",
"(",
"target",
".",
"name",
")",
"Column",
".",
... | Set the column id number based on the table number and the sequence
id for the column. | [
"Set",
"the",
"column",
"id",
"number",
"based",
"on",
"the",
"table",
"number",
"and",
"the",
"sequence",
"id",
"for",
"the",
"column",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/column.py#L670-L678 |
twisted/epsilon | epsilon/process.py | spawnProcess | 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 iterable. This should be
of strings naming packages the subprocess is to be able to
import.
"""
env = env.copy()
pythonpath = []
for pkg in packages:
p = os.path.split(imp.find_module(pkg)[1])[0]
if p.startswith(os.path.join(sys.prefix, 'lib')):
continue
pythonpath.append(p)
pythonpath = list(set(pythonpath))
pythonpath.extend(env.get('PYTHONPATH', '').split(os.pathsep))
env['PYTHONPATH'] = os.pathsep.join(pythonpath)
return reactor.spawnProcess(processProtocol, executable, args,
env, path, uid, gid, usePTY) | python | 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 iterable. This should be
of strings naming packages the subprocess is to be able to
import.
"""
env = env.copy()
pythonpath = []
for pkg in packages:
p = os.path.split(imp.find_module(pkg)[1])[0]
if p.startswith(os.path.join(sys.prefix, 'lib')):
continue
pythonpath.append(p)
pythonpath = list(set(pythonpath))
pythonpath.extend(env.get('PYTHONPATH', '').split(os.pathsep))
env['PYTHONPATH'] = os.pathsep.join(pythonpath)
return reactor.spawnProcess(processProtocol, executable, args,
env, path, uid, gid, usePTY) | [
"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 iterable. This should be
of strings naming packages the subprocess is to be able to
import. | [
"Launch",
"a",
"process",
"with",
"a",
"particular",
"Python",
"environment",
"."
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/process.py#L19-L43 |
twisted/epsilon | epsilon/process.py | spawnPythonProcess | 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(processProtocol, sys.executable,
args, env, path, uid, gid, usePTY,
packages) | python | 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(processProtocol, sys.executable,
args, env, path, uid, gid, usePTY,
packages) | [
"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. | [
"Launch",
"a",
"Python",
"process"
] | train | https://github.com/twisted/epsilon/blob/e85fa985a41983ef06e1d3bb26639181e1f78b24/epsilon/process.py#L45-L55 |
CivicSpleen/ambry | ambry/bundle/events.py | _runable_for_event | 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:
return False
return True | python | 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:
return False
return True | [
"def",
"_runable_for_event",
"(",
"f",
",",
"tag",
",",
"stage",
")",
":",
"if",
"not",
"hasattr",
"(",
"f",
",",
"'__ambry_event__'",
")",
":",
"return",
"False",
"f_tag",
",",
"f_stage",
"=",
"f",
".",
"__ambry_event__",
"if",
"stage",
"is",
"None",
... | Loot at the event property for a function to see if it should be run at this stage. | [
"Loot",
"at",
"the",
"event",
"property",
"for",
"a",
"function",
"to",
"see",
"if",
"it",
"should",
"be",
"run",
"at",
"this",
"stage",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/bundle/events.py#L38-L52 |
sailthru/relay | relay/util.py | load_obj_from_path | 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
if it isn't already there. For instance:
load_obj_from_path('module.func', prefix='mypackage')
is the same as
load_obj_from_path('mypackage.module.func')
`ld` (dict) key:value data to pass to the logger if an error occurs
"""
if prefix and not import_path.startswith(prefix):
import_path = '.'.join([prefix, import_path])
log.debug(
'attempting to load a python object from an import path',
extra=dict(import_path=import_path, **ld))
try:
mod = importlib.import_module(import_path)
return mod # yay, we found a module. return it
except:
pass # try to extract an object from a module
try:
path, obj_name = import_path.rsplit('.', 1)
except ValueError:
log_raise(
("import path needs at least 1 period in your import path."
" An example import path is something like: module.obj"),
dict(import_path=import_path, **ld), InvalidImportPath)
try:
mod = importlib.import_module(path)
except ImportError:
newpath = path.replace(prefix, '', 1).lstrip('.')
log.debug(
"Could not load import path. Trying a different one",
extra=dict(oldpath=path, newpath=newpath))
path = newpath
mod = importlib.import_module(path)
try:
obj = getattr(mod, obj_name)
except AttributeError:
log_raise(
("object does not exist in given module."
" Your import path is not"
" properly defined because the given `obj_name` does not exist"),
dict(import_path=path, obj_name=obj_name, **ld),
InvalidImportPath)
return obj | python | 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
if it isn't already there. For instance:
load_obj_from_path('module.func', prefix='mypackage')
is the same as
load_obj_from_path('mypackage.module.func')
`ld` (dict) key:value data to pass to the logger if an error occurs
"""
if prefix and not import_path.startswith(prefix):
import_path = '.'.join([prefix, import_path])
log.debug(
'attempting to load a python object from an import path',
extra=dict(import_path=import_path, **ld))
try:
mod = importlib.import_module(import_path)
return mod # yay, we found a module. return it
except:
pass # try to extract an object from a module
try:
path, obj_name = import_path.rsplit('.', 1)
except ValueError:
log_raise(
("import path needs at least 1 period in your import path."
" An example import path is something like: module.obj"),
dict(import_path=import_path, **ld), InvalidImportPath)
try:
mod = importlib.import_module(path)
except ImportError:
newpath = path.replace(prefix, '', 1).lstrip('.')
log.debug(
"Could not load import path. Trying a different one",
extra=dict(oldpath=path, newpath=newpath))
path = newpath
mod = importlib.import_module(path)
try:
obj = getattr(mod, obj_name)
except AttributeError:
log_raise(
("object does not exist in given module."
" Your import path is not"
" properly defined because the given `obj_name` does not exist"),
dict(import_path=path, obj_name=obj_name, **ld),
InvalidImportPath)
return obj | [
"def",
"load_obj_from_path",
"(",
"import_path",
",",
"prefix",
"=",
"None",
",",
"ld",
"=",
"dict",
"(",
")",
")",
":",
"if",
"prefix",
"and",
"not",
"import_path",
".",
"startswith",
"(",
"prefix",
")",
":",
"import_path",
"=",
"'.'",
".",
"join",
"(... | 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
if it isn't already there. For instance:
load_obj_from_path('module.func', prefix='mypackage')
is the same as
load_obj_from_path('mypackage.module.func')
`ld` (dict) key:value data to pass to the logger if an error occurs | [
"import",
"a",
"python",
"object",
"from",
"an",
"import",
"path"
] | train | https://github.com/sailthru/relay/blob/995209346c6663675d96d0cbff3bb67b9758c8e2/relay/util.py#L16-L67 |
project-ncl/pnc-cli | pnc_cli/swagger_client/models/artifact_rest.py | ArtifactRest.artifact_quality | 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", "TEMPORARY"]
if artifact_quality not in allowed_values:
raise ValueError(
"Invalid value for `artifact_quality` ({0}), must be one of {1}"
.format(artifact_quality, allowed_values)
)
self._artifact_quality = artifact_quality | python | 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", "TEMPORARY"]
if artifact_quality not in allowed_values:
raise ValueError(
"Invalid value for `artifact_quality` ({0}), must be one of {1}"
.format(artifact_quality, allowed_values)
)
self._artifact_quality = artifact_quality | [
"def",
"artifact_quality",
"(",
"self",
",",
"artifact_quality",
")",
":",
"allowed_values",
"=",
"[",
"\"NEW\"",
",",
"\"VERIFIED\"",
",",
"\"TESTED\"",
",",
"\"DEPRECATED\"",
",",
"\"BLACKLISTED\"",
",",
"\"DELETED\"",
",",
"\"TEMPORARY\"",
"]",
"if",
"artifact_... | Sets the artifact_quality of this ArtifactRest.
:param artifact_quality: The artifact_quality of this ArtifactRest.
:type: str | [
"Sets",
"the",
"artifact_quality",
"of",
"this",
"ArtifactRest",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/models/artifact_rest.py#L179-L193 |
CivicSpleen/ambry | ambry/orm/source.py | _get_sqlite_columns | 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 type of the column, position is ordinal position of the column.
"""
# TODO: Move to the sqlite wrapper.
# TODO: Consider sqlalchemy mapping.
SQL_TO_PYTHON_TYPES = {
'INT': int,
'INTEGER': int,
'TINYINT': int,
'SMALLINT': int,
'MEDIUMINT': int,
'BIGINT': int,
'UNSIGNED BIG INT': int,
'INT': int,
'INT8': int,
'NUMERIC': float,
'REAL': float,
'FLOAT': float,
'DOUBLE': float,
'BOOLEAN': bool,
'CHARACTER': str,
'VARCHAR': str,
'TEXT': str
}
query = 'PRAGMA table_info(\'{}\');'
result = connection.execute(query.format(table))
ret = []
for row in result:
position = row[0] + 1
name = row[1]
datatype = row[2]
try:
datatype = SQL_TO_PYTHON_TYPES[datatype]
except KeyError:
raise Exception(
'Do not know how to convert {} sql datatype to python data type.'
.format(datatype))
ret.append((name, datatype, position))
return ret | python | 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 type of the column, position is ordinal position of the column.
"""
# TODO: Move to the sqlite wrapper.
# TODO: Consider sqlalchemy mapping.
SQL_TO_PYTHON_TYPES = {
'INT': int,
'INTEGER': int,
'TINYINT': int,
'SMALLINT': int,
'MEDIUMINT': int,
'BIGINT': int,
'UNSIGNED BIG INT': int,
'INT': int,
'INT8': int,
'NUMERIC': float,
'REAL': float,
'FLOAT': float,
'DOUBLE': float,
'BOOLEAN': bool,
'CHARACTER': str,
'VARCHAR': str,
'TEXT': str
}
query = 'PRAGMA table_info(\'{}\');'
result = connection.execute(query.format(table))
ret = []
for row in result:
position = row[0] + 1
name = row[1]
datatype = row[2]
try:
datatype = SQL_TO_PYTHON_TYPES[datatype]
except KeyError:
raise Exception(
'Do not know how to convert {} sql datatype to python data type.'
.format(datatype))
ret.append((name, datatype, position))
return ret | [
"def",
"_get_sqlite_columns",
"(",
"connection",
",",
"table",
")",
":",
"# TODO: Move to the sqlite wrapper.",
"# TODO: Consider sqlalchemy mapping.",
"SQL_TO_PYTHON_TYPES",
"=",
"{",
"'INT'",
":",
"int",
",",
"'INTEGER'",
":",
"int",
",",
"'TINYINT'",
":",
"int",
",... | 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 type of the column, position is ordinal position of the column. | [
"Returns",
"list",
"of",
"tuple",
"containg",
"columns",
"of",
"the",
"table",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L441-L489 |
CivicSpleen/ambry | ambry/orm/source.py | DataSourceBase.partition | 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 | 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) | [
"def",
"partition",
"(",
"self",
")",
":",
"if",
"self",
".",
"urltype",
"!=",
"'partition'",
":",
"return",
"None",
"return",
"self",
".",
"_bundle",
".",
"library",
".",
"partition",
"(",
"self",
".",
"url",
")"
] | For partition urltypes, return the partition specified by the ref | [
"For",
"partition",
"urltypes",
"return",
"the",
"partition",
"specified",
"by",
"the",
"ref"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L161-L167 |
CivicSpleen/ambry | ambry/orm/source.py | DataSourceBase.datafile | def datafile(self):
"""Return an MPR datafile from the /ingest directory of the build filesystem"""
from ambry_sources import MPRowsFile
if self._datafile is None:
if self.urltype == 'partition':
self._datafile = self.partition.datafile
else:
self._datafile = MPRowsFile(self._bundle.build_ingest_fs, self.name)
return self._datafile | python | def datafile(self):
"""Return an MPR datafile from the /ingest directory of the build filesystem"""
from ambry_sources import MPRowsFile
if self._datafile is None:
if self.urltype == 'partition':
self._datafile = self.partition.datafile
else:
self._datafile = MPRowsFile(self._bundle.build_ingest_fs, self.name)
return self._datafile | [
"def",
"datafile",
"(",
"self",
")",
":",
"from",
"ambry_sources",
"import",
"MPRowsFile",
"if",
"self",
".",
"_datafile",
"is",
"None",
":",
"if",
"self",
".",
"urltype",
"==",
"'partition'",
":",
"self",
".",
"_datafile",
"=",
"self",
".",
"partition",
... | Return an MPR datafile from the /ingest directory of the build filesystem | [
"Return",
"an",
"MPR",
"datafile",
"from",
"the",
"/",
"ingest",
"directory",
"of",
"the",
"build",
"filesystem"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L170-L180 |
CivicSpleen/ambry | ambry/orm/source.py | DataSourceBase.spec | 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 | 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) | [
"def",
"spec",
"(",
"self",
")",
":",
"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 a SourceSpec to describe this source | [
"Return",
"a",
"SourceSpec",
"to",
"describe",
"this",
"source"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L183-L192 |
CivicSpleen/ambry | ambry/orm/source.py | DataSourceBase.account | 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 | 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']) | [
"def",
"account",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"util",
"import",
"parse_url_to_dict",
"d",
"=",
"parse_url_to_dict",
"(",
"self",
".",
"url",
")",
"return",
"self",
".",
"_bundle",
".",
"library",
".",
"account",
"(",
"d",
"[",
"'netloc'"... | Return an account record, based on the host in the url | [
"Return",
"an",
"account",
"record",
"based",
"on",
"the",
"host",
"in",
"the",
"url"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L195-L201 |
CivicSpleen/ambry | ambry/orm/source.py | DataSourceBase.update_table | 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_id, source_header=c.name, dest_header=c.name,
datatype=c.datatype, description = c.description)
elif self.datafile.exists:
with self.datafile.reader as r:
names = set()
for col in r.columns:
name = col['name']
if name in names: # Handle duplicate names.
name = name+"_"+str(col['pos'])
names.add(name)
c = st.column(name)
dt = col['resolved_type'] if col['resolved_type'] != 'unknown' else unknown_type
if c:
c.datatype = TypeIntuiter.promote_type(c.datatype, col['resolved_type'])
else:
c = st.add_column(col['pos'],
source_header=name,
dest_header=name,
datatype=col['resolved_type'],
description=col['description'],
has_codes=col['has_codes']) | python | 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_id, source_header=c.name, dest_header=c.name,
datatype=c.datatype, description = c.description)
elif self.datafile.exists:
with self.datafile.reader as r:
names = set()
for col in r.columns:
name = col['name']
if name in names: # Handle duplicate names.
name = name+"_"+str(col['pos'])
names.add(name)
c = st.column(name)
dt = col['resolved_type'] if col['resolved_type'] != 'unknown' else unknown_type
if c:
c.datatype = TypeIntuiter.promote_type(c.datatype, col['resolved_type'])
else:
c = st.add_column(col['pos'],
source_header=name,
dest_header=name,
datatype=col['resolved_type'],
description=col['description'],
has_codes=col['has_codes']) | [
"def",
"update_table",
"(",
"self",
",",
"unknown_type",
"=",
"'str'",
")",
":",
"from",
"ambry_sources",
".",
"intuit",
"import",
"TypeIntuiter",
"st",
"=",
"self",
".",
"source_table",
"if",
"self",
".",
"reftype",
"==",
"'partition'",
":",
"for",
"c",
"... | Update the source table from the datafile | [
"Update",
"the",
"source",
"table",
"from",
"the",
"datafile"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L271-L310 |
CivicSpleen/ambry | ambry/orm/source.py | DataSourceBase.update_spec | 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']
self.comment_lines = r.info['comment_rows']
self.start_line = r.info['data_start_row']
self.end_line = r.info['data_end_row'] | python | 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']
self.comment_lines = r.info['comment_rows']
self.start_line = r.info['data_start_row']
self.end_line = r.info['data_end_row'] | [
"def",
"update_spec",
"(",
"self",
")",
":",
"if",
"self",
".",
"datafile",
".",
"exists",
":",
"with",
"self",
".",
"datafile",
".",
"reader",
"as",
"r",
":",
"self",
".",
"header_lines",
"=",
"r",
".",
"info",
"[",
"'header_rows'",
"]",
"self",
"."... | Update the source specification with information from the row intuiter, but only if the spec values
are not already set. | [
"Update",
"the",
"source",
"specification",
"with",
"information",
"from",
"the",
"row",
"intuiter",
"but",
"only",
"if",
"the",
"spec",
"values",
"are",
"not",
"already",
"set",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L312-L322 |
CivicSpleen/ambry | ambry/orm/source.py | TransientDataSource.dict | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
SKIP_KEYS = ('_source_table', '_dest_table', 'd_vid', 't_vid', 'st_id',
'dataset', 'hash', 'process_records')
return OrderedDict([(k, getattr(self, k)) for k in self.properties if k not in SKIP_KEYS]) | python | def dict(self):
"""A dict that holds key/values for all of the properties in the
object.
:return:
"""
SKIP_KEYS = ('_source_table', '_dest_table', 'd_vid', 't_vid', 'st_id',
'dataset', 'hash', 'process_records')
return OrderedDict([(k, getattr(self, k)) for k in self.properties if k not in SKIP_KEYS]) | [
"def",
"dict",
"(",
"self",
")",
":",
"SKIP_KEYS",
"=",
"(",
"'_source_table'",
",",
"'_dest_table'",
",",
"'d_vid'",
",",
"'t_vid'",
",",
"'st_id'",
",",
"'dataset'",
",",
"'hash'",
",",
"'process_records'",
")",
"return",
"OrderedDict",
"(",
"[",
"(",
"k... | A dict that holds key/values for all of the properties in the
object.
:return: | [
"A",
"dict",
"that",
"holds",
"key",
"/",
"values",
"for",
"all",
"of",
"the",
"properties",
"in",
"the",
"object",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/orm/source.py#L429-L438 |
CivicSpleen/ambry | ambry/run.py | get_runconfig | 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 | 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) | [
"def",
"get_runconfig",
"(",
"path",
"=",
"None",
",",
"root",
"=",
"None",
",",
"db",
"=",
"None",
")",
":",
"return",
"load",
"(",
"path",
",",
"root",
"=",
"root",
",",
"db",
"=",
"db",
")"
] | Load the main configuration files and accounts file.
Debprecated. Use load() | [
"Load",
"the",
"main",
"configuration",
"files",
"and",
"accounts",
"file",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L16-L22 |
CivicSpleen/ambry | ambry/run.py | load | 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:
config.remotes = AttrDict()
for k, v in remotes.remotes.items():
config.remotes[k] = v
accounts = load_accounts(path, load_user=load_user)
# The external file overwrites the main config
if accounts:
if not 'accounts' in config:
config.accounts = AttrDict()
for k, v in accounts.accounts.items():
config.accounts[k] = v
update_config(config)
if root:
config.library.filesystem_root = root
if db:
config.library.database = db
return config | python | 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:
config.remotes = AttrDict()
for k, v in remotes.remotes.items():
config.remotes[k] = v
accounts = load_accounts(path, load_user=load_user)
# The external file overwrites the main config
if accounts:
if not 'accounts' in config:
config.accounts = AttrDict()
for k, v in accounts.accounts.items():
config.accounts[k] = v
update_config(config)
if root:
config.library.filesystem_root = root
if db:
config.library.database = db
return config | [
"def",
"load",
"(",
"path",
"=",
"None",
",",
"root",
"=",
"None",
",",
"db",
"=",
"None",
",",
"load_user",
"=",
"True",
")",
":",
"config",
"=",
"load_config",
"(",
"path",
",",
"load_user",
"=",
"load_user",
")",
"remotes",
"=",
"load_remotes",
"(... | Load all of the config files. | [
"Load",
"all",
"of",
"the",
"config",
"files",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L25-L57 |
CivicSpleen/ambry | ambry/run.py | find_config_file | def find_config_file(file_name, extra_path=None, load_user=True):
"""
Find a configuration file in one of these directories, tried in this order:
- A path provided as an argument
- A path specified by the AMBRY_CONFIG environmenal variable
- ambry in a path specified by the VIRTUAL_ENV environmental variable
- ~/ambry
- /etc/ambry
:param file_name:
:param extra_path:
:param load_user:
:param path:
:return:
"""
paths = []
if extra_path is not None:
paths.append(extra_path)
if os.getenv(ENVAR.CONFIG):
paths.append(os.getenv(ENVAR.CONFIG))
if os.getenv(ENVAR.VIRT):
paths.append(os.path.join(os.getenv(ENVAR.VIRT), USER_DIR))
if load_user:
paths.append(os.path.expanduser('~/' + USER_DIR))
paths.append(ROOT_DIR)
for path in paths:
if os.path.isdir(path) and os.path.exists(os.path.join(path, file_name)):
f = os.path.join(path, file_name)
return f
raise ConfigurationError(
"Failed to find configuration file '{}'. Looked for : {} ".format(file_name, paths)) | python | def find_config_file(file_name, extra_path=None, load_user=True):
"""
Find a configuration file in one of these directories, tried in this order:
- A path provided as an argument
- A path specified by the AMBRY_CONFIG environmenal variable
- ambry in a path specified by the VIRTUAL_ENV environmental variable
- ~/ambry
- /etc/ambry
:param file_name:
:param extra_path:
:param load_user:
:param path:
:return:
"""
paths = []
if extra_path is not None:
paths.append(extra_path)
if os.getenv(ENVAR.CONFIG):
paths.append(os.getenv(ENVAR.CONFIG))
if os.getenv(ENVAR.VIRT):
paths.append(os.path.join(os.getenv(ENVAR.VIRT), USER_DIR))
if load_user:
paths.append(os.path.expanduser('~/' + USER_DIR))
paths.append(ROOT_DIR)
for path in paths:
if os.path.isdir(path) and os.path.exists(os.path.join(path, file_name)):
f = os.path.join(path, file_name)
return f
raise ConfigurationError(
"Failed to find configuration file '{}'. Looked for : {} ".format(file_name, paths)) | [
"def",
"find_config_file",
"(",
"file_name",
",",
"extra_path",
"=",
"None",
",",
"load_user",
"=",
"True",
")",
":",
"paths",
"=",
"[",
"]",
"if",
"extra_path",
"is",
"not",
"None",
":",
"paths",
".",
"append",
"(",
"extra_path",
")",
"if",
"os",
".",... | Find a configuration file in one of these directories, tried in this order:
- A path provided as an argument
- A path specified by the AMBRY_CONFIG environmenal variable
- ambry in a path specified by the VIRTUAL_ENV environmental variable
- ~/ambry
- /etc/ambry
:param file_name:
:param extra_path:
:param load_user:
:param path:
:return: | [
"Find",
"a",
"configuration",
"file",
"in",
"one",
"of",
"these",
"directories",
"tried",
"in",
"this",
"order",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L90-L129 |
CivicSpleen/ambry | ambry/run.py | load_accounts | 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:
accts_file = None
if accts_file is not None and os.path.exists(accts_file):
config = AttrDict()
config.update_yaml(accts_file)
if not 'accounts' in config:
config.remotes = AttrDict()
config.accounts.loaded = [accts_file, getmtime(accts_file)]
return config
else:
return None | python | 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:
accts_file = None
if accts_file is not None and os.path.exists(accts_file):
config = AttrDict()
config.update_yaml(accts_file)
if not 'accounts' in config:
config.remotes = AttrDict()
config.accounts.loaded = [accts_file, getmtime(accts_file)]
return config
else:
return None | [
"def",
"load_accounts",
"(",
"extra_path",
"=",
"None",
",",
"load_user",
"=",
"True",
")",
":",
"from",
"os",
".",
"path",
"import",
"getmtime",
"try",
":",
"accts_file",
"=",
"find_config_file",
"(",
"ACCOUNTS_FILE",
",",
"extra_path",
"=",
"extra_path",
"... | Load the yaml account files
:param load_user:
:return: An `AttrDict` | [
"Load",
"the",
"yaml",
"account",
"files"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L132-L157 |
CivicSpleen/ambry | ambry/run.py | load_remotes | 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, extra_path=extra_path, load_user=load_user)
except ConfigurationError:
remotes_file = None
if remotes_file is not None and os.path.exists(remotes_file):
config = AttrDict()
config.update_yaml(remotes_file)
if not 'remotes' in config:
config.remotes = AttrDict()
config.remotes.loaded = [remotes_file, getmtime(remotes_file)]
return config
else:
return None | python | 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, extra_path=extra_path, load_user=load_user)
except ConfigurationError:
remotes_file = None
if remotes_file is not None and os.path.exists(remotes_file):
config = AttrDict()
config.update_yaml(remotes_file)
if not 'remotes' in config:
config.remotes = AttrDict()
config.remotes.loaded = [remotes_file, getmtime(remotes_file)]
return config
else:
return None | [
"def",
"load_remotes",
"(",
"extra_path",
"=",
"None",
",",
"load_user",
"=",
"True",
")",
":",
"from",
"os",
".",
"path",
"import",
"getmtime",
"try",
":",
"remotes_file",
"=",
"find_config_file",
"(",
"REMOTES_FILE",
",",
"extra_path",
"=",
"extra_path",
"... | 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` | [
"Load",
"the",
"YAML",
"remotes",
"file",
"which",
"sort",
"of",
"combines",
"the",
"Accounts",
"file",
"with",
"part",
"of",
"the",
"remotes",
"sections",
"from",
"the",
"main",
"config"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L160-L186 |
CivicSpleen/ambry | ambry/run.py | load_config | def load_config(path=None, load_user=True):
"""
Load configuration information from a config directory. Tries directories in this order:
- A path provided as an argument
- A path specified by the AMBRY_CONFIG environmenal variable
- ambry in a path specified by the VIRTUAL_ENV environmental variable
- /etc/ambry
- ~/ambry
:param path: An iterable of additional paths to load.
:return: An `AttrDict` of configuration information
"""
from os.path import getmtime
config = AttrDict()
if not path:
path = ROOT_DIR
config_file = find_config_file(CONFIG_FILE, extra_path=path, load_user=load_user)
if os.path.exists(config_file):
config.update_yaml(config_file)
config.loaded = [config_file, getmtime(config_file)]
else:
# Probably never get here, since the find_config_dir would have thrown a ConfigurationError
config = AttrDict()
config.loaded = [None, 0]
return config | python | def load_config(path=None, load_user=True):
"""
Load configuration information from a config directory. Tries directories in this order:
- A path provided as an argument
- A path specified by the AMBRY_CONFIG environmenal variable
- ambry in a path specified by the VIRTUAL_ENV environmental variable
- /etc/ambry
- ~/ambry
:param path: An iterable of additional paths to load.
:return: An `AttrDict` of configuration information
"""
from os.path import getmtime
config = AttrDict()
if not path:
path = ROOT_DIR
config_file = find_config_file(CONFIG_FILE, extra_path=path, load_user=load_user)
if os.path.exists(config_file):
config.update_yaml(config_file)
config.loaded = [config_file, getmtime(config_file)]
else:
# Probably never get here, since the find_config_dir would have thrown a ConfigurationError
config = AttrDict()
config.loaded = [None, 0]
return config | [
"def",
"load_config",
"(",
"path",
"=",
"None",
",",
"load_user",
"=",
"True",
")",
":",
"from",
"os",
".",
"path",
"import",
"getmtime",
"config",
"=",
"AttrDict",
"(",
")",
"if",
"not",
"path",
":",
"path",
"=",
"ROOT_DIR",
"config_file",
"=",
"find_... | Load configuration information from a config directory. Tries directories in this order:
- A path provided as an argument
- A path specified by the AMBRY_CONFIG environmenal variable
- ambry in a path specified by the VIRTUAL_ENV environmental variable
- /etc/ambry
- ~/ambry
:param path: An iterable of additional paths to load.
:return: An `AttrDict` of configuration information | [
"Load",
"configuration",
"information",
"from",
"a",
"config",
"directory",
".",
"Tries",
"directories",
"in",
"this",
"order",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L189-L222 |
CivicSpleen/ambry | ambry/run.py | update_config | def update_config(config, use_environ=True):
"""Update the configuration from environmental variables. Updates:
- config.library.database from the AMBRY_DB environmental variable.
- config.library.filesystem_root from the AMBRY_ROOT environmental variable.
- config.accounts.password from the AMBRY_PASSWORD environmental variable.
:param config: An `attrDict` of configuration information.
"""
from ambry.util import select_from_url
try:
_ = config.library
except KeyError:
config.library = AttrDict()
try:
_ = config.filesystem
except KeyError:
config.filesystem = AttrDict()
try:
_ = config.accounts
except KeyError:
config.accounts = AttrDict()
if not config.accounts.get('loaded'):
config.accounts.loaded = [None, 0]
try:
_ = config.accounts.password
except KeyError:
config.accounts.password = None
try:
_ = config.remotes
except KeyError:
config.remotes = AttrDict() # Default empty
if not config.remotes.get('loaded'):
config.remotes.loaded = [None, 0]
if use_environ:
if os.getenv(ENVAR.DB):
config.library.database = os.getenv(ENVAR.DB)
if os.getenv(ENVAR.ROOT):
config.library.filesystem_root = os.getenv(ENVAR.ROOT)
if os.getenv(ENVAR.PASSWORD):
config.accounts.password = os.getenv(ENVAR.PASSWORD)
# Move any remotes that were configured under the library to the remotes section
try:
for k, v in config.library.remotes.items():
config.remotes[k] = {
'url': v
}
del config.library['remotes']
except KeyError as e:
pass
# Then move any of the account entries that are linked to remotes into the remotes.
try:
for k, v in config.remotes.items():
if 'url' in v:
host = select_from_url(v['url'], 'netloc')
if host in config.accounts:
config.remotes[k].update(config.accounts[host])
del config.accounts[host]
except KeyError:
pass
# Set a default for the library database
try:
_ = config.library.database
except KeyError:
config.library.database = 'sqlite:///{root}/library.db'
# Raise exceptions on missing items
checks = [
'config.library.filesystem_root',
]
for check in checks:
try:
_ = eval(check)
except KeyError:
raise ConfigurationError("Configuration is missing '{}'; loaded from {} "
.format(check, config.loaded[0]))
_, config.library.database = normalize_dsn_or_dict(config.library.database)
for k, v in filesystem_defaults.items():
if k not in config.filesystem:
config.filesystem[k] = v
config.modtime = max(config.loaded[1], config.remotes.loaded[1], config.accounts.loaded[1]) | python | def update_config(config, use_environ=True):
"""Update the configuration from environmental variables. Updates:
- config.library.database from the AMBRY_DB environmental variable.
- config.library.filesystem_root from the AMBRY_ROOT environmental variable.
- config.accounts.password from the AMBRY_PASSWORD environmental variable.
:param config: An `attrDict` of configuration information.
"""
from ambry.util import select_from_url
try:
_ = config.library
except KeyError:
config.library = AttrDict()
try:
_ = config.filesystem
except KeyError:
config.filesystem = AttrDict()
try:
_ = config.accounts
except KeyError:
config.accounts = AttrDict()
if not config.accounts.get('loaded'):
config.accounts.loaded = [None, 0]
try:
_ = config.accounts.password
except KeyError:
config.accounts.password = None
try:
_ = config.remotes
except KeyError:
config.remotes = AttrDict() # Default empty
if not config.remotes.get('loaded'):
config.remotes.loaded = [None, 0]
if use_environ:
if os.getenv(ENVAR.DB):
config.library.database = os.getenv(ENVAR.DB)
if os.getenv(ENVAR.ROOT):
config.library.filesystem_root = os.getenv(ENVAR.ROOT)
if os.getenv(ENVAR.PASSWORD):
config.accounts.password = os.getenv(ENVAR.PASSWORD)
# Move any remotes that were configured under the library to the remotes section
try:
for k, v in config.library.remotes.items():
config.remotes[k] = {
'url': v
}
del config.library['remotes']
except KeyError as e:
pass
# Then move any of the account entries that are linked to remotes into the remotes.
try:
for k, v in config.remotes.items():
if 'url' in v:
host = select_from_url(v['url'], 'netloc')
if host in config.accounts:
config.remotes[k].update(config.accounts[host])
del config.accounts[host]
except KeyError:
pass
# Set a default for the library database
try:
_ = config.library.database
except KeyError:
config.library.database = 'sqlite:///{root}/library.db'
# Raise exceptions on missing items
checks = [
'config.library.filesystem_root',
]
for check in checks:
try:
_ = eval(check)
except KeyError:
raise ConfigurationError("Configuration is missing '{}'; loaded from {} "
.format(check, config.loaded[0]))
_, config.library.database = normalize_dsn_or_dict(config.library.database)
for k, v in filesystem_defaults.items():
if k not in config.filesystem:
config.filesystem[k] = v
config.modtime = max(config.loaded[1], config.remotes.loaded[1], config.accounts.loaded[1]) | [
"def",
"update_config",
"(",
"config",
",",
"use_environ",
"=",
"True",
")",
":",
"from",
"ambry",
".",
"util",
"import",
"select_from_url",
"try",
":",
"_",
"=",
"config",
".",
"library",
"except",
"KeyError",
":",
"config",
".",
"library",
"=",
"AttrDict... | Update the configuration from environmental variables. Updates:
- config.library.database from the AMBRY_DB environmental variable.
- config.library.filesystem_root from the AMBRY_ROOT environmental variable.
- config.accounts.password from the AMBRY_PASSWORD environmental variable.
:param config: An `attrDict` of configuration information. | [
"Update",
"the",
"configuration",
"from",
"environmental",
"variables",
".",
"Updates",
":"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L225-L329 |
CivicSpleen/ambry | ambry/run.py | normalize_dsn_or_dict | 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 # Already a real dict
config = d
dsn = None
elif isinstance(d, string_types):
config = None
dsn = d
else:
raise ConfigurationError("Can't deal with database config '{}' type '{}' ".format(d, type(d)))
if dsn:
if dsn.startswith('sqlite') or dsn.startswith('spatialite'):
driver, path = dsn.split(':', 1)
slashes, path = path[:2], path[2:]
if slashes != '//':
raise ConfigurationError("Sqlite DSNs must start with at least 2 slashes")
if len(path) == 1 and path[0] == '/':
raise ConfigurationError("Sqlite DSNs can't have only 3 slashes in path")
if len(path) > 1 and path[0] != '/':
raise ConfigurationError("Sqlite DSNs with a path must have 3 or 4 slashes.")
path = path[1:]
config = dict(
server=None,
username=None,
password=None,
driver=driver,
dbname=path
)
else:
d = parse_url_to_dict(dsn)
config = dict(
server=d['hostname'],
dbname=d['path'].strip('/'),
driver=d['scheme'],
password=d.get('password', None),
username=d.get('username', None)
)
else:
up = d.get('username', '') or ''
if d.get('password'):
up += ':' + d.get('password', '')
if up:
up += '@'
if up and not d.get('server'):
raise ConfigurationError("Can't construct a DSN with a username or password without a hostname")
host_part = up + d.get('server', '') if d.get('server') else ''
if d.get('dbname', False):
path_part = '/' + d.get('dbname')
# if d['driver'] in ('sqlite3', 'sqlite', 'spatialite'):
# path_part = '/' + path_part
else:
path_part = '' # w/ no dbname, Sqlite should use memory, which required 2 slash. Rel dir is 3, abs dir is 4
dsn = '{}://{}{}'.format(d['driver'], host_part, path_part)
return config, dsn | python | 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 # Already a real dict
config = d
dsn = None
elif isinstance(d, string_types):
config = None
dsn = d
else:
raise ConfigurationError("Can't deal with database config '{}' type '{}' ".format(d, type(d)))
if dsn:
if dsn.startswith('sqlite') or dsn.startswith('spatialite'):
driver, path = dsn.split(':', 1)
slashes, path = path[:2], path[2:]
if slashes != '//':
raise ConfigurationError("Sqlite DSNs must start with at least 2 slashes")
if len(path) == 1 and path[0] == '/':
raise ConfigurationError("Sqlite DSNs can't have only 3 slashes in path")
if len(path) > 1 and path[0] != '/':
raise ConfigurationError("Sqlite DSNs with a path must have 3 or 4 slashes.")
path = path[1:]
config = dict(
server=None,
username=None,
password=None,
driver=driver,
dbname=path
)
else:
d = parse_url_to_dict(dsn)
config = dict(
server=d['hostname'],
dbname=d['path'].strip('/'),
driver=d['scheme'],
password=d.get('password', None),
username=d.get('username', None)
)
else:
up = d.get('username', '') or ''
if d.get('password'):
up += ':' + d.get('password', '')
if up:
up += '@'
if up and not d.get('server'):
raise ConfigurationError("Can't construct a DSN with a username or password without a hostname")
host_part = up + d.get('server', '') if d.get('server') else ''
if d.get('dbname', False):
path_part = '/' + d.get('dbname')
# if d['driver'] in ('sqlite3', 'sqlite', 'spatialite'):
# path_part = '/' + path_part
else:
path_part = '' # w/ no dbname, Sqlite should use memory, which required 2 slash. Rel dir is 3, abs dir is 4
dsn = '{}://{}{}'.format(d['driver'], host_part, path_part)
return config, dsn | [
"def",
"normalize_dsn_or_dict",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"dict",
")",
":",
"try",
":",
"# Convert from an AttrDict to a real dict",
"d",
"=",
"d",
".",
"to_dict",
"(",
")",
"except",
"AttributeError",
":",
"pass",
"# Already a rea... | Clean up a database DSN, or dict version of a DSN, returning both the cleaned DSN and dict version | [
"Clean",
"up",
"a",
"database",
"DSN",
"or",
"dict",
"version",
"of",
"a",
"DSN",
"returning",
"both",
"the",
"cleaned",
"DSN",
"and",
"dict",
"version"
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/run.py#L332-L414 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/productversions_api.py | ProductversionsApi.create_new_product_version | def create_new_product_version(self, **kwargs):
"""
Create a new ProductVersion for a Product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_new_product_version(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param ProductVersionRest body:
:return: ProductVersionSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_new_product_version_with_http_info(**kwargs)
else:
(data) = self.create_new_product_version_with_http_info(**kwargs)
return data | python | def create_new_product_version(self, **kwargs):
"""
Create a new ProductVersion for a Product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_new_product_version(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param ProductVersionRest body:
:return: ProductVersionSingleton
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.create_new_product_version_with_http_info(**kwargs)
else:
(data) = self.create_new_product_version_with_http_info(**kwargs)
return data | [
"def",
"create_new_product_version",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"create_new_product_version_with_htt... | Create a new ProductVersion for a Product
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.create_new_product_version(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param ProductVersionRest body:
:return: ProductVersionSingleton
If the method is called asynchronously,
returns the request thread. | [
"Create",
"a",
"new",
"ProductVersion",
"for",
"a",
"Product",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productversions_api.py#L42-L66 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/productversions_api.py | ProductversionsApi.get_build_configuration_sets | def get_build_configuration_sets(self, id, **kwargs):
"""
Gets build configuration sets associated with a product version
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_build_configuration_sets(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Product Version id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationSetPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_build_configuration_sets_with_http_info(id, **kwargs)
else:
(data) = self.get_build_configuration_sets_with_http_info(id, **kwargs)
return data | python | def get_build_configuration_sets(self, id, **kwargs):
"""
Gets build configuration sets associated with a product version
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_build_configuration_sets(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Product Version id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationSetPage
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_build_configuration_sets_with_http_info(id, **kwargs)
else:
(data) = self.get_build_configuration_sets_with_http_info(id, **kwargs)
return data | [
"def",
"get_build_configuration_sets",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"get_build_configur... | Gets build configuration sets associated with a product version
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_build_configuration_sets(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Product Version id (required)
:param int page_index: Page Index
:param int page_size: Pagination size
:param str sort: Sorting RSQL
:param str q: RSQL Query
:return: BuildConfigurationSetPage
If the method is called asynchronously,
returns the request thread. | [
"Gets",
"build",
"configuration",
"sets",
"associated",
"with",
"a",
"product",
"version",
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productversions_api.py#L260-L288 |
project-ncl/pnc-cli | pnc_cli/swagger_client/apis/productversions_api.py | ProductversionsApi.update_build_configuration_sets | def update_build_configuration_sets(self, id, **kwargs):
"""
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_build_configuration_sets(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Product Version id (required)
:param list[BuildConfigurationSetRest] body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_build_configuration_sets_with_http_info(id, **kwargs)
else:
(data) = self.update_build_configuration_sets_with_http_info(id, **kwargs)
return data | python | def update_build_configuration_sets(self, id, **kwargs):
"""
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_build_configuration_sets(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Product Version id (required)
:param list[BuildConfigurationSetRest] body:
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.update_build_configuration_sets_with_http_info(id, **kwargs)
else:
(data) = self.update_build_configuration_sets_with_http_info(id, **kwargs)
return data | [
"def",
"update_build_configuration_sets",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'callback'",
")",
":",
"return",
"self",
".",
"update_build_co... | This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.update_build_configuration_sets(id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param int id: Product Version id (required)
:param list[BuildConfigurationSetRest] body:
:return: None
If the method is called asynchronously,
returns the request thread. | [
"This",
"method",
"makes",
"a",
"synchronous",
"HTTP",
"request",
"by",
"default",
".",
"To",
"make",
"an",
"asynchronous",
"HTTP",
"request",
"please",
"define",
"a",
"callback",
"function",
"to",
"be",
"invoked",
"when",
"receiving",
"the",
"response",
".",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/swagger_client/apis/productversions_api.py#L598-L621 |
project-ncl/pnc-cli | pnc_cli/tools/utils.py | execute_command | 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 | 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 | [
"def",
"execute_command",
"(",
"cmd",
",",
"execute",
",",
"echo",
"=",
"True",
")",
":",
"if",
"execute",
":",
"if",
"echo",
":",
"print",
"(",
"\"Executing: \"",
"+",
"cmd",
")",
"return",
"os",
".",
"system",
"(",
"cmd",
")",
"else",
":",
"print",... | Execute a command in shell or just print it if execute is False | [
"Execute",
"a",
"command",
"in",
"shell",
"or",
"just",
"print",
"it",
"if",
"execute",
"is",
"False"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/utils.py#L20-L28 |
project-ncl/pnc-cli | pnc_cli/tools/utils.py | set_log_level | 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 (lLevel == 'warning'):
loglevel = logging.WARNING
elif (lLevel == 'error'):
loglevel = logging.ERROR
elif (lLevel == 'critical'):
loglevel = logging.CRITICAL
else:
loglevel = logging.DEBUG
unrecognized = True
formatter = logging.Formatter('%(asctime)s %(levelname)s %(filename)s:%(lineno)d/%(funcName)s: %(message)s')
console = logging.StreamHandler()
console.setLevel(loglevel)
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logging.getLogger('').setLevel(loglevel)
#logging.basicConfig(format='%(asctime)s %(levelname)s %(filename)s:%(lineno)d/%(funcName)s: %(message)s', level=loglevel)
if lLevel != 'debug-all':
# lower the loglevel for enumerated packages to avoid unwanted messages
packagesWarning = ["requests.packages.urllib3", "urllib3", "requests_kerberos", "jenkinsapi"]
for package in packagesWarning:
logging.debug("Setting loglevel for %s to WARNING.", package)
logger = logging.getLogger(package)
logger.setLevel(logging.WARNING)
if unrecognized:
logging.warning('Unrecognized log level: %s Log level set to debug', level)
#TODO ref: use external log config
fh = logging.FileHandler('builder.log')
fh.setLevel(loglevel)
fh.setFormatter(formatter)
logging.getLogger('').addHandler(fh) | python | 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 (lLevel == 'warning'):
loglevel = logging.WARNING
elif (lLevel == 'error'):
loglevel = logging.ERROR
elif (lLevel == 'critical'):
loglevel = logging.CRITICAL
else:
loglevel = logging.DEBUG
unrecognized = True
formatter = logging.Formatter('%(asctime)s %(levelname)s %(filename)s:%(lineno)d/%(funcName)s: %(message)s')
console = logging.StreamHandler()
console.setLevel(loglevel)
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
logging.getLogger('').setLevel(loglevel)
#logging.basicConfig(format='%(asctime)s %(levelname)s %(filename)s:%(lineno)d/%(funcName)s: %(message)s', level=loglevel)
if lLevel != 'debug-all':
# lower the loglevel for enumerated packages to avoid unwanted messages
packagesWarning = ["requests.packages.urllib3", "urllib3", "requests_kerberos", "jenkinsapi"]
for package in packagesWarning:
logging.debug("Setting loglevel for %s to WARNING.", package)
logger = logging.getLogger(package)
logger.setLevel(logging.WARNING)
if unrecognized:
logging.warning('Unrecognized log level: %s Log level set to debug', level)
#TODO ref: use external log config
fh = logging.FileHandler('builder.log')
fh.setLevel(loglevel)
fh.setFormatter(formatter)
logging.getLogger('').addHandler(fh) | [
"def",
"set_log_level",
"(",
"level",
")",
":",
"lLevel",
"=",
"level",
".",
"lower",
"(",
")",
"unrecognized",
"=",
"False",
"if",
"(",
"lLevel",
"==",
"'debug-all'",
")",
":",
"loglevel",
"=",
"logging",
".",
"DEBUG",
"elif",
"(",
"lLevel",
"==",
"'d... | Sets the desired log level. | [
"Sets",
"the",
"desired",
"log",
"level",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/utils.py#L30-L71 |
project-ncl/pnc-cli | pnc_cli/tools/utils.py | parse_conf_args | def parse_conf_args(argv):
"""Parse command line options into {section: (option, key)} which can be
used for overlaying on top of config
:param argv: list of argumets to be parsed
:return: Dictionary in the following format: {section: (option, key)}"""
args = {}
for rarg in argv:
if re.match("^--.*", rarg):
arg = rarg.replace('--','', 1)
fsplit = arg.split('=', 1)
if len(fsplit) != 2:
raise Exception(
"Command option '%s' not recognized." % rarg)
rkey, value = fsplit
ssplit = rkey.split('.', 1)
if len(ssplit) != 2 or not ssplit[1]:
raise Exception(
"Command option '%s' not recognized." % rarg)
section, option = ssplit
args[section] = (option, value)
else:
raise Exception(
"Command option '%s' not recognized." % rarg)
return args | python | def parse_conf_args(argv):
"""Parse command line options into {section: (option, key)} which can be
used for overlaying on top of config
:param argv: list of argumets to be parsed
:return: Dictionary in the following format: {section: (option, key)}"""
args = {}
for rarg in argv:
if re.match("^--.*", rarg):
arg = rarg.replace('--','', 1)
fsplit = arg.split('=', 1)
if len(fsplit) != 2:
raise Exception(
"Command option '%s' not recognized." % rarg)
rkey, value = fsplit
ssplit = rkey.split('.', 1)
if len(ssplit) != 2 or not ssplit[1]:
raise Exception(
"Command option '%s' not recognized." % rarg)
section, option = ssplit
args[section] = (option, value)
else:
raise Exception(
"Command option '%s' not recognized." % rarg)
return args | [
"def",
"parse_conf_args",
"(",
"argv",
")",
":",
"args",
"=",
"{",
"}",
"for",
"rarg",
"in",
"argv",
":",
"if",
"re",
".",
"match",
"(",
"\"^--.*\"",
",",
"rarg",
")",
":",
"arg",
"=",
"rarg",
".",
"replace",
"(",
"'--'",
",",
"''",
",",
"1",
"... | Parse command line options into {section: (option, key)} which can be
used for overlaying on top of config
:param argv: list of argumets to be parsed
:return: Dictionary in the following format: {section: (option, key)} | [
"Parse",
"command",
"line",
"options",
"into",
"{",
"section",
":",
"(",
"option",
"key",
")",
"}",
"which",
"can",
"be",
"used",
"for",
"overlaying",
"on",
"top",
"of",
"config"
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/utils.py#L102-L131 |
project-ncl/pnc-cli | pnc_cli/tools/utils.py | required | 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." % field)
else:
return result
return wrappedf
return wrap | python | 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." % field)
else:
return result
return wrappedf
return wrap | [
"def",
"required",
"(",
"field",
")",
":",
"def",
"wrap",
"(",
"f",
")",
":",
"def",
"wrappedf",
"(",
"*",
"args",
")",
":",
"result",
"=",
"f",
"(",
"*",
"args",
")",
"if",
"result",
"is",
"None",
"or",
"result",
"==",
"\"\"",
":",
"raise",
"E... | Decorator that checks if return value is set, if not, raises exception. | [
"Decorator",
"that",
"checks",
"if",
"return",
"value",
"is",
"set",
"if",
"not",
"raises",
"exception",
"."
] | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/utils.py#L144-L157 |
project-ncl/pnc-cli | pnc_cli/tools/utils.py | split_unescape | def split_unescape(s, delim, escape='\\', unescape=True):
"""
>>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo$,bar', ',', '$')
['foo,bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=True)
['foo$', 'bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=False)
['foo$$', 'bar']
>>> split_unescape('foo$', ',', '$', unescape=True)
['foo$']
"""
ret = []
current = []
itr = iter(s)
for ch in itr:
if ch == escape:
try:
# skip the next character; it has been escaped!
if not unescape:
current.append(escape)
current.append(next(itr))
except StopIteration:
if unescape:
current.append(escape)
elif ch == delim:
# split! (add current to the list and reset it)
ret.append(''.join(current))
current = []
else:
current.append(ch)
ret.append(''.join(current))
return ret | python | def split_unescape(s, delim, escape='\\', unescape=True):
"""
>>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo$,bar', ',', '$')
['foo,bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=True)
['foo$', 'bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=False)
['foo$$', 'bar']
>>> split_unescape('foo$', ',', '$', unescape=True)
['foo$']
"""
ret = []
current = []
itr = iter(s)
for ch in itr:
if ch == escape:
try:
# skip the next character; it has been escaped!
if not unescape:
current.append(escape)
current.append(next(itr))
except StopIteration:
if unescape:
current.append(escape)
elif ch == delim:
# split! (add current to the list and reset it)
ret.append(''.join(current))
current = []
else:
current.append(ch)
ret.append(''.join(current))
return ret | [
"def",
"split_unescape",
"(",
"s",
",",
"delim",
",",
"escape",
"=",
"'\\\\'",
",",
"unescape",
"=",
"True",
")",
":",
"ret",
"=",
"[",
"]",
"current",
"=",
"[",
"]",
"itr",
"=",
"iter",
"(",
"s",
")",
"for",
"ch",
"in",
"itr",
":",
"if",
"ch",... | >>> split_unescape('foo,bar', ',')
['foo', 'bar']
>>> split_unescape('foo$,bar', ',', '$')
['foo,bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=True)
['foo$', 'bar']
>>> split_unescape('foo$$,bar', ',', '$', unescape=False)
['foo$$', 'bar']
>>> split_unescape('foo$', ',', '$', unescape=True)
['foo$'] | [
">>>",
"split_unescape",
"(",
"foo",
"bar",
")",
"[",
"foo",
"bar",
"]",
">>>",
"split_unescape",
"(",
"foo$",
"bar",
"$",
")",
"[",
"foo",
"bar",
"]",
">>>",
"split_unescape",
"(",
"foo$$",
"bar",
"$",
"unescape",
"=",
"True",
")",
"[",
"foo$",
"bar... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/tools/utils.py#L164-L197 |
PythonRails/rails | rails/views/jinja.py | JinjaView.render | 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 | 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) | [
"def",
"render",
"(",
"self",
",",
"template_name",
",",
"variables",
"=",
"None",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"{",
"}",
"template",
"=",
"self",
".",
"_engine",
".",
"get_template",
"(",
"template_name",
")",
"retur... | Render a template with the passed variables. | [
"Render",
"a",
"template",
"with",
"the",
"passed",
"variables",
"."
] | train | https://github.com/PythonRails/rails/blob/1e199b9da4da5b24fef39fc6212d71fc9fbb18a5/rails/views/jinja.py#L17-L24 |
PythonRails/rails | rails/views/jinja.py | JinjaView.render_source | 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 | 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) | [
"def",
"render_source",
"(",
"self",
",",
"source",
",",
"variables",
"=",
"None",
")",
":",
"if",
"variables",
"is",
"None",
":",
"variables",
"=",
"{",
"}",
"template",
"=",
"self",
".",
"_engine",
".",
"from_string",
"(",
"source",
")",
"return",
"t... | Render a source with the passed variables. | [
"Render",
"a",
"source",
"with",
"the",
"passed",
"variables",
"."
] | train | https://github.com/PythonRails/rails/blob/1e199b9da4da5b24fef39fc6212d71fc9fbb18a5/rails/views/jinja.py#L26-L33 |
SmartTeleMax/iktomi | iktomi/web/url_templates.py | construct_re | 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 name: [converter name, converter args (str)]},
list of (variable name, converter name, converter args name))
If anonymous=True is set, regexp will be compiled without names of variables.
This is handy for example, if you want to dump an url map to JSON.
'''
# needed for reverse url building (or not needed?)
builder_params = []
# found url params and their converters
url_params = {}
result = r'^'
parts = _split_pattern.split(url_template)
for i, part in enumerate(parts):
is_url_pattern = _static_url_pattern.match(part)
if is_url_pattern:
#NOTE: right order:
# - make part str if it was unicode
# - urlquote part
# - escape all specific for re chars in part
result += re.escape(urlquote(part))
builder_params.append(part)
continue
is_converter = _converter_pattern.match(part)
if is_converter:
groups = is_converter.groupdict()
converter_name = groups['converter'] or default_converter
conv_object = init_converter(converters[converter_name],
groups['args'])
variable = groups['variable']
builder_params.append((variable, conv_object))
url_params[variable] = conv_object
if anonymous:
result += conv_object.regex
else:
result += '(?P<{}>{})'.format(variable, conv_object.regex)
continue
raise ValueError('Incorrect url template {!r}'.format(url_template))
if match_whole_str:
result += '$'
return re.compile(result), url_params, builder_params | python | 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 name: [converter name, converter args (str)]},
list of (variable name, converter name, converter args name))
If anonymous=True is set, regexp will be compiled without names of variables.
This is handy for example, if you want to dump an url map to JSON.
'''
# needed for reverse url building (or not needed?)
builder_params = []
# found url params and their converters
url_params = {}
result = r'^'
parts = _split_pattern.split(url_template)
for i, part in enumerate(parts):
is_url_pattern = _static_url_pattern.match(part)
if is_url_pattern:
#NOTE: right order:
# - make part str if it was unicode
# - urlquote part
# - escape all specific for re chars in part
result += re.escape(urlquote(part))
builder_params.append(part)
continue
is_converter = _converter_pattern.match(part)
if is_converter:
groups = is_converter.groupdict()
converter_name = groups['converter'] or default_converter
conv_object = init_converter(converters[converter_name],
groups['args'])
variable = groups['variable']
builder_params.append((variable, conv_object))
url_params[variable] = conv_object
if anonymous:
result += conv_object.regex
else:
result += '(?P<{}>{})'.format(variable, conv_object.regex)
continue
raise ValueError('Incorrect url template {!r}'.format(url_template))
if match_whole_str:
result += '$'
return re.compile(result), url_params, builder_params | [
"def",
"construct_re",
"(",
"url_template",
",",
"match_whole_str",
"=",
"False",
",",
"converters",
"=",
"None",
",",
"default_converter",
"=",
"'string'",
",",
"anonymous",
"=",
"False",
")",
":",
"# needed for reverse url building (or not needed?)",
"builder_params",... | url_template - str or unicode representing template
Constructed pattern expects urlencoded string!
returns (compiled re pattern,
dict {url param name: [converter name, converter args (str)]},
list of (variable name, converter name, converter args name))
If anonymous=True is set, regexp will be compiled without names of variables.
This is handy for example, if you want to dump an url map to JSON. | [
"url_template",
"-",
"str",
"or",
"unicode",
"representing",
"template"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url_templates.py#L38-L85 |
SmartTeleMax/iktomi | iktomi/web/url_templates.py | UrlTemplate.match | def match(self, path, **kw):
'''
path - str (urlencoded)
'''
m = self._pattern.match(path)
if m:
kwargs = m.groupdict()
# convert params
for url_arg_name, value_urlencoded in kwargs.items():
conv_obj = self._url_params[url_arg_name]
unicode_value = unquote(value_urlencoded)
if isinstance(unicode_value, six.binary_type):
# XXX ??
unicode_value = unicode_value.decode('utf-8', 'replace')
try:
kwargs[url_arg_name] = conv_obj.to_python(unicode_value, **kw)
except ConvertError as err:
logger.debug('ConvertError in parameter "%s" '
'by %r, value "%s"',
url_arg_name,
err.converter.__class__,
err.value)
return None, {}
return m.group(), kwargs
return None, {} | python | def match(self, path, **kw):
'''
path - str (urlencoded)
'''
m = self._pattern.match(path)
if m:
kwargs = m.groupdict()
# convert params
for url_arg_name, value_urlencoded in kwargs.items():
conv_obj = self._url_params[url_arg_name]
unicode_value = unquote(value_urlencoded)
if isinstance(unicode_value, six.binary_type):
# XXX ??
unicode_value = unicode_value.decode('utf-8', 'replace')
try:
kwargs[url_arg_name] = conv_obj.to_python(unicode_value, **kw)
except ConvertError as err:
logger.debug('ConvertError in parameter "%s" '
'by %r, value "%s"',
url_arg_name,
err.converter.__class__,
err.value)
return None, {}
return m.group(), kwargs
return None, {} | [
"def",
"match",
"(",
"self",
",",
"path",
",",
"*",
"*",
"kw",
")",
":",
"m",
"=",
"self",
".",
"_pattern",
".",
"match",
"(",
"path",
")",
"if",
"m",
":",
"kwargs",
"=",
"m",
".",
"groupdict",
"(",
")",
"# convert params",
"for",
"url_arg_name",
... | path - str (urlencoded) | [
"path",
"-",
"str",
"(",
"urlencoded",
")"
] | train | https://github.com/SmartTeleMax/iktomi/blob/80bc0f1408d63efe7f5844367d1f6efba44b35f2/iktomi/web/url_templates.py#L111-L135 |
CivicSpleen/ambry | ambry/exporters/ckan/core.py | export | 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 private (for debugging
purposes).
Raises:
EnvironmentError: if ckan credentials are missing or invalid.
UnpublishedAccessError: if dataset has unpublished access - one from ('internal', 'test',
'controlled', 'restricted', 'census').
"""
if not ckan:
raise EnvironmentError(MISSING_CREDENTIALS_MSG)
# publish dataset.
try:
ckan.action.package_create(**_convert_bundle(bundle))
except ckanapi.ValidationError:
if force:
logger.warning(
'{} dataset already exported, but new export forced. Continue to export dataset stuff.'
.format(bundle.dataset))
else:
raise
# set permissions.
access = bundle.dataset.config.metadata.about.access
if access == 'restricted' and force_restricted:
access = 'private'
assert access, 'CKAN publishing requires access level.'
if access in ('internal', 'controlled', 'restricted', 'census'):
# Never publish dataset with such access.
raise UnpublishedAccessError(
'{} dataset can not be published because of {} access.'
.format(bundle.dataset.vid, bundle.dataset.config.metadata.about.access))
elif access == 'public':
# The default permission of the CKAN allows to edit and create dataset without logging in. But
# admin of the certain CKAN instance can change default permissions.
# http://docs.ckan.org/en/ckan-1.7/authorization.html#anonymous-edit-mode
user_roles = [
{'user': 'visitor', 'domain_object': bundle.dataset.vid.lower(), 'roles': ['editor']},
{'user': 'logged_in', 'domain_object': bundle.dataset.vid.lower(), 'roles': ['editor']},
]
elif access == 'registered':
# Anonymous has no access, logged in users can read/edit.
# http://docs.ckan.org/en/ckan-1.7/authorization.html#logged-in-edit-mode
user_roles = [
{'user': 'visitor', 'domain_object': bundle.dataset.vid.lower(), 'roles': []},
{'user': 'logged_in', 'domain_object': bundle.dataset.vid.lower(), 'roles': ['editor']}
]
elif access in ('private', 'licensed', 'test'):
# Organization users can read/edit
# http://docs.ckan.org/en/ckan-1.7/authorization.html#publisher-mode
# disable access for anonymous and logged_in
user_roles = [
{'user': 'visitor', 'domain_object': bundle.dataset.vid.lower(), 'roles': []},
{'user': 'logged_in', 'domain_object': bundle.dataset.vid.lower(), 'roles': []}
]
organization_users = ckan.action.organization_show(id=CKAN_CONFIG.organization)['users']
for user in organization_users:
user_roles.append({
'user': user['id'], 'domain_object': bundle.dataset.vid.lower(), 'roles': ['editor']}),
for role in user_roles:
# http://docs.ckan.org/en/ckan-2.4.1/api/#ckan.logic.action.update.user_role_update
ckan.action.user_role_update(**role)
# TODO: Using bulk update gives http500 error. Try later with new version.
# http://docs.ckan.org/en/ckan-2.4.1/api/#ckan.logic.action.update.user_role_bulk_update - the same
# ckan.action.user_role_bulk_update(user_roles=user_roles)
# publish partitions
for partition in bundle.partitions:
ckan.action.resource_create(**_convert_partition(partition))
# publish schema.csv
ckan.action.resource_create(**_convert_schema(bundle))
# publish external documentation
for name, external in six.iteritems(bundle.dataset.config.metadata.external_documentation):
ckan.action.resource_create(**_convert_external(bundle, name, external)) | python | 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 private (for debugging
purposes).
Raises:
EnvironmentError: if ckan credentials are missing or invalid.
UnpublishedAccessError: if dataset has unpublished access - one from ('internal', 'test',
'controlled', 'restricted', 'census').
"""
if not ckan:
raise EnvironmentError(MISSING_CREDENTIALS_MSG)
# publish dataset.
try:
ckan.action.package_create(**_convert_bundle(bundle))
except ckanapi.ValidationError:
if force:
logger.warning(
'{} dataset already exported, but new export forced. Continue to export dataset stuff.'
.format(bundle.dataset))
else:
raise
# set permissions.
access = bundle.dataset.config.metadata.about.access
if access == 'restricted' and force_restricted:
access = 'private'
assert access, 'CKAN publishing requires access level.'
if access in ('internal', 'controlled', 'restricted', 'census'):
# Never publish dataset with such access.
raise UnpublishedAccessError(
'{} dataset can not be published because of {} access.'
.format(bundle.dataset.vid, bundle.dataset.config.metadata.about.access))
elif access == 'public':
# The default permission of the CKAN allows to edit and create dataset without logging in. But
# admin of the certain CKAN instance can change default permissions.
# http://docs.ckan.org/en/ckan-1.7/authorization.html#anonymous-edit-mode
user_roles = [
{'user': 'visitor', 'domain_object': bundle.dataset.vid.lower(), 'roles': ['editor']},
{'user': 'logged_in', 'domain_object': bundle.dataset.vid.lower(), 'roles': ['editor']},
]
elif access == 'registered':
# Anonymous has no access, logged in users can read/edit.
# http://docs.ckan.org/en/ckan-1.7/authorization.html#logged-in-edit-mode
user_roles = [
{'user': 'visitor', 'domain_object': bundle.dataset.vid.lower(), 'roles': []},
{'user': 'logged_in', 'domain_object': bundle.dataset.vid.lower(), 'roles': ['editor']}
]
elif access in ('private', 'licensed', 'test'):
# Organization users can read/edit
# http://docs.ckan.org/en/ckan-1.7/authorization.html#publisher-mode
# disable access for anonymous and logged_in
user_roles = [
{'user': 'visitor', 'domain_object': bundle.dataset.vid.lower(), 'roles': []},
{'user': 'logged_in', 'domain_object': bundle.dataset.vid.lower(), 'roles': []}
]
organization_users = ckan.action.organization_show(id=CKAN_CONFIG.organization)['users']
for user in organization_users:
user_roles.append({
'user': user['id'], 'domain_object': bundle.dataset.vid.lower(), 'roles': ['editor']}),
for role in user_roles:
# http://docs.ckan.org/en/ckan-2.4.1/api/#ckan.logic.action.update.user_role_update
ckan.action.user_role_update(**role)
# TODO: Using bulk update gives http500 error. Try later with new version.
# http://docs.ckan.org/en/ckan-2.4.1/api/#ckan.logic.action.update.user_role_bulk_update - the same
# ckan.action.user_role_bulk_update(user_roles=user_roles)
# publish partitions
for partition in bundle.partitions:
ckan.action.resource_create(**_convert_partition(partition))
# publish schema.csv
ckan.action.resource_create(**_convert_schema(bundle))
# publish external documentation
for name, external in six.iteritems(bundle.dataset.config.metadata.external_documentation):
ckan.action.resource_create(**_convert_external(bundle, name, external)) | [
"def",
"export",
"(",
"bundle",
",",
"force",
"=",
"False",
",",
"force_restricted",
"=",
"False",
")",
":",
"if",
"not",
"ckan",
":",
"raise",
"EnvironmentError",
"(",
"MISSING_CREDENTIALS_MSG",
")",
"# publish dataset.",
"try",
":",
"ckan",
".",
"action",
... | 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 private (for debugging
purposes).
Raises:
EnvironmentError: if ckan credentials are missing or invalid.
UnpublishedAccessError: if dataset has unpublished access - one from ('internal', 'test',
'controlled', 'restricted', 'census'). | [
"Exports",
"bundle",
"to",
"ckan",
"instance",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/exporters/ckan/core.py#L50-L138 |
CivicSpleen/ambry | ambry/exporters/ckan/core.py | is_exported | 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['results']) > 0 | python | 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['results']) > 0 | [
"def",
"is_exported",
"(",
"bundle",
")",
":",
"if",
"not",
"ckan",
":",
"raise",
"EnvironmentError",
"(",
"MISSING_CREDENTIALS_MSG",
")",
"params",
"=",
"{",
"'q'",
":",
"'name:{}'",
".",
"format",
"(",
"bundle",
".",
"dataset",
".",
"vid",
".",
"lower",
... | Returns True if dataset is already exported to CKAN. Otherwise returns False. | [
"Returns",
"True",
"if",
"dataset",
"is",
"already",
"exported",
"to",
"CKAN",
".",
"Otherwise",
"returns",
"False",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/exporters/ckan/core.py#L141-L147 |
CivicSpleen/ambry | ambry/exporters/ckan/core.py | _convert_bundle | 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_create
"""
# shortcut for metadata
meta = bundle.dataset.config.metadata
notes = ''
for f in bundle.dataset.files:
if f.path.endswith('documentation.md'):
contents = f.unpacked_contents
if isinstance(contents, six.binary_type):
contents = contents.decode('utf-8')
notes = json.dumps(contents)
break
ret = {
'name': bundle.dataset.vid.lower(),
'title': meta.about.title,
'author': meta.contacts.wrangler.name,
'author_email': meta.contacts.wrangler.email,
'maintainer': meta.contacts.maintainer.name,
'maintainer_email': meta.contacts.maintainer.email,
'license_id': '',
'notes': notes,
'url': meta.identity.source,
'version': bundle.dataset.version,
'state': 'active',
'owner_org': CKAN_CONFIG['organization'],
}
return ret | python | 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_create
"""
# shortcut for metadata
meta = bundle.dataset.config.metadata
notes = ''
for f in bundle.dataset.files:
if f.path.endswith('documentation.md'):
contents = f.unpacked_contents
if isinstance(contents, six.binary_type):
contents = contents.decode('utf-8')
notes = json.dumps(contents)
break
ret = {
'name': bundle.dataset.vid.lower(),
'title': meta.about.title,
'author': meta.contacts.wrangler.name,
'author_email': meta.contacts.wrangler.email,
'maintainer': meta.contacts.maintainer.name,
'maintainer_email': meta.contacts.maintainer.email,
'license_id': '',
'notes': notes,
'url': meta.identity.source,
'version': bundle.dataset.version,
'state': 'active',
'owner_org': CKAN_CONFIG['organization'],
}
return ret | [
"def",
"_convert_bundle",
"(",
"bundle",
")",
":",
"# shortcut for metadata",
"meta",
"=",
"bundle",
".",
"dataset",
".",
"config",
".",
"metadata",
"notes",
"=",
"''",
"for",
"f",
"in",
"bundle",
".",
"dataset",
".",
"files",
":",
"if",
"f",
".",
"path"... | 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_create | [
"Converts",
"ambry",
"bundle",
"to",
"dict",
"ready",
"to",
"send",
"to",
"CKAN",
"API",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/exporters/ckan/core.py#L150-L188 |
CivicSpleen/ambry | ambry/exporters/ckan/core.py | _convert_partition | 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.headers
if headers:
writer.writerow(headers)
for row in partition:
writer.writerow([row[h] for h in headers])
csvfile.seek(0)
# prepare dict.
ret = {
'package_id': partition.dataset.vid.lower(),
'url': 'http://example.com',
'revision_id': '',
'description': partition.description or '',
'format': 'text/csv',
'hash': '',
'name': partition.name,
'resource_type': '',
'mimetype': 'text/csv',
'mimetype_inner': '',
'webstore_url': '',
'cache_url': '',
'upload': csvfile
}
return ret | python | 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.headers
if headers:
writer.writerow(headers)
for row in partition:
writer.writerow([row[h] for h in headers])
csvfile.seek(0)
# prepare dict.
ret = {
'package_id': partition.dataset.vid.lower(),
'url': 'http://example.com',
'revision_id': '',
'description': partition.description or '',
'format': 'text/csv',
'hash': '',
'name': partition.name,
'resource_type': '',
'mimetype': 'text/csv',
'mimetype_inner': '',
'webstore_url': '',
'cache_url': '',
'upload': csvfile
}
return ret | [
"def",
"_convert_partition",
"(",
"partition",
")",
":",
"# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create",
"# convert bundle to csv.",
"csvfile",
"=",
"six",
".",
"StringIO",
"(",
")",
"writer",
"=",
"unicodecsv",
".",
"writer",
"(",
"csvfile... | Converts partition to resource dict ready to save to CKAN. | [
"Converts",
"partition",
"to",
"resource",
"dict",
"ready",
"to",
"save",
"to",
"CKAN",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/exporters/ckan/core.py#L191-L222 |
CivicSpleen/ambry | ambry/exporters/ckan/core.py | _convert_schema | 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.unpacked_contents
if isinstance(contents, six.binary_type):
contents = contents.decode('utf-8')
schema_csv = six.StringIO(contents)
schema_csv.seek(0)
break
ret = {
'package_id': bundle.dataset.vid.lower(),
'url': 'http://example.com',
'revision_id': '',
'description': 'Schema of the dataset tables.',
'format': 'text/csv',
'hash': '',
'name': 'schema',
'upload': schema_csv,
}
return ret | python | 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.unpacked_contents
if isinstance(contents, six.binary_type):
contents = contents.decode('utf-8')
schema_csv = six.StringIO(contents)
schema_csv.seek(0)
break
ret = {
'package_id': bundle.dataset.vid.lower(),
'url': 'http://example.com',
'revision_id': '',
'description': 'Schema of the dataset tables.',
'format': 'text/csv',
'hash': '',
'name': 'schema',
'upload': schema_csv,
}
return ret | [
"def",
"_convert_schema",
"(",
"bundle",
")",
":",
"# 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",
"(... | Converts schema of the dataset to resource dict ready to save to CKAN. | [
"Converts",
"schema",
"of",
"the",
"dataset",
"to",
"resource",
"dict",
"ready",
"to",
"save",
"to",
"CKAN",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/exporters/ckan/core.py#L225-L249 |
CivicSpleen/ambry | ambry/exporters/ckan/core.py | _convert_external | 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,
'description': external.description,
'name': name,
}
return ret | python | 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,
'description': external.description,
'name': name,
}
return ret | [
"def",
"_convert_external",
"(",
"bundle",
",",
"name",
",",
"external",
")",
":",
"# http://docs.ckan.org/en/latest/api/#ckan.logic.action.create.resource_create",
"ret",
"=",
"{",
"'package_id'",
":",
"bundle",
".",
"dataset",
".",
"vid",
".",
"lower",
"(",
")",
"... | Converts external documentation to resource dict ready to save to CKAN. | [
"Converts",
"external",
"documentation",
"to",
"resource",
"dict",
"ready",
"to",
"save",
"to",
"CKAN",
"."
] | train | https://github.com/CivicSpleen/ambry/blob/d7f2be4bf1f7ffd086f3fadd4fcae60c32473e42/ambry/exporters/ckan/core.py#L252-L262 |
project-ncl/pnc-cli | pnc_cli/bpmbuildconfigurations.py | create_build_configuration_process | def create_build_configuration_process(repository, revision, **kwargs):
"""
Create a new BuildConfiguration. BuildConfigurations represent the settings and configuration required to run a build of a specific version of the associated Project's source code.
If a ProductVersion ID is provided, the BuildConfiguration will have access to artifacts which were produced for that version, but may not have been released yet.
:return BPM Task ID of the new BuildConfiguration creation
"""
if not kwargs.get("dependency_ids"):
kwargs["dependency_ids"] = []
if not kwargs.get("build_configuration_set_ids"):
kwargs["build_configuration_set_ids"] = []
if kwargs.get("generic_parameters"):
kwargs["generic_parameters"] = ast.literal_eval(kwargs.get("generic_parameters"))
if not kwargs.get("project"):
kwargs["project"] = pnc_api.projects.get_specific(kwargs.get("project_id")).content
if not kwargs.get("environment"):
kwargs["environment"] = pnc_api.environments.get_specific(kwargs.get("build_environment_id")).content
build_configuration = create_build_conf_object(scm_revision=revision, **kwargs)
repo_creation = swagger_client.RepositoryCreationUrlAutoRest()
repo_creation.scm_url = repository
repo_creation.build_configuration_rest = build_configuration
response = utils.checked_api_call(
pnc_api.bpm, 'start_r_creation_task_with_single_url', body=repo_creation)
if response:
return response | python | def create_build_configuration_process(repository, revision, **kwargs):
"""
Create a new BuildConfiguration. BuildConfigurations represent the settings and configuration required to run a build of a specific version of the associated Project's source code.
If a ProductVersion ID is provided, the BuildConfiguration will have access to artifacts which were produced for that version, but may not have been released yet.
:return BPM Task ID of the new BuildConfiguration creation
"""
if not kwargs.get("dependency_ids"):
kwargs["dependency_ids"] = []
if not kwargs.get("build_configuration_set_ids"):
kwargs["build_configuration_set_ids"] = []
if kwargs.get("generic_parameters"):
kwargs["generic_parameters"] = ast.literal_eval(kwargs.get("generic_parameters"))
if not kwargs.get("project"):
kwargs["project"] = pnc_api.projects.get_specific(kwargs.get("project_id")).content
if not kwargs.get("environment"):
kwargs["environment"] = pnc_api.environments.get_specific(kwargs.get("build_environment_id")).content
build_configuration = create_build_conf_object(scm_revision=revision, **kwargs)
repo_creation = swagger_client.RepositoryCreationUrlAutoRest()
repo_creation.scm_url = repository
repo_creation.build_configuration_rest = build_configuration
response = utils.checked_api_call(
pnc_api.bpm, 'start_r_creation_task_with_single_url', body=repo_creation)
if response:
return response | [
"def",
"create_build_configuration_process",
"(",
"repository",
",",
"revision",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"kwargs",
".",
"get",
"(",
"\"dependency_ids\"",
")",
":",
"kwargs",
"[",
"\"dependency_ids\"",
"]",
"=",
"[",
"]",
"if",
"not",
... | Create a new BuildConfiguration. BuildConfigurations represent the settings and configuration required to run a build of a specific version of the associated Project's source code.
If a ProductVersion ID is provided, the BuildConfiguration will have access to artifacts which were produced for that version, but may not have been released yet.
:return BPM Task ID of the new BuildConfiguration creation | [
"Create",
"a",
"new",
"BuildConfiguration",
".",
"BuildConfigurations",
"represent",
"the",
"settings",
"and",
"configuration",
"required",
"to",
"run",
"a",
"build",
"of",
"a",
"specific",
"version",
"of",
"the",
"associated",
"Project",
"s",
"source",
"code",
... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/bpmbuildconfigurations.py#L32-L62 |
project-ncl/pnc-cli | pnc_cli/bpmbuildconfigurations.py | create_repository_configuration | def create_repository_configuration(repository, no_sync=False):
"""
Create a new RepositoryConfiguration. If the provided repository URL is for external repository, it is cloned into internal one.
:return BPM Task ID of the new RepositoryConfiguration creation
"""
repo = create_repository_configuration_raw(repository, no_sync)
if repo:
return utils.format_json(repo) | python | def create_repository_configuration(repository, no_sync=False):
"""
Create a new RepositoryConfiguration. If the provided repository URL is for external repository, it is cloned into internal one.
:return BPM Task ID of the new RepositoryConfiguration creation
"""
repo = create_repository_configuration_raw(repository, no_sync)
if repo:
return utils.format_json(repo) | [
"def",
"create_repository_configuration",
"(",
"repository",
",",
"no_sync",
"=",
"False",
")",
":",
"repo",
"=",
"create_repository_configuration_raw",
"(",
"repository",
",",
"no_sync",
")",
"if",
"repo",
":",
"return",
"utils",
".",
"format_json",
"(",
"repo",
... | Create a new RepositoryConfiguration. If the provided repository URL is for external repository, it is cloned into internal one.
:return BPM Task ID of the new RepositoryConfiguration creation | [
"Create",
"a",
"new",
"RepositoryConfiguration",
".",
"If",
"the",
"provided",
"repository",
"URL",
"is",
"for",
"external",
"repository",
"it",
"is",
"cloned",
"into",
"internal",
"one",
".",
":",
"return",
"BPM",
"Task",
"ID",
"of",
"the",
"new",
"Reposito... | train | https://github.com/project-ncl/pnc-cli/blob/3dc149bf84928f60a8044ac50b58bbaddd451902/pnc_cli/bpmbuildconfigurations.py#L67-L74 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.