content
stringlengths
22
815k
id
int64
0
4.91M
def _directly_configure_from_flags(fields): """Helper function that translate flag values to a dict.""" return {field: getattr(FLAGS, field) for field in fields}
61,000
def draw_smiley( pos_x: float, pos_y: float, fade_in_frames: int ) -> Generator[Image.Image, None, None]: """ Generator method for rendering an emoji style smiley face :param pos_x: x axes offset for the center of the smiley face :param pos_y: y axes offset for the center of the smiley face :par...
61,001
def clean_text(text): """ Applies all the filters to input text. :param text: The input string. :type text: String. :returns: The processed String. :return type: String. """ text = text.lower() text = strip_accents(text) text = strip_digitsAndSpecialChars(text) retur...
61,002
def get_sleep_time(time_start, time_now, poll_int): """Calculate time to sleep. Args: time_start(datetime): Time loop started time_now(datetime): Current time poll_int(int): Poll interval in seconds Returns: sleep_time(float) """ time_sleep = poll_int...
61,003
def sqrt(node) -> Node: """square root of the node, np.sqrt""" return Node(node, None, np.sqrt(node.value), 'sqrt' )
61,004
def permute_code_object(baseline): """Take a code object and change one byte of the bytecode.""" bytecode = list(baseline.co_code) bytecode[random.randint(0, len(bytecode) - 1)] = random_char() return clone_code_object(baseline, code="".join(bytecode))
61,005
def check_scraped(name_dataset, term, year, num): """ """ name_src, name_dst, name_summary, name_unique, plot_unique = name_paths(name_dataset) paths_to_check = [] paths_to_check.append(os.path.join(retrieve_path(name_src))) paths_to_check.append(os.path.join(retrieve_path('pub_gschola...
61,006
def expand_session(name): """ Helper function that creates the session names for the original mkdir and the actual code being run. """ user_name = os.environ.get('SUDO_USER') or os.environ['USER'] return "{}_cp_{}".format(user_name, name), "{}_run_{}".format(user_name, name)
61,007
def _fix_values(key, md): """ Recursively search each item in metadata and reassign values. """ i = md[key] md = _set_val(i, key, md) if isinstance(i, list): new = [] for idx in range(len(i)): new.append(_fix_values(idx, i)[idx]) md[key] = new if isins...
61,008
def p_declarationList(t): """ declarationList : declarationList declaration | declaration """ if len(t) == 3: t[1].append(t[2]) t[0] = t[1] else: t[0] = [t[1]] repGrammar.append(t.slice)
61,009
def test_custom_environment_failures(env_name, sub_sampling_factor, action): """ Test custom implementations of our environments fail when disallowed actions are passed to them. :return: """ environment = Environment(name=env_name, sub_sampling_factor=sub_sampling_...
61,010
def type_msg(string): """ Stimulates typing a string of characters Args: string (str) : A string of characters to enter """ k = PyKeyboard() k.type_string(string)
61,011
def imstackshow(im_stack, time_points=None, color_mapper=None, downscale=1, plot_height=400): """ Build display of image stack. Parameters ---------- im_stack : list of tuple of 2d Numpy arrays List of images time_points : ndarray, default None ...
61,012
def distinct_count(daskDf, columnName): """Counts distint number of values in Dask dataframe Keyword arguments: daskDf -- Dask dataframe columnName -- Column name Return: return -- Distinct number of values """ return daskDf[columnName].drop_duplicates().size
61,013
def pow_3_of(number): """ cube input number helper function from lalsimulation/src/LALSimIMRPhenomD_internals.h """ return number*number*number
61,014
def boolean_search( query, inverted_index ) -> list: """ Implementation of the boolean search by keywords: {"AND", "OR"} :type query: str, :type inverted_index: defaultdict """ resulting_index = [] # Extracting the dict of key/value pairs, where key is token query_dict = ...
61,015
def test_build_file(build_file: str, repo: str): """Verify that build file syntax is correct.""" logging.debug("Testing %s...", build_file) subprocess.check_output(["buck", "audit", "rules", build_file], cwd=repo)
61,016
def sample_views(nviews): """View sampling function. Args: nviews: Number of views to be sampled Returns: rot_trans_list: list of (rot, trans) tuples """ rot_trans_list = [] for _ in range(nviews): x_cam = np.random.uniform(-0.5, 0.5) y_cam = np.random.uniform(-0.5, 0.5) z_cam = 0 ...
61,017
def get_step_rolling(cycle_nr=1): """ Get the step name for rolling step in cycle cycle_nr :param cycle_nr: The cycle number :type cycle_nr: int :returns: The step name :rtype: str """ return 'rolling_' + cycle_str(cycle_nr)
61,018
def read_list_h5(h5): """ Read list from h5 file. A list is a group of groups named with their index, and attributes as the data. The format corresponds to that written in write_lattice_h5 """ # Convert to ints for sorting ixlist = sorted([int(k) for k in h5]) # Back to s...
61,019
def resultSetFacetsHandler(session, val, resp, resultSet=[], db=None): """Put facet for requested index into extraSearchRetrieveData val is a CQL query. Boolean used is meaningless, facets are returned for each clause. Term in each clause is also meaningless and need be nothing more th...
61,020
def verse(num_of_bottles): """bottle verse""" b = "bottle" if num_of_bottles == 1 else "bottles" if num_of_bottles==1: last = "No more bottles" elif num_of_bottles==2: last = "1 bottle" else: last = f'{num_of_bottles-1} bottles' return '\n'.join([ f'{num_of_bot...
61,021
def fizz_buzz(tuple): """ Transform the input tuple to a string that follows the Fizz Buzz rules Args: tuple: tuple Returns: string """ if tuple == 0: return None ret_val = "" if tuple % 3 == 0: ret_val += "Fizz" if tuple % 5 == 0: ret...
61,022
def f1_score(precision, recall): """Creates an op for calculating the F1 score. Args: precision: A tensor representing precision. recall: A tensor representing recall. Returns: A tensor with the result of the F1 calculation. """ return tf.where( tf.greater(precision + recall, 0), 2 * ( ...
61,023
def observe_contour(firemap: GeoData, contour: float, n_uavs, uav_speed, duty_cycle=0.25): """Extract a contour and then simulate it is observed by N UAVs. Each UAV gets an equal size chunk and observed a contigous portion of it (duty_cycle) The observation time is estimated from the speed speed is in m...
61,024
def mover(path_from: str, path_to: str, file: str): """ This function moves the file from the directory of path_from to the directory of path_to. """ shutil.copyfile(path_from + "/" + file, path_to + "/" + file)
61,025
def gradient_and_profile_with_spline(T, F, period, phase_given, time_half_transit, amplitude, spline): """a variant of profile wtih spline it also returns gradient""" if period < 0.0: print(("Invalid period in gradient_and_profile_with_spline")) raise ValueError elif time_half_transit <...
61,026
def disk_to_dict(disk): """Converts a lxml.objectify.ObjectifiedElement disk object to a dict. :param lxml.objectify.ObjectifiedElement disk: an object containing EntityType.DISK XML data. :return: dictionary representation of disk object. :rtype: dict """ result = {} result['name...
61,027
def download_geometry(geometry, year=2019, out_dir="."): """ Get spatial information for a census geometry in geojson format and save it to disk :param geometry: type of census geometry to use :param year: Year to get geometry for :param out_dir: Directory to save downloaded files in. Note that due...
61,028
def get_hashID(username, hashMode=64, tableGroup=4): """根据 username 确定唯一 hash 值(确定分表) # 分组公式:64 = 每组多少个count * group需要分组的个数 # 数据所在环的位置(也就是在哪个库中):value = key mode 64 / count * count hash(key)在0~3之间在第0号表 hash(key)在4~7之间在第4号表 hash(key)在8~11之间在第8号表 hash(key)在0~3之间在第0号库 hash(key)在4~7之间在...
61,029
def helm(): """Manage CKAN instances deployed via Helm""" pass
61,030
def test_from_string_study_uri(suffix): """Checks that Study URI is parsed correctly and behaves as expected.""" uri = _STUDY_URI if suffix is None else f'{_STUDY_URI}/{suffix.value}' study_uri = URI.from_string(uri) # Properties. assert study_uri.base_url == _BASE_URL assert study_uri.study_ins...
61,031
def save_chain(config, chain): """ Encode a chain of operation classes as json. :param config: dictionary with settings. :param chain: OrderedDict of operation class lists. :return: string-encoded version of the above. """ di = OrderedDict() di['__config__'] = config for key, ops in chain.items(): di[ke...
61,032
def _trigger_task(options): """Triggers a task on the compile server by creating a file in storage.""" task = _create_task_dict(options) # Check to see if file already exists in Google Storage. if not _does_task_exist_in_storage(task): _write_to_storage(task) return task
61,033
def test_addresses(): """ Test IP address utility functions """ from paradrop.lib.utils import addresses ipaddr = "192.168.1.1" assert addresses.isIpValid(ipaddr) ipaddr = "192.168.1.256" assert not addresses.isIpValid(ipaddr) chute = MockChute(name="first") chute.IPs.append("...
61,034
def identical_data_outputs(pre_restart_path, post_restart_path, output_dir): """ Returns whether the contents of {pre_restart_path}/{output_dir} and {post_restart_path}/{output_dir} are identical Parameters ---------- pre_restart_path : str Path to directory that stores sets of outputs ...
61,035
def map_vcf_row(row, df_cell_vcf): """ get ref and UMI for each variant row: each row from merged_vcf """ pos = row['pos'] chrom = row['chrom'] alt = row['alt'] df_pos = df_cell_vcf[(df_cell_vcf['pos'] == pos) & (df_cell_vcf['chrom'] == chrom)] df_ref = df_pos[df_pos['alt'] == '.'] ...
61,036
def calculate_fid_given_paths(paths, batch_size, cuda, dims, bootstrap=True, n_bootstraps=10, model_type='inception'): """Calculates the FID of two paths""" pths = [] for p in paths: if not os.path.exists(p): raise RuntimeError('Invalid path: %s' % p) if os.path.isdir(p) or os.pa...
61,037
def plot_no_pooling_model( samples: MonteCarloSamples, query: RVIdentifier, df: pd.DataFrame, ) -> Figure: """ Plot the no-pooling model. :param samples: Bean Machine inference object. :type samples: MonteCarloSamples :param query: Bean Machine query object. :type query: RVIdentifie...
61,038
def get_space_permissions(id_value, id_type='browse_id', return_type='list'): """This **deprecated** function returns all of the defined permissions (aka ``appliedEntitlements``) for a space. .. deprecated:: 2.6.0 The function has been renamed to be :py:func:`khorosjx.places.spaces.get_space_content_per...
61,039
def validate(schema_filename, data_filename, seen_uids): """Validate a YAML file according to the supplied schema.""" schema = yamale.make_schema(schema_filename) data = yamale.make_data(data_filename) try: print("") print("Checking file '{}'...".format(data_filename)) yamale.va...
61,040
def test_trustee_invalid_minting(helpers, addresses): """ Trustees trying to mint new tokens using invalid output (negative value), txn fails """ [address1, address2, *_] = addresses outputs = [{ADDRESS: address1, AMOUNT: -20}, {ADDRESS: address2, AMOUNT: 100}] with pytest.raises(RequestNac...
61,041
def register_shellcontext(app): """Register shell context objects.""" def shell_context(): """Shell context objects.""" return { 'db': mongo} app.shell_context_processor(shell_context)
61,042
def db_connection_string(dbconf): # type: (dict) -> str """ Constructs a database connection string from the passed configuration object. """ user = dbconf["user"] password = dbconf["password"] db_name = "traffic_ops" if dbconf["type"] == "Pg" else dbconf["type"] hostname = dbconf["hostname"] port = dbconf["por...
61,043
def memory_stream_one_way_pair(): """Create a connected, pure-Python, unidirectional stream with infinite buffering and flexible configuration options. You can think of this as being a no-operating-system-involved Trio-streamsified version of :func:`os.pipe` (except that :func:`os.pipe` returns the...
61,044
def round2sigfig(num,nfig=1): """Round number to significant figures""" def ndecimal(x): if x==0 or not np.isfinite(x): # "Behaviour not defined" => should not be relied upon. return 1 else: return -int(floor(log10(abs(x)))) nfig =nfig-1 n = nfig ...
61,045
def compara_datasets_em_relacao_ao_psnr_e_ssim_medio(imagens_ground_truth: np.ndarray, imagens_filtradas: np.ndarray, data_range: int = 256): """ Imprime o PSNR e o SSIM médio entre os datasets ground truth e as imagens filtradas. """ assert imagens_ground_truth.shape == imagens_filtradas.shape, 'O...
61,046
def _subsample_selection_to_desired_neg_pos_ratio( indices, match, max_negatives_per_positive, min_negatives_per_image): """Subsample a collection of selected indices to a desired neg:pos ratio. Arguments: indices: an int or long tensor with shape [M], it represents a collection of ...
61,047
def clean_cache(database, now): """ Remove files from gallery cache if they no longer exist. This is determined by if the file was checked when rebuilding the cache @param now: time at which the cache was updated. """ database.pages.delete_many({ 'lastChecked': {'$lt': now} })
61,048
def normalize_units( df, unitsmap, targetunit, paramcol="parameter", rescol="res", unitcol="units", napolicy="ignore", ): """ Normalize units of measure in a dataframe. Parameters ---------- df : pandas.DataFrame Dataframe contained results and units of measure d...
61,049
def shorten(k): """ k an attrname like foo_bar_baz. We return fbb, fbbaz, which we'll match startswith style if exact match not unique. """ parts = k.split('_') r = ''.join([s[0] for s in parts if s]) return r, r + parts[-1][1:]
61,050
def get_time_query_for_trip_like(key, trip_like_id): """ Returns the query that returns all the points associated with this trip-like (examples of trip-like objects are: raw trip, cleaned trip, raw section) """ trip = get_object(key, trip_like_id) return get_time_query_for_trip_like_object(trip...
61,051
def test_context_3(): """ store and load 10 global variables, load the 10 variables again, repeat with different values """ nvars = 10 numlist1 = [str(random_ndigits(10)) for _ in range(nvars)] numlist2 = [str(random_ndigits(10)) for _ in range(nvars)] inplist = numlist1 + ['po...
61,052
def drop_short_sentences(X, min_len=2): """ :param X: a data matrix: a list wrapping a list of strings, with each sublist being a sentence. :return: >>> drop_short_sentences([['ita', 'vero'], ['quid', 'est', 'veritas'], ['vir', 'qui', 'adest']]) [['quid', 'est', 'veritas'], ['vir', 'qui', 'adest']]...
61,053
def reflowed_lines(lines, regex, line_length): """Get the realigned lines This method takes a list of strings and lays them out respecting the given line length while also lining up the hanging lines :param lines: list of strings to realign :param regex: regex to identify the lines to reflow :...
61,054
def get_current_formatted_date(): """Get current date or previous business day""" try: current_time = get_current_time() diff = 0 if current_time.weekday() == 5: diff = 1 if current_time.weekday() == 6: diff = 2 return format_date(current_time - ...
61,055
def pdb_target_dataset(original_dataset_path, go_dataset_path, mapping_dataset_path, human_dataset_path, col_name_entry = 'entry_ac', col_name_pdb = 'pdb_ids'): """ 1. original_dataset_path: the path of the target dataset, a.k.a the dataset of protein tha passed ou...
61,056
def search(request): """ Search IETF Groups **Templates:** * ``groups/search.html`` **Template Variables:** * form, results """ results = [] if request.method == 'POST': form = SearchForm(request.POST) if form.is_valid(): kwargs = {} grou...
61,057
def elitist_selection(chromosome: AbstractChromosome, mutated_chromosomes: List[AbstractChromosome], objective: Objective) -> AbstractChromosome: """ Selects a chromosome using the elitist strategy Args: chromosome (AbstractChromosome): The source chromosome mutated_chromo...
61,058
def prettyprint_jobs_single(data: dict) -> str: """ Prettyprinter for single job output """ output = '' job_data = data['data']['jobs'][0] result = 'None' exception = 'None' if job_data['exception'] is not None and 'message' in job_data['exception']: exception = job_data['exce...
61,059
def logger_critical(message: str) -> None: """Adds a critical error message to the log file. This is used for reporting errors in the program that occur that do or could prevent parts of the program working.""" # Sets the config for the logger. logging.basicConfig(filename='../pysys.log', level=logg...
61,060
def main(*args): """ Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. @param args: command line arguments @type args: str """ pywikibot.output(color_format("Start: {white}{0}{default}", datetime.now())) local_args = pywikibot.handle_args(args...
61,061
def test_lti_document_upload(page: Page, live_server: LiveServer): """Test LTI Document upload.""" page, _ = _preview_document(live_server, page) page.click("text=Upload a document") with page.expect_file_chooser() as fc_info: page.click("text=Select a file to upload") file_chooser = fc_in...
61,062
def download(pipeline, release, outdir, compress, force, container, singularity_cache_only, parallel_downloads): """ Download a pipeline, nf-core/configs and pipeline singularity images. Collects all files in a single archive and configures the downloaded workflow to use relative paths to the configs a...
61,063
def extractLightNovelCafe(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Evolution Theory of the Hunter' in item['tags']: return buildReleaseMessageWithType(item, 'Evolution Theory of t...
61,064
async def poll_control_device(zha_device_restored, zigpy_device_mock): """Poll control device fixture.""" cluster_id = zigpy.zcl.clusters.general.PollControl.cluster_id zigpy_dev = zigpy_device_mock( {1: {"in_clusters": [cluster_id], "out_clusters": [], "device_type": 0x1234}}, "00:11:22:33:...
61,065
def visit_image( translator: HTMLTranslator, node: Node, old_visit_image: Callable[[HTMLTranslator, Node], None], app: Sphinx, img_datas: Set[ImgData], ): """ Wrap the existing `visit_image`. Let the old one generate an img tag using all of its own logic first. Then, we yoink that fr...
61,066
def pad_binary(f): """ Pads the binary to the given size. """ binary_file_size = f.tell() if (binary_file_size < PADDING_SIZE): padding_size = 0x4000 - binary_file_size f.write(bytes([0] * padding_size))
61,067
def load_tf_sess_variables_to_keras_single_gpu(path: 'str', compressed_ops: List['str']) -> tf.compat.v1.keras.Model: """ Creates a Keras model subclass and loads the saved session, meta graph and variables to Keras model :param path: Path to load the tf session saved using save_session_graph_and_variables...
61,068
def standardizeText(line, forward=True): """ Remove whitespace, lowercase, and end with termination character \r """ text = line.strip().lower()[:63] return (text if forward else text[::-1]) + '\r'
61,069
def backup_all(filename): """Create a backup of all current Rst2Html sites filename: name for the file to backup to (use %d to include a date-time stamp) """ _do_backup([FULLBACKUP_HEADER], dml.list_sites(), filename)
61,070
def selstr(a, start, stop): """ Select elements of a string from an array. :param a: array containing a string. :param start: int referring to the first character index to select. :param stop: int referring to the last character index to select. :return: array of strings """ if type(a...
61,071
def detect_phrases( docs_reader: Callable, passes: int = 1, lowercase: bool = False, detect_entities: bool = False, detect_noun_chunks: bool = False, token_regex: Optional[Pattern] = None, min_count: int = 5, threshold: float = 10.0, max_vocab_size: float = 40_000_000, connector_...
61,072
def format_sents_for_output(sents: List[str], doc_id: str) -> Dict[str, Dict[str, Any]]: """ Transform a list of sentences into a dict of format: { "sent_id": {"text": "sentence text", "label": []} } """ formatted_sents = {} for i, sent in enumerate(sents): forma...
61,073
def get_sale(word): """Convert the input into a dictionary, with keys matching the CSV column headers in the scrape_util module. """ number_word = [idx for idx, val in enumerate(word) if is_number(val)] cattle_string = word[number_word[0]+1] # Skip lines describing sales of non-cattle ...
61,074
def error_handler(update: object, context: CallbackContext) -> None: """ Name: error_handler Description: Manage any error from the dispatcher logging it and send it to the developer chat id. Inputs: :update: type(Update): update handler object. :context: type(CallbackContext). ...
61,075
def get_all_feed_groups_detached(feed_name): """ Returns a list of FeedMetadata objects populated with FeedGroupMetadata objects as returned by the db, but detached from the session. :return: list of FeedMetadata objects """ db_session = get_session() try: feeds = lookup_feed(db_session...
61,076
def solv_MKL_sparse(nsteps, dX, rho_inv, int_m, dec_m, phi, grid_idcs): # mu_loss_handler): """`Intel MKL sparse BLAS <https://software.intel.com/en-us/articles/intel-mkl-sparse-blas-overview?language=en>`_ implementation of forward-euler integration. Function requires that the path to the MKL runt...
61,077
def test_edit_districtid(db_session): """Test that editing district works correctly.""" sample_row = db_session.query(Tract).first() sample_row.disrictid = 50 assert sample_row.disrictid == 50
61,078
def get_nearest_neighbors( node_ids: List[Union[int, str]], embeddings: np.ndarray, num_nearest: int ) -> Dict[Union[int, str], Set[Union[int, str]]]: """ Compute similar nodes among a set of embeddings. Parameters ---------- node_ids: Names of each embedding sample. embeddings: ...
61,079
def mem_report(): """ Returns available device and device properties """ print("CPU RAM Free: " + humanize.naturalsize(psutil.virtual_memory().available)) GPUs = GPUtil.getGPUs() for i, gpu in enumerate(GPUs): print(f'GPU {i:d} ... Mem Free: {gpu.memoryFree:.0f}MB / {gpu.memoryTotal:....
61,080
def compress_ind(x: np.ndarray, width: int): """ Compress array to a given size (width). :param x: Array :param width: Total size of the new array. :return: Compressed array. """ comp_arr = np.empty(width, dtype=np.float32) comp_arr[:], ind_width, i = np.NaN, int(...
61,081
def unzip_files(directory): """ This function iterates through all the files in a directory and unzip those that are zipped (.zip) to that same folder :param directory(str): A directory or path to a folder """ assert isinstance(directory, str) zip_list = findFiles(directory, ['.zip']) bugs ...
61,082
def setup(skye): """Called when the plugin is set up. Used to register commands and other initializations Arguments: skye {Skye} -- The singleton Skye instance """ news_plugin = NewsPlugin(skye) skye.register_command(("news", "briefing", "flash briefing"), news...
61,083
def test_form__DatetimeDataConverter__toWidgetValue__2(DatetimeDataConverter): """`toWidgetValue` renders naive datetime unchanged.""" assert u'13/02/01 17:20' == DatetimeDataConverter.toWidgetValue( datetime(2013, 2, 1, 17, 20))
61,084
def get_link_target(path): """Takes a path to a .lnk file and returns a path the .lnk file is targeting or None. """ from quodlibet.util.path import fsnative link = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink...
61,085
def _op_type_domain_classifier(dtype): """ Defines *op_type* and *op_domain* based on `dtype`. """ if dtype == numpy.float32: return 'TreeEnsembleClassifier', 'ai.onnx.ml', 1 if dtype == numpy.float64: return 'TreeEnsembleClassifierDouble', 'mlprodict', 1 raise RuntimeError( # p...
61,086
def richardson_extrapolation_lspr(test_result): """ Performs an estimate of the exact solution using Richardson extrapolation, given by f_ex = (f_1 * f_3 - f_2^2) / (f_3 - 2*f_2+f_1) where f_1 is a result from the finest grid and f_3 is from the coarsest. The grids f_1, f_2, f_3 should have th...
61,087
def get_guess(guesses): """ This function will get the user's guess. """ # Get the user's guess. guess = input("------\nGuess a letter: ") # Check if the user has already guessed the letter. if guess in guesses: print("You've already guessed that letter.") return get_guess(guesses) # Return the guess. re...
61,088
def primes(n): """Prime number less than n""" return takewhile(lambda p: p < n, erat2())
61,089
def _include_patterns(*patterns): """Factory function that can be used with copytree() ignore parameter. Arguments define a sequence of glob-style patterns that are used to specify what files to NOT ignore. Creates and returns a function that determines this for each directory in the file hierarchy...
61,090
def get_config(config_file: str = None) -> dict: """Returns the configuration from a config file :param config_file: json file with the configurations :type config_file: str :return: dictionary with the configurations :rtype: dict """ if not config_file: return CONFIG with open...
61,091
def browse(session, queue, timeout=0, transform=lambda m: m.content): """Return a list with the contents of each message on queue.""" r = session.receiver("%s;{mode:browse}"%(queue)) r.capacity = 100 try: return [transform(m) for m in receiver_iter(r, timeout)] finally: r.close()
61,092
def _run_pmm_one_variable( input_matrix, max_percentile_level=100): """Applies PMM to one variable. E = number of examples (realizations over which to average) :param input_matrix: numpy array. The first axis must have length E. Other axes are assumed to be spatial dimensions. Thus, input...
61,093
def latitudinal_summary(ds, lat_dim='lat', lon_dim='lon', lat_res=5): """Compute latitudinal (bin) statistics, averaging over longitude.""" # Check lat_dim and lon_dim # Check lat_res < 90 # TODO: lon between -180 and 180 , lat between -90 and 90 aggregating_dims = list(ds[lon_dim].dims) bins...
61,094
def test_atomic_time_min_inclusive_1_nistxml_sv_iv_atomic_time_min_inclusive_2_4(mode, save_output, output_format): """ Type atomic/time is restricted by facet minInclusive with value 21:11:44. """ assert_bindings( schema="nistData/atomic/time/Schema+Instance/NISTSchema-SV-IV-atomic-time-min...
61,095
def set_ppr_template_data(report_data): """Set up the PPR search data for the report, modifying the original for the template output.""" set_addresses(report_data) set_date_times(report_data) set_vehicle_collateral(report_data) set_general_collateral(report_data)
61,096
def test_analyze_warnings_print(warnreformfile): """ Test TaxCalcIO.analyze method when there is a reform warning. """ taxyear = 2020 recdict = {'RECID': 1, 'MARS': 1, 'e00300': 100000, 's006': 1e8} recdf = pd.DataFrame(data=recdict, index=[0]) tcio = TaxCalcIO(input_data=recdf, ...
61,097
def is_addon_dir(addon_dir): """ Test if a directory contains an Odoo addon. """ return bool(get_manifest_path(addon_dir))
61,098
def stats_summary(X, sigma=5.0, n_min=5, kde=True, bw=None, prefix=None, verbose=False, return_clipped=False): """ Statistical summary of an array. """ keys = ['low', 'upp', 'mean', 'median', 'std', 'kde', 'sigmaclip'] if prefix is not None: keys = ['_'.join([prefix, key]) ...
61,099