text stringlengths 81 112k |
|---|
Convert coordintes from TWD97 to WGS84
The east and north coordinates should be in meters and in float
pkm true for Penghu, Kinmen and Matsu area
You can specify one of the following presentations of the returned values:
dms - A tuple with degrees (int), minutes (int) and seconds (float)
dm... |
Convert coordintes from WGS84 to TWD97
pkm true for Penghu, Kinmen and Matsu area
The latitude and longitude can be in the following formats:
[+/-]DDD°MMM'SSS.SSSS" (unicode)
[+/-]DDD°MMM.MMMM' (unicode)
[+/-]DDD.DDDDD (string, unicode or float)
The returned coordinates are in meter... |
Makes sure that value is within a specific range.
If not, then the lower or upper bounds is returned
def clipValue(self, value, minValue, maxValue):
'''
Makes sure that value is within a specific range.
If not, then the lower or upper bounds is returned
'''
return min(ma... |
returns the ground resolution for based on latitude and zoom level.
def getGroundResolution(self, latitude, level):
'''
returns the ground resolution for based on latitude and zoom level.
'''
latitude = self.clipValue(latitude, self.min_lat, self.max_lat);
mapSize = self.getMapD... |
returns the map scale on the dpi of the screen
def getMapScale(self, latitude, level, dpi=96):
'''
returns the map scale on the dpi of the screen
'''
dpm = dpi / 0.0254 # convert to dots per meter
return self.getGroundResolution(latitude, level) * dpm |
returns the x and y values of the pixel corresponding to a latitude
and longitude.
def convertLatLngToPixelXY(self, lat, lng, level):
'''
returns the x and y values of the pixel corresponding to a latitude
and longitude.
'''
mapSize = self.getMapDimensionsByZoomLevel(lev... |
converts a pixel x, y to a latitude and longitude.
def convertPixelXYToLngLat(self, pixelX, pixelY, level):
'''
converts a pixel x, y to a latitude and longitude.
'''
mapSize = self.getMapDimensionsByZoomLevel(level)
x = (self.clipValue(pixelX, 0, mapSize - 1) / mapSize) - 0.5
... |
Computes quadKey value based on tile x, y and z values.
def tileXYZToQuadKey(self, x, y, z):
'''
Computes quadKey value based on tile x, y and z values.
'''
quadKey = ''
for i in range(z, 0, -1):
digit = 0
mask = 1 << (i - 1)
if (x & mask) != ... |
Computes tile x, y and z values based on quadKey.
def quadKeyToTileXYZ(self, quadKey):
'''
Computes tile x, y and z values based on quadKey.
'''
tileX = 0
tileY = 0
tileZ = len(quadKey)
for i in range(tileZ, 0, -1):
mask = 1 << (i - 1)
va... |
Returns the upper-left hand corner lat/lng for a tile
def getTileOrigin(self, tileX, tileY, level):
'''
Returns the upper-left hand corner lat/lng for a tile
'''
pixelX, pixelY = self.convertTileXYToPixelXY(tileX, tileY)
lng, lat = self.convertPixelXYToLngLat(pixelX, pixelY, lev... |
Returns a list of tile urls by extent
def getTileUrlsByLatLngExtent(self, xmin, ymin, xmax, ymax, level):
'''
Returns a list of tile urls by extent
'''
# Upper-Left Tile
tileXMin, tileYMin = self.tileUtils.convertLngLatToTileXY(xmin, ymax,
... |
returns new tile url based on template
def createTileUrl(self, x, y, z):
'''
returns new tile url based on template
'''
return self.tileTemplate.replace('{{x}}', str(x)).replace('{{y}}', str(
y)).replace('{{z}}', str(z)) |
Handles navigational reference frame updates.
These are necessary to assign geo coordinates to alerts and other
misc things.
:param event with incoming referenceframe message
def referenceframe(self, event):
"""Handles navigational reference frame updates.
These are necessary t... |
Checks if an alert is ongoing and alerts the newly connected
client, if so.
def userlogin(self, event):
"""Checks if an alert is ongoing and alerts the newly connected
client, if so."""
client_uuid = event.clientuuid
self.log(event.user, pretty=True, lvl=verbose)
self... |
AlertManager event handler for incoming events
:param event with incoming AlertManager message
def trigger(self, event):
"""AlertManager event handler for incoming events
:param event with incoming AlertManager message
"""
topic = event.data.get('topic', None)
if topi... |
AlertManager event handler for incoming events
:param event with incoming AlertManager message
def cancel(self, event):
"""AlertManager event handler for incoming events
:param event with incoming AlertManager message
"""
topic = event.data.get('topic', None)
if topic... |
Isomer Management Tool
This tool supports various operations to manage isomer instances.
Most of the commands are grouped. To obtain more information about the
groups' available sub commands/groups, try
iso [group]
To display details of a command or its sub groups, try
iso [group] [subgroup... |
Primary entry point for all AstroCats catalogs.
From this entry point, all internal catalogs can be accessed and their
public methods executed (for example: import scripts).
def main():
"""Primary entry point for all AstroCats catalogs.
From this entry point, all internal catalogs can be accessed and... |
Setup a configuration file in the user's home directory.
Currently this method stores default values to a fixed configuration
filename. It should be modified to run an interactive prompt session
asking for parameters (or at least confirming the default ones).
Arguments
---------
log : `loggin... |
Load settings from the user's confiuration file, and add them to `args`.
Settings are loaded from the configuration file in the user's home
directory. Those parameters are added (as attributes) to the `args`
object.
Arguments
---------
args : `argparse.Namespace`
Namespace object to w... |
Load and parse command-line arguments.
Arguments
---------
args : str or None
'Faked' commandline arguments passed to `argparse`.
Returns
-------
args : `argparse.Namespace` object
Namespace in which settings are stored - default values modified by the
given command-lin... |
Load a `logging.Logger` object.
Arguments
---------
args : `argparse.Namespace` object
Namespace containing required settings:
{`args.debug`, `args.verbose`, and `args.log_filename`}.
Returns
-------
log : `logging.Logger` object
def load_log(args):
"""Load a `logging.Logg... |
Function compares dictionaries by key-value recursively.
Old and new input data are both dictionaries
def compare_dicts(old_full, new_full, old_data, new_data, depth=0):
"""Function compares dictionaries by key-value recursively.
Old and new input data are both dictionaries
"""
depth = depth + 1
... |
Clips a line to a rectangular area.
This implements the Cohen-Sutherland line clipping algorithm. xmin,
ymax, xmax and ymin denote the clipping area, into which the line
defined by x1, y1 (start point) and x2, y2 (end point) will be
clipped.
If the line does not intersect with the rectangular cli... |
Horn Schunck legacy OpenCV function requires we use these old-fashioned cv matrices, not numpy array
def setupuv(rc):
"""
Horn Schunck legacy OpenCV function requires we use these old-fashioned cv matrices, not numpy array
"""
if cv is not None:
(r, c) = rc
u = cv.CreateMat(r, c, cv.CV_... |
Initialize a CatDict object, checking for errors.
def _init_cat_dict(self, cat_dict_class, key_in_self, **kwargs):
"""Initialize a CatDict object, checking for errors.
"""
# Catch errors associated with crappy, but not unexpected data
try:
new_entry = cat_dict_class(self, ke... |
Add a CatDict to this Entry if initialization succeeds and it
doesn't already exist within the Entry.
def _add_cat_dict(self,
cat_dict_class,
key_in_self,
check_for_dupes=True,
**kwargs):
"""Add a CatDict to this En... |
Wrapper for `tqdm` progress bar.
def pbar(iter, desc='', **kwargs):
"""Wrapper for `tqdm` progress bar.
"""
return tqdm(
iter,
desc=('<' + str(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + '> ' +
desc),
dynamic_ncols=True,
**kwargs) |
Wrapper for `tqdm` progress bar which also sorts list of strings
def pbar_strings(files, desc='', **kwargs):
"""Wrapper for `tqdm` progress bar which also sorts list of strings
"""
return tqdm(
sorted(files, key=lambda s: s.lower()),
desc=('<' + str(datetime.now().strftime("%Y-%m-%d %H:%M:%... |
Get the task `priority` corresponding to the given `task_priority`.
If `task_priority` is an integer or 'None', return it.
If `task_priority` is a str, return the priority of the task it matches.
Otherwise, raise `ValueError`.
def _get_task_priority(tasks, task_priority):
"""Get the task `priority` co... |
Run all of the import tasks.
This is executed by the 'scripts.main.py' when the module is run as an
executable. This can also be run as a method, in which case default
arguments are loaded, but can be overriden using `**kwargs`.
def import_data(self):
"""Run all of the import tasks.
... |
Load the list of tasks in this catalog's 'input/tasks.json' file.
A `Task` object is created for each entry, with the parameters filled
in. These are placed in an OrderedDict, sorted by the `priority`
parameter, with positive values and then negative values,
e.g. [0, 2, 10, -10, -1]... |
Find an existing entry in, or add a new one to, the `entries` dict.
FIX: rename to `create_entry`???
Returns
-------
entries : OrderedDict of Entry objects
newname : str
Name of matching entry found in `entries`, or new entry added to
`entries`
def add_... |
Return the first entry name with the given 'alias' included in its
list of aliases.
Returns
-------
name of matching entry (str) or 'None' if no matches
def find_entry_name_of_alias(self, alias):
"""Return the first entry name with the given 'alias' included in its
list... |
Used by `merge_duplicates`
def copy_entry_to_entry(self,
fromentry,
destentry,
check_for_dupes=True,
compare_to_existing=True):
"""Used by `merge_duplicates`
"""
self.log.info("Copy e... |
Merge and remove duplicate entries.
Compares each entry ('name') in `stubs` to all later entries to check
for duplicates in name or alias. If a duplicate is found, they are
merged and written to file.
def merge_duplicates(self):
"""Merge and remove duplicate entries.
Compares... |
Load all events in their `stub` (name, alias, etc only) form.
Used in `update` mode.
def load_stubs(self, log_mem=False):
"""Load all events in their `stub` (name, alias, etc only) form.
Used in `update` mode.
"""
# Initialize parameter related to diagnostic output of memory u... |
Delete the file associated with the given entry.
def _delete_entry_file(self, entry_name=None, entry=None):
"""Delete the file associated with the given entry.
"""
if entry_name is None and entry is None:
raise RuntimeError("Either `entry_name` or `entry` must be given.")
el... |
Write all entries in `entries` to files, and clear. Depending on
arguments and `tasks`.
Iterates over all elements of `entries`, saving (possibly 'burying')
and deleting.
- If ``clear == True``, then each element of `entries` is deleted,
and a `stubs` entry is added
def ... |
Choose between each entries given name and its possible aliases for
the best one.
def set_preferred_names(self):
"""Choose between each entries given name and its possible aliases for
the best one.
"""
if len(self.entries) == 0:
self.log.error("WARNING: `entries` is ... |
Get a list of files which should be added to the given repository.
Notes
-----
* Finds files in the *root* of the given repository path.
* If `file_types` is given, only use those file types.
* If an uncompressed file is above the `size_limit`, it is compressed.
* If a c... |
Load the given URL, or a cached-version.
Load page from url or cached file, depending on the current settings.
'archived' mode applies when `args.archived` is true (from
`--archived` CL argument), and when this task has `Task.archived`
also set to True.
'archived' mode:
... |
Download text from the given url.
Returns `None` on failure.
Arguments
---------
self
url : str
URL web address to download.
timeout : int
Duration after which URL request should terminate.
fail : bool
If `True`, then an error... |
Merge the source alias lists of two CatDicts.
def append_sources_from(self, other):
"""Merge the source alias lists of two CatDicts."""
# Get aliases lists from this `CatDict` and other
self_aliases = self[self._KEYS.SOURCE].split(',')
other_aliases = other[self._KEYS.SOURCE].split(',')... |
Name of current action for progress-bar output.
The specific task string is depends on the configuration via `args`.
Returns
-------
ctask : str
String representation of this task.
def current_task(self, args):
"""Name of current action for progress-bar output.
... |
Whether previously archived data should be loaded.
def load_archive(self, args):
"""Whether previously archived data should be loaded.
"""
import warnings
warnings.warn("`Task.load_archive()` is deprecated! "
"`Catalog.load_url` handles the same functionality.")
... |
Use `git rev-parse HEAD <REPO>` to get current SHA.
def get_sha(path=None, log=None, short=False, timeout=None):
"""Use `git rev-parse HEAD <REPO>` to get current SHA.
"""
# git_command = "git rev-parse HEAD {}".format(repo_name).split()
# git_command = "git rev-parse HEAD".split()
git_command = ["... |
Add all files in each data repository tree, commit, push.
Creates a commit message based on the current catalog version info.
If either the `git add` or `git push` commands fail, an error will be
raised. Currently, if `commit` fails an error *WILL NOT* be raised
because the `commit` command will retu... |
Perform a 'git pull' in each data repository.
> `git pull -s recursive -X theirs`
def git_pull_all_repos(cat, strategy_recursive=True, strategy='theirs'):
"""Perform a 'git pull' in each data repository.
> `git pull -s recursive -X theirs`
"""
# raise RuntimeError("THIS DOESNT WORK YET!")
log... |
Perform a 'git clone' for each data repository that doesnt exist.
def git_clone_all_repos(cat):
"""Perform a 'git clone' for each data repository that doesnt exist.
"""
log = cat.log
log.debug("gitter.git_clone_all_repos()")
all_repos = cat.PATHS.get_all_repo_folders()
out_repos = cat.PATHS.ge... |
Perform a 'git reset' in each data repository.
def git_reset_all_repos(cat, hard=True, origin=False, clean=True):
"""Perform a 'git reset' in each data repository.
"""
log = cat.log
log.debug("gitter.git_reset_all_repos()")
all_repos = cat.PATHS.get_all_repo_folders()
for repo in all_repos:
... |
Perform a 'git status' in each data repository.
def git_status_all_repos(cat, hard=True, origin=False, clean=True):
"""Perform a 'git status' in each data repository.
"""
log = cat.log
log.debug("gitter.git_status_all_repos()")
all_repos = cat.PATHS.get_all_repo_folders()
for repo_name in all_... |
Given a list of repositories, make sure they're all cloned.
Should be called from the subclassed `Catalog` objects, passed a list
of specific repository names.
Arguments
---------
all_repos : list of str
*Absolute* path specification of each target repository.
def clone(repo, log, depth=1... |
Use `subprocess` to call a command in a certain (repo) directory.
Logs the output (both `stderr` and `stdout`) to the log, and checks the
return codes to make sure they're valid. Raises error if not.
Raises
------
exception `subprocess.CalledProcessError`: if the command fails
def _call_command_... |
Check that spectrum has legal combination of attributes.
def _check(self):
"""Check that spectrum has legal combination of attributes."""
# Run the super method
super(Spectrum, self)._check()
err_str = None
has_data = self._KEYS.DATA in self
has_wave = self._KEYS.WAVELE... |
Check if spectrum is duplicate of another.
def is_duplicate_of(self, other):
"""Check if spectrum is duplicate of another."""
if super(Spectrum, self).is_duplicate_of(other):
return True
row_matches = 0
for ri, row in enumerate(self.get(self._KEYS.DATA, [])):
lam... |
Logic for sorting keys in a `Spectrum` relative to one another.
def sort_func(self, key):
"""Logic for sorting keys in a `Spectrum` relative to one another."""
if key == self._KEYS.TIME:
return 'aaa'
if key == self._KEYS.DATA:
return 'zzy'
if key == self._KEYS.SO... |
Sorting logic for `Quantity` objects.
def sort_func(self, key):
"""Sorting logic for `Quantity` objects."""
if key == self._KEYS.VALUE:
return 'aaa'
if key == self._KEYS.SOURCE:
return 'zzz'
return key |
Return this class's attribute names (those not stating with '_').
Also retrieves the attributes from base classes, e.g.
For: ``ENTRY(KeyCollection)``, ``ENTRY.keys()`` gives just the
attributes of `ENTRY` (`KeyCollection` has no keys).
For: ``SUPERNOVA(ENTRY)``, ``SUPERNOVA.keys()`... |
Return this class's attribute values (those not stating with '_').
Returns
-------
_vals : list of objects
List of values of internal attributes. Order is effectiely random.
def vals(cls):
"""Return this class's attribute values (those not stating with '_').
Retur... |
Return this class's attribute values (those not stating with '_'),
but only for attributes with `compare` set to `True`.
Returns
-------
_compare_vals : list of objects
List of values of internal attributes to use when comparing
`CatDict` objects. Order sorted by... |
Return a 'pretty' string representation of this `Key`.
note: do not override the builtin `__str__` or `__repr__` methods!
def pretty(self):
"""Return a 'pretty' string representation of this `Key`.
note: do not override the builtin `__str__` or `__repr__` methods!
"""
retval =... |
Make sure given value is consistent with this `Key` specification.
NOTE: if `type` is 'None', then `listable` also is *not* checked.
def check(self, val):
"""Make sure given value is consistent with this `Key` specification.
NOTE: if `type` is 'None', then `listable` also is *not* checked.
... |
Create a standard logger object which logs to file and or stdout stream.
If a logger has already been created in this session, it is returned
(unless `name` is given).
Arguments
---------
name : str,
Handle for this logger, must be distinct for a distinct logger.
stream_fmt : str or `N... |
Log an error message and raise an error.
Arguments
---------
log : `logging.Logger` object
err_str : str
Error message to be logged and raised.
err_type : `Exception` object
Type of error to raise.
def log_raise(log, err_str, err_type=RuntimeError):
"""Log an error message and ... |
Log the current memory usage.
def log_memory(log, pref=None, lvl=logging.DEBUG, raise_flag=True):
"""Log the current memory usage.
"""
import os
import sys
cyc_str = ""
KB = 1024.0
if pref is not None:
cyc_str += "{}: ".format(pref)
# Linux returns units in Bytes; OSX in kiloby... |
img: can be RGB (MxNx3) or gray (MxN)
http://docs.opencv.org/master/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html
http://docs.opencv.org/trunk/modules/features2d/doc/drawing_function_of_keypoints_and_matches.html
def doblob(morphed, blobdet, img, anno=True):
"""
img: can be RGB ... |
Parse arguments and return configuration settings.
def load_args(self, args, clargs):
"""Parse arguments and return configuration settings.
"""
# Parse All Arguments
args = self.parser.parse_args(args=clargs, namespace=args)
# Print the help information if no subcommand is give... |
Create `argparse` instance, and setup with appropriate parameters.
def _setup_argparse(self):
"""Create `argparse` instance, and setup with appropriate parameters.
"""
parser = argparse.ArgumentParser(
prog='catalog', description='Parent Catalog class for astrocats.')
subpa... |
Create parser for 'import' subcommand, and associated arguments.
def _add_parser_arguments_import(self, subparsers):
"""Create parser for 'import' subcommand, and associated arguments.
"""
import_pars = subparsers.add_parser(
"import", help="Import data.")
import_pars.add_a... |
Create a sub-parsers for git subcommands.
def _add_parser_arguments_git(self, subparsers):
"""Create a sub-parsers for git subcommands.
"""
subparsers.add_parser(
"git-clone",
help="Clone all defined data repositories if they dont exist.")
subparsers.add_parser(... |
Create a parser for the 'analyze' subcommand.
def _add_parser_arguments_analyze(self, subparsers):
"""Create a parser for the 'analyze' subcommand.
"""
lyze_pars = subparsers.add_parser(
"analyze",
help="Perform basic analysis on this catalog.")
lyze_pars.add_ar... |
Compress the file with the given name and delete the uncompressed file.
The compressed filename is simply the input filename with '.gz' appended.
Arguments
---------
fname : str
Name of the file to compress and delete.
Returns
-------
comp_fname : str
Name of the compresse... |
draws flow vectors on image
this came from opencv/examples directory
another way: http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_drawing_functions/py_drawing_functions.html
def draw_flow(img, flow, step=16, dtype=uint8):
"""
draws flow vectors on image
this came from opencv/examples direct... |
mag must be uint8, uint16, uint32 and 2-D
ang is in radians (float)
def draw_hsv(mag, ang, dtype=uint8, fn=None):
"""
mag must be uint8, uint16, uint32 and 2-D
ang is in radians (float)
"""
assert mag.shape == ang.shape
assert mag.ndim == 2
maxval = iinfo(dtype).max
hsv = dstack(((... |
flow dimensions y,x,2 3-D. flow[...,0] is magnitude, flow[...,1] is angle
def flow2magang(flow, dtype=uint8):
"""
flow dimensions y,x,2 3-D. flow[...,0] is magnitude, flow[...,1] is angle
"""
fx, fy = flow[..., 0], flow[..., 1]
return hypot(fx, fy).astype(dtype), arctan2(fy, fx) + pi |
dir
One of IOC_NONE, IOC_WRITE, IOC_READ, or IOC_READ|IOC_WRITE.
Direction is from the application's point of view, not kernel's.
size (14-bits unsigned integer)
Size of the buffer passed to ioctl's "arg" argument.
def IOC(dir, type, nr, size):
"""
dir
One of IOC_NONE, IOC_W... |
Returns the size of given type, and check its suitability for use in an
ioctl command number.
def IOC_TYPECHECK(t):
"""
Returns the size of given type, and check its suitability for use in an
ioctl command number.
"""
result = ctypes.sizeof(t)
assert result <= _IOC_SIZEMASK, result
retu... |
An ioctl with read parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
def IOR(type, nr, size):
"""
An ioctl with read parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
... |
An ioctl with write parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
def IOW(type, nr, size):
"""
An ioctl with write parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
... |
An ioctl with both read an writes parameters.
size (ctype type or instance)
Type/structure of the argument passed to ioctl's "arg" argument.
def IOWR(type, nr, size):
"""
An ioctl with both read an writes parameters.
size (ctype type or instance)
Type/structure of the argument passed ... |
Get a path including only the trailing `num` directories.
Returns
-------
last_path : str
def _get_last_dirs(path, num=1):
"""Get a path including only the trailing `num` directories.
Returns
-------
last_path : str
"""
head, tail = os.path.split(path)
last_path = str(tail)
... |
Run the analysis routines determined from the given `args`.
def analyze(self, args):
"""Run the analysis routines determined from the given `args`.
"""
self.log.info("Running catalog analysis")
if args.count:
self.count()
return |
Analyze the counts of ...things.
Returns
-------
retvals : dict
Dictionary of 'property-name: counts' pairs for further processing
def count(self):
"""Analyze the counts of ...things.
Returns
-------
retvals : dict
Dictionary of 'propert... |
Count the number of tasks, both in the json and directory.
Returns
-------
num_tasks : int
The total number of all tasks included in the `tasks.json` file.
def _count_tasks(self):
"""Count the number of tasks, both in the json and directory.
Returns
-------... |
Count the number of files in the data repositories.
`_COUNT_FILE_TYPES` are used to determine which file types are checked
explicitly.
`_IGNORE_FILES` determine which files are ignored in (most) counts.
Returns
-------
repo_files : int
Total number of (non-i... |
Construct a string showing the number of different file types.
Returns
-------
f_str : str
def _file_nums_str(self, n_all, n_type, n_ign):
"""Construct a string showing the number of different file types.
Returns
-------
f_str : str
"""
# 'other... |
Count files in the given path, with the given pattern.
If `ignore = True`, skip files in the `_IGNORE_FILES` list.
Returns
-------
num_files : int
def _count_files_by_type(self, path, pattern, ignore=True):
"""Count files in the given path, with the given pattern.
If ... |
Given a URL, try to find the ADS bibcode.
Currently: only `ads` URLs will work, e.g.
Returns
-------
code : str or 'None'
The Bibcode if found, otherwise 'None'
def bibcode_from_url(cls, url):
"""Given a URL, try to find the ADS bibcode.
Currently: only `a... |
Return the path that this Entry should be saved to.
def _get_save_path(self, bury=False):
"""Return the path that this Entry should be saved to."""
filename = self.get_filename(self[self._KEYS.NAME])
# Put objects that shouldn't belong in this catalog in the boneyard
if bury:
... |
Convert the object into a plain OrderedDict.
def _ordered(self, odict):
"""Convert the object into a plain OrderedDict."""
ndict = OrderedDict()
if isinstance(odict, CatDict) or isinstance(odict, Entry):
key = odict.sort_func
else:
key = None
nkeys = li... |
Return a unique hash associated with the listed keys.
def get_hash(self, keys=[]):
"""Return a unique hash associated with the listed keys."""
if not len(keys):
keys = list(self.keys())
string_rep = ''
oself = self._ordered(deepcopy(self))
for key in keys:
... |
Clean quantity value before it is added to entry.
def _clean_quantity(self, quantity):
"""Clean quantity value before it is added to entry."""
value = quantity.get(QUANTITY.VALUE, '').strip()
error = quantity.get(QUANTITY.E_VALUE, '').strip()
unit = quantity.get(QUANTITY.U_VALUE, '').st... |
Convert `OrderedDict` into `Entry` or its derivative classes.
def _convert_odict_to_classes(self,
data,
clean=False,
merge=True,
pop_schema=True,
com... |
Check that a source exists and that a quantity isn't erroneous.
def _check_cat_dict_source(self, cat_dict_class, key_in_self, **kwargs):
"""Check that a source exists and that a quantity isn't erroneous."""
# Make sure that a source is given
source = kwargs.get(cat_dict_class._KEYS.SOURCE, None... |
Add a `CatDict` to this `Entry`.
CatDict only added if initialization succeeds and it
doesn't already exist within the Entry.
def _add_cat_dict(self,
cat_dict_class,
key_in_self,
check_for_dupes=True,
compare_to_ex... |
Construct a new `Entry` instance from an input file.
The input file can be given explicitly by `path`, or a path will
be constructed appropriately if possible.
Arguments
---------
catalog : `astrocats.catalog.catalog.Catalog` instance
The parent catalog object of wh... |
Add an alias, optionally 'cleaning' the alias string.
Calls the parent `catalog` method `clean_entry_name` - to apply the
same name-cleaning as is applied to entry names themselves.
Returns
-------
alias : str
The stored version of the alias (cleaned or not).
def a... |
Add an `Error` instance to this entry.
def add_error(self, value, **kwargs):
"""Add an `Error` instance to this entry."""
kwargs.update({ERROR.VALUE: value})
self._add_cat_dict(Error, self._KEYS.ERRORS, **kwargs)
return |
Add a `Photometry` instance to this entry.
def add_photometry(self, compare_to_existing=True, **kwargs):
"""Add a `Photometry` instance to this entry."""
self._add_cat_dict(
Photometry,
self._KEYS.PHOTOMETRY,
compare_to_existing=compare_to_existing,
**kwa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.