input
stringlengths
11
7.65k
target
stringlengths
22
8.26k
async def open(self): pass
def quitDriver(self): self.driver.quit() self.driver = None
async def open(self): pass
def runSpider(self, lstSubcommand=None): strSubcommand = lstSubcommand[0] strArg1 = None if len(lstSubcommand) == 2: strArg1 = lstSubcommand[1] self.initDriver() #init selenium driver self.dicSubCommandHandler[strSubcommand](strArg1) self.quitDriver() #quit se...
async def open(self): pass
def downloadIndexPage(self, uselessArg1=None): logging.info("download index page") strIndexHtmlFolderPath = self.SOURCE_HTML_BASE_FOLDER_PATH + u"\\TECHORANGE" if not os.path.exists(strIndexHtmlFolderPath): os.mkdir(strIndexHtmlFolderPath) #mkdir source_html/TECHORANGE/ #科技報橘...
async def open(self): pass
def downloadTagPag(self, uselessArg1=None): logging.info("download tag page") strTagHtmlFolderPath = self.SOURCE_HTML_BASE_FOLDER_PATH + u"\\TECHORANGE\\tag" if not os.path.exists(strTagHtmlFolderPath): os.mkdir(strTagHtmlFolderPath) #mkdir source_html/TECHORANGE/tag/ strTagW...
async def open(self): pass
def limitStrLessThen128Char(self, strStr=None): if len(strStr) > 128: logging.info("limit str less then 128 char") return strStr[:127] + u"_" else: return strStr
async def open(self): pass
def downloadNewsPage(self, strTagName=None): if strTagName is None: #未指定 tag lstStrObtainedTagName = self.db.fetchallCompletedObtainedTagName() for strObtainedTagName in lstStrObtainedTagName: self.downloadNewsPageWithGivenTagName(strTagName=strObtainedTagName...
async def open(self): pass
def downloadNewsPageWithGivenTagName(self, strTagName=None): logging.info("download news page with tag %s"%strTagName) strNewsHtmlFolderPath = self.SOURCE_HTML_BASE_FOLDER_PATH + u"\\TECHORANGE\\news" if not os.path.exists(strNewsHtmlFolderPath): os.mkdir(strNewsHtmlFolderPath) #mkdi...
async def open(self): pass
def write(): try: p = round(weather.pressure(),2) c = light.light() print('{"light": '+str(c)+', "pressure": '+str(p)+' }') except KeyboardInterrupt: pass
async def open(self): pass
def signal_handler_mapping(self): """A dict mapping (signal number) -> (a method handling the signal).""" # Could use an enum here, but we never end up doing any matching on the specific signal value, # instead just iterating over the registered signals to set handlers, so a dict is probably ...
async def open(self): pass
def __init__(self): self._ignore_sigint_lock = threading.Lock() self._threads_ignoring_sigint = 0 self._ignoring_sigint_v2_engine = False
async def open(self): pass
def _check_sigint_gate_is_correct(self): assert ( self._threads_ignoring_sigint >= 0 ), "This should never happen, someone must have modified the counter outside of SignalHandler."
async def open(self): pass
def _handle_sigint_if_enabled(self, signum, _frame): with self._ignore_sigint_lock: self._check_sigint_gate_is_correct() threads_ignoring_sigint = self._threads_ignoring_sigint ignoring_sigint_v2_engine = self._ignoring_sigint_v2_engine if threads_ignoring_sigint == 0...
async def open(self): pass
def _toggle_ignoring_sigint_v2_engine(self, toggle: bool): with self._ignore_sigint_lock: self._ignoring_sigint_v2_engine = toggle
async def open(self): pass
def _ignoring_sigint(self): with self._ignore_sigint_lock: self._check_sigint_gate_is_correct() self._threads_ignoring_sigint += 1 try: yield finally: with self._ignore_sigint_lock: self._threads_ignoring_sigint -= 1 ...
async def open(self): pass
def handle_sigint(self, signum, _frame): raise KeyboardInterrupt("User interrupted execution with control-c!")
async def open(self): pass
def __init__(self, signum, signame): self.signum = signum self.signame = signame self.traceback_lines = traceback.format_stack() super(SignalHandler.SignalHandledNonLocalExit, self).__init__()
async def open(self): pass
def handle_sigquit(self, signum, _frame): raise self.SignalHandledNonLocalExit(signum, "SIGQUIT")
async def open(self): pass
def handle_sigterm(self, signum, _frame): raise self.SignalHandledNonLocalExit(signum, "SIGTERM")
async def open(self): pass
def __new__(cls, *args, **kwargs): raise TypeError("Instances of {} are not allowed to be constructed!".format(cls.__name__))
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
def _exiter(self) -> Optional[Exiter]: return ExceptionSink.get_global_exiter()
async def open(self): pass
def get_global_exiter(cls) -> Optional[Exiter]: return cls._exiter
async def open(self): pass
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 ...
async def open(self): pass
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_...
async def open(self): pass
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!...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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()
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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)
async def open(self): pass
def _iso_timestamp_for_now(cls): return datetime.datetime.now().isoformat()
async def open(self): pass
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, )
async def open(self): pass
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
async def open(self): pass
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 "" ...
async def open(self): pass
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...
async def open(self): pass
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_...
async def open(self): pass
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(...
async def open(self): pass
def __init__(self, raw_data): self._raw = raw_data
async def open(self): pass
def __getitem__(self, key): return self._raw[key]
async def open(self): pass
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] ...
async def open(self): pass
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 ...
async def open(self): pass
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 (...
async def open(self): pass
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()
async def open(self): pass
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...
async def open(self): pass
def chunkstring(s, n): return [ s[i:i+n] for i in xrange(0, len(s), n) ]
async def open(self): pass
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...
async def open(self): pass
def __init__(self, key): self.bs = 32 self.key = hashlib.sha256(key.encode()).digest()
async def open(self): pass
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...
async def open(self): pass
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)
async def open(self): pass
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-...
async def open(self): pass
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')
async def open(self): pass
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" ...
async def open(self): pass
def _pad(self, s): return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)
async def open(self): pass
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...
async def open(self): pass
def _unpad(s): return s[:-ord(s[len(s)-1:])]
async def open(self): pass
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, ...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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\...
async def open(self): pass
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 `...
async def open(self): pass
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
async def open(self): pass
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...
async def open(self): pass
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: ...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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"...
async def open(self): pass
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...
async def open(self): pass
def close(self): time.sleep(0.1) self.sock.close() return 0
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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 ...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
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 `...
async def open(self): pass
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, ...
async def open(self): pass
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...
async def open(self): pass
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...
async def open(self): pass
def get_schema(self): """Returns the set YAML schema for the metric class. Returns: YAML schema of the metrics type. """ return self._schema
async def open(self): pass
def get(self): return os.environ[self._name]
async def open(self): pass
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...
async def open(self): pass
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 ...
async def open(self): pass
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 = {}
async def open(self): pass
def get(self): return self._method(self._key)
async def open(self): pass
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]
async def open(self): pass
def __init__(self, child_proxy): self._child_proxy = child_proxy
async def open(self): pass
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...
async def open(self): pass
def get(self): return json.loads(self._child_proxy.get())
async def open(self): pass
def __init__(self): super().__init__('confidence_metrics.yaml') self._initialized = True
async def open(self): pass
def __init__(self): super().__init__('confusion_matrix.yaml') self._matrix = [[]] self._categories = [] self._initialized = True
async def open(self): pass
def get(self): return base64.b64decode(self._child_proxy.get())
async def open(self): pass
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 = ...
async def open(self): pass
def __init__(self, key, child_proxy): try: self._key = int(key) except ValueError: self._key = key self._child_proxy = child_proxy
async def open(self): pass
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...