content
stringlengths
22
815k
id
int64
0
4.91M
def parse_request_GET(request): """ Parse JSON-RPC parameters from the request query string.""" args = request.GET.get('params') if args is not None: try: request.rpc_args = json.loads(args) except ValueError: raise JsonRpcParseError else: request.rpc_args...
5,324,000
def analyze_integration_target_dependencies(integration_targets): # type: (t.List[IntegrationTarget]) -> t.Dict[str, t.Set[str]] """Analyze the given list of integration test targets and return a dictionary expressing target names and the target names which depend on them.""" real_target_root = os.path.realpat...
5,324,001
def newton_cotes(order, domain=(0, 1), growth=False, segments=1): """ Generate the abscissas and weights in Newton-Cotes quadrature. Newton-Cotes quadrature, are a group of formulas for numerical integration based on evaluating the integrand at equally spaced points. Args: order (int, nump...
5,324,002
def rename_img(path): """ 对图片排序后改名 :param path: :return: """ imgs = os.listdir(path) for i,fi in enumerate(imgs): old_name=os.path.join(path,fi) new_name=os.path.join(path,str(i+2)+'.jpg') print(new_name) os.rename(old_name,new_name)
5,324,003
def internalpackage_remove(package_name): """Removes an internal package by deleting the folder on the PyPi packages dir :param package_name: String of package to remove""" dst_dir = os.path.join(PACKAGES_DIR, package_name) if os.path.exists(dst_dir): shutil.rmtree(dst_dir)
5,324,004
def transpose(a, axes=None): """transpose(a, axes=None) returns array with dimensions permuted according to axes. If axes is None (default) returns array with dimensions reversed. """ # if axes is None: # this test has been moved into multiarray.transpose # axes = arange(len(array(a).shape))[...
5,324,005
def test_gan_loss(): """test gan loss.""" with pytest.raises(NotImplementedError): loss_cfg = dict( type='GANLoss', gan_type='test', real_label_val=1.0, fake_label_val=0.0, loss_weight=1) _ = build_loss(loss_cfg) input_1 = torch.on...
5,324,006
def migrate(engine: Engine) -> None: """Ensures that the connected database has all the database objects. Very simple migration. Does not handle changing the models currently. Parameters ---------- engine: Engine SQLAlchemy engine. """ Base.metadata.create_all(engine)
5,324,007
def find_next_prime(N: int) -> int: """Find next prime >= N Parameters ---------- N : int Starting point to find the next prime >= N. Returns ------- int the next prime found after the number N """ def is_prime(n): if n % 2 == 0: return False ...
5,324,008
def in_16(library, session, space, offset, extended=False): """Reads in an 16-bit value from the specified memory space and offset. Corresponds to viIn16* function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :para...
5,324,009
def match_head(subject, pattern): """Checks if the head of subject matches the pattern's head.""" if isinstance(pattern, Pattern): pattern = pattern.expression pattern_head = get_head(pattern) if pattern_head is None: return True if issubclass(pattern_head, OneIdentityOperatio...
5,324,010
def update(number): """ update() : Update document in Firestore collection with request body. Ensure you pass a custom ID as part of json body in post request, e.g. json={'id': '1', 'title': 'Write a blog post today'} """ try: todo_ref = user_ref.document(number).collection("...
5,324,011
def test_using_name_in_text_without_explicit_timer(capsys): """Test that the name of the timer can be referenced in the text""" name = "NamedTimer" with Timer(name=name, text="{name}: {:.2f}"): waste_time() stdout, stderr = capsys.readouterr() assert re.match(f"{name}: " + r"0\.\d{2}", stdo...
5,324,012
def sfn_result(session, arn, wait=10): """Get the results of a StepFunction execution Args: session (Session): Boto3 session arn (string): ARN of the execution to get the results of wait (int): Seconds to wait between polling Returns: dict|None: Dict of Json data or ...
5,324,013
def forum_latest_user_posts(parser, token): """ {% forum_latest_user_posts user [number] as [context_var] %} """ bits = token.contents.split() if len(bits) not in (2, 3, 5): raise TemplateSyntaxError('%s tag requires one, two or four arguments' % bits[0]) if bits[3] != 'as': rais...
5,324,014
def gene_symbol_writeout(outdir, gene_set): """write out file with gene symbols that are targeted :param outdir: absolute filepath to output directory :param gene_set: first output of determine_gene_targets() :return: writes out a file with gene symbols that are targeted """ with open('%s/gene...
5,324,015
def parse_args(args): """Parse command line arguments. """ parser = argparse.ArgumentParser(description='YouTube Subscription Search') parser.add_argument( '-s', '--secrets-file', default='client_id.json', help='Client secret file. See README.md on how to get this file.') parser.add...
5,324,016
def test_irc_nickname_strings(test_input, rescue_plain_fx: Rescue): """ Verifies the irc nickname can be set when passed a string Args: test_input (str): values to test rescue_plain_fx (Rescue): Rescue fixture """ rescue_plain_fx.irc_nickname = test_input assert re...
5,324,017
def PureMultiHeadedAttention(x, params, num_heads=8, dropout=0.0, mode='train', **kwargs): """Pure transformer-style multi-headed attention. Args: x: inputs ((q, k, v), mask) params: parameters (none) num_heads: int: number of attention heads dropout: float: dropout rat...
5,324,018
def validate_options(options): """ Validate the options and return bool. :param options: options to validate :type options: dict :rtype: bool """ pywikibot.log('Options:') notice_keys = [ 'email_subject', 'email_subject2', 'email_text', 'email_text2', ...
5,324,019
def verify() -> bool: """Verify access to the NFVIS Device.""" print("==> Verifying access to the NFVIS Device Environment.") nip, url, login, password = nvfis_getgcred() s = requests.Session() s.auth = (login, password) s.headers = ({'Content-type': 'application/vnd.yang.data+json', 'Accept': ...
5,324,020
def main( domain: InnerEnv, planner: planning_types.Planner, belief: belief_types.Belief, runs: int, logging_level: str, ) -> List[Dict[str, Any]]: """plan online function of online planning Handles calling :func:`episode` :: for r in runs: rewards = episode(domain, pla...
5,324,021
def convert_to_target(filepath, data_ann_path_out, target_map): """ Saves the image as a .png in the data path """ if not os.path.isfile(filepath): print("No such file found: ", filepath) return False ann_file = os.path.basename(filepath) # open the image mask = target_map...
5,324,022
def mvrth(value): """ relative move kphi by value """ yield from _quickmove_rel_plan(value,arpes_motors.m4)
5,324,023
def format_color( color: Union[ColorInputType, Any], warn_if_invalid: bool = True ) -> Union[ColorType, Any]: """ Format color from string, int, or tuple to tuple type. Available formats: - Color name str: name of the color to use, e.g. ``"red"`` (all the supported name strings can be f...
5,324,024
def is_yaml_requested( content_type: str = None, proto: ExtendedProto = None, path_suffix: Optional[str] = None, ) -> bool: """Checks whether YAML is requested by the user, depending on params.""" is_yaml = False if content_type is not None: is_yaml = ("yaml" in content_type) or ("yml" i...
5,324,025
def _pqs_in_range(dehn_pq_limit, num_cusps): """ Return an iterator. This iterator, at each step, returns a tuple. The contents of this tuple are num_cusps other tuples, and each of these is of the form (p,q), where 0 <= p <= dehn_pq_limit, -dehn_pq_limit <= q <= dehn_pq_limit, and gcd(p,q) <= 1. ...
5,324,026
def _units_defaults(calendar, has_year_zero=None): """ Set calendar specific default units as 'days since reference_date' Day 0 of *excel* and *excel1900* starts at 1899-12-31 00:00:00. Day 0 of *excel1904* starts at 1903-12-31 00:00:00. Decimal calendars *decimal*, *decimal360*, *decimal365*, an...
5,324,027
def test_use_mount(aggregator, instance_basic_mount, gauge_metrics, rate_metrics): """ Same as above, using mount to tag """ c = Disk('disk', None, {}, [instance_basic_mount]) c.check(instance_basic_mount) for name, value in iteritems(gauge_metrics): aggregator.assert_metric(name, value...
5,324,028
def submit_a_feed(request): """ 用户添加一个自定义的订阅源 """ feed_url = request.POST.get('url', '').strip()[:1024] user = get_login_user(request) if feed_url: host = get_host_name(feed_url) if host in settings.ALLOWED_HOSTS: rsp = add_self_feed(feed_url) elif settings....
5,324,029
def check_existing_credendtials(account_Name): """ Function that check if a Credentials exists with that account name and return a Boolean """ return Credentials.credential_exist(account_Name)
5,324,030
def hash_paths(paths, log_interval): """Returns a map of the base64 hash to the filename for all paths in path.""" output = {} count_since_log = 0 for path in paths: output[hash_file(path)] = os.path.basename(path) count_since_log += 1 if count_since_log >= log_interval: ...
5,324,031
def scmplx(p,a,b): """ p is a string designating a type, either scalar_f or scalar_d. """ if p == 'scalar_f': return vsip_cmplx_f(a,b) elif p == 'scalar_d': return vsip_cmplx_d(a,b) else: assert False,'Type %s not defined for cmplx.'%p
5,324,032
def ips_description(request): """See :class:`bgpranking.api.get_ips_descs`""" asn = request.get('asn') block = request.get('block') if asn is None or block is None: return json.dumps({}) return json.dumps(bgpranking.get_ips_descs(asn, block, request.get('date'), request...
5,324,033
def handle_msg(msg: dict) ->list: """ Handler for message request object. Logs message and returns list of responses.""" msg_alert(msg['From'], msg['Body']) msg, lol = parse_msg(msg) if lol is not None: resp = lol elif lol is None: resp = get_response(msg) log_msg = [ {...
5,324,034
def create_app(register_blueprints=True): """Function to instantiate, configure, and return a flask app""" app = Flask(__name__, instance_relative_config=True) app.config.from_object('app.default_config') # default config # app.config.from_pyfile('application.cfg.py') # server config file, do not inc...
5,324,035
def RoleAdmin(): """超级管理员""" return 1
5,324,036
def _get_proj_info(): """Information on system PROJ Returns ------- proj_info: dict system PROJ information """ import pyproj from pyproj.exceptions import DataDirError try: data_dir = pyproj.datadir.get_data_dir() except DataDirError: data_dir = None b...
5,324,037
def run_program(intcodes): """run intcodes, which are stored as a dict of step: intcode pairs""" pc = 0 last = len(intcodes) - 1 while pc <= last: if intcodes[pc] == 1: # add if pc + 3 > last: raise Exception("out of opcodes") arg1 = intcodes[...
5,324,038
def concat(lst, cat_symb=None, append_to_end=False): """Concatenates `lst` of Tensors, optionally with a join symbol. Args: lst: list of Tensors to concatenate. cat_symb: concatenation symbol. append_to_end: if set to ``True``, it will add the `cat_symb` to the end of the co...
5,324,039
async def get_the_pointer_there(): """ - Figure out where we are currently pointing (read acc/mag) - Calculate diff with forward azimuth - Turn the pointer """ for cycle in range(STEPPER_MOVES_PER_CYCLE): acc_x, acc_y, acc_z = accel.acceleration # m/s^2 mag_x, mag_y, mag_z = mag....
5,324,040
def find_mcs(mols): """Function to count the number of molecules making ito the end of the test""" out_mols = ROMol_Vect() while mols.hasNext(): molobj = mols.next() rdmol, molobj = get_or_create_rdmol(molobj) # Add this mol to that vector out_mols.add(rdmol) # Now find t...
5,324,041
def save_csv(df, data_dir, filename): """ Saves a pandas DataFrame df inside a data_dir folder with a filename.csv extension Robust for all OS because of pathlib module """ import pandas as pd from pathlib import Path df.to_csv(Path(data_dir).joinpath(filename), index=False)
5,324,042
def build_karel3(): """ This function builds the third karel """ add = 2 head = GOval(80, 55, x=190 + 120 * add, y=167) head.filled = True head.color = 'black' head.fill_color = 'gray' window.add(head) r_eye = GRect(13, 13, x=212 + 120 * add, y=189) r_eye.filled = True r_...
5,324,043
def to_numpy(tensor): """Convert 3-D torch tensor to a 3-D numpy array. Args: tensor: Tensor to be converted. """ return tensor.transpose(0, 1).transpose(1, 2).clone().numpy()
5,324,044
def calib_constants(det, exp=None, ctype='pedestals', run=None, time_sec=None, vers=None, url=cc.URL) : """Returns calibration constants and document with metadata for specified parameters. To get meaningful constants, at least a few parameters must be specified, e.g.: - det, ctype, time_sec -...
5,324,045
def decode(src, dst): """Decodes media file at src and stores it at dst""" cmd = f""" ffmpeg -y -hide_banner -nostats -v warning -i {src} -c:v rawvideo -an {dst} """ try: subprocess.check_call(shlex.split(cmd)) except subprocess.CalledProcessError as err: raise DecodeFailed(f...
5,324,046
def check_a_better_than_b(model_a, model_b, X_y_func, metric): """Trains two models and checks that model_a does better than model_b.""" from .. import model_selection metric_a = model_selection.online_score( X_y=X_y_func(), model=model_a, metric=copy.deepcopy(metric) ) met...
5,324,047
def is_cluster_healthy(admin, zk, retries=10, retry_wait=30): """Return true if cluster is healthy.""" retries_left = retries while retries_left: md = _request_meta(admin) if md is not None and not _unhealthy(md, zk): logger.info("Cluster is healthy!") return True ...
5,324,048
def load_data(loc): """ Load in the csv file """ df = pd.read_csv(loc, engine = "python", encoding = "utf-8") df.fillna("") df = np.asarray(df) return df
5,324,049
def listdir(folder, suffix): """ Output the path of files in the folder with specific suffix""" list_path = [] for root, _, files in os.walk(folder, followlinks=True): for f in files: if f.endswith(suffix): list_path.append(osp.join(root, f)) return list_path
5,324,050
def mqtt_subscribe_cb(topic: str, msg: str): """ Callback method that is executed anytime an MQTT message is received. Args: topic (str): The MQTT topic that was received msg (str): The MQTT message that was received """ print((topic, msg)) if topic == b'notification' and msg == b'received': ...
5,324,051
def book_meta_data(book_link, book_title, author_name): """ book_link: Direct link to the book book_title: Title of the book author_name: Name of the author """ global soup i, retries = 0, 3 # fetching the metadata for each of the books try: print("Fetching book...
5,324,052
def clif_deps_to_cclibs(labels): """Gets the cc_library name for each of label as a list.""" return [_clif_to_lib(name, PYCLIF_CC_LIB_SUFFIX) for name in labels]
5,324,053
def _get_cache_filename(year=2020): """Returns the `Path` to the COBS data file for a given year.""" return CACHEDIR / f'cobs{year}.feather'
5,324,054
def get_critical_hours_end(critical_ffmc: float, solar_noon_ffmc: float, critical_hour_start: float): """ Returns the hour of day (on 24H clock) at which the hourly FFMC drops below the threshold of critical_ffmc. Should only be called if critical_hour_start is not None. """ if critical_hour_start i...
5,324,055
def dolpc(x, model_order=8): """ Function dolpc computes the autoregressive model from spectral magnitude samples. @param x: Critical band filters. @param model_order: Order of model. Default is 8. @returns: Autoregressive model from spectral magnitude samples. """ num_bands, num_frames...
5,324,056
def filter_domains(domains, by="evalue", coverage_pct=0.5, tolerance_pct=0.1): """Filter overlapping Domain objects and test adjcency rules. Adjacency rules are tested again here, in case they are missed within overlap groups. For example, the NRPS-para261 domain is not always entirely contained by a c...
5,324,057
def _replicate_and_maybe_restore_latest_checkpoint( unreplicated_optimizer_state, unreplicated_params, unreplicated_batch_stats, unreplicated_training_metrics_grabber, train_dir, use_deprecated_checkpointing): """Restore from the latest checkpoint, if it exists.""" uninitialized_global_step ...
5,324,058
def minkowskiSum(obj1, obj2): """ Minkowski sum of two polygon objects Args: obj1, obj2: (n,2) array of corner point Return: poly: (n,2) array of minkowski polygon vertices centered at (0, 0) bound: [min_x, min_y] max/min signed distances from vertices ...
5,324,059
def get_rotated_image_from_contour(img, contour, rotation=90): """ Returns a rotated version of img based on cv2.minAreaRect of contour. First side, (i.e most left to top edge) is always "Width" from minAreaRect. If our width > height, we know we have the sheet rotated to the right. We nee...
5,324,060
def test_set_const_crashes__setattr(): """Attempting to set a const field via attribute access crashes. Only use attribute access to avoid interaction with __setitem__. """ with pytest.raises( errors.ImmutableFieldError, match=re.escape( "Cannot assign to immutable field: <b...
5,324,061
def config(config: Config, key: str, value: str): """Change the configuration.""" config.update(key, value)
5,324,062
def fix_dataset_dims(d): """Given one of the dataset files given by the organizers, fix its dimensions so its easier to concatenate and use with xr.open_mfdataset. Arguments: d. xr.Dataset. The dataset you get when you open one of the provided files. """ month = int(d.forecast_time[0].dt.mon...
5,324,063
def prettyprint_xml(element): """ A rough and dirty way to prettyprint an Element with indention. :param lxml.etree._Element element: The Element or ElementTree to format. :rtype: str :returns: A prettyprinted representation of the element. """ return etree.tostring(element, pretty_print=T...
5,324,064
def load_vimba_lib(vimba_project: str): """ Load shared library shipped with the Vimba installation Arguments: vimba_project - Library name without prefix or extension Return: CDLL or WinDLL Handle on loaded library Raises: VimbaSystemError if given library could not be loaded...
5,324,065
def decorator(IterativeReconAlg, name=None, docstring=None): """ Calls run_main_iter when parameters are given to it. :param IterativeReconAlg: obj, class instance of IterativeReconAlg :param name: str for name of func :param docstring: str other documentation that ...
5,324,066
def read_json_file(filepath: str) -> Any: """Read JSON from a file. Args: filepath (str): Path to file Returns: Any: The parsed JSON """ with open(filepath, 'r') as json_file: data = json.load(json_file) return data
5,324,067
def penalized_loss(loss_func, model, inputs, targets, output_regularization, l2_regularization = 0.0, use_dnn = False): """Computes penalized loss with L2 regularization and output penalty. Args: l...
5,324,068
async def test_platform_manually_configured(hass): """Test that we do not discover anything or try to set up a gateway.""" assert await async_setup_component(hass, climate.DOMAIN, { 'climate': { 'platform': deconz.DOMAIN } }) is True assert deconz.DOMAIN not in hass.data
5,324,069
def main(json_file): """Extracts information about the tools present on this host. Args: json_file: File to write JSON containing the tools information. """ info = { } info['Xcode Version'], info['Xcode Build Version'] = extract_xcode_version( utils.call('xcodebuild', '-version').stdout) info['...
5,324,070
def test_clean_output(_py_controller, msg): """Check if output text is getting cleaned from Result. When `Result: Hello` is present, clean output should return only Hello. If output is only `Hello`, clean output should do nothing """ assert _py_controller._clean_output(msg) == 'Hello'
5,324,071
def load_corpus(corpus_id: str, download_if_missing=False) -> Optional[list]: """Loads a corpus that has previously been downloaded Parameters ---------- corpus_id: str The id of the corpus to load. download_if_missing: bool, False If the corpus is not present on disk, should Canary...
5,324,072
def tx_deserialize( tx_hex ): """ Given a serialized transaction, return its inputs, outputs, locktime, and version Each input will have: * txid: string * vout: int * [optional] sequence: int * [optional] scriptSig: {"asm": ..., "hex": ...} Each output will have: * value: Dec...
5,324,073
def wait_for_result(polling_function, polling_config): """ wait_for_result will periodically run `polling_function` using the parameters described in `polling_config` and return the output of the polling function. Args: polling_config (PollingConfig): The parameters to u...
5,324,074
def regrid(idx): """ Decorator factory to compute a model on a constant grid, then interpolate. This is to be used for reconvolution fits when the independant axis isn't evently spaced. This function returns a decorator. You should call the result of this function with the model to regrid. The constant grid...
5,324,075
def create_random_bytes( min_length: Optional[int] = None, max_length: Optional[int] = None, lower_case: bool = False ) -> bytes: """Generates a random bytes given the constraints""" if min_length is None: min_length = 0 if max_length is None: max_length = min_length + 1 * 2 length =...
5,324,076
def calculate_v_correction(df, photopic_response): """ Closure to calculate the e correction factor from a dataframe """ # Get angles from column names first try: angles = df.drop(["0_deg", "wavelength"], axis=1).columns.to_numpy(float) except: angles = df.drop(["wavele...
5,324,077
def wrap_statement(token_str): """ Wraps a long string of space-separated tokens or a list of tokens. """ if isinstance(token_str, list): token_str = ' '.join(token_str) wrap_ind = '\n' + INDENT * 4 return wrap_ind.join(gtextWrapper.wrap(token_str))
5,324,078
def mlas_packb(B, K, N, transb_size, transb=True): """Pre-pack B matrix if it is constant for mlas_matmul, C = A * B^T. It only supports float32 datatype. Parameters ---------- B : tvm.te.Tensor The second input of mlas_matmul. K : int The number of colums of A. N : int ...
5,324,079
def file_version_summary(list_of_files): """ Given the result of list_file_versions, returns a list of all file versions, with "+" for upload and "-" for hide, looking like this: ['+ photos/a.jpg', '- photos/b.jpg', '+ photos/c.jpg'] """ return [('+ ' if (f['action'] == 'upload') else '-...
5,324,080
def make_players(data, what_to_replace_null_data_with): """ 1. feature selection 2. replacing null values :param data: :param what_to_replace_null_data_with: accepted values: "1", "mean", "median" :return: players """ players = data[["Overall", "Potential", "Position", "Skill Moves", "C...
5,324,081
def pwm_to_duty_cycle(pulsewidth_micros, pwm_params): """Converts a pwm signal (measured in microseconds) to a corresponding duty cycle on the gpio pwm pin Parameters ---------- pulsewidth_micros : float Width of the pwm signal in microseconds pwm_params : PWMParams PWMParams ob...
5,324,082
def update_plugin_packages_in_kv(rid, runit): """Update the plugin packages for this unit in the kv store. It returns a tuple of 'install_packages' and 'purge_packages' that are different from that which was previously stored. :param rid: The relation_id of the unit :type rid: str :param runit...
5,324,083
def get_a_record(dns_name, zone_name): """Lookup an 'A' record with the supplied name. Args: dns_name: DNS nname of the resource. zone_name: Cloud DNS managed zone name. Returns: The first A record for the DNS resource. None if not found """ rr_set_response = api.CLIENTS.dn...
5,324,084
def get_file_obj(fname, mode='r', encoding=None): """ Light wrapper to handle strings and let files (anything else) pass through. It also handle '.gz' files. Parameters ---------- fname: string or file-like object File to open / forward mode: string Argument passed to the '...
5,324,085
def decode(codes, alphabet): """ Converts one-hot encodings to string Parameters ---------- code : torch.Tensor One-hot encodings. alphabet : Alphabet Matches one-hot encodings to letters. Returns ------- genes : list of Tensor List of proteins others : list...
5,324,086
def GetSuites(milo_client, waterfall, builder_name, build_number): """Gets a list of suites ids for a given build from Milo. Args: milo_client: MiloClient object. waterfall: Buildbot waterfall. builder_name: Buildbot builder name. build_number: Buidlbot build number. Returns: A set of suite ...
5,324,087
def test_sdfi(X_raw): """Test SimpleDataFrameImputer.""" train = X_raw.iloc[:30, :] test = X_raw.iloc[30:, :] print('\ntrain.shape:', train.shape) print('test.shape:', test.shape) imputer = SimpleDataFrameImputer(median_cols=['Age'], mode_cols=['Embarked']) imputer.fit(train) tes...
5,324,088
def getNormform_space(synonym): """ """ return re.sub("[^a-z0-9]", " ", synonym.lower())
5,324,089
def generate_chart_dataset(path_to_csv, dataset_type): """create the dataset""" worker1 = multiprocessing.Process( target=fn_task_generate_filled_line_fusion, args=(path_to_csv, dataset_type) ) worker2 = multiprocessing.Process( target=fn_task_generate_candlestick_fusion, args=(path_to_c...
5,324,090
def electrolyte_conductivity_PeymanMPM(c_e, T): """ Conductivity of LiPF6 in EC:DMC as a function of ion concentration. The original data is from [1]. The fit is from Dualfoil [2]. References ---------- .. [1] C Capiglia et al. 7Li and 19F diffusion coefficients and thermal properties of no...
5,324,091
def turn_off(): """ Turn off the cofee machine. Exit the program """ machine_on = False quit()
5,324,092
def rename_leaves_taxids(tree): """ Rename the leaf nodes with just the NCBI taxonomy ID if we have it :param tree: the tree to rename :return: the tree with renamed leaves """ for n in tree.get_leaves(): m = re.search(r'\[(\d+)\]', n.name) if m: n.name = m.groups()[...
5,324,093
def hshift(x, shifts=0): """shift batch of images horizontally""" return paddle.roll(x, int(shifts*x.shape[3]), axis=3)
5,324,094
def getFirstCatalogKeyPath(cataloglist, keypath, default = None): """ Get the value of the keypath in the first catalog containing it. """ for name in cataloglist: catalog = getCatalog(name) if catalog is not None: value = valueForKeyPath(catalog, keypath) if valu...
5,324,095
def load_context(): """Load and parse command line arguments and create runtime context. Parse command line arguments and create runtime context. Also set any logging parameters passed in (just to file for the moment). Returns: context: runtime parameters """ context = None tr...
5,324,096
def pinv(a: numpy.ndarray, rcond: float): """ usage.statsmodels: 1 """ ...
5,324,097
def HT_DCPHASE(ds, count): """Hilbert Transform - Dominant Cycle Phase""" return call_talib_with_ds(ds, count, talib.HT_DCPHASE)
5,324,098
def split_every(n, iterable): """https://stackoverflow.com/questions/9475241/split-string-every-nth-character""" i = iter(iterable) piece = list(islice(i, n)) while piece: yield piece piece = list(islice(i, n))
5,324,099