sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def _translate(self, input_filename, output_filename): """Translate KML file to geojson for import""" command = [ self.translate_binary, '-f', 'GeoJSON', output_filename, input_filename ] result = self._runcommand(command) self.log...
Translate KML file to geojson for import
entailment
def _update_guide(self, guide, update=False, clear=True): """Update a single specified guide""" kml_filename = os.path.join(self.cache_path, guide + '.kml') geojson_filename = os.path.join(self.cache_path, guide + '.geojson') if not os.path.exists(geojson_filename) or update: ...
Update a single specified guide
entailment
def send_mail_worker(config, mail, event): """Worker task to send out an email, which is a blocking process unless it is threaded""" log = "" try: if config.get('ssl', True): server = SMTP_SSL(config['server'], port=config['port'], timeout=30) else: server = SMTP(con...
Worker task to send out an email, which is a blocking process unless it is threaded
entailment
def send_mail(self, event): """Connect to mail server and send actual email""" mime_mail = MIMEText(event.text) mime_mail['Subject'] = event.subject if event.account == 'default': account_name = self.config.default_account else: account_name = event.acco...
Connect to mail server and send actual email
entailment
def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provision a system user""" from hfos.provisions.base import provisionList from hfos.database import objectmodels # TODO: Add a root user and make sure owner can access it later. # Setting up de...
Provision a system user
entailment
def AlternatesGroup(expressions, final_function, name=""): """ Group expressions using the OR character ``|`` >>> from collections import namedtuple >>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None) >>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah') >>> gro...
Group expressions using the OR character ``|`` >>> from collections import namedtuple >>> expr = namedtuple('expr', 'regex group_lengths run')('(1)', [1], None) >>> grouping = AlternatesGroup([expr, expr], lambda f: None, 'yeah') >>> grouping.regex # doctest: +IGNORE_UNICODE '(?:(1))|(?:(1))' >...
entailment
def Group(expressions, final_function, inbetweens, name=""): """ Group expressions together with ``inbetweens`` and with the output of a ``final_functions``. """ lengths = [] functions = [] regex = "" i = 0 for expression in expressions: regex += inbetweens[i] regex += "(?:" ...
Group expressions together with ``inbetweens`` and with the output of a ``final_functions``.
entailment
def findall(self, string): """ Parse string, returning all outputs as parsed by functions """ output = [] for match in self.pattern.findall(string): if hasattr(match, 'strip'): match = [match] self._list_add(output, self.run(match)) return ...
Parse string, returning all outputs as parsed by functions
entailment
def scan(self, string): """ Like findall, but also returning matching start and end string locations """ return list(self._scanner_to_matches(self.pattern.scanner(string), self.run))
Like findall, but also returning matching start and end string locations
entailment
def run(self, matches): """ Run group functions over matches """ def _run(matches): group_starting_pos = 0 for current_pos, (group_length, group_function) in enumerate(zip(self.group_lengths, self.group_functions)): start_pos = current_pos + group_starting...
Run group functions over matches
entailment
def set_logfile(path, instance): """Specify logfile path""" global logfile logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
Specify logfile path
entailment
def is_muted(what): """ Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in there will be logged! :param what: :return: """ state = False for item in solo: if item not in what: state = True else: ...
Checks if a logged event is to be muted for debugging purposes. Also goes through the solo list - only items in there will be logged! :param what: :return:
entailment
def hfoslog(*what, **kwargs): """Logs all *what arguments. :param *what: Loggable objects (i.e. they have a string representation) :param lvl: Debug message level :param exc: Switch to better handle exceptions, use if logging in an except clause :param emitter: Optional log source, ...
Logs all *what arguments. :param *what: Loggable objects (i.e. they have a string representation) :param lvl: Debug message level :param exc: Switch to better handle exceptions, use if logging in an except clause :param emitter: Optional log source, where this can't be determined ...
entailment
def get_tagged(self, event): """Return a list of tagged objects for a schema""" self.log("Tagged objects request for", event.data, "from", event.user, lvl=debug) if event.data in self.tags: tagged = self._get_tagged(event.data) response = { ...
Return a list of tagged objects for a schema
entailment
def provision_system_vessel(items, database_name, overwrite=False, clear=False, skip_user_check=False): """Provisions the default system vessel""" from hfos.provisions.base import provisionList from hfos.database import objectmodels vessel = objectmodels['vessel'].find_one({'name': 'Default System Ves...
Provisions the default system vessel
entailment
def get_tile(url): """ Threadable function to retrieve map tiles from the internet :param url: URL of tile to get """ log = "" connection = None try: if six.PY3: connection = urlopen(url=url, timeout=2) # NOQA else: connection = urlopen(url=url) ...
Threadable function to retrieve map tiles from the internet :param url: URL of tile to get
entailment
def tilecache(self, event, *args, **kwargs): """Checks and caches a requested tile to disk, then delivers it to client""" request, response = event.args[:2] self.log(request.path, lvl=verbose) try: filename, url = self._split_cache_url(request.path, 'tilecache') ...
Checks and caches a requested tile to disk, then delivers it to client
entailment
def todegdec(origin): """ Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD """ # if the input is already a float (or can be converted to float) try: return float(origin) except ValueError: pass # DMS format m = dms_re.search(origin) if m: ...
Convert from [+/-]DDD°MMM'SSS.SSSS" or [+/-]DDD°MMM.MMMM' to [+/-]DDD.DDDDD
entailment
def tomindec(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes) """ origin = float(origin) degrees = int(origin) minutes = (origin % 1) * 60 return degrees, minutes
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes)
entailment
def tomindecstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM' """ degrees, minutes = tomindec(origin) return u'%d°%f\'' % (degrees, minutes)
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM'
entailment
def todms(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds) """ degrees, minutes = tomindec(origin) seconds = (minutes % 1) * 60 return degrees, int(minutes), seconds
Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes, seconds)
entailment
def todmsstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD" """ degrees, minutes, seconds = todms(origin) return u'%d°%d\'%f"' % (degrees, minutes, seconds)
Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD"
entailment
def towgs84(E, N, pkm=False, presentation=None): """ 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 wit...
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...
entailment
def fromwgs84(lat, lng, pkm=False): """ 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 ...
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...
entailment
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(max(value, minValue), maxValue)
Makes sure that value is within a specific range. If not, then the lower or upper bounds is returned
entailment
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.getMapDimensionsByZoomLevel(level) return math.cos( lati...
returns the ground resolution for based on latitude and zoom level.
entailment
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 map scale on the dpi of the screen
entailment
def convertLatLngToPixelXY(self, lat, lng, level): ''' returns the x and y values of the pixel corresponding to a latitude and longitude. ''' mapSize = self.getMapDimensionsByZoomLevel(level) lat = self.clipValue(lat, self.min_lat, self.max_lat) lng = self.clipVa...
returns the x and y values of the pixel corresponding to a latitude and longitude.
entailment
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 y = 0.5 - (self.clipValue(pixelY, 0, mapSize ...
converts a pixel x, y to a latitude and longitude.
entailment
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) != 0: digit += 1 if (y & mask) !...
Computes quadKey value based on tile x, y and z values.
entailment
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) value = quadKey[tileZ - i] if value == '...
Computes tile x, y and z values based on quadKey.
entailment
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, level) return (lat, lng)
Returns the upper-left hand corner lat/lng for a tile
entailment
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, level) ...
Returns a list of tile urls by extent
entailment
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))
returns new tile url based on template
entailment
def referenceframe(self, event): """Handles navigational reference frame updates. These are necessary to assign geo coordinates to alerts and other misc things. :param event with incoming referenceframe message """ self.log("Got a reference frame update! ", event, lvl=e...
Handles navigational reference frame updates. These are necessary to assign geo coordinates to alerts and other misc things. :param event with incoming referenceframe message
entailment
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.log('Adding client') self.clients[event.clientuuid] = event.user fo...
Checks if an alert is ongoing and alerts the newly connected client, if so.
entailment
def trigger(self, event): """AlertManager event handler for incoming events :param event with incoming AlertManager message """ topic = event.data.get('topic', None) if topic is None: self.log('No alert topic to trigger', lvl=warn) return alert ...
AlertManager event handler for incoming events :param event with incoming AlertManager message
entailment
def cancel(self, event): """AlertManager event handler for incoming events :param event with incoming AlertManager message """ topic = event.data.get('topic', None) if topic is None: self.log('No alert topic to cancel', lvl=warn) return self._can...
AlertManager event handler for incoming events :param event with incoming AlertManager message
entailment
def cli(ctx, instance, quiet, verbose, log_level, dbhost, dbname): """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 disp...
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...
entailment
def main(): """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). """ from datetime import datetime # Initialize Command-Line and User-Config Settings, Log # --------...
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).
entailment
def setup_user_config(log): """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). Argume...
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...
entailment
def load_user_config(args, log): """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....
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...
entailment
def load_command_line_args(clargs=None): """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 ...
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...
entailment
def load_log(args): """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 """ from ast...
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
entailment
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 indent = " "*depth # Print with an indentation matching the nested-dictionary depth def my_pri...
Function compares dictionaries by key-value recursively. Old and new input data are both dictionaries
entailment
def cohensutherland(xmin, ymax, xmax, ymin, x1, y1, x2, y2): """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 c...
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...
entailment
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_32FC1) v = cv.CreateMat(r, c, cv.CV_32FC1) return (u, v) else: return [Non...
Horn Schunck legacy OpenCV function requires we use these old-fashioned cv matrices, not numpy array
entailment
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, key=key_in_self, **kwargs) except CatDictErro...
Initialize a CatDict object, checking for errors.
entailment
def _add_cat_dict(self, cat_dict_class, key_in_self, check_for_dupes=True, **kwargs): """Add a CatDict to this Entry if initialization succeeds and it doesn't already exist within the Entry. """ # Try...
Add a CatDict to this Entry if initialization succeeds and it doesn't already exist within the Entry.
entailment
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.
entailment
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, ...
Wrapper for `tqdm` progress bar which also sorts list of strings
entailment
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_priorit...
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`.
entailment
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 ...
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`.
entailment
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,...
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]...
entailment
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 `e...
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`
entailment
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[a...
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
entailment
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 '{}'".fo...
Used by `merge_duplicates`
entailment
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: ...
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.
entailment
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.getp...
Load all events in their `stub` (name, alias, etc only) form. Used in `update` mode.
entailment
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: ...
Delete the file associated with the given entry.
entailment
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`....
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
entailment
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_t...
Choose between each entries given name and its possible aliases for the best one.
entailment
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 ----- ...
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...
entailment
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, ...
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: ...
entailment
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 U...
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...
entailment
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[...
Merge the source alias lists of two CatDicts.
entailment
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.n...
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.
entailment
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
Whether previously archived data should be loaded.
entailment
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....
Use `git rev-parse HEAD <REPO>` to get current SHA.
entailment
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 ra...
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...
entailment
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 ...
Perform a 'git pull' in each data repository. > `git pull -s recursive -X theirs`
entailment
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...
Perform a 'git clone' for each data repository that doesnt exist.
entailment
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)) ...
Perform a 'git reset' in each data repository.
entailment
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(re...
Perform a 'git status' in each data repository.
entailment
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 rep...
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.
entailment
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 ------ excep...
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
entailment
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...
Check that spectrum has legal combination of attributes.
entailment
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...
Check if spectrum is duplicate of another.
entailment
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
Logic for sorting keys in a `Spectrum` relative to one another.
entailment
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
Sorting logic for `Quantity` objects.
entailment
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(ENT...
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()`...
entailment
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 `_val...
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.
entailment
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 ...
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...
entailment
def pretty(self): """Return a 'pretty' string representation of this `Key`. note: do not override the builtin `__str__` or `__repr__` methods! """ retval = ("Key(name={}, type={}, listable={}, compare={}, " "priority={}, kind_preference={}, " "replace...
Return a 'pretty' string representation of this `Key`. note: do not override the builtin `__str__` or `__repr__` methods!
entailment
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. """ # If there is no `type` requirement, everything is allowed if self.type is None: return True is_...
Make sure given value is consistent with this `Key` specification. NOTE: if `type` is 'None', then `listable` also is *not* checked.
entailment
def get_logger(name=None, stream_fmt=None, file_fmt=None, date_fmt=None, stream_level=None, file_level=None, tofile=None, tostr=True): """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 ...
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...
entailment
def log_raise(log, err_str, err_type=RuntimeError): """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. """ log.error(err...
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.
entailment
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 kilobytes UNIT = KB*KB if sys.pla...
Log the current memory usage.
entailment
def doblob(morphed, blobdet, img, anno=True): """ 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 """ keypo...
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
entailment
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 given # subcommand is required for operation ...
Parse arguments and return configuration settings.
entailment
def _setup_argparse(self): """Create `argparse` instance, and setup with appropriate parameters. """ parser = argparse.ArgumentParser( prog='catalog', description='Parent Catalog class for astrocats.') subparsers = parser.add_subparsers( description='valid subcom...
Create `argparse` instance, and setup with appropriate parameters.
entailment
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_argument( '--update', '-u', dest='update', ...
Create parser for 'import' subcommand, and associated arguments.
entailment
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( "git-push", help="...
Create a sub-parsers for git subcommands.
entailment
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_argument( '--count', '-c', dest='coun...
Create a parser for the 'analyze' subcommand.
entailment
def compress_gz(fname): """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 : st...
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...
entailment
def draw_flow(img, flow, step=16, dtype=uint8): """ 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 """ maxval = iinfo(img.dtype).max # scaleFact = 1. #arbit...
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
entailment
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(((degrees(ang)/2).astype(dtype), # /2 to keep less than 255 ...
mag must be uint8, uint16, uint32 and 2-D ang is in radians (float)
entailment
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
flow dimensions y,x,2 3-D. flow[...,0] is magnitude, flow[...,1] is angle
entailment
def IOC(dir, type, nr, size): """ 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. """ assert dir <= _IOC_DIRM...
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.
entailment
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 return result
Returns the size of given type, and check its suitability for use in an ioctl command number.
entailment