content
stringlengths
22
815k
id
int64
0
4.91M
def uiTemplate(q=1,e=1,dt="string",ex=1,ut="string"): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/uiTemplate.html ----------------------------------------- uiTemplate is undoable, queryable, and editable. This command creates a new command template object. Template objects can...
34,200
def save_image(image: Image, path: str): """ Open an image using Image.save(...) method from PIL lib. Args: image (Image): Image to get pixel from. path (str): Path to the save location. Returns: None """ image.save(path)
34,201
def save_CSV_from_file(h5_file, h5_path='/', append='', mirror=False): """ Saves the tfp, shift, and fixed_tfp as CSV files :param h5_file: Reminder you can always type: h5_svd.file or h5_avg.file for this :type h5_file: H5Py file :param h5_path: specific folder path to search for the tfp data. Usually not ne...
34,202
def _split_vector(expr, ranges, fill_ranges=True): """Extract the components of the given vector or matrix. Parameters ========== expr : Vector, DenseMatrix or list/tuple ranges : list/tuple Returns ======= split_expr : tuple Tuple of the form (x_expr, y_expr, z...
34,203
def Transition_rep(source_State_name, target_State_name): """Representation of a transition :param source_State_name: The sequence of "name" values of State objects referred to by attribute "source" in this Transition :type source_State_name: Array :param target_State_name: The sequence of "name" value...
34,204
def debug(dataset): """Debugging utility for tf.data.Dataset.""" iterator = tf.data.Iterator.from_structure( dataset.output_types, dataset.output_shapes) next_element = iterator.get_next() ds_init_op = iterator.make_initializer(dataset) with tf.Session() as sess: sess.run(ds_init_o...
34,205
def tifread(ifile, metaData): """Read raster from file.""" file = gdal.Open(ifile, GA_ReadOnly) projection = file.GetProjection() src = osr.SpatialReference() src.ImportFromWkt(projection) proj = src.ExportToWkt() Nx = file.RasterXSize Ny = file.RasterYSize trans = file.GetGeoTransfo...
34,206
def search_model(trial: optuna.trial.Trial) -> List[Any]: """Search model structure from user-specified search space.""" model = [] n_stride = 0 MAX_NUM_STRIDE = 5 UPPER_STRIDE = 2 # 5(224 example): 224, 112, 56, 28, 14, 7 n_layers = trial.suggest_int("n_layers", 8, 12) stride = 1 input...
34,207
def create_search_forms(name, language_code, script_code): """Return a list of names suitable for searching. Arguments: name -- string name language_code -- string code of language script_code -- string code of script """ # QAZ: It would be useful if something could be done here (or # ...
34,208
def iv_params(*, N_s, T_degC, I_ph_A, I_rs_1_A, n_1, I_rs_2_A, n_2, R_s_Ohm, G_p_S, minimize_scalar_bounded_options=minimize_scalar_bounded_options_default, newton_options=newton_options_default): """ Compute I-V curve parameters. Inputs (any broadcast-compatible combination of ...
34,209
def list_class_names(dir_path): """ Return the mapping of class names in all files in dir_path to their file path. Args: dir_path (str): absolute path of the folder. Returns: dict: mapping from the class names in all python files in the folder to their file path. """ ...
34,210
def update_domain( uuid, name=None, disabled=None, project_id=None, user_id=None): """Update an existing domain.""" res = get_domain(uuid=uuid) if disabled is not None: res['disabled'] = disabled if name is not None: res['name'] = name if project_id is not None: res[...
34,211
def ja_of(tree: Tree) -> str: """tree string in the Japanese CCGBank's format Args: tree (Tree): tree object Returns: str: tree string in Japanese CCGBank's format """ def rec(node): if node.is_leaf: cat = node.cat word = normalize(node.word) ...
34,212
def test(): """Test MagicGrid's default text alignment rules.""" root = Tk() root.title("Text Alignment Rules Test") for seq in "<Escape>", "<Control-w>", "<Control-q>": root.bind(seq, lambda event: root.destroy()) mg = MagicGrid(root) mg.pack(side="top", expand=1, fill="both") #...
34,213
def cut_flowlines_at_points(flowlines, joins, points, next_lineID): """General method for cutting flowlines at points and updating joins. Only new flowlines are returned; any that are not cut by points are omitted. Parameters ---------- flowlines : GeoDataFrame joins : DataFrame flowli...
34,214
def export(gen, directory, file_prefix='{uid}-', **kwargs): """ Export a stream of documents to nxstxm_baseline. .. note:: This can alternatively be used to write data to generic buffers rather than creating files on disk. See the documentation for the ``directory`` parameter below...
34,215
def get_test_dataset(path): """ Gets a dataset that only has features :param string path: The path the the dataset file after /datasets/ :return: features """ with open(os.path.abspath(os.path.join(os.getcwd(), "../datasets/", path)), "r") as file: data = [line.split(',') for line in fil...
34,216
def services(): """ Returns the grader-notebook list used as services in jhub Response: json example: ``` { services: [{"name":"<course-id", "url": "http://grader-<course-id>:8888"...}], groups: {"formgrade-<course-id>": ["grader-<course-id>"] } } ``` """ service...
34,217
def chunks(l, k): """ Take a list, l, and create k sublists. """ n = len(l) return [l[i * (n // k) + min(i, n % k):(i+1) * (n // k) + min(i+1, n % k)] for i in range(k)]
34,218
def bfs(adj, src, dst, cache=None): """BFS search from source to destination. Check whether a path exists, does not return the actual path. Work on directed acyclic graphs where we assume that there is no path to the node itself. Args: adj: Adjacency matrix. src: Source node index, 0-based. dst: ...
34,219
def get_source_ast(name: str) -> _ast.Module: """ Return ast of source code """ with open(name, "r") as f: data = f.read() return ast.parse(data)
34,220
def fit_grain_FF_reduced(grain_id): """ Perform non-linear least-square fit for the specified grain. Parameters ---------- grain_id : int The grain id. Returns ------- grain_id : int The grain id. completeness : float The ratio of predicted to measured (obse...
34,221
def floor(base): """Get the floor of a number""" return math.floor(float(base))
34,222
def show_mask(bot, trigger): """Show the topic mask for the current channel.""" if bot.privileges[trigger.sender][trigger.nick] < OP: return if not bot.db: bot.say("I'm afraid I can't do that.") elif trigger.sender.lower() in bot.db.preferences: bot.say(bot.db.preferences.get(tri...
34,223
def test_atomic_base64_binary_pattern_2_nistxml_sv_iv_atomic_base64_binary_pattern_3_1(mode, save_output, output_format): """ Type atomic/base64Binary is restricted by facet pattern with value [a-zA-Z0-9+/]{64}. """ assert_bindings( schema="nistData/atomic/base64Binary/Schema+Instance/NISTSc...
34,224
def test_list_g_year_white_space_nistxml_sv_iv_list_g_year_white_space_1_3(mode, save_output, output_format): """ Type list/gYear is restricted by facet whiteSpace with value collapse. """ assert_bindings( schema="nistData/list/gYear/Schema+Instance/NISTSchema-SV-IV-list-gYear-whiteSpace-1.xsd",...
34,225
def TranslateSecureTagsForFirewallPolicy(client, secure_tags): """Returns a list of firewall policy rule secure tags, translating namespaced tags if needed. Args: client: compute client secure_tags: array of secure tag values Returns: List of firewall policy rule secure tags """ ret_secure_tags...
34,226
def _find_files(directory, pattern): """Searches a directory finding all files and dirs matching unix pattern. Args: directory : (str) The directory to search in. patterns : (str) A unix style pattern to search for. This should be the same style of pattern ...
34,227
def AddImportDestinationFlag(parser, folder): """Adds a --destination flag for a storage import command to a parser. Args: parser: argparse.ArgumentParser, the parser to which to add the flag folder: str, the top-level folder in the bucket into which the import command will write. Should not contai...
34,228
def memoize(func: Callable): """ A decorator that memoizes a function by storing its inputs and outputs. Calling the function again with the same arguments will return the cached output. This function is somewhat more permissive than :func:`functools.lru_cache` in what kinds of arguments can be...
34,229
def mini_batch(positive_rdd, negative_rdd, num_iterations): """get the positive and negative classes with index for mini-batch""" # mini-batch preparation pos_num = int(batch_size / 46) neg_num = pos_num * 45 i = num_iterations % int(74 / pos_num) # get the new mini-batch rdd for this iteration new_rdd = positi...
34,230
def draw_polygon(img, max_sides=8, min_len=32, min_label_len=64): """ Draw a polygon with a random number of corners and return the position of the junctions + line map. Parameters: max_sides: maximal number of sides + 1 """ num_corners = random_state.randint(3, max_sides) min_dim = mi...
34,231
def order_budget_update(request, order_id): """ Update budget for order """ serializer = OrderBudgetSerializer(data=request.data) if serializer.is_valid(raise_exception=True): order = get_object_or_404(Order, pk=order_id) budget = serializer.validated_data['budget'] order.bud...
34,232
def analyse_readability_metrics(article_text): """ Use the textstat library to report multiple readability measures. The readability metrics analysed are: * The Flesch Reading Ease Score. A score from 100 (very easy to read) to 0 (very confusing). * The grade score using the Flesch-Kincaid Grade Fo...
34,233
def sbsplot(spec, output, show_lines, transitions, z, x_axis, x_col, x_min, x_max, y_axis, y_col, identifier): """ """ pdf = PdfPages(output) specs = glob.glob(spec) crrls.natural_sort(specs) # If only one file is passed, it probably contains a list if len(specs) ...
34,234
def dx(data): """ Derivative by central difference Edges are takes as difference between nearest points Parameters ---------- data : ndarray Array of NMR data. Returns ------- ndata : ndarray Derivate of NMR data. """ z = np.empty_like(data) z[..., 0] ...
34,235
def grad(w): """ Dao ham """ N = Xbar.shape[0] return 1/N * Xbar.T.dot(Xbar.dot(w) - y)
34,236
def test_sanity_download(cfg): """ test if the cfg file is valid for downloading""" repo_root=utils.get_root()+'/' # test store_path exists store_path=cfg['DOWNLOAD']['store_path'] if not(os.path.exists(repo_root+store_path)): utils.throw_error(print_prefix+'cannot locate:'+repo_ro...
34,237
def main(inp_file, exp_file, out_file, th=5, motif_file="", motifout_file="", use_vcf=True): """ If use_vcf true then: For a given motif annotated vcf file (already run through motifs.py), remove all motif matches for TFs that are not expressed in at least one sample abov...
34,238
def from_tensorflow(graphdef, output_nodes=[], preprocessor=None, **kwargs): """ Converts a TensorFlow GraphDef to a UFF model. Args: graphdef (tensorflow.GraphDef): The TensorFlow graph to convert. output_nodes (list(str)): The names of the outputs of the graph. If not provided, graphsurge...
34,239
def random_binary(): """ 测试 cached 缓存视图的装饰器 设置 key :return: """ return [random.randrange(0, 2) for i in range(500)]
34,240
def remove_from_end(string, text_to_remove): """ Remove a String from the end of a string if it exists Args: string (str): string to edit text_to_remove (str): the text to remove Returns: the string with the text removed """ if string is not None and string.endswith(text_to_rem...
34,241
def is_3pt_shot(blob): """Parses the play description to determine if shot was 3pt attempt""" raise NotImplementedError("Pass a dictionary or pd.DataFrame")
34,242
def spec_to_hole( spec: specs.Spec, inputs: Optional[Iterable] = None, output: Optional[Any] = None ) -> "Impl": """Returns a default, incomplete schedule for a Spec which consume given inputs. If either `inputs` or `output` is None, default Tensors from the corresponding TensorSpecs will be constructe...
34,243
def get_node_number(self, node, typ) -> str: """Get the number for the directive node for HTML.""" ids = node.attributes.get("ids", [])[0] if isinstance(self, LaTeXTranslator): docname = find_parent(self.builder.env, node, "section") else: docname = node.attributes.get("docname", "") ...
34,244
def count_mp3_files_below(adir_path): """counts all mp3 files below given dir including subdirs""" matches = [] for root, dirnames, filenames in os.walk(adir_path): for filename in fnmatch.filter(filenames, '*.mp3'): matches.append(os.path.join(root, filename)) return len(matches)
34,245
def get_client(client, aws_access_key_id, aws_secret_access_key, region=None): """Shortcut for getting an initialized instance of the boto3 client.""" return boto3.client( client, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key, region_name=regio...
34,246
def main(req: func.HttpRequest) -> func.HttpResponse: """ main function for status/http """ logging.info('Status processed a request.') try: response = get_http_response_by_status(200) if req.get_body() and len(req.get_body()): response = get_http_response_by_status(202) ...
34,247
def _variable_map_by_name(variables): """ Returns Dict,representing referenced variable fields mapped by name. Keyword Parameters: variables -- list of 'variable_python_type' Warehouse support DTOs >>> from pprint import pprint >>> var1 = { 'column':'frob_hz', 'title':'Frobniz Resonance (Hz)'...
34,248
def test_show_info_retrieve_core_info_by_ids(show_ids: List[int]): """Testing for :py:meth:`wwdtm.show.ShowInfoMultiple.retrieve_core_info_by_ids` :param show_id: Show ID to test retrieving show core information """ info = ShowInfoMultiple(connect_dict=get_connect_dict()) shows = info.retrieve_core...
34,249
def test_generator_setattr_typechecking(): """ setattr should provide type checking based on PROPERTIES definition """ for type in SAMPLES: mock = Mock(Resource) object.__setattr__(mock, 'PROPERTIES', {'key': type}) object.__setattr__(mock, '_dirty', dict()) for t2, sampl...
34,250
def _apply_nat_net_less_greedy_subnet(): """By default, VirtualBox claims 10.0.2.x for itself as part of its NAT routing scheme. This subnet is commonly used on internal networks, making this a pretty damn greedy choice. We instead alter the VM to use the less greedy subnet of 10.174.249.x which is less...
34,251
def true_divide(x, y): """Divides x / y elementwise (using Python 3 division operator semantics). NOTE: Prefer using the Tensor operator or tf.divide which obey Python division operator semantics. This function forces Python 3 division operator semantics where all integer arguments are cast to flo...
34,252
def ObjectNotFoundError(NDARError): """S3 object not found""" def __init__(self, object): self.object = object return def __str__(self): return 'Object not found: %s' % self.object
34,253
def test_get_bool(): """get_bool should get the bool from the environment variable, or raise an exception if it's not parseable as a bool""" assert envs.get_bool(name="TRUE", default=1234, description="description") is True assert envs.get_bool(name="FALSE", default=1234, description="description") is False...
34,254
def hello(): """ Say hello using a template file. """ return render_template('index.html')
34,255
def pause_sale(ctx): """ Pause the token sale :param ctx:GetContext() used to access contract storage :return:bool Whether pausing the sale was successful """ if CheckWitness(TOKEN_OWNER): Put(ctx, SALE_STATUS_KEY, SALE_PAUSED) return True return False
34,256
def parse_item_hash(value): """ Parses the item-hash datatype, e.g. sha-256:5b8e5ee02caedd0a6f3539b19d6b462dd2d08918764e7f476506996024f7b84a :param value: a string to parse :return: parsed value """ if isinstance(value, ItemHash): return value if not isinstance(value, str): r...
34,257
def __convert_swizzle_scale(scale, export_settings): """Convert a scale from Blender coordinate system to glTF coordinate system.""" if export_settings[gltf2_blender_export_keys.YUP]: return Vector((scale[0], scale[2], scale[1])) else: return Vector((scale[0], scale[1], scale[2]))
34,258
def launch_plugin_flow(current, client_id, rekall_session, plugin, plugin_arg): """Launch the flow on the client.""" db = current.db flow_id = utils.new_flow_id() spec = plugins.RekallAPI(current).get(plugin) if not spec: raise ValueError("Unknown plugin") # Validate both plugin args an...
34,259
def deletePressed(self): """ TOWRITE """ qDebug("deletePressed()") QApplication.setOverrideCursor(Qt.WaitCursor) mdiWin = self.mdiArea.activeSubWindow() # MdiWindow* mdiWin = qobject_cast<MdiWindow*>(mdiArea->activeSubWindow()); if mdiWin: mdiWin.deletePressed() QApplication.res...
34,260
def setup(): """Initial power up routine. Additionally ramps up and monitors the heater temperature. """ spdc.peltier_loop_on() spdc.heater_loop_on() spdc.save_settings() spdc.heater_temp_setpoint = HSETTEMP # heater ramp spdc.laser_on(LCURRENT) # laser current ramp # Monitor te...
34,261
def set_gain(camera, gain, value): """Set the analog gain of a PiCamera. camera: the picamera.PiCamera() instance you are configuring gain: either MMAL_PARAMETER_ANALOG_GAIN or MMAL_PARAMETER_DIGITAL_GAIN value: a numeric value that can be converted to a rational number. """ if gain not in [MMA...
34,262
def load_config_from_expt_dir(experiment_dir: Path, loop_config: Type[OptimizerConfig]) -> OptimizerConfig: """ Locate a config file in experiment_dir or one of its subdirectories (for a per-seed config). Config files are now normally in seed subdirectories, as they contain seed values. """ config_f...
34,263
def glsadf_delay(order, stage): """Delay for glsadf Parameters ---------- order : int Order of glsadf filter coefficients stage : int -1 / gamma Returns ------- delay : array Delay """ return np.zeros(_sptk.glsadf_delay_length(order, stage))
34,264
def find_next(s: str)->[int]: """ input:string output:the next array of string """ if len(s) == 1: return [-1] result = [0 for i in range(len(s))] result[0] = -1 result[1] = 0 i = 2 cn = 0 while i < len(result): if s[i-1] == s[cn]: cn += 1 ...
34,265
def _read_date(): """ read date from input; default to today """ # show date while 1: dts = prompt("Date", default=str(datetime.date.today())) try: datetime.datetime.strptime(dts, "%Y-%m-%d") break except ValueError: continue return dts
34,266
def handle_pending_submission(self, request, layout=None): """ Renders a pending submission, takes it's input and allows the user to turn the submission into a complete submission, once all data is valid. This view has two states, a completable state where the form values are displayed without a fo...
34,267
def i18n_view(tpl_base_name=None, **defaults): """ Renders a template with locale name as suffix. Unlike the normal view decorator, the template name should not have an extension. The locale names are appended to the base template name using underscore ('_') as separator, and lower-case locale ident...
34,268
def tempfile_delete(tfile): """delete a temp file""" if tfile: tfile.close() os.unlink(tfile.name)
34,269
def git_file_list(path_patterns=()): """Returns: List of files in current git revision matching `path_patterns`. This is basically git ls-files. """ return exec_output_lines(['git', 'ls-files', '--exclude-standard'] + path_patterns, False)
34,270
def _keep_it_real(): """ Keep the native """ if not getattr(boto3, "real_client", None): boto3.real_client = boto3.client
34,271
def unreserve_id(): """ Removes the reservation of a SCSI ID as well as the memo for the reservation """ scsi_id = request.form.get("scsi_id") reserved_ids = get_reserved_ids()["ids"] reserved_ids.remove(scsi_id) process = reserve_scsi_ids(reserved_ids) if process["status"]: RESE...
34,272
def compress_delete_outdir(outdir): """Compress the contents of the passed directory to .tar.gz and delete.""" # Compress output in .tar.gz file and remove raw output tarfn = outdir + ".tar.gz" logger.info("\tCompressing output from %s to %s", outdir, tarfn) with tarfile.open(tarfn, "w:gz") as fh: ...
34,273
def iprint( img: np.ndarray, title: str = "", info: bool = False, ) -> None: """ Image displaying, can print information and the title of the image. Args: img (np.ndarray): Image which is displayed title (str, optional): Title of the image. Defaults to ''. info (bool, op...
34,274
def integral_sqrt_a2_minus_x2(x, a): """Integral of $\sqrt(a^2 - x^2)$ --- see (30) at http://integral-table.com. """ return 0.5*x*np.sqrt(a**2 - x**2) + 0.5*a**2*np.arctan2(x, np.sqrt(a**2 - x**2))
34,275
def do_qc(fn, df, year): """Run some checks on this dataframe""" (lon, lat) = fn2lonlat(fn) stage4 = compute_stage4(lon, lat, year) # Does the frame appear to have all dates? if len(df.index) != len(df.resample("D").mean().index): print("ERROR: Appears to be missing dates!") if open(fn)...
34,276
def read_length(file_obj): # pragma: no cover """ Numpy trick to get a 32-bit length from four bytes Equivalent to struct.unpack('<i'), but suitable for numba-jit """ sub = file_obj.read(4) return sub[0] + sub[1]*256 + sub[2]*256*256 + sub[3]*256*256*256
34,277
def check_and_reorder_reads(input_files, output_folder, temp_output_files): """ Check if reads are ordered and if not reorder """ # read in the ids from the first pair (only check the first 100) ids = [] for count, lines in zip(range(100),read_file_n_lines(input_files[0],4)): ids.append(get_rea...
34,278
def acquires_lock(expires, should_fail=True, should_wait=False, resource=None, prefix=DEFAULT_PREFIX, create_id=None): """ Decorator to ensure function only runs when it is unique holder of the resource. Any invocations of the functions before the first is done will raise RuntimeError. Locks are s...
34,279
def ifttt_comparator_alpha_options(): """ Option values for alphanumeric comparators """ errmsg = check_ifttt_service_key() if errmsg: return errmsg, 401 data = {"data": [ {"value": "ignore", "label": "ignore"}, {"value": "equal", "label": "is equal to"}, {"value": "not_...
34,280
def flat_abs_maximum(data, preserve_sign=True): """ Function to return the absolute maximum value in an array. By default, this function will preserve the sign, meaning that if an array contains [-75, -25, 0, 25, 50] then the function will return -75 because that value has the highest magnitude but it w...
34,281
def get_doctop_vis(clustering_pipeline, media='videos'): """ calls a function to generate bokeh visualization Parameters ---------- clustering_pipeline : class reference The current modeling pipeling media : str, optional 'articles' or 'videos', by default 'videos' """ bokeh...
34,282
def get_image_to_groundplane_homography(P): """Given the 3x4 camera projection matrix P, returns the homography mapping image plane points onto the ground plane.""" return np.linalg.inv(get_groundplane_to_image_homography(P))
34,283
def create_object_detection_edge_training( train_object_detection_edge_model_request: TrainImageEdgeModel, ): """[Train a Object Detection Model for Edge in AutoML GCP] Args: train_object_detection_edge_model_request (TrainImageEdgeModel): [Based on Input Schema] Raises: error: [Error]...
34,284
def download_all(links, destination): """Download all files from a list of urls.""" for link in links: download_file(link, destination)
34,285
def readOneLineFileWithCommas(filepath: str) -> List[str]: """ Reads a file that is one line long, separated by commas """ try: with open(filepath) as fp: s: str = fp.readline() return s.split(",") except: raise Exception(f"Failed to open {filepath}")
34,286
def argparser(parser): """Default argument parser for regressions. """ parser.add_argument("--local", action="store_true", help="run regression in local mode without docker-compose down", default=True)
34,287
def package_search(filters, context, limit=None, catalog=False): """Search packages with different filters Catalog param controls the base query creation. Catalog queries only search packages a user can deploy. Non-catalog queries searches packages a user can edit. * Admin is allowed to brow...
34,288
def is_valid(listener_tuple): """ There are a few rules that aws has when creating listeners, this function ensures those rules are met before we try and create or update a listener. While these could be caught with boto exception handling, I would rather be nice and catch these early before we...
34,289
def change_name(player_obj): """Changes the player objects name for specified user.""" username = get_random_username() player_obj.name = username player_obj.save()
34,290
def _run_wrapped( func, is_multimachine, master_ip, port, world_size, rank, dev, device_type, args, kwargs, backend, queue: mp.Queue, machine_ranks: list, ): """Init distributed process group and run wrapped function.""" _check_device_initialized(device_type, ...
34,291
def _jitter_boxes(gt_boxes, jitter=0.05): """ """ jittered_boxes = gt_boxes.copy() ws = jittered_boxes[:, 2] - jittered_boxes[:, 0] + 1.0 hs = jittered_boxes[:, 3] - jittered_boxes[:, 1] + 1.0 width_offset = (np.random.rand(jittered_boxes.shape[0]) - 0.5) * jitter * ws height_offset = (np.ra...
34,292
def last_model_path(exp_name): """ get path of the last model in the exp """ model_path = os.path.join(constants.ET_LOGS, exp_name, "latest.pth") assert os.path.islink(model_path) return model_path
34,293
def lcm_gcd(a, b): """Finds the least common multiple of two integers Args: a, b: integers greater than or equal to 1 """ return a * b//greatest_common_divisor(a, b)
34,294
def test_ahocorasick_rs_overlapping(benchmark, test_data): """ahocorasick_rs overlapping matches.""" patterns, haystacks = test_data ac = ahocorasick_rs.AhoCorasick(patterns) def run(): for haystack in haystacks: x = ac.find_matches_as_strings(haystack, overlapping=True) ret...
34,295
def merge_frames(frames): """ Merge the multiple data files downloaded from the M2M system or the Gold Copy THREDDS server into a single xarray data set. Keep track of how many files fail to merge. :param frames: The data frames to concatenate/merge into a single data set :return data: The fina...
34,296
def sorted_nicely(l): """ This function sorts the given iterable in the way that is expected Obtained from: https://arcpy.wordpress.com/2012/05/11/sorting-alphanumeric-strings-in-python/ :param l: The iterable to be sorted :return: Sorted iterable """ convert = lambda text...
34,297
def run_board(effects: list, audio: np.array, sample_rate: float) -> np.array: """Run board on input audio data. Args: board (list): List of Pedalboard effects. audio (np.array): Input audio data. Returns: Output (effected) audio data """ board = Pedalboard(effects, sample_...
34,298
def html_escape( s ): """ """ s = s.replace( '&', '&amp' ) s = s.replace( '<', '&lt' ) s = s.replace( '>', '&gt' ) return s
34,299