Search is not available for this dataset
text
stringlengths
75
104k
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...
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: ...
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...
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...
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...
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...
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 += "(?:" ...
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 ...
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))
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...
def set_logfile(path, instance): """Specify logfile path""" global logfile logfile = os.path.normpath(path) + '/hfos.' + instance + '.log'
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: ...
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, ...
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 = { ...
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...
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) ...
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') ...
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: ...
def tomindec(origin): """ Convert [+/-]DDD.DDDDD to a tuple (degrees, minutes) """ origin = float(origin) degrees = int(origin) minutes = (origin % 1) * 60 return degrees, minutes
def tomindecstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM.MMMM' """ degrees, minutes = tomindec(origin) return u'%d°%f\'' % (degrees, minutes)
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
def todmsstr(origin): """ Convert [+/-]DDD.DDDDD to [+/-]DDD°MMM'DDD.DDDDD" """ degrees, minutes, seconds = todms(origin) return u'%d°%d\'%f"' % (degrees, minutes, seconds)
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...
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 ...
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)
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...
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
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...
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 ...
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) !...
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 == '...
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)
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) ...
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))
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...
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...
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 ...
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...
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...
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 # --------...
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...
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....
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 ...
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...
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...
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...
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...
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...
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...
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)
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, ...
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...
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 ...
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,...
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...
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...
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...
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: ...
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...
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: ...
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`....
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...
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 ----- ...
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, ...
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...
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[...
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...
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....
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...
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 ...
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...
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)) ...
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...
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...
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...
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...
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...
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(ENT...
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...
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 ...
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...
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_...
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 ...
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...
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...
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...
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 ...
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...
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', ...
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="...
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...
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...
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...
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 ...
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
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...
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