code stringlengths 1 18.2k |
|---|
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:%S")) + '> ' + desc), dynamic_ncols=True, **kwargs) |
def _get_task_priority(tasks, task_priority): """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`. """ if task_priority is None: return None if... |
def import_data(self): """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`. """ tasks_list = self.load_task_list() warnings.filterwarnings( '... |
(previously constructed) output files if self.args.delete_old: self.log.warning("Deleting all old entry files.") self.delete_old_entry_files() # In update mode, load all entry stubs. if self.args.load_stubs or self.args.update: self.load_stubs() if self.args.travis: self.log.warning("Running in `travis` mode.") prev_pr... |
= task_obj.priority # Make sure things are running in the correct order if priority < prev_priority and priority > 0: raise RuntimeError("Priority for '{}': '{}', less than prev," "'{}': '{}'.\n{}" .format(task_name, priority, prev_task_name, prev_priority, task_obj)) self.log.debug("\t{}, {}, {}, {}".format(nice_name,... |
num_stubs)) self.journal_entries() num_events, num_stubs = self.count() self.log.warning("Journal finished. Events: {}, Stubs: {}".format( num_events, num_stubs)) prev_priority = priority prev_task_name = task_name process = psutil.Process(os.getpid()) memory = process.memory_info().rss self.log.warning('Memory used (M... |
def load_task_list(self): """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]. """ # ... |
'update' mode.") self.args.delete_old = False # Dont allow both a 'min' and 'max' task priority # FIX: this is probably unnecessary... having both could be useful if ((self.args.min_task_priority is not None and self.args.max_task_priority is not None)): raise ValueError("Can only use *either* 'min' *or* 'max' priority... |
all valid args_lists = [ self.args.args_task_list, self.args.yes_task_list, self.args.no_task_list ] args_names = ['--tasks', '--yes', '--no'] for arglist, lname in zip(args_lists, args_names): if arglist is not None: for tname in arglist: if tname not in task_names: raise ValueError( "Value '{}' in '{}' list does not ... |
self.args.max_task_priority) task_groups = self.args.task_groups if task_groups is not None: if not isinstance(task_groups, list): task_groups = [task_groups] # Iterate over all tasks to determine which should be (in)active # -------------------------------------------------------------- for key in tasks: # If in updat... |
is not None: if key in self.args.args_task_list: tasks[key].active = True else: tasks[key].active = False # Only run tasks above minimum priority # (doesn't modify negtive priority tasks) if min_priority is not None and tasks[key].priority >= 0: tasks[key].active = False if tasks[key].priority >= min_priority: tasks[ke... |
and tasks[key].priority >= 0: tasks[key].active = False if tasks[key].priority <= max_priority: tasks[key].active = True # Set 'yes' tasks to *active* if self.args.yes_task_list is not None: if key in self.args.yes_task_list: tasks[key].active = True # Set 'no' tasks to *inactive* if self.args.no_task_list is not None:... |
tasks[key].groups is not None: # Go through each group defined in the command line for given_group in task_groups: # If this task is a member of any of those groups if given_group in tasks[key].groups: tasks[key].active = True break # Sort entries as positive values, then negative values # [0, 1, 2, 2, 10, -100, -10, -... |
'0' if positive), then # second (here normal order) tasks = OrderedDict( sorted( tasks.items(), key=lambda t: (t[1].priority < 0, t[1].priority, t[1].name))) # Find the first task that has "always_journal" set to True for key in tasks: if tasks[key].active and tasks[key].always_journal: self.min_journal_priority = task... |
".join(nn for nn in names_act)) self.log.debug("Inactive Tasks:\n\t" + ", ".join(nn for nn in names_inact)) return tasks |
def add_entry(self, name, load=True, delete=True): """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` """ newname = self.cl... |
If entry already exists, return if newname in self.entries: self.log.debug("`newname`: '{}' (name: '{}') already exists.". format(newname, name)) # If this is a stub, we need to continue, possibly load file if self.entries[newname]._stub: self.log.debug("'{}' is a stub".format(newname)) # If a full (non-stub) event exi... |
`entries`, find and return that match_name = self.find_entry_name_of_alias(newname) if match_name is not None: self.log.debug( "`newname`: '{}' (name: '{}') already exists as alias for " "'{}'.".format(newname, name, match_name)) newname = match_name # Load entry from file if load: loaded_name = self.load_entry_from_na... |
entry new_entry = self.proto(catalog=self, name=newname) new_entry[self.proto._KEYS.SCHEMA] = self.SCHEMA.URL self.log.log(self.log._LOADED, "Created new entry for '{}'".format(newname)) # Add entry to dictionary self.entries[newname] = new_entry return newname |
def find_entry_name_of_alias(self, alias): """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 """ if alias in self.aliases: name = self.aliases[alias] if name in self.entries: return name else: # Name wasn't found, ... |
= entry.get_aliases(includename=False) if alias in aliases: if (ENTRY.DISTINCT_FROM not in entry or alias not in entry[ENTRY.DISTINCT_FROM]): return name return None |
def copy_entry_to_entry(self, fromentry, destentry, check_for_dupes=True, compare_to_existing=True): """Used by `merge_duplicates` """ self.log.info("Copy entry object '{}' to '{}'".format(fromentry[ fromentry._KEYS.NAME], destentry[destentry._KEYS.NAME])) newsourcealiases = {} if self.proto._KEYS.SOURCES in fromentry:... |
in fromentry: key = fromentry._KEYS.get_key_by_name(rkey) if key.no_source: continue for item in fromentry[key]: # isd = False if 'source' not in item: raise ValueError("Item has no source!") nsid = [] for sid in item['source'].split(','): if sid in newsourcealiases: source = newsourcealiases[sid] nsid.append(destentry... |
newmodelaliases: model = newmodelaliases[mid] nmid.append(destentry.add_model(**model)) else: raise ValueError("Couldn't find model alias!") item['model'] = uniq_cdl(nmid) if key == ENTRY.PHOTOMETRY: destentry.add_photometry( compare_to_existing=compare_to_existing, **item) elif key == ENTRY.SPECTRA: destentry.add_spec... |
def merge_duplicates(self): """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. """ if len(self.entries) == 0: self.log.error("WARNING: `entries` is empty, loading stub... |
= self.load_stubs() task_str = self.get_current_task_str() keys = list(sorted(self.entries.keys())) n1 = 0 mainpbar = tqdm(total=len(keys), desc=task_str) while n1 < len(keys): name1 = keys[n1] if name1 not in self.entries: self.log.info("Entry for {} not found, likely already " "deleted in merging process.".format(nam... |
name1 == name2: continue if name1 not in self.entries: self.log.info("Entry for {} not found, likely already " "deleted in merging process.".format(name1)) continue if name2 not in self.entries: self.log.info("Entry for {} not found, likely already " "deleted in merging process.".format(name2)) continue allnames2 = set... |
aliases " "('{}' and '{}'), merging.".format(name1, name2)) load1 = self.proto.init_from_file(self, name=name1) load2 = self.proto.init_from_file(self, name=name2) if load1 is not None and load2 is not None: # Delete old files self._delete_entry_file(entry=load1) self._delete_entry_file(entry=load2) self.entries[name1]... |
priority1 > priority2: self.copy_to_entry_in_catalog(name2, name1) keys.append(name1) del self.entries[name2] else: self.copy_to_entry_in_catalog(name1, name2) keys.append(name2) del self.entries[name1] else: self.log.warning('Duplicate already deleted') # if len(self.entries) != 1: # self.log.error( # "WARNING: len(en... |
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 usage if log_mem: import psutil process = psutil.Process(os.getpid()) rss = process.memory_info().rss LOG_MEMORY_INT = 1000 MEMOR... |
creating a full `Entry` instance, then using the `Entry.get_stub()` method to trim it down. This was very slow and memory intensive, hence this improved approach. """ # FIX: should this be ``fi.endswith(``.gz')`` ? fname = uncompress_gz(_fname) if '.gz' in _fname else _fname stub = None stub_name = None with codecs.ope... |
Extract the top-level keys (should just be the name of the # entry) stub_name = list(data.keys()) # Make sure there is only a single top-level entry if len(stub_name) != 1: err = "json file '{}' has multiple keys: {}".format( fname, list(stub_name)) self._log.error(err) raise ValueError(err) stub_name = stub_name[0] # ... |
and not self.entries[ stub_name]._stub: err_str = ( "ERROR: non-stub entry already exists with name '{}'" .format(stub_name)) self.log.error(err_str) raise RuntimeError(err_str) # Remove the outmost dict level data = data[stub_name] # Create a new `Entry` (subclass) instance proto = self.proto stub = proto(catalog=self... |
data[ proto._KEYS.DISTINCT_FROM] if proto._KEYS.RA in data: stub[proto._KEYS.RA] = data[proto._KEYS.RA] if proto._KEYS.DEC in data: stub[proto._KEYS.DEC] = data[proto._KEYS.DEC] if proto._KEYS.DISCOVER_DATE in data: stub[proto._KEYS.DISCOVER_DATE] = data[ proto._KEYS.DISCOVER_DATE] if proto._KEYS.SOURCES in data: stub[... |
'manually' (extract stub parameters directly from JSON) _add_stub_manually(_fname) if log_mem: rss = process.memory_info().rss / 1024 / 1024 if ii % LOG_MEMORY_INT == 0 or rss > MEMORY_LIMIT: log_memory(self.log, "\nLoaded stub {}".format(ii), logging.INFO) if rss > MEMORY_LIMIT: err = ( "Memory usage {}, has exceeded ... |
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.") elif entry_name is not None and entry is not None: raise RuntimeError("Cannot use both `entry_na... |
to check for gzipped files?? entry_filename = self.entry_filename(entry_name) if self.args.write_entries: self.log.info("Deleting entry file '{}' of entry '{}'".format( entry_filename, entry_name)) if not os.path.exists(entry_filename): self.log.error( "Filename '{}' does not exist".format(entry_filename)) os.remove(en... |
def journal_entries(self, clear=True, gz=False, bury=False, write_stubs=False, final=False): """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... |
Write it all out! # NOTE: this needs to use a `list` wrapper to allow modification of # dict for name in list(self.entries.keys()): if self.args.write_entries: # If this is a stub and we aren't writing stubs, skip if self.entries[name]._stub and not write_stubs: continue # Bury non-SN entries here if only claimed type ... |
prefix. bury_entry = False save_entry = True if bury: (bury_entry, save_entry) = self.should_bury(name) if save_entry: save_name = self.entries[name].save( bury=bury_entry, final=final) self.log.info( "Saved {} to '{}'.".format(name.ljust(20), save_name)) if (gz and os.path.getsize(save_name) > self.COMPRESS_ABOVE_FILE... |
+ '.json; git add -f ' + filename + '.json.gz; cd ' + self.PATHS.PATH_BASE) if clear: self.entries[name] = self.entries[name].get_stub() self.log.debug("Entry for '{}' converted to stub".format(name)) return |
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 empty, loading stubs") self.load_stubs() task_str = self.get_current_task_str() for ni, oname in enumerate(pbar(self.entries, task_str)... |
def _prep_git_add_file_list(self, repo, size_limit, fail=True, file_types=None): """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... |
an error is raised (if `fail = True`) or it is skipped (if `fail == False`). Arguments --------- repo : str Path to repository size_limit : scalar fail : bool Raise an error if a compressed file is still above the size limit. file_types : list of str or None Exclusive list of file types to add. 'None' to add all filety... |
= [] if file_types is None: file_patterns = ['*'] else: self.log.error( "WARNING: uncertain behavior with specified file types!") file_patterns = ['*.' + ft for ft in file_types] # Construct glob patterns for each file-type file_patterns = [os.path.join(repo, fp) for fp in file_patterns] for pattern in file_patterns: f... |
the found file is too large if fsize > size_limit: self.log.debug("File '{}' size '{}' MB.".format( fname, fsize / 1028 / 1028)) # If the file is already compressed... fail or skip if ff.endswith('.gz'): self.log.error( "File '{}' is already compressed.".format(fname)) comp_failed = True # Not yet compressed - compress... |
/ 1028 / 1028)) # If still too big, fail or skip if fsize > size_limit: comp_failed = True # If compressed file is too large, skip file or raise error if comp_failed: # Raise an error if fail: raise RuntimeError( "File '{}' cannot be added!".format(fname)) # Skip file without adding it self.log.info("Skipping file.") c... |
add_files.append(fname) return add_files |
def load_url(self, url, fname, repo=None, timeout=120, post=None, fail=False, write=True, json_sort=None, cache_only=False, archived_mode=None, archived_task=None, update_mode=None, verify=False): """Load the given URL, or a cached-version. Load page from url or cached file, depending on the current settings. 'archived... |
* If cache does not exist, try to load from web. * If neither works, raise an error if ``fail == True``, otherwise return None non-'archived' mode: * Try to load from url, save to cache file. * If url fails, try to load existing cache file. * If neither works, raise an error if ``fail == True``, otherwise return None '... |
In update mode, try to compare URL to cached file. * If URL fails, return None (cannot update) * If URL data matches cached data, return None (dont need to update) * If URL is different from data, return url data (proceed with update) Arguments --------- self url : str URL to download. fname : str Filename to which to ... |
suffix. NOTE: in general, this should be the source's BIBCODE. repo : str or None The full path of the data-repository the cached file should be saved/loaded from. If 'None', then the current task is used to determine the repo. timeout : int Time (in seconds) after which a URL query should exit. post : dict List of arg... |
requesting it. archived : bool Load a previously archived version of the file. fail : bool If the file/url cannot be loaded, raise an error. write : bool Save a new copy of the cached file. json_sort : str or None If data is being saved to a json file, sort first by this str. quiet : bool Whether to emit error messages... |
being unable to find files. verify : bool Whether to check for valid SSL cert when downloading """ file_txt = None url_txt = None # Load default settings if needed # ------------------------------- # Determine if we are running in archived mode if archived_mode is None: archived_mode = self.args.archived # Determine if... |
= self.current_task.archived # Determine if running in update mode if update_mode is None: update_mode = self.args.update # Construct the cached filename if repo is None: repo = self.get_current_task_repo() cached_path = os.path.join(repo, fname) # Load cached file if it exists # ---------------------------- if os.path... |
task - try to return the cached page if archived_mode or (archived_task and not update_mode): if file_txt is not None: return file_txt # If this flag is set, don't even attempt to download from web if cache_only: return None # If file does not exist, log error, continue else: self.log.error("Task {}: Cached file '{}' d... |
returned on failure - handle that below url_txt = self.download_url( url, timeout, fail=False, post=post, verify=verify) # At this point, we might have both `url_txt` and `file_txt` # If either of them failed, then they are set to None # If URL download failed, error or return cached data # ----------------------------... |
"Both url and file retrieval failed!" # If we should raise errors on failure if fail: err_str += " `fail` set." self.log.error(err_str) raise RuntimeError(err_str) # Otherwise warn and return None self.log.warning(err_str) return None # Otherwise, if only url failed, return file data else: # If we are trying to update,... |
updates, url download failed.") return None # Otherwise, return file data self.log.warning("URL download failed, using cached data.") return file_txt # Here: `url_txt` exists, `file_txt` may exist or may be None # Determine if update should happen, and if file should be resaved # Write new url_txt to cache file # -----... |
`file_txt` doesnt exist but were not writing.. warn elif file_txt is None: err_str = "Warning: cached file '{}' does not exist.".format( cached_path) err_str += " And is not being saved." self.log.warning(err_str) # Check if we need to update this data # ------------------------------------ # If both `url_txt` and `fil... |
md5 url_md5 = md5(url_txt.encode('utf-8')).hexdigest() file_md5 = md5(file_txt.encode('utf-8')).hexdigest() self.log.debug("URL: '{}', File: '{}'.".format(url_md5, file_md5)) # If the data is the same, no need to parse (update), return None if url_md5 == file_md5: self.log.info( "Skipping file '{}', no changes.".format... |
file." self.log.warning(err_str) return url_txt |
def download_url(self, url, timeout, fail=False, post=None, verify=True): """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 will be raised o... |
arguments to post to URL when requesting it. verify : bool Whether to check for valid SSL cert when downloading Returns ------- url_txt : str or None On success the text of the url is returned. On failure `None` is returned. """ _CODE_ERRORS = [500, 307, 404] import requests session = requests.Session() try: headers = ... |
'10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/39.0.2171.95 Safari/537.36' } if post: response = session.post( url, timeout=timeout, headers=headers, data=post, verify=verify) else: response = session.get( url, timeout=timeout, headers=headers, verify=verify) response.raise_for_status() # Look for errors fo... |
except Exception as err: err_str = ("URL Download of '{}' failed ('{}')." .format(url, str(err))) # Raise an error on failure if fail: err_str += " and `fail` is set." self.log.error(err_str) raise RuntimeError(err_str) # Log a warning on error, and return None else: self.log.warning(err_str) return None return url_txt |
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(',') # Store alias to `self` self[self._KEYS.SOURCE] = uniq_cdl(self_aliases + othe... |
def current_task(self, args): """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. """ ctask = self.nice_name if self.nice_name is not None else self.name if args is not None: if args.updat... |
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.") return self.archived or args.archived |
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 = ["git", "rev-parse"] if short: git_command.append("--short") git_command.ap... |
= subprocess.check_output(git_command, **kwargs) try: sha = sha.decode('ascii').strip() except: if log is not None: log.debug("decode of '{}' failed".format(sha)) return sha |
def git_add_commit_push_all_repos(cat): """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 `c... |
add... which we dont want to raise an error. FIX: improve the error checking on this. """ log = cat.log log.debug("gitter.git_add_commit_push_all_repos()") # Do not commit/push private repos all_repos = cat.PATHS.get_all_repo_folders(private=False) for repo in all_repos: log.info("Repo in: '{}'".format(repo)) # Get the... |
log.info("Found {} Files to add.".format(len(add_files))) if len(add_files) == 0: continue try: # Add all files in the repository directory tree git_comm = ["git", "add"] if cat.args.travis: git_comm.append("-f") git_comm.extend(add_files) _call_command_in_repo( git_comm, repo, cat.log, fail=True, log_flag=False) # Com... |
files in the repository directory tree git_comm = ["git", "push"] if not cat.args.travis: _call_command_in_repo(git_comm, repo, cat.log, fail=True) except Exception as err: try: git_comm = ["git", "reset", "HEAD"] _call_command_in_repo(git_comm, repo, cat.log, fail=True) except: pass raise err return |
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 = cat.log log.debug("gitter.git_pull_all_repos()") log.warning("WARNING: using experimental `git_pull_all_re... |
# Construct the command to call git_comm = "git pull --verbose" if strategy_recursive: git_comm += " -s recursive" if strategy is not None: git_comm += " -X {:s}".format(strategy) log.debug("Calling '{}'".format(git_comm)) # Call git command (do this manually to use desired options) # Set `with_exceptions=False` to han... |
if len(out): log.info(out) if len(err): log.info(err) # Hangle error-codes if code != 0: err_str = "Command '{}' returned exit code '{}'!".format(git_comm, code) err_str += "\n\tout: '{}'\n\terr: '{}'".format(out, err) log.error(err_str) raise RuntimeError(err_str) sha_end = get_sha(repo_name) if sha_end != sha_beg: lo... |
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.get_repo_output_folders() for repo in all_repos: log.info("Repo in: '{}'".format(repo)) if os.... |
exist!") raise # Get the initial git SHA sha_beg = get_sha(repo) log.debug("Current SHA: '{}'".format(sha_beg)) return |
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: log.warning("Repo in: '{}'".format(repo)) # Get the initial git SHA sha_beg... |
says: '{}'".format(retval)) # Clean if clean: log.info("cleaning") # [q]uiet, [f]orce, [d]irectories retval = grepo.clean('-qdf') if len(retval): log.warning("Git says: '{}'".format(retval)) sha_end = get_sha(repo) if sha_end != sha_beg: log.debug("Updated SHA: '{}'".format(sha_end)) return |
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_repos: log.info("Repo in: '{}'".format(repo_name)) # Get the initial git S... |
def clone(repo, log, depth=1): """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. """ kwargs = {} if depth ... |
".git" log.warning("Cloning '{}' (only needs to be done ".format(repo) + "once, may take few minutes per repo).") grepo = git.Repo.clone_from(repo_name, repo, **kwargs) except: log.error("CLONING '{}' INTERRUPTED".format(repo)) raise return grepo |
def _call_command_in_repo(comm, repo, log, fail=False, log_flag=True): """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.CalledProc... |
= process.communicate() if stderr is not None: err_msg = stderr.decode('ascii').strip().splitlines() for em in err_msg: log.error(em) if stdout is not None: out_msg = stdout.decode('ascii').strip().splitlines() for om in out_msg: log.warning(om) # Raises an error if the command failed. if fail: if process.returncode: r... |
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.WAVELENGTHS in self has_flux = self._KEYS.FLUXES in self has_filename = self._KEYS.FILENAME in self if not has_da... |
needed".format( self._KEYS.WAVELENGTHS, self._KEYS.FLUXES)) if err_str is not None: raise ValueError(err_str) return |
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, [])): lambda1, flux1 = tuple(row[0:2]) if (self._KEYS.DATA not in other or ri > len(other[self._KEYS.DATA])):... |
+ 1] and float(flux1[:minfluxlen + 1]) != 0.0): row_matches += 1 # Five row matches should be enough to be sure spectrum is a dupe. if row_matches >= 5: return True # Matches need to happen in the first 10 rows. if ri >= 10: break return False |
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.SOURCE: return 'zzz' return key |
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 |
def keys(cls): """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()`` gives both the att... |
if cls._keys: return cls._keys # If `_keys` is not yet defined, create it # ---------------------------------------- _keys = [] # get the keys from all base-classes aswell (when this is subclasses) for mro in cls.__bases__: # base classes below `KeyCollection` (e.g. `object`) wont work if issubclass(mro, KeyCollection)... |
kk for kk in vars(cls).keys() if not kk.startswith('_') and not callable(getattr(cls, kk)) ]) # Store for future retrieval cls._keys = _keys return cls._keys |
def vals(cls): """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. """ if cls._vals: return cls._vals # If `_vals` is not yet defined, create it # ---------------------------------------- _vals =... |
# base classes below `KeyCollection` (e.g. `object`) wont work if issubclass(mro, KeyCollection): _vals.extend(mro.vals()) # Get the keys from this particular subclass # Only non-hidden (no '_') and variables (non-callable) _vals.extend([ vv for kk, vv in vars(cls).items() if not kk.startswith('_') and not callable(get... |
def compare_vals(cls, sort=True): """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 `Key` priority, fol... |
---------------------------------------- _compare_vals = [] # get the keys from all base-classes aswell (when this is subclasses) for mro in cls.__bases__: # base classes below `KeyCollection` (e.g. `object`) wont work if issubclass(mro, KeyCollection): _compare_vals.extend(mro.compare_vals(sort=False)) # Get the keys ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.