content
stringlengths
22
815k
id
int64
0
4.91M
def install_signal_handlers(): """Sets up a the global terminator greenlet to: * Set GLOBAL_SHUTDOWN on an interrupt signal (which should occur at LUCI_CONTEXT['deadline']['soft_deadline'], OR if the build is canceled). * Set GLOBAL_QUITQUITQUIT after LUCI_CONTEXT['deadline']['grace_period']-1 se...
13,400
def get_inputs(): """ inputsdict contains {'Yte': Yte, 'Ytr': Ytr, 'Xtr': Xtr, 'Xte': Xte} where values are np.arrays np. arrays are truncated to evenly split into batches of size = batchsize """ with open(os.path.join(dpath, dfile), 'rb') as f: d_all = pickle.load(f) return d_a...
13,401
def _apply(input_bundle_name, output_bundle_name, pipeline_class_name, pipeline_args, input_tags, output_tags, output_bundle_uuid=None, force=False): """Apply a pipeline to an input bundle, and save the results in an output bundle. Args: input_bundle_name: The human name of the input bun...
13,402
def reviews( app_id, token=None, pagination_delay=1, review_size=100, sort_by='most_relevant', rating=0, lang='en'): """Generator, gets all reviews. Parameters ---------- app_id : str App id/Package name. token : str | None For continuation of revie...
13,403
def arcColor(renderer, x, y, rad, start, end, color): """Draws an arc to the renderer with a given color. The start and end of the arc are defined in units of degrees, with 0 being the bottom of the arc circle and increasing counter-clockwise (e.g. 90 being the rightmost point of the circle). If t...
13,404
def SMLSL(cpu_context: ProcessorContext, instruction: Instruction): """Signed multiply-subtract long (vector form)""" logger.debug("%s instruction not currently implemented.", instruction.mnem)
13,405
def save_json(filepath, data_dict): """ 將 dict 轉成 JSON 檔案,並指定縮排以提升文件可讀性 Note: 可用於保存 Keras 模型的 JSON 檔案 此文件可搭配 Keras 的 models.model_from_json() """ # solve models.model_from_json() if isinstance(data_dict, str): data_dict = json.loads(data_dict) with open(filepath, 'w') as f:...
13,406
def delete_original_and_processed_slice_from_storage(mapper: Mapper, connection: Connection, target: Slice) -> None: """Delete original and processed Slices from storage.""" original_slice = OriginalSlice.get(id=target.id) original_slice.delete() processed_slice = ProcessedSlice.get(id=target.id) pr...
13,407
def test_auth_info(): """ Test singleton AuthInfo :return: """ auth_info = qradar_utils.AuthInfo.get_authInfo() auth_info.create(host, username=username, password=password, token=None, cafile=cafile) asser...
13,408
def dos_element_spd( folder, element_spd_dict, output='dos_element_spd.png', fill=True, alpha=0.3, linewidth=1.5, sigma=0.05, energyaxis='x', color_list=None, legend=True, total=True, figsize=(4, 3), erange=[-6, 6], spin='up', combination_method='add', fon...
13,409
def load(m, schema=UPLOAD_MANIFEST_SCHEMA): """ Load and validate a manifest. """ manifest = yaml.load(m) validate( manifest, schema=schema, ) return manifest
13,410
def transform_phenotype(inv_root, y, fam_indices, null_mean = None): """ Transform phenotype based on inverse square root of phenotypic covariance matrix. If the null model included covariates, the fitted mean is removed rather than the overall mean """ # Mean normalise phenotype if null_mean is...
13,411
def download_site_build(event_file: str, download_path: str = "build-site.tar.gz") -> int: """Will download the site bulid if this is a forked PR bulid. Args: event_file (str): event file from the workflow Returns: int: PR num of the build if relevant """ with open(event_file, 'r')...
13,412
def createVskDataDict(labels,data): """Creates a dictionary of vsk file values from labels and data. Parameters ---------- labels : array List of label names for vsk file values. data : array List of subject measurement values corresponding to the label names in `labels`. Returns -------...
13,413
def remove_dates(scan_result): """ Remove date fields from scan. """ for scanned_file in scan_result['files']: scanned_file.pop('date', None)
13,414
def window_partition(x, window_size): """ Args: x: (B, H, W, C) window_size (int): window size Returns: windows: (num_windows*B, window_size, window_size, C) """ B, H, W, L, C = x.shape #print(x.shape) #print(window_size[0]) x = x.view(B, H // window_size[0], wind...
13,415
def _get_unique(node_list, key, mode=None): """ Returns number or names of unique nodes in a list. :param node_list: List of dictionaries returned by Neo4j transactions. :param key: Key accessing specific node in dictionary. :param mode: If 'num', the number of unique nodes is returned. :return...
13,416
def calculate_cpufreq_weighted_time_in_state( final_time_in_cpufreq_state_by_cpu, time_in_cpufreq_state_by_cpu): """Calculate the weighted average in each CPU frequency state. Args: final_time_in_cpufreq_state_by_cpu: Final time in each CPU frequency state. See the return value of parse_cpufreq_stat...
13,417
def array2imgdata_pil(A, format='PNG'): """get png data from array via converting to PIL Image""" from PIL import Image if A.shape[2] == 3: mode = 'RGB' elif A.shape[2] == 4: mode = 'RGBA' else: mode = 'L' img = Image.fromstring(mode, A.shape[:2], A.tostring()) return...
13,418
def h_eval(data): """ Function takes dictionary Evaluate values and convert string to correct type (boolean/int/float/long/string) """ if isinstance(data, dict): for _k in list(data.keys()): data[_k] = h_eval(data[_k]) if data[_k] is None or (isinstance(data[_k], dic...
13,419
def _recursive_simplify(expr): """ Simplify the expression as much as possible based on domain knowledge. """ input_expr = expr # Simplify even further, based on domain knowledge: # windowses = ('WIN32', 'WINRT') apples = ("MACOS", "UIKIT", "IOS", "TVOS", "WATCHOS") bsds = ("FREEBSD", "...
13,420
def dropzone(url, **kwargs): """Dropzone component A basic dropzone component that supports drag and drop uploading of files which are posted to the URL provided. >>> zoom.system.site = zoom.sites.Site() >>> zoom.system.site.packages = {} >>> zoom.system.request = zoom.utils.Bunch(app=zoom.uti...
13,421
def fmt_bytes(size_bytes): """Return a nice 'total_size' string with Gb, Mb, Kb, and Byte ranges""" units = ["Bytes", "KB", "MB", "GB"] if size_bytes == 0: return f"{0} Bytes" for unit in units: digits = int(math.log10(size_bytes)) + 1 if digits < 4: return f"{round(s...
13,422
def plot_points(x, point_size=0.005, c='g'): """ x: point_nr,3 """ if c == 'b': k = 245 elif c == 'g': k = 25811000 elif c == 'r': k = 11801000 elif c == 'black': k = 2580 else: k = 2580 colors = np.ones(x.shape[0]) * k plot = k3d.plot(name...
13,423
def julianDays(year, month, day, hour, minute): """ Calculate the julian day (day of year) based on the known date/time information. :param year: :class:`numpy.ndarray` of the year of all observations. :param month: As for year, but for the month of observation. :param day: As for year, but for...
13,424
def get_valid_split(records: dict, train_val_test: Union[list, np.ndarray]) -> dict: """ Gets a train, val, test split with at least one instance of every class Keep doing train_test_split until each split of the data has at least one single example of every behavior in the dataset. it would be bad if you...
13,425
def _random_op(sites, ldim, hermitian=False, normalized=False, randstate=None, dtype=np.complex_): """Returns a random operator of shape (ldim,ldim) * sites with local dimension `ldim` living on `sites` sites in global form. :param sites: Number of local sites :param ldim: Local ldimens...
13,426
def test_history_beats_optimizer(): """Test overwriting from history vs whatever the optimizer reports.""" problem = CRProblem( x_guesses=np.array([0.25, 0.25]).reshape(1, -1) ).get_problem() max_fval = 10 scipy_options = {"maxfun": max_fval} result_hist = optimize.minimize( pr...
13,427
def enron_dataset_part012() -> Path: """ Returns: A directory with two PST files: chris_dorland_000_1_1_1.pst chris_dorland_001_1_1_1.pst """ name = "chris_dorland" files = ["chris_dorland_000_1_1_1.pst", "chris_dorland_001_1_1_1.pst"] url = f"{ENRON_DATASET_URL}/chris_d...
13,428
def set_compute_type(type): """ Sets the compute type of the convolution operation, and other operations """ global COMPUTE_TYPE COMPUTE_TYPE = type
13,429
def minimize(system, positions, platform=None, tolerance=1.0*unit.kilocalories_per_mole/unit.angstroms, maxIterations=50): """Minimize the energy of the given system. Parameters ---------- platform : simtk.openmm.Platform or None, optional If None, the global GLOBAL_ALCHEMY_PLATFORM will be use...
13,430
async def fetch(url="", headers=DEFAULT_HEADERS, params={}, payload={}, method="GET", loop=None): """fetch content from the url""" if not url: return async with aiohttp.ClientSession(loop=loop, headers=headers) as session: _method = getattr(session, method.lower()) async with _method...
13,431
def retrieve_prefix_fixture(): """Load test fixture data.""" j = json.load(open("./tests/fixtures/s3_prefix_list.json")) return j
13,432
def test_multiline_attribute(): """ Test parsing multiline attributes in LDIF. """ text = "dn: cn=unimaginably+sn=very,ou=very,dc=very,dc=long,\n dc=line\ncn: unimaginably\nsn: very\nsn: long\n" with StringIO(text) as test: reader = LDIFReader(test) ent = next(reader) assert ent.dn == "c...
13,433
def parse_args(version: str) -> Namespace: """ Parse arguments passed to the application. A custom argument parser handles multiple commands and options to launch the desired function. Parameters ---------- version : string A ``string`` of the Bobber version. Returns -----...
13,434
def test_train_small_ensemblemodel_benchmark(small_moddata, tf_session): """Tests the `matbench_benchmark()` method for ensemble models.""" from modnet.matbench.benchmark import matbench_benchmark from modnet.models import EnsembleMODNetModel data = small_moddata # set 'optimal' features manually ...
13,435
def organizations_virtual_dns(self): """ API core commands for Cloudflare API""" self.add('AUTH', "organizations", "virtual_dns") self.add('VOID', "organizations", "virtual_dns", "dns_analytics") self.add('AUTH', "organizations", "virtual_dns", "dns_analytics/report") self.add('AUTH', "organization...
13,436
def grid_reference_to_northing_easting(grid_reference): """ Needs to include reference :param grid_reference: :return: """ grid_reference = grid_reference.strip().replace(' ', '') if len(grid_reference) == 0 or len(grid_reference) % 2 == 1 or len(grid_reference) > 12: return None, No...
13,437
def tflite_copts_warnings(): """Defines common warning flags used primarily by internal TFLite libraries.""" # TODO(b/155906820): Include with `tflite_copts()` after validating clients. return select({ clean_dep("//tensorflow:windows"): [ # We run into trouble on Windows toolchains wit...
13,438
async def send_events(count, sleep, channel, server): """ Allow to send fake event to the server """ for i in range(count): await asyncio.sleep(sleep) server.push_result(channel, {"foo": i})
13,439
def deleteMatches(): """Remove all the match records from the database.""" db = connect() db_cursor = db.cursor() query = "DELETE FROM matches" db_cursor.execute(query) db.commit() db.close()
13,440
def write_seqs_to_tfrecords(record_name, name_to_seqs, label, frame_labels_string): """Write frames to a TFRecord file.""" writer = tf.io.TFRecordWriter(record_name) for name in name_to_seqs: if isinstance(label,int): lb=label else: lb=label[name] ex = get_examp...
13,441
def sn_random_numbers(shape, antithetic=True, moment_matching=True, fixed_seed=False): """Returns an ndarray object of shape with (pseudo)random numbers that are standard normally distributed. Parameters ---------- shape : tuple (o, n, m) Generation of array with shape...
13,442
def blue(N: int) -> np.ndarray: """ Blue noise. * N: Amount of samples. Power increases with 6 dB per octave. Power density increases with 3 dB per octave. https://github.com/python-acoustics """ x = white(N) X = rfft(x) / N S = np.sqrt(np.arange(X.size)) # Filter y = irf...
13,443
def _remove_attribute(note_dict: Dict, attribute: str) -> Dict: """ Create a copy of the note where a single attribute is removed """ d = dict(note_dict) d[attribute] = None return d
13,444
def get_config(path: str) -> config_schema: """Load the config from the path, validate and return the dcitionary Args: path (str): Path the config.yaml Returns: config_schema: The configuration dictionary """ config_path = Path(path) config = yaml.full_load(open(config_path...
13,445
def compare_chars(first, second): """ Returns the greater of the two characters :param first: :param second: :return: char """ return chr(max(ord(first), ord(second)))
13,446
def get_file_path(filename): """Find filename in the relative directory `../data/` . Args: filename (str): file we're looking for in the ./data/ directory. Returns: str: absolute path to file "filename" in ./data/ dir. """ root_dir = Path(__file__).parent.parent file_dir = os....
13,447
def parse_arguments() -> typing.Dict[typing.Any, typing.Any]: """Parses command line parameters.""" argument_parser = argparse.ArgumentParser( usage=f"Database transfer tool for Cloud Composer v.{SCRIPT_VERSION}.\n\n" + USAGE + "\n" ) argument_parser.add_argument("operation", typ...
13,448
def find_author(): """This returns 'The NeuroKit's development team'""" result = re.search( r'{}\s*=\s*[\'"]([^\'"]*)[\'"]'.format("__author__"), open("../neurokit2/__init__.py").read(), ) return str(result.group(1))
13,449
def tate_pairing(E, P, Q, m, k=2): """ Calculate Tate Pairing Args: E: The Elliptic Curve P: A point over E which has order m Q: A point over E which has order m m: The order of P, Q on E k: [Optional] The Embedding Degree of m on E """ from ecpy.utils.util import is_enable_native, _native...
13,450
def kl_loss(img,decoded_img,encoder_log_var,encoder_mu): """ LK loss for VAEs """ kl_loss = -0.5 * tf.reduce_sum( (1+encoder_log_var-tf.exp(encoder_log_var)-encoder_mu**2), axis=[1,2,3],name='klloss' ) return tf.reduce_mean(kl_loss,axis=0)
13,451
def steady(L, maxiter=10, tol=1e-6, itertol=1e-5, method='solve', use_umfpack=True, use_precond=False): """ Deprecated. See steadystate instead. """ message = "steady has been deprecated, use steadystate instead" warnings.warn(message, DeprecationWarning) return steadystate(L, [], max...
13,452
def and_intersection(map_list): """ Bitwise or a list of HealSparseMaps as an intersection. Only pixels that are valid in all the input maps will have valid values in the output. Only works on integer maps. Parameters ---------- map_list : `list` of `HealSparseMap` Input list of map...
13,453
def parse(url): """Parses a cache URL.""" config = {} url = urlparse.urlparse(url) # Handle python 2.6 broken url parsing path, query = url.path, url.query if '?' in path and query == '': path, query = path.split('?', 1) cache_args = dict([(key.upper(), ';'.join(val)) for key, val ...
13,454
def states_state(id=""): """ displays a HTML page with a list of cities by states """ states = storage.all(State).values() states = sorted(states, key=lambda k: k.name) found = 0 state = "" cities = [] for i in states: if id == i.id: state = i found = 1 ...
13,455
def make_tree_item(parent, text, icon, first_col_text=None, second_col_text=None): """ 构造树的子项 :param parent: 要构造子项的父节点元素 :param text: 构造的子节点信息 :param icon: 图标,该元素的展示图标对象 :param first_col_text: 第一列隐藏信息 :param second_col_text: 第二列隐藏信息 """ item = MyTreeWidgetItem(parent) item.setIco...
13,456
def deploy_results(run_once=False): """ Harvest data and deploy slides indefinitely """ while True: start = time() safe_execute('ap.update') safe_execute('data.update') safe_execute('deploy_bop') safe_execute('deploy_results') safe_execute('deploy_big_boar...
13,457
def get_boundary_condition(name): """ Return a boundary condition by name """ try: return _BOUNDARY_CONDITIONS[name] except KeyError: ocellaris_error( 'Boundary condition "%s" not found' % name, 'Available boundary conditions:\n' + '\n'.join( ...
13,458
def run(ts): """ Actually do the hard work of getting the USDM in geojson """ pgconn = get_dbconn('postgis') cursor = pgconn.cursor(cursor_factory=psycopg2.extras.DictCursor) # Look for polygons into the future as well as we now have Flood products # with a start time in the future cursor.execu...
13,459
def mtxslv_user_ratings(user_id, dataset): """ Receives user_id and dataset. Look for all occurences of user_id in dataset and returns such subset. If no user_id is found, return an empty numpy array. """ subset = [] # the same thing as I_i (set of item user_id has voted) for it in range(0,np.shape...
13,460
def random_rotation(min, max, prng=DEFAULT_PRNG): """ Construct a random rotation between -max and max. Args min: a scalar for the minimum absolute angle in radians max: a scalar for the maximum absolute angle in radians prng: the pseudo-random number generator to use. Returns ...
13,461
def test_save_pred_vs_label_7tuple_short_side_60_img(): """ When the image is too low in resolution (e.g. short side 60), we cannot use cv2's text rendering code. Instead, we will also save the upsampled version. """ short_side = 60 # pixels data_dir = f'{TEST_DATA_ROOT}/Camvid_test_data' img_fpath = f'{data_...
13,462
def test_save_and_load(tmp_path): """Verify that we can save the label image and load it correctly.""" array = np.zeros((2, 3, 4), dtype=np.int32) pixel_coordinates = { Axes.X: [2, 3, 4, 5], Axes.ZPLANE: [0, 1], } physical_coordinates = { Coordinates.X: [0, 0.5, 1.0, 1.5], ...
13,463
def precheck(files, dirs): """Checks whether the files/dirs user specified exists or are valid Arguments: files {list} -- File list dirs {list} -- Dir list Raises: AssertionError -- Raises if the given file doesn't exist or isn't a valid file AssertionError -- Raise...
13,464
def continued_fraction_iterator(x): """ Return continued fraction expansion of x as iterator. Examples ======== >>> from sympy.core import Rational, pi >>> from sympy.ntheory.continued_fraction import continued_fraction_iterator >>> list(continued_fraction_iterator(Rational(3, 8))) [0...
13,465
def country_code_from_name(country_names,l3=False): """2 letter ['BE'] or 3 letter codes ['BEL'] from country names Accepts string or list of strings e.g, 'Serbia' or ['Belgium','Slovakia'] Update 3/1/2022: also accepts non uppercase titles, e.g. ['united Kingdom', 'hungary'] Arguments: *co...
13,466
def steem_amount(value): """Returns a decimal amount, asserting units are STEEM""" return parse_amount(value, 'STEEM')
13,467
def get_edge_angle(fx,fy): """エッジ強度と勾配を計算する関数 """ # np.power : 行列のn乗を計算 # np.sqrt : 各要素の平方根を計算 edge = np.sqrt(np.power(fx.astype(np.float32),2)+np.power(fy.astype(np.float32),2)) edge = np.clip(edge, 0, 255) fx = np.maximum(fx, 1e-5) angle = np.arctan(fy/fx) return edge,angle
13,468
def write_site_pair_score_data_to_file(sorted_data_list, output_file_path, algorithm_used, max_iterations=None, num_threads=None): """Since site indices are starting from zero within python we add one to each of them when they are being written to output file. """ formater = '#' + '='*100 formater +...
13,469
def cs_2tuple_list(value): """ Parses a comma separated 2-tuple strings into a python list of tuples >>> cs_2tuple_list('') [] >>> cs_2tuple_list('(foobar, "test")') [('foobar', 'test')] >>> cs_2tuple_list('(foobar, "test"), ('"'barfoo', "' lalala) ') [('foobar', 'test'), ('bar...
13,470
def expectatedCapacityFactorFromDistribution( powerCurve, windspeedValues, windspeedCounts): """Computes the expected capacity factor of a wind turbine based on an explicitly-provided wind speed distribution """ windspeedValues = np.array(windspeedValues) windspeedCounts = np.array(windspeedCounts) ...
13,471
def check_icon_arg(src, default): """ Checks if icon arguments are valid: either a URL or an absolute path. :param src: Source of the icon :param default: default value of the icon :return: src (possibly pre-pended with "file://") """ if src != default: # check if URl if no...
13,472
def setup_2d_em_pic(): """ Returns a 2D electromagnetic PIC for testing """ params = { "length": [2 * np.pi, 2 * np.pi], "cells": [32, 32], "dimensions": 2, "nppc": 10, "single_stream": { # defaults for single stream instability "stream_v": ...
13,473
def young_laplace(Bo,nPoints,L): """ Bo = float - Bond number nPoints = int - number of integration points desired L = float - final arc length for range of integration """ #integration range and number of integration points s1=L N=nPoints #set initial values ...
13,474
def get_uncertain_point_coords_on_grid(uncertainty_map, num_points): """ Find `num_points` most uncertain points from `uncertainty_map` grid. Args: uncertainty_map (Tensor): A tensor of shape (N, 1, H, W) that contains uncertainty values for a set of points on a regular H x W grid. ...
13,475
def amex_credit_card(input_filename, month): """Format is just contents. date, description, amount""" test = _make_month_test(0, month) def transform(xs): return [xs[0], xs[1], '-' + xs[2] if xs[2][0] != '-' else xs[2][1:]] return _csv_transform(input_filename, test, trans...
13,476
def loadf(file_like, *args, attributes=None, **kwargs): """Read a data file and load it -- scaled -- in memory. This function differs from `read` in several ways: * The output data type should be a floating point type. * If an affine scaling (slope, intercept) is defined in the file, ...
13,477
def test_directive2_report_txt_md(checker): """The copy of .md file in fenced code block is the same as the file.""" check_first_block( markdown_path="doc/directive2_report_txt.md", contents_path="doc/directive2_report.txt", checker_function=checker, )
13,478
def download_if_not_exists(filename, url): """ Download a URL to a file if the file does not exist already. Returns ------- True if the file was downloaded, False if it already existed """ if not os.path.exists(filename): down_load_file(filename, url) return True ...
13,479
def _backsubstitution(A: MatrixData, B: List[float]) -> List[float]: """ Solve equation A . x = B for an upper triangular matrix A by backsubstitution. Args: A: row major matrix B: vector of floats """ num = len(A) x = [0.0] * num for i in range(num - 1, -1, -1): x[i] =...
13,480
def deiterize(func): """The inverse of iterize. Takes an "iterized" (a.k.a. "vectorized") function (i.e. a function that works on iterables), and That is, takes a func(X,...) function and returns a next(iter(func([X], ...))) function.""" return Pipe(wrap_first_arg_in_list(func), iter, next)
13,481
def ecg_data(rdb, day, patient, time): """ Returns DatFrame to plot ecg signal """ sql = """SELECT * FROM ECG where "Day"='{0}' and "Patient"='{1}' and "Date"::time='{2}' """.format(day, patient, time) try: df = pd.read_sql(sql, rdb) except: df = pd.DataFrame() return df
13,482
def evaluate(data_set_file_or_name, data_format=None, data_directory=None, map_features=None, feature_selection=None, example_filter=None, noisy_preprocessing_methods=None, preprocessing_methods=None, split_data_set=None, splitting_method=None, splitting_fraction=None...
13,483
def subscriptions(db_path, auth): """Download feedly goals for the authenticated user""" db = sqlite_utils.Database(db_path) try: data = json.load(open(auth)) token = data["developer_token"] except (KeyError, FileNotFoundError): utils.error( "Cannot find authenticati...
13,484
def deploy_new_company(company_id): """ Deploy new company contract :param company_id: Company off chain id for deploy :return: True in case of successful, false otherwise """ try: instance = Company.objects.get(pk=company_id) except Company.DoesNotExist: logger.error('Compan...
13,485
def MEMB(G,rb,cycle=0): """ It returns a dictionary with {box_id:subgraph_generated_by_the_nodes_in_this_box} The box_id is the center of the box. cycle: Ignore this parameter. Use the default cycle=0. """ adj = G.adj number_of_nodes = G.number_of_nodes() covered_nodes = set() center...
13,486
def test_stationconfiguration_not_equal_to_other_objects(): """ Verify that StationConfiguration objects are not considered equal to objects of other types. """ config = StationConfiguration(1) assert config is not None assert config != 1 assert config != object()
13,487
def set_app_path(required=False): """Find app directory and set value to environment variable.""" import os from pathlib import Path from getpass import getuser matched_path = None config_paths = (Path.home() / "hyperglass-agent", Path("/etc/hyperglass-agent/")) for path in config_paths: ...
13,488
def compfile(file_path, name="", list_files=None): """ Compare files to avoid that the same file is given multiple times or in different ways (e.g. different name but same content). """ __string(file_path, "%s path" % name, True) if list_files is None: list_files = [] elif n...
13,489
def shownames(namespace, **args): """helper method to generate a template keyword for a namespace""" ctx = args['ctx'] repo = ctx.repo() ns = repo.names[namespace] names = ns.names(repo, ctx.node()) return showlist(ns.templatename, names, plural=namespace, **args)
13,490
def only_half_radius( subsampled_radius: float, full_diameter: float, radius_constraint: float ): """ Check if radius is smaller than fraction of full radius. """ assert 0.0 <= radius_constraint <= 1.0 return subsampled_radius <= ((full_diameter / 2) * radius_constraint)
13,491
def test_brain_add_foci(renderer): """Test adding foci in _Brain instance.""" brain = _Brain(subject_id, hemi='lh', size=500, surf=surf, subjects_dir=subjects_dir) brain.add_foci([0], coords_as_verts=True, hemi='lh', color='blue') brain.close()
13,492
def complete_from_man(context: CommandContext): """ Completes an option name, based on the contents of the associated man page. """ if context.arg_index == 0 or not context.prefix.startswith("-"): return cmd = context.args[0].value def completions(): for desc, opts in _pars...
13,493
def sanitise_description(original: str) -> str: """ Remove newlines from ticket descriptions. :param original: the string to sanitise :return: the same string, with newlines as spaces """ return original.replace("\n", " ")
13,494
def dnsdomain_get_all(context): """Get a list of all dnsdomains in our database.""" return IMPL.dnsdomain_get_all(context)
13,495
def mockselect(r, w, x, timeout=0): # pylint: disable=W0613 """Simple mock for select() """ readable = [s for s in r if s.ready_for_read] return readable, w[:], []
13,496
def load_imgs(path): """Given a path load image(s). The input path can either be (i) a directory in which case all the JPG-images will be loaded into a dictionary, or (ii) an image file. Returns: imgs: A dictionary of of n-dim images. Keys are the original filenames """ ## Get filena...
13,497
async def cryptoQuotesSSEAsync(symbols=None, token="", version=""): """This returns the quote for a specified cryptocurrency. Quotes are available via REST and SSE Streaming. https://iexcloud.io/docs/api/#cryptocurrency-quote Args: symbols (str): Tickers to request token (str): Access toke...
13,498
def solve_5c2c9af4(x): """ Required Transformation: The input contains 3 cells with non-zero value. The non-zero valued cells are diagonally positioned with some amount of gap between each non-zero valued cells. The program should identify the colour and their position in the grid and form a squared box...
13,499