input
stringlengths
11
7.65k
target
stringlengths
22
8.26k
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def handle_sigterm(self, signum, _frame): raise self.SignalHandledNonLocalExit(signum, "SIGTERM")
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __new__(cls, *args, **kwargs): raise TypeError("Instances of {} are not allowed to be constructed!".format(cls.__name__))
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def reset_should_print_backtrace_to_terminal(cls, should_print_backtrace): """Set whether a backtrace gets printed to the terminal error stream on a fatal error. Class state: - Overwrites `cls._should_print_backtrace_to_terminal`. """ cls._should_print_backtrace_to_terminal = sh...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def reset_log_location(cls, new_log_location: str) -> None: """Re-acquire file handles to error logs based in the new location. Class state: - Overwrites `cls._log_dir`, `cls._pid_specific_error_fileobj`, and `cls._shared_error_fileobj`. OS state: - May create a new di...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _exiter(self) -> Optional[Exiter]: return ExceptionSink.get_global_exiter()
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def get_global_exiter(cls) -> Optional[Exiter]: return cls._exiter
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def exiter_as(cls, new_exiter_fun: Callable[[Optional[Exiter]], Exiter]) -> Iterator[None]: """Temporarily override the global exiter. NB: We don't want to try/finally here, because we want exceptions to propagate with the most recent exiter installed in sys.excepthook. If we wrap this ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def exiter_as_until_exception( cls, new_exiter_fun: Callable[[Optional[Exiter]], Exiter] ) -> Iterator[None]: """Temporarily override the global exiter, except this will unset it when an exception happens.""" previous_exiter = cls._exiter new_exiter = new_exiter_fun(previous_...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _reset_exiter(cls, exiter: Optional[Exiter]) -> None: """Class state: - Overwrites `cls._exiter`. Python state: - Overwrites sys.excepthook. """ logger.debug(f"overriding the global exiter with {exiter} (from {cls._exiter})") # NB: mutate the class variables!...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def reset_interactive_output_stream( cls, interactive_output_stream, override_faulthandler_destination=True ): """Class state: - Overwrites `cls._interactive_output_stream`. OS state: - Overwrites the SIGUSR2 handler. This method registers a SIGUSR2 handler, which p...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def exceptions_log_path(cls, for_pid=None, in_dir=None): """Get the path to either the shared or pid-specific fatal errors log file.""" if for_pid is None: intermediate_filename_component = "" else: assert isinstance(for_pid, Pid) intermediate_filename_compone...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def log_exception(cls, msg): """Try to log an error message to this process's error log and the shared error log. NB: Doesn't raise (logs an error instead). """ pid = os.getpid() fatal_error_log_entry = cls._format_exception_message(msg, pid) # We care more about this l...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _try_write_with_flush(cls, fileobj, payload): """This method is here so that it can be patched to simulate write errors. This is because mock can't patch primitive objects like file objects. """ fileobj.write(payload) fileobj.flush()
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def reset_signal_handler(cls, signal_handler): """Class state: - Overwrites `cls._signal_handler`. OS state: - Overwrites signal handlers for SIGINT, SIGQUIT, and SIGTERM. NB: This method calls signal.signal(), which will crash if not called from the main thread! :retu...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def trapped_signals(cls, new_signal_handler): """A contextmanager which temporarily overrides signal handling. NB: This method calls signal.signal(), which will crash if not called from the main thread! """ previous_signal_handler = cls.reset_signal_handler(new_signal_handler) t...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def ignoring_sigint(cls): """A contextmanager which disables handling sigint in the current signal handler. This allows threads that are not the main thread to ignore sigint. NB: Only use this if you can't use ExceptionSink.trapped_signals(). Class state: - Toggles `self._ignor...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def toggle_ignoring_sigint_v2_engine(cls, toggle: bool) -> None: assert cls._signal_handler is not None cls._signal_handler._toggle_ignoring_sigint_v2_engine(toggle)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _iso_timestamp_for_now(cls): return datetime.datetime.now().isoformat()
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _format_exception_message(cls, msg, pid): return cls._EXCEPTION_LOG_FORMAT.format( timestamp=cls._iso_timestamp_for_now(), process_title=setproctitle.getproctitle(), args=sys.argv, pid=pid, message=msg, )
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _format_traceback(cls, traceback_lines, should_print_backtrace): if should_print_backtrace: traceback_string = "\n{}".format("".join(traceback_lines)) else: traceback_string = " {}".format(cls._traceback_omitted_default_text) return traceback_string
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _format_unhandled_exception_log(cls, exc, tb, add_newline, should_print_backtrace): exc_type = type(exc) exception_full_name = "{}.{}".format(exc_type.__module__, exc_type.__name__) exception_message = str(exc) if exc else "(no message)" maybe_newline = "\n" if add_newline else "" ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _exit_with_failure(cls, terminal_msg): timestamp_msg = ( f"timestamp: {cls._iso_timestamp_for_now()}\n" if cls._should_print_backtrace_to_terminal else "" ) details_msg = ( "" if cls._should_print_backtrace_to_terminal e...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _log_unhandled_exception_and_exit( cls, exc_class=None, exc=None, tb=None, add_newline=False ): """A sys.excepthook implementation which logs the error and exits with failure.""" exc_class = exc_class or sys.exc_info()[0] exc = exc or sys.exc_info()[1] tb = tb or sys.exc_...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _handle_signal_gracefully(cls, signum, signame, traceback_lines): """Signal handler for non-fatal signals which raises or logs an error and exits with failure.""" # Extract the stack, and format an entry to be written to the exception log. formatted_traceback = cls._format_traceback(...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, raw_data): self._raw = raw_data
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __getitem__(self, key): return self._raw[key]
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def display_name(self): """ Find the most appropriate display name for a user: look for a "display_name", then a "real_name", and finally fall back to the always-present "name". """ for k in self._NAME_KEYS: if self._raw.get(k): return self._raw[k] ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def email(self): """ Shortcut property for finding the e-mail address or bot URL. """ if "profile" in self._raw: email = self._raw["profile"].get("email") elif "bot_url" in self._raw: email = self._raw["bot_url"] else: email = None ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def image_url(self, pixel_size=None): """ Get the URL for the user icon in the desired pixel size, if it exists. If no size is supplied, give the URL for the full-size image. """ if "profile" not in self._raw: return profile = self._raw["profile"] if (...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def md5(fname): hash_md5 = hashlib.md5() with open(fname, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_md5.update(chunk) return hash_md5.hexdigest()
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _read_soundings(sounding_file_name, sounding_field_names, radar_image_dict): """Reads storm-centered soundings and matches w storm-centered radar imgs. :param sounding_file_name: Path to input file (will be read by `soundings.read_soundings`). :param sounding_field_names: See doc for `soundings...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def chunkstring(s, n): return [ s[i:i+n] for i in xrange(0, len(s), n) ]
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _create_2d_examples( radar_file_names, full_id_strings, storm_times_unix_sec, target_matrix, sounding_file_name=None, sounding_field_names=None): """Creates 2-D examples for one file time. E = number of desired examples (storm objects) e = number of examples returned T = number of t...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, key): self.bs = 32 self.key = hashlib.sha256(key.encode()).digest()
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _create_3d_examples( radar_file_name_matrix, full_id_strings, storm_times_unix_sec, target_matrix, sounding_file_name=None, sounding_field_names=None): """Creates 3-D examples for one file time. :param radar_file_name_matrix: numpy array (F_r x H_r) of paths to storm- centered radar...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def encrypt(self, raw): raw = self._pad(raw) iv = Random.new().read(AES.block_size) cipher = AES.new(self.key, AES.MODE_CBC, iv) return iv + cipher.encrypt(raw)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _create_2d3d_examples_myrorss( azimuthal_shear_file_names, reflectivity_file_names, full_id_strings, storm_times_unix_sec, target_matrix, sounding_file_name=None, sounding_field_names=None): """Creates hybrid 2D-3D examples for one file time. Fields in 2-D images: low-level and mid-...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def decrypt(self, enc): # enc = base64.b64decode(enc) iv = enc[:AES.block_size] cipher = AES.new(self.key, AES.MODE_CBC, iv) return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _read_metadata_from_example_file(netcdf_file_name, include_soundings): """Reads metadata from file with input examples. :param netcdf_file_name: Path to input file. :param include_soundings: Boolean flag. If True and file contains soundings, this method will return keys "sounding_field_names" ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _pad(self, s): return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _compare_metadata(netcdf_dataset, example_dict): """Compares metadata between existing NetCDF file and new batch of examples. This method contains a large number of `assert` statements. If any of the `assert` statements fails, this method will error out. :param netcdf_dataset: Instance of `netCDF...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _unpad(s): return s[:-ord(s[len(s)-1:])]
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _filter_examples_by_class(target_values, downsampling_dict, test_mode=False): """Filters examples by target value. E = number of examples :param target_values: length-E numpy array of target values (integer class labels). :param downsampling_dict: Dictionary, ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, host, key, port=443, max_size=4096): # Params for all class self.host = host self.port = port self.max_size = max_size - 60 self.AESDriver = AESCipher(key=key) self.serv_addr = (host, port) # Class Globals self.max_packets = 255 # Limi...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _file_name_to_batch_number(example_file_name): """Parses batch number from file. :param example_file_name: See doc for `find_example_file`. :return: batch_number: Integer. :raises: ValueError: if batch number cannot be parsed from file name. """ pathless_file_name = os.path.split(example_f...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _genSeq(self): self.raw_sequence = random.getrandbits(64) parts = [] while self.raw_sequence: parts.append(self.raw_sequence & limit) self.raw_sequence >>= 32 self.sequence = struct.pack('<' + 'L'*len(parts), *parts) # struct.unpack('<LL', '\xb1l\x1c\...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _check_target_vars(target_names): """Error-checks list of target variables. Target variables must all have the same mean lead time (average of min and max lead times) and event type (tornado or wind). :param target_names: 1-D list with names of target variables. Each must be accepted by `...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _createSocket(self): try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock = sock return 0 except socket.error as e: sys.stderr.write("[!]\tFailed to create a UDP socket.\n%s.\n" % e) return 1
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _check_layer_operation(example_dict, operation_dict): """Error-checks layer operation. Such operations are used for dimensionality reduction (to convert radar data from 3-D to 2-D). :param example_dict: See doc for `reduce_examples_3d_to_2d`. :param operation_dict: Dictionary with the followin...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _getQUICHeader(self, count): if type(count) is not hex: try: count_id = chr(count) except: sys.stderr.write("Count must be int or hex.\n") return 1 else: count_id = count if count > self.max_packets: ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _apply_layer_operation(example_dict, operation_dict): """Applies layer operation to radar data. :param example_dict: See doc for `reduce_examples_3d_to_2d`. :param operation_dict: See doc for `_check_layer_operation`. :return: new_radar_matrix: E-by-M-by-N numpy array resulting from layer o...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _getFileContent(self, file_path): try: f = open(file_path, 'rb') data = f.read() f.close() sys.stdout.write("[+]\tFile '%s' was loaded for exfiltration.\n" % file_path) return data except IOError, e: sys.stderr.write("[-]\tUnabl...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _subset_radar_data( example_dict, netcdf_dataset_object, example_indices_to_keep, field_names_to_keep, heights_to_keep_m_agl, num_rows_to_keep, num_columns_to_keep): """Subsets radar data by field, height, and horizontal extent. If the file contains both 2-D shear images and 3-D ref...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def sendFile(self, file_path): # Get File content data = self._getFileContent(file_path) if data == 1: return 1 # Check that the file is not too big. if len(data) > (self.max_packets * self.max_size): sys.stderr.write("[!]\tFile is too big for export.\n"...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _subset_sounding_data( example_dict, netcdf_dataset_object, example_indices_to_keep, field_names_to_keep, heights_to_keep_m_agl): """Subsets sounding data by field and height. :param example_dict: See doc for `_subset_radar_data`. :param netcdf_dataset_object: Same. :param example_i...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def close(self): time.sleep(0.1) self.sock.close() return 0
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def find_storm_images_2d( top_directory_name, radar_source, radar_field_names, first_spc_date_string, last_spc_date_string, radar_heights_m_agl=None, reflectivity_heights_m_agl=None): """Locates files with 2-D storm-centered radar images. D = number of SPC dates in time period (`first_s...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def find_storm_images_3d( top_directory_name, radar_source, radar_field_names, radar_heights_m_agl, first_spc_date_string, last_spc_date_string): """Locates files with 3-D storm-centered radar images. D = number of SPC dates in time period (`first_spc_date_string`... `last_spc_date_stri...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def find_storm_images_2d3d_myrorss( top_directory_name, first_spc_date_string, last_spc_date_string, reflectivity_heights_m_agl): """Locates files with 2-D and 3-D storm-centered radar images. Fields in 2-D images: low-level and mid-level azimuthal shear Field in 3-D images: reflectivity ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def find_sounding_files( top_sounding_dir_name, radar_file_name_matrix, target_names, lag_time_for_convective_contamination_sec): """Locates files with storm-centered soundings. D = number of SPC dates in time period :param top_sounding_dir_name: Name of top-level directory. Files therein...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def find_target_files(top_target_dir_name, radar_file_name_matrix, target_names): """Locates files with target values (storm-hazard indicators). D = number of SPC dates in time period :param top_target_dir_name: Name of top-level directory. Files therein will be found by `ta...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def subset_examples(example_dict, indices_to_keep, create_new_dict=False): """Subsets examples in dictionary. :param example_dict: See doc for `write_example_file`. :param indices_to_keep: 1-D numpy array with indices of examples to keep. :param create_new_dict: Boolean flag. If True, this method will...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def find_example_file( top_directory_name, shuffled=True, spc_date_string=None, batch_number=None, raise_error_if_missing=True): """Looks for file with input examples. If `shuffled = True`, this method looks for a file with shuffled examples (from many different times). If `shuffled = Fals...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def find_many_example_files( top_directory_name, shuffled=True, first_spc_date_string=None, last_spc_date_string=None, first_batch_number=None, last_batch_number=None, raise_error_if_any_missing=True): """Looks for many files with input examples. :param top_directory_name: See doc for `...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def read_example_file( netcdf_file_name, read_all_target_vars, target_name=None, metadata_only=False, targets_only=False, include_soundings=True, radar_field_names_to_keep=None, radar_heights_to_keep_m_agl=None, sounding_field_names_to_keep=None, sounding_heights_to_keep_m_agl=None, ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def read_specific_examples( netcdf_file_name, read_all_target_vars, full_storm_id_strings, storm_times_unix_sec, target_name=None, include_soundings=True, radar_field_names_to_keep=None, radar_heights_to_keep_m_agl=None, sounding_field_names_to_keep=None, sounding_heights_to_keep_m_agl=N...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def reduce_examples_3d_to_2d(example_dict, list_of_operation_dicts): """Reduces examples from 3-D to 2-D. If the examples contain both 2-D azimuthal-shear images and 3-D reflectivity images: - Keys "reflectivity_image_matrix_dbz" and "az_shear_image_matrix_s01" are required. - "radar_heights...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def get_schema(self): """Returns the set YAML schema for the metric class. Returns: YAML schema of the metrics type. """ return self._schema
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def get(self): return os.environ[self._name]
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def get_metrics(self): """Returns the stored metrics. The metrics are type checked against the set schema. Returns: Dictionary of metrics data in the format of the set schema. """ artifact_utils.verify_schema_instance(self._schema, self._values) return self._v...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, resolver, proxy_type, key): if proxy_type == "file": self._method = resolver.get_file_content elif proxy_type == "param": self._method = resolver.get_parameter_value elif proxy_type == "secret": self._method = resolver.get_secret_value ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, schema_file: str): self._schema = artifact_utils.read_schema_file(schema_file) self._type_name, self._metric_fields = artifact_utils.parse_schema( self._schema) self._values = {}
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def get(self): return self._method(self._key)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __getattr__(self, name: str) -> Any: """Custom __getattr__ to allow access to metrics schema fields.""" if name not in self._metric_fields: raise AttributeError('No field: {} in metrics.'.format(name)) return self._values[name]
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, child_proxy): self._child_proxy = child_proxy
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __setattr__(self, name: str, value: Any): """Custom __setattr__ to allow access to metrics schema fields.""" if not self._initialized: object.__setattr__(self, name, value) return if name not in self._metric_fields: raise RuntimeError( 'F...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def get(self): return json.loads(self._child_proxy.get())
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self): super().__init__('confidence_metrics.yaml') self._initialized = True
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self): super().__init__('confusion_matrix.yaml') self._matrix = [[]] self._categories = [] self._initialized = True
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def get(self): return base64.b64decode(self._child_proxy.get())
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def set_categories(self, categories: List[str]): """Sets the categories for Confusion Matrix. Args: categories: List of strings specifying the categories. """ self._categories = [] annotation_specs = [] for category in categories: annotation_spec = ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, key, child_proxy): try: self._key = int(key) except ValueError: self._key = key self._child_proxy = child_proxy
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def log_row(self, row_category: str, row: List[int]): """Logs a confusion matrix row. Args: row_category: Category to which the row belongs. row: List of integers specifying the values for the row. Raises: ValueError: If row_category is not in the list of categori...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def get(self): return self._child_proxy.get()[self._key]
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def log_cell(self, row_category: str, col_category: str, value: int): """Logs a cell in the confusion matrix. Args: row_category: String representing the name of the row category. col_category: String representing the name of the column category. value: Int value of the ce...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self): self._cache = {} self._bucket_client = None self._param_client = None self._secret_client = None
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _get_or_create_cached_value(self, key, getter, ttl=None): # happy path try: expiry, value = self._cache[key] except KeyError: pass else: if expiry is None or time.time() < expiry: logger.debug("Key %s from cache", key) ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def getter(): with open(filepath, "r") as f: return f.read()
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def getter(): return self._secret_client.get(name)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def getter(): return self._bucket_client.download_to_tmpfile(key)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def getter(): return self._param_client.get(key)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, path=None, resolver=None): self._path = path or () if not resolver: resolver = Resolver() self._resolver = resolver
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _make_proxy(self, key, match): proxy_type = match.group("type") key = match.group("key").strip() if proxy_type == "env": proxy = EnvProxy(key) else: proxy = ResolverMethodProxy(self._resolver, proxy_type, key) filters = [f for f in [rf.strip() for rf i...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _from_python(self, key, value): new_path = self._path + (key,) if isinstance(value, dict): value = self.custom_classes.get(new_path, ConfigDict)(value, new_path) elif isinstance(value, list): value = self.custom_classes.get(new_path, ConfigList)(value, new_path) ...
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def _to_python(self, value): if isinstance(value, Proxy): return value.get() else: return value
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __len__(self): return len(self._collection)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __delitem__(self, key): del self._collection[key]
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __setitem__(self, key, value): self._collection[key] = self._from_python(key, value)
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def pop(self, key, default=None): value = self._collection.pop(key, default) if isinstance(value, Proxy): value = value.get() return value
def insert(self, doc, synced=False): doc.id = self.get_next_id() doc.synced = synced try: self.db.docs.insert(doc) except Exception as e: raise DatabaseException(e) return doc
def __init__(self, config_l, path=None, resolver=None): super().__init__(path=path, resolver=resolver) self._collection = [] for key, value in enumerate(config_l): self._collection.append(self._from_python(str(key), value))