content
stringlengths
22
815k
id
int64
0
4.91M
def main(): """ Program entrypoint, orchestrates the pipeline""" args = parse_args() tfidf = create_tf_idf(args.input) information_extractor = InformationExtractor(args.vectors, read_gazetter(args.brands), read_gazetter(args.styles), read_gazetter(args.ma...
73,600
def data_source_get_all(context, regex_search=False, **kwargs): """Get all Data Sources filtered by **kwargs. :param context: The context, and associated authentication, to use with this operation :param regex_search: If True, enable regex matching for filter v...
73,601
def normalize_img(img: Union[np.ndarray, torch.Tensor]) -> Union[np.ndarray, torch.Tensor]: """ Normalizes an input image. Parameters ---------- img: Image which should be normalized. Returns ------- img: Normalized image. """ if type(img) is np.ndarray: img = img.asty...
73,602
def test_update_upper(trust_region): """ Test initial upper.""" trust_region.update_bounds() eva = trust_region.upper true = trust_region.x_center + 0.1 assert np.array_equal(eva, true)
73,603
def get_horizon_endpoint(goc_db_url, path, service_type, host): """ Retrieve the Horizon OpenStack dashboard of the given hostname """ dashboard_endpoint = "" endpoints = get_GOCDB_endpoints(goc_db_url, path, service_type) for item in endpoints.findall("SERVICE_ENDPOINT"): sitename = item.find...
73,604
def create_process_chain_entry(input_object: DataObject, formula, operators, output_object: DataObject): """Create a Actinia process description. :param input_object: The input time series object :param output_object: The output time series or raster object :return: A Act...
73,605
def checksync(st, resample=False): """Check if all traces in st are synced, if so, return basic info """ samprates = [trace.stats.sampling_rate for trace in st] if np.mean(samprates) != samprates[0]: if resample: print('sample rates are not all equal, resampling to lowest sample rat...
73,606
def hill_estimator(points, counts, xmin, xmax=np.inf, discrete=False, **kwargs): """ Give the MLE for continuous power-law distribution exponent. :param points: observed values, shape (n,) :param counts: number of occurrences for `points`, shape (n,) :param xmin: the cutoff of the power law :par...
73,607
def askcolor(color=None, **options): """Display dialog window for selection of a color. Convenience wrapper for the Chooser class. Displays the color chooser dialog with color as the initial value. """ if color: options = options.copy() options["initialcolor"] = color ...
73,608
def list_providers_packages(): """List all provider packages.""" providers = get_all_providers() for provider in providers: print(provider)
73,609
def query_suggestions(query_fields_and_values): """Queries for suggestions. Args: query_fields_and_values: list(tuple(str, str)). A list of queries. The first element in each tuple is the field to be queried, and the second element is its value. Returns: list(Sugges...
73,610
def group_dataframe_iter(iterator, group_by): """splits an iterator of dataframes into group chunks. This is a useful utility function in conjunction with :meth:`read_avro_path_as_dataframe_iter` as it allows a one pass looping over presorted chunked data with keys crossing file boundaries. This funct...
73,611
def get_urls(listen_port=None): """ :param listen_port: if set, will not try to determine the listen port from other running instances. """ try: if listen_port: port = listen_port else: __, __, port = get_status() urls = [] ...
73,612
def oo_image_tag_to_rpm_version(version, include_dash=False): """ Convert an image tag string to an RPM version if necessary Empty strings and strings that are already in rpm version format are ignored. Also remove non semantic version components. Ex. v3.2.0.10 -> -3.2.0.10 v1.2...
73,613
def ofc_kmer(args): """ Calculate an observe feature frequency Args: args (TODO): TODO Returns: TODO """ desc = "Calculate average number of common feature" parser = argparse.ArgumentParser(description=desc) parser.add_argument("filenames", nargs="+", help="file(s) of signature")...
73,614
def input_fn(mode, input_context=None): """A simple dataset builder function. This function creates a simple dataset for traning the auto encoder model below. Note that param `article_to_take` only available for `TRAIN` mode. """ max_charcode = 0x024F def to_sequence(article): # ...
73,615
def csum(arrays, dtype=None, ignore_nan=False): """ CUDA-enabled sum of stream of arrays. Arrays are summed along the streaming axis for performance reasons. Parameters ---------- arrays : iterable Arrays to be summed. ignore_nan : bool, optional If True, NaNs are ignored. D...
73,616
def _split_and_load(batch, ctx_list): """Split data to 1 batch each device.""" new_batch = [] for _, data in enumerate(batch): if isinstance(data, (list, tuple)): new_data = [x.as_in_context(ctx) for x, ctx in zip(data, ctx_list)] else: new_data = [data.as_in_context(...
73,617
def h3_show(ax, h3_data, cmap=None, norm=None, aspect=None, vmin=None, vmax=None, url=None, alpha=1.0, fill=0.0, **kwargs): """Plot H3 DGG data in a way friendly to projected maps. This is derived from Axes.imshow. Parameters ---------- ax : matplotlib Axes h3_data : dict mapping ...
73,618
def _daofind_centroidfit(obj, kernel, axis): """ Find the source centroid along one axis by fitting a 1D Gaussian to the marginal x or y distribution of the unconvolved source data. Parameters ---------- obj : array_like The 2D array of the source cutout. kernel : `_FindObjKernel` ...
73,619
def _GatherReturnElements(requested_return_elements, graph, results): """Returns the requested return elements from results. Args: requested_return_elements: list of strings of operation and tensor names graph: Graph results: wrapped TF_ImportGraphDefResults Returns: list of `Operation` and/or `...
73,620
def get_series_val(series): """ Get value series """ # Create a clean timeseries list of (dt,val) tuples val = [float(vd['value']) for vd in series['values']] val = np.ma.masked_equal(val, -9999) val = np.ma.masked_equal(val, 0.0) return val
73,621
def get_embeds_portkey(list_of_dicts_of_metadata): """make and return portkey archive embeds for story metadata""" embeds_list = [] for data in list_of_dicts_of_metadata: data = data["story"] sid = data["id"] embed = Embed( title= data['title'], url= f"https:...
73,622
def shear_y_only_bboxes(image, bboxes, prob, level, replace): """Apply shear_y to each bbox in the image with probability prob.""" func_changes_bbox = False prob = _scale_bbox_only_op_probability(prob) return _apply_multi_bbox_augmentation_wrapper( image, bboxes, prob, shear_y, func_changes_bbox, level, r...
73,623
def batch_generator(batch_size, sequence_length): """ Generator function for creating random batches of training-data. """ # Infinite loop. while True: # Allocate a new array for the batch of input-signals. x_shape = (batch_size, sequence_length, num_x_signals) x_batch = np....
73,624
def _check_initial_values(initial_values, shape): """ Raises a AssertionError if the input initial values: * Are not a numpy array OR * Do not have the shape (n_nodes, max_delay+1) Parameters ---------- graph : array Lagged connectivity matrices. Shape is (n_nodes, n_nodes, ...
73,625
def split_by_commas(maybe_s: str) -> Tuple[str, ...]: """Split a string by commas, but allow escaped commas. - If maybe_s is falsey, returns an empty tuple - Ignore backslashed commas """ if not maybe_s: return () parts: List[str] = [] split_by_backslash = maybe_s.split(r'\,') fo...
73,626
def postscriptFullNameFallback(info): """ Fallback to *openTypeNamePreferredFamilyName openTypeNamePreferredSubfamilyName*. """ return "%s %s" % ( getAttrWithFallback(info, "openTypeNamePreferredFamilyName"), getAttrWithFallback(info, "openTypeNamePreferredSubfamilyName"), )
73,627
def _normalize_and_hash(s): """Normalizes and hashes a string with SHA-256. Private customer data must be hashed during upload, as described at: https://support.google.com/google-ads/answer/7474263 Args: s: The string to perform this operation on. Returns: A normalized (lowercase,...
73,628
def replace_flooded_chars(text): """replace 3 or more repetitions of any character patterns w/ 2 occurrences of the shortest pattern""" return re.sub(r'(.+?)\1\1+', r'\1\1', text)
73,629
async def add_pack_member(request, pack_id): """Add a member to the roles of a pack""" log_request(request) required_fields = ["id"] validate_fields(required_fields, request.json) pack_id = escape_user_input(pack_id) conn = await create_connection() pack_resource = await packs_query.fetch_p...
73,630
def dataset_currency_selection_currency_name_post(currencyName): # noqa: E501 """Selects a specific currency type The currency type should be either bitcoin, bitconnect, dash, ethereum, iota, litecoin, monero, nem, neo, numeraire, omisego, qtum, ripple, stratis, or waves # noqa: E501 :param currencyName:...
73,631
def compress_G1(pt: G1Uncompressed) -> G1Compressed: """ A compressed point is a 384-bit integer with the bit order (c_flag, b_flag, a_flag, x), where the c_flag bit is always set to 1, the b_flag bit indicates infinity when set to 1, the a_flag bit helps determine the y-coordinate when decompressin...
73,632
def pairwise_correlation(df): """docstring goes here""" metric = pd.DataFrame() for index_i, row_i in df.iterrows(): row_i_to_all_rows(df, index_i, row_i, metric) return metric
73,633
def plaintext2html(text, container_tag=False): """ Convert plaintext into html. Content of the text is escaped to manage html entities, using cgi.escape(). - all \n,\r are replaced by <br /> - enclose content into <p> - 2 or more consecutive <br /> are considered as paragraph breaks ...
73,634
def test_update_contact(client, jwt, session, keycloak_mock): # pylint:disable=unused-argument """Assert that a contact can be updated on an org.""" headers = factory_auth_header(jwt=jwt, claims=TestJwtClaims.public_user_role) rv = client.post('/api/v1/users', headers=headers, content_type='application/jso...
73,635
def trend(data): """ Calcul de la pente. """ argmin = np.argmin(data) argmax = np.argmax(data) divider = (data[argmax] + data[argmin]) if divider == 0.0: return 0.0 if argmin < argmax: return (data[argmax] - data[argmin]) / (data[argmax] + data[argmin]) elif argmin...
73,636
def getAtomType(atom, bonds): """ Determine the appropriate atom type for an :class:`Atom` object `atom` with local bond structure `bonds`, a ``dict`` containing atom-bond pairs. """ cython.declare(atomSymbol=str) cython.declare(molFeatureList=cython.list, atomTypeFeatureList=cython.list) ...
73,637
def main(args): """Main function. Launches the uris contained in file to specific url retrieved on launch parameters. All uris are encoded before launch and all line break contained at the end of each line of the file will be deleted :param args: command-line retrieved arguments :type ar...
73,638
def sim_poisson_pop(n_seconds, fs, n_neurons=1000, firing_rate=2): """Simulate a Poisson population. Parameters ---------- n_seconds : float Simulation time, in seconds. fs : float Sampling rate of simulated signal, in Hz. n_neurons : int, optional, default: 1000 Number ...
73,639
def save_checkpoint_g(avg, gnet, dnet, ckpt_dir, i_batch): """save_checkpoint""" save_checkpoint(gnet, os.path.join(ckpt_dir, "G_{}.ckpt".format(i_batch))) save_checkpoint(avg, os.path.join(ckpt_dir, "AvG_{}.ckpt".format(i_batch))) save_checkpoint(dnet, os.path.join(ckpt_dir, "D_{}.ckpt".format(i_batch)...
73,640
def visualize_boxes_and_labels_on_image_array_V1(image, boxes, scores_step1, instance_masks=None, keypoints=None, ...
73,641
def slash_default_member_permission(permission: "Permissions") -> Any: """ A decorator to permissions members need to have by default to use a command. Args: permission: The permissions to require for to this command """ def wrapper(func: Coroutine) -> Coroutine: if hasattr(func, ...
73,642
def create_or_update_move_stop_by_dist_time( move_data: Union['PandasMoveDataFrame', 'DaskMoveDataFrame'], dist_radius: Optional[float] = 30, time_radius: Optional[float] = 900, label_id: Optional[Text] = TRAJ_ID, new_label: Optional[Text] = SEGMENT_STOP, inplace: Optional[bool] = True ) -> Opti...
73,643
def test_create_from_peer(ctx, config): """ osd should stop creating new pools if the number of pg it servers exceeds the max-pg-per-osd setting, and it should resume the previously suspended pg creations once the its pg number drops down below the setting How it works:: 0. create 4 OSDs. 1...
73,644
def fsapi(session, stream, env, imsi): """Handle FS API requests. Args: imsi: a subscriber's number """ try: auth = subscriber.is_authed(imsi) except Exception: # handle all failures as no auth exc_type, exc_value, _ = sys.exc_info() consoleLog('error', "%s: %s\n" % (e...
73,645
def _build(tmplspec, *repls): """Create raw parsed tree from a template revset statement >>> _build(b'f(_) and _', (b'string', b'1'), (b'symbol', b'2')) ('and', ('func', ('symbol', 'f'), ('string', '1')), ('symbol', '2')) """ template = _cachedtree(tmplspec) return parser.buildtree(template, ('...
73,646
def kalman_predict(m, P, A, Q): """Kalman filter prediction step""" m_p = A @ m P_p = A @ P @ A.T + Q return m_p, P_p
73,647
def _drive_status(device, handle_mix = 0): """ check the current disc in device return: no disc (0), audio cd (1), data cd (2), blank cd (3) """ CDROM_DRIVE_STATUS=0x5326 CDSL_CURRENT=( (int ) ( ~ 0 >> 1 ) ) CDROM_DISC_STATUS=0x5327 CDS_AUDIO=100 CDS_MIXED=105 CDS_DISC_OK=4 C...
73,648
def test_input_objects_position_bad(): """bad input: magpy.Sensor(position=inp)""" bads = [ (1, 2), (1, 2, 3, 4), [(1, 2, 3, 4)] * 2, (((1, 2, 3), (1, 2, 3)), ((1, 2, 3), (1, 2, 3))), "x", ["x", "y", "z"], dict(woot=15), True, ] for bad in ...
73,649
def set_node_deployment_steps(task): """Set up the node with deployment step information for deploying. Get the deploy steps from the driver. :raises: InstanceDeployFailure if there was a problem getting the deployment steps. """ node = task.node driver_internal_info = node.driver...
73,650
def limit(df: pd.DataFrame, rows: int) -> pd.DataFrame: """Limit the number of rows in a data frame. Returns a data frame that contains at most the first n (n=rows) rows from the input data frame. Parameters ---------- df: pd.DataFrame Input data frame. rows: int Limit on number...
73,651
def _fill_gaps(wires, out): """Fill 1-minute gaps.""" mask = np.array([[1, 0, 1]]) return np.logical_or( wires, ndimage.binary_hit_or_miss(wires, mask), out=out)
73,652
async def test_abort_on_socket_failed(hass): """Test we abort of we have errors during socket creation.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": "user"} ) with patch( "homeassistant.components.cert_expiry.helper.get_cert", side_effect=soc...
73,653
def test_filewritejson_empty_path_raises(): """Empty path raises.""" context = Context({ 'fileWriteJson': { 'path': None }}) with pytest.raises(KeyInContextHasNoValueError) as err_info: filewrite.run_step(context) assert str(err_info.value) == ( "context['fi...
73,654
def live_view(self): """Test that live view is handled properly by clickhouse-backup. """ base_table_name = self.context.views_base_name views_outline(view_name="lview", view_contents_query=f"SELECT * FROM {base_table_name}_lview", view_create_query=f"CREATE LIVE VIEW {base_table_name...
73,655
def has_prefix(sub_s, dic): """ :param sub_s: (str) apart of word :return: (bool) if correct: True """ for word in dic: if word.startswith(sub_s): return True return False
73,656
def permission_denied(request): """Return the view for permission denied errors. Note that this is a bit buggy, we need to render the template and return te content. """ return TemplateResponse(request, '403.html').render()
73,657
def nansum(*args, **kwargs): """ This will check for numpy array first and call np.sum otherwise use builtin for isntance c={1,2,3} and sum(c) should work also """ args = _convert_cat_args(args) if isinstance(args[0], np.ndarray): return args[0].nansum(*args[1:], **kwargs) ...
73,658
def get_publictag(tagkey): """ Return tag and bookmarks in this public tag collection """ this_tag = PublicTag.get(PublicTag.tagkey == tagkey) bookmarks = Bookmark.select().where( Bookmark.userkey == this_tag.userkey, Bookmark.tags.contains(this_tag.tag), Bookmark.status == Bookmark....
73,659
def listmodules(package_name=''): """List modules in a package or directory""" import os,imp package_name_os = package_name.replace('.','/') file, pathname, description = imp.find_module(package_name_os) if file: # Not a package return [] ret = [] for module in os.li...
73,660
def _get_window(point, image, radius, padding_value): """Extract a square 2d window around a given pixel in the image. If the point has coordinates (-1, -1), the window will be filled with `padding_value`. Args: point: The coordinates of the center point in the extracted window. image: The image to ex...
73,661
def make_docs(*args, **kwargs): """Make the documents for a `Request` or `OpReply`. Takes a variety of argument styles, returns a list of dicts. Used by `make_prototype_request` and `make_reply`, which are in turn used by `MockupDB.receives`, `Request.replies`, and so on. See examples in tutorial....
73,662
def read_description_file(dirpath): """Read the contents of a file in 'dirpath' called DESCRIPTION, if one exists. This returns the file text as a string, or None if no description was found.""" descr_path = os.path.join(dirpath, 'DESCRIPTION') if os.access(descr_path, os.R_OK): descr_file...
73,663
def Divider(clk, rst, io): """ A 32-bit divider. WARNING: the op_divs/op_divu signal must be asserted only one cycle. Keeping it asserted for more than one cycle will restart the operation. The operation can be aborted by asserting the reset signal. :param clk: System c...
73,664
def is_probably_gzip(response): """ Determine if a urllib response is likely gzip'd. :param response: the urllib response """ return (response.url.endswith('.gz') or response.getheader('Content-Encoding') == 'gzip' or response.getheader('Content-Type') == 'application/x-gzip...
73,665
def quat_to_SO3(quat): """ :param quat: (N, 4, ) or (4, ) np :return: (N, 3, 3) or (3, 3) np """ x = RotLib.from_quat(quat) R = x.as_matrix() return R
73,666
def word_tokenizer(text: str) -> List[Word]: """Return words from sentence. Removing stopwords and punctuation. do lowarcase e.g: "Hello World!" >> "hello", "world" """ return WORD_TOKENIZER(text)
73,667
def l1_loss(inputs, target, reduction='none'): """ Computes l1 loss. Args: inputs(akg.tvm.Tensor): Supported data type is float16, float32. target(akg.tvm.Tensor): With same type as inputs. reduction(str): Default is 'none', could be 'sum' or 'mean', if 'mean', loss result will be d...
73,668
def run_main(argsin: Optional[Namespace] = None) -> int: """Run main process for average_nucleotide_identity.py script. :param argsin: Namespace, command-line arguments :param logger: logging object """ time0 = time.time() # Process command-line and build logger args = process_arguments(...
73,669
def correlated_uniforms(N,rho=0): """ This function generates N uniform random variables (0,1) that may or may not be correlated, default is independent; when rho=0""" # check the correlation has acceptable value if rho>1 or rho<-1: print("Error, correlation coefficient must be between -1 an...
73,670
def _create_observable_table(yaml_dict: dict): """ Creates an observable table from the observable block in the given yaml_dict. Arguments: yaml_dict Returns: observable_table: pandas data frame containing the observable table. (if observable block is not empty, else None)...
73,671
def load_config(*path: Tuple[str], update: bool = False) -> None: """Loads the global spines configuration Parameters ---------- path : :obj:`str` (or multiple), optional File(s) to load the configuration from (defaults to the correct spines hierarchy for configuration files). updat...
73,672
def buffon(needlesNbr, groovesLen, needlesLen): """Simulates Buffon's needle experiments.""" intersects = 0 for i in range(needlesNbr): y = random.random() * needlesLen / 2 angle = random.random() * math.pi z = groovesLen / 2 * math.sin(angle) if y <= z: intersects += 1 expFreq = intersects / needlesN...
73,673
def test_verify_new_cbp_creation_not_blocked_by_invalid_cbp(teardown_factory): """ Test to verify new ceph block pool can be created without deleting ceph block pool having invalid parameters Verifies bz 1711814 """ log.info("Trying creating ceph block pool with invalid failure domain.") cbp...
73,674
def ucerf_classical(rupset_idx, ucerf_source, src_filter, gsims, monitor): """ :param rupset_idx: indices of the rupture sets :param ucerf_source: an object taking the place of a source for UCERF :param src_filter: a source filter returning the sites affected by the source :p...
73,675
def SNRvsTPR(data, true_flags, flags): """ Calculates the signal-to-noise ratio versus true positive rate (recall). """ SNR = np.linspace(0.0, 4.0, 30) snr_tprs = [] data_ = np.copy(data) flags_ = np.copy(flags) true_flags_ = np.copy(true_flags) for snr_ in SNR: snr_map = np....
73,676
def stringify(plaintext): """ Used to convert hex integers into a string when decrypting. :param plaintext: a hex integer number. :return: a ascii string. """ if len(plaintext) % 2 == 1: plaintext = '0' + plaintext lst = [] end = len(plaintext) // 2 for i in range(end): ...
73,677
def p_selectstmt_u(t): """selectStmt : R_SELECT selectParams R_FROM tableExp""" # t[0] = instruction.Select(t[2].params, t[4])
73,678
def register_decoder(decoder_fct, type_identifier): """ Register a function to use for the JSON deserialization of a given object type identifier. The decoding function `decoder_fct` will be registered to the ``AwesoJSONDecoder`` class as the function to use to deserialize the objects for which the tex...
73,679
def get_new_snp(vcf_file): """ Gets the positions of the new snp in a vcf file :param vcf_file: py_vcf file :return: list of new snp """ new_snp = [] for loci in vcf_file: if "gff3_notarget" in loci.FILTER: new_snp.append(loci) return(new_snp)
73,680
def get_isob_quant_data(pquant, featfield, fnid, featmap, qmap): """Turns a dict from a line of protein/peptide quant data into a set of tuples that can be stored in db""" feat_dbid = featmap[pquant[featfield]] for channel_name, (channel_id, psmfield) in qmap[fnid].items(): if psmfield is None: ...
73,681
def map(data, settings): """ Returns a new DataFrame applying the expression to the specified column. :param data: A pandas's DataFrame; :param settings: A dictionary that contains: - function: A lambda function; - alias: New column name; :return: Returns pandas's DataFrame with th...
73,682
def my_function() -> dict: """Return a set of data into a dictionary""" hills_of_rome = { 'Aventine Hill': {'Latin': 'Aventinus', 'Height': 46.6, 'Italian': 'Aventino'}, 'Caelian Hill': {'Latin': r'Cælius', 'Height': 50...
73,683
def run(config_file): """ runs the NEAT algorithm to train a neural network to play flappy bird. :param config_file: location of config file :return: None """ config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultSt...
73,684
def forced_vibration_particular(vt, k, m, F0, Omega, zeta): """ Particualr solution to forced harmonic vibrations, , x=H0 sin(Omega t - Phi) """ omega0 = np.sqrt(k / m) H0, phi = forced_vibration_particular_cst(Omega/omega0, F0/k, zeta) x_particular = H0 * np.sin(Omega * vt + phi) ...
73,685
def most_freq(neighbors): """ Returns the dominant color with the greater frequency Example: num_dominating = [paper, paper, paper, spock, spock, spock, spock, spock] Returns: spock """ return max(set(neighbors), key=neighbors.count)
73,686
def test5(): """ test graph mark for cnn1 with NaiveSGD optimizer """ num_classes = 1470 model = M.cnn1(num_classes=num_classes) inputs = FloatTensor([32, 3, 448, 448], name="data") weights = list(model.weights) mse_loss = nn.MSELoss() labels = FloatTensor([32, num_classes], name="l...
73,687
def testing_guard(decorator_func): """ Decorator that only applies another decorator if the TESTING environment variable is not set. Args: decorator_func: The decorator function. Returns: Function that calls a function after applying the decorator if TESTING environment var...
73,688
def create_scratch(request): """ Create a scratch """ ser = ScratchCreateSerializer(data=request.data) ser.is_valid(raise_exception=True) data = ser.validated_data platform = data.get("platform") compiler = data.get("compiler") if platform: if CompilerWrapper.platform_from...
73,689
def encrypt(password, key, challenge=None): """Encrypts password with a key and returns the base64 encoded string""" ciph = _get_ciph(key, challenge) return base64.b64encode(ciph.encrypt(password))
73,690
def get_func_store() -> dict: """Returns a dictionary with Callable objects supported in our function store, indexed by their function names.""" return {o[0]: o[1] for o in getmembers(knowledge_horizons) if isfunction(o[1])}
73,691
def test_check_file(): """ Test check_file. """ assert transform.check_file(Helpers.test_multilayer_file_path) is None try: transform.check_file(Helpers.test_dir_path) except IsADirectoryError: pass try: transform.check_file(Helpers.test_invalid_path) except FileN...
73,692
def _efficient_sample_matheron_rule( inducing_variable: InducingVariables, kernel: KernelWithFeatureDecomposition, q_mu: tf.Tensor, *, q_sqrt: Optional[TensorType] = None, whiten: bool = False, ) -> Sample: """ Implements the efficient sampling rule from :cite:t:`wilson2020efficiently` u...
73,693
def verify_contents_quiet(unicodestring:str, filename:str, book_code:str, lang_code:str) -> Tuple[List[str],str]: """ This is called by the USFM linter. """ global error_log error_log = [] # enable error logging state = State() state.r...
73,694
def plot_fig4(filename_res=None): """ filename_res : filename to precomputed results if filename_res == None, calculate approximate X_corr distributions using both Seita et al. method and GMM based method proposed in our paper. """ save_plot_to_disk = True use_log = False if filename_res!=None: plot_only = Tr...
73,695
def email2dict(msg: Message, include_all: bool = False) -> "MessageDict": """ Convert a `Message` object to a `dict`. All encoded text & bytes are decoded into their natural values. Need to examine a `Message` but find the builtin Python API too fiddly? Need to check that a `Message` has the conte...
73,696
def greater_than_days_cutoff(timestamp, cutoff): """ Helper function to calculate if PR is past cutoff """ # Convert string to datetime object last_update = datetime.strptime(timestamp[0:22], '%Y-%m-%dT%H:%M:%S.%f') # Get the number of days since this PR has been last updated last_update_days...
73,697
def make_dir(dirname): """ Make a directory if it doesn't already exist. """ try: os.makedirs(dirname) except OSError as exc: if exc.errno == errno.EEXIST: pass else: raise Exception("Unable to create directory: " + dirname)
73,698
def view(path, light=False, wait=True, page=0, fullscreen=False, zoom=0): """View document. path (str) light (bool) force to use DocuWorks Viewer Light. Note that DocuWorks Viewer is used if Light version is not avaiable. wait (bool) wait until viewer...
73,699