content
stringlengths
22
815k
id
int64
0
4.91M
def remove_reads_file(request): """ Clear out the reads file mapping after executing a test case. """ def clear_pararead(): processor.PARA_READ_FILES = {} request.addfinalizer(clear_pararead)
75,200
def foldingWrite(VO, ln1, ln2, cFolds): #{{{3 """Write "o" marks in Body headlines.""" cFolds = {}.fromkeys(cFolds) marker_re = VO.marker_re bnodes = VO.bnodes Body = VO.Body for ln in xrange(ln1,ln2+1): if not nodeHasChildren(VO, ln): continue bln = bnodes[ln-1] ...
75,201
def _chunk_slice( t: torch.Tensor, flat_start: int, flat_end: int, no_batch_dims: int, ): """ Equivalent to t.reshape((-1,) + t.shape[no_batch_dims:])[flat_start:flat_end] but without the need for the reshape call, which can be memory-intensive in certa...
75,202
def filter_class_boxes( src_images_dir: str, src_annotations_dir: str, dest_images_dir: str, dest_annotations_dir: str, class_label_counts: Dict, annotation_format: str, darknet_labels_path: str = None, ): """ TODO :param src_images_dir: :param sr...
75,203
def dimshuffle(arr, pattern): """ Based on theano's dimshuffle function. Permutes the axes of an array and inserts new singleton axes. e.g. if x has shape (2,3), then dimshuffle(x, [1,0,'x']) has shape (3,2,1) note that dimshuffle can not drop dimensions. inputs ------ pattern: list...
75,204
def utc_to_local(utc_dt, local_tz): """Accepts a datetime object in UTC time, and returns the same time, in the timezone that was also passed""" local_dt = utc_dt.replace(tzinfo=pytz.utc).astimezone(local_tz) return local_tz.normalize(local_dt)
75,205
def within_limits(cave: ArrayLike, coord: tuple[int, int]) -> bool: """Check whether a given coordinate is within the limits of the cave.""" return ( (0 <= coord[0]) & (coord[0] <= cave.shape[1] - 1) & (0 <= coord[1]) & (coord[1] <= cave.shape[0] - 1) )
75,206
def apps_get(section): """Get dictionary key-value pairs of app names and package names.""" """获取apps.ini里的包名和app名称""" acfg = NewSafeConfigParser() acfgpath = os.path.join(sys.path[0], 'cfg','apps.ini') if not os.path.isfile(acfgpath): raise IOError('%s NOT FOUND.' % acfgpath) with codec...
75,207
def get_project_settings_map(ctx): """ Get the map of all project settings that were found in the root folder Util function to load the <engine root>/<project name>/project.json file and cache it within the build context. :param ctx: :return: """ try: return ctx.project_settings_map...
75,208
def unpack_from(fmt, buf, offset=0): """ Unpack the buffer, containing packed C structure data, according to fmt starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt). See struct.__doc__ for more on format strings. """ try: o = _cache[fmt] except KeyError: o = _c...
75,209
def load_single_mat(mat_file_floder,n_clip=1,dataset="Avenue",vis=True): """ :param mat_file: mat file path :return: anomaly boundary [num ,2] """ filename = '%s/%d_label.mat' % (mat_file_floder, n_clip) data=sio.loadmat(filename) volLabel=data["volLabel"] n_bin = np.array([np.sum(vol...
75,210
def _ScatterAddNdimShape(unused_op): """Shape function for ScatterAddNdim Op.""" return []
75,211
def sanitize_name(original_name: str): """Sanitize name for output into compiler artifacts Parameters ---------- original_name : str Original name to sanitize """ return _backend.SanitizeName(original_name)
75,212
def plot_temporal_communities(matched_labels,nodes_of_interest=[],deltas=[],tiled_figsize='(36,16)',manual_colormap=None,label_cmap='Paired',frameon=True,xlabel="Time",ylabel="Node ID",label_fontsize=20,show_title=True,fontsize=28,colorbar=False,show_yticklabels=False,nodelabel_func=None,xtick_separation=5,snapshotlabe...
75,213
def parse(sql, category=None): """ Returns data structure for SQL statement. @param category expected statement category if any, like "table" @return ({..}, None), or (None, error) """ result, err = None, None try: result, err = Parser().parse(sql, category) except...
75,214
def store_to_flat_XML(model, vpath): """Store current LO document to vpath, as a ODF flat XML file""" return store_to__by_extn(model, vpath, '.fodt') or \ store_to__by_extn(model, vpath, '.fods') or False
75,215
def eDFA(F: np.ndarray) -> np.ndarray: """ In the reference indicated below a measure of nonstationarity was added by including a subsequent calculation of the extrema of the DFA. Denoted :math:`dF_q^2(s)` the difference of the extrema at each segment, i.e., .. math:: dF_q^2(s) = \max[F_q^...
75,216
def train(loader, model, epoch, criterion, optimizer, threshold, class_weights=None, use_cuda=None): """ :param loader: :param model: :param epoch: :param criterion: :param optimizer: :param threshold: :param class_weights: :param use_cuda: :return: """ model.train() ...
75,217
def run_parse_simap_to_csv(pathdict, s, logging): """For a dataframe containing a list of proteins, for each protein parses the SIMAP XML file to a csv file. Parameters ---------- pathdict : dict Dictionary of the key paths and files associated with that List number. s : dict Settin...
75,218
def notify_on_subscription(email_to): """Notify on subscription.""" email_send(email_to)
75,219
def main(DATASET='campbell', N_AGE_MIX=1): """Fit and save the the an N_AGE_MIX number of Gaussians mixture to the given DATASET. DATASET: str campbell, campbellG, ..., N_AGE_MIX: int Number of Gaussian mixtures to use. Should be >0. """ files = glob(f'resources/SN*_{DATASET}_ch...
75,220
def unload_cog(bot: commands.Bot, cog_name: str) -> None: """Unload a cog""" #assert cog_name in list(map(lambda filename: filename[:-5], listdir(".\cogs"))), "Invlaid cog name" bot.unload_extension(f"cogs.{cog_name}")
75,221
def test_launch_mesos_grace_period(marathon_service_name): """Tests 'taskKillGracePeriodSeconds' option using a Mesos container in a Marathon environment. Read more details about this test in `test_root_marathon.py::test_launch_mesos_root_marathon_grace_period` """ app_id = '/mesos-grace-period-app'...
75,222
def test(): """Test the DirWatcher Class""" watch_path = file_utils.relative_dir(__file__, '../../data') print('Watching Directory: %s' % watch_path) DirWatcher(watch_path, my_callback) # Create a file and then delete it temp_file = os.path.join(watch_path, 'test.tmp') open(temp_file, 'w')....
75,223
def memoize(timeout=None, fast=False): """ Cache a function based on its arguments. Args: timeout: Time the result stays valid in the cache. Returns: The functions result. """ assert (not fast or (fast and timeout is not None) ), "You cannot set fast cache without a ...
75,224
def print_err(msg, view = True, toexit = True): """ Handles stderr. """ if view: sys.stderr.write(msg + '\n') sys.stderr.flush() if toexit: sys.exit(1)
75,225
def get_appliance_bgp_neighbors( self, ne_id: str, ) -> dict: """Returns appliance BGP neighbor configuration .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - bgp - GET - /bgp/config/neighbor/{neId} :param ...
75,226
def test_tokenize_train_generate(): """Tokenization, training and generation main scripts can be run correctly""" run_tokenize_train_generate()
75,227
def pages_sub_menu(context, page, url='/'): """Get the root page of the given page and render a nested list of all root's children pages. Good for rendering a secondary menu. :param page: the page where to start the menu from. :param url: not used anymore. """ lang = context.get('lang', pag...
75,228
def JsonToMessage(message_type, message): """Convert the given JSON to a message of type message_type.""" return _ProtoJsonApiTools.Get().decode_message(message_type, message)
75,229
def generate_angular_spectrum_kernel(shape, pixel_size, wavelength, \ numerical_aperture=None, flag_band_limited=True, \ dtype=torch.float32, device=torch.device('cuda')): """ Function that generates angular spectrum propagation kernel W...
75,230
def getBarcodesFromSnap(fname: str) -> List[str]: """Read barcodes from a snap file Attributes: fname - a snap-format file Return: a dictionary contains all barcode in the snap file """ with h5py.File(fname, "r") as f: barcodes: List[str] = [item.decode() for item in f["BD/...
75,231
def slicing_where(condition, full_input, true_branch, false_branch): """Split 'full_input' between 'true_branch' and 'false_branch' on 'condition'. Args: condition: A boolean Tensor with shape [B_1, ..., B_N]. full_input: A Tensor or nested tuple of Tensors of any dtype, each with shape [B_1, ..., B_...
75,232
def feature_selection_example(m: int, k: int): """ Feature selection example. :param m: Number of all features. :param k: Number of features to select. """ if VERBOSE: print("Feature selection example") data, big_data, labels = generate_data_frame(m * m, m, k) y_true, y_predicted...
75,233
def radiation_pressure_length_noise( ff, Pin, finesse, mass=2.92, lam=1064e-9, ): """Radiation pressure length noise for a single optic in a cavity in units of m/rtHz. Inputs: ------- ff: float audio frequency in Hz Pin: float cavity input power in watts fines...
75,234
def run(env_file, config_file, debug): """Geospatial data hoarding system """ env.load(env_file) contrib.load() cfg = config.load(config_file) engine.run(cfg)
75,235
def snic_distance_mod(pos_i, pos_j, col_i, col_j, si, mi): """ Computes the SNIC pixel distance None of the components can be negative -> omitting the root does not change item order :param pos_i: position of pixel i :param pos_j: position of pixel j :param col_i: color of pixel i :param col...
75,236
def write_multi_sheet_from_DataFrames( data_frames, file_name, sheet_order=None, auto_size_cells=True ): """ Save multiple pandas.DataFrames to one file Parameters ---------- file_name : str, Path the file_name to save under. if no ending is provided, saved as .xlsx data_frames : di...
75,237
def get_gradient_clip_fn(hparams=None): """Creates a gradient clipping function based on the hyperparameters. See the :attr:`gradient_clip` field in :meth:`~texar.core.optimization.default_optimization_hparams` for all hyperparameters and default values. The gradient clipping function takes a list...
75,238
def test_attribute_parsing(suitesparse_mycielskian: SuiteSparseMatrix): """Test whether the attributes listed on the SuiteSparse Matrix Collection site are parsed correctly.""" assert suitesparse_mycielskian.matid == "2759" assert suitesparse_mycielskian.group == "Mycielski" assert suitesparse_mycie...
75,239
def com_google_fonts_check_gdef_mark_chars(ttFont): """Check mark characters are in GDEF mark glyph class""" from fontbakery.utils import pretty_print_list if "GDEF" in ttFont and ttFont["GDEF"].table.GlyphClassDef: cmap = ttFont.getBestCmap() mark_class_glyphnames = _get_mark_class_glyphnames(ttFont) ...
75,240
def find_delimiter_in(value): """Find a good delimiter to split the value by""" for d in [';', ':', ',']: if d in value: return d return ';'
75,241
def powerDetection(n, largest_exp=False): """ param positive integer n param boolean largest_exp return integer x, k s.t. n == x ** k (2 <= k if exist else x, k == n, 1) if largest_exp is true then return largest k """ from nzmath.prime import generator_eratosthenes as gene...
75,242
def get_parser_from_config(): """ Uses the 'parser' field in the config file to find and return the parser :return: """ parser_instance = config.read_config_option("parser") return parsers.parser_factory(parser_instance)
75,243
def writedb(database,table,operation,data): """Writing to the database""" connection = psycopg2.connect(user = "postgres",password = "password",host = "localhost",port = "5432",database = database) cursor = connection.cursor() if(operation == "insert"): if(table == "users"): query = "INSERT INTO users(us...
75,244
def test_bounds(app): """test GET /mosaicjson/bounds endpoint""" response = app.get("/mosaicjson/bounds", params={"url": MOSAICJSON_FILE}) assert response.status_code == 200 body = response.json() assert len(body["bounds"]) == 4 assert body["bounds"][0] < body["bounds"][2] assert body["bound...
75,245
def _SeqPaddingLength(inputs_nmap): """Returns the lengths of paddings at the beginning and end of the sequence. Args: inputs_nmap: A `.NestedMap` of tensors that may have 'padding' Every tensor's 0-th dim has the same size. Returns: padding length at the beginning, padding length at th...
75,246
def restart_global_span(): """ This fixture initialize the span to be empty. """ yield SpansContainer._span = None
75,247
def cfit(): """ a curve_fit (or optimize.minimize, or lmfit) apply_along_axis function might be good, for special cases when we don't care about using more computation time """ # # curve_fit, with exponential. (not easily vectorized) # from scipy.optimize import curve_fit # tmax = np.ama...
75,248
def get_ROT(ch,pe,te,ze,verbose=True): """ calculate ROT and depol ratio """ args = [ch, pe, ze, te, MISSING, verbose] ROT, depol_ratio, rc = VLIDORT_POLAR_.rot_calc(*args) return ROT,depol_ratio
75,249
def process_nthread_arg(args): """ Extract and set nthreads. """ if args.nthreads != blosc.ncores: blosc.set_nthreads(args.nthreads) print_verbose('using %d thread%s' % (args.nthreads, 's' if args.nthreads > 1 else ''))
75,250
def getFailsafeQueue(): """ Method returns failsafe queue """ global failsafeq return failsafeq
75,251
def wait_for_read(socks, timeout=None): """Waits for reading to be available from a list of sockets or optionally a single socket if passed in. Returns: A list of sockets that can be read from immediately. """ return _wait_for_io_events(socks, EVENT_READ, timeout)
75,252
def alpha_032(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: Series:index 为成分股代码,values为对应的因子值 公式: (scale(((sum(close, 7) / 7) - close)) + (20\* scale(correlation(vwap, delay(close, 5), 230)))) """ enddate = to_...
75,253
def make_custom_logger() -> Logger: """ Set up a new custom logger for using across modules of the bot :return: new logging.Logger() instance """ log_folder = './log' # __name__ needs to add name of corresponding module in a log message new_log = logging.getLogger(__name__) new_log.se...
75,254
def group_frame(frame_partitions, num_new_parts, key_columns): """Group frame to prepare for the join """ return [ local_shuffle(part, num_new_parts, key_columns) for part in frame_partitions ]
75,255
def post_message(data: str): """helper for debugging""" payload = json.loads(data, parse_float=Decimal) result = BETS.post_message(payload) return result
75,256
def read(**kwds): """ Read all data. """ title = kwds.get("title") text = kwds.get("text") tags = kwds.get("tags") offset = kwds.get("offset") limit = kwds.get("limit") query = Article.query if title: query = query.filter(Article.title.contains(title)) if text: ...
75,257
def reward_word2vec_coherence(conversations): """Allocates reward for coherence between user input and bot response in word2vec embedding space""" if 'word2vec' not in globals(): print('Loading word2vec dict') global word2vec, keys word2vec_path = os.path.join(ROOT_DIR, "datasets/Goo...
75,258
def evaluation_io(parser, ann_suffix, det_suffix, ann_dir=None, det_dir=None): """ Add evaluation input/output and formatting related arguments to an existing parser object. Parameters ---------- parser : argparse parser instance Existing argparse parser object. ann_suffix : str ...
75,259
def cublasZhpr(handle, uplo, n, alpha, x, incx, AP): """ Rank-1 operation on double precision Hermitian packed matrix. References ---------- `cublas<t>hpr <http://docs.nvidia.com/cuda/cublas/#cublas-lt-t-gt-hpr>`_ """ status = _libcublas.cublasZhpr_v2(handle, ...
75,260
def project_with_max_gross_value_added(): """Test fixture returns an investment project with the max gross value.""" gva_multiplier = GVAMultiplierFactory( multiplier=Decimal('9.999999'), financial_year=1980, ) with mock.patch( 'datahub.investment.project.gva_utils.GrossValueAdd...
75,261
def Adaptor3d_HSurfaceTool_VResolution(*args): """ :param S: :type S: Handle_Adaptor3d_HSurface & :param R3d: :type R3d: float :rtype: float """ return _Adaptor3d.Adaptor3d_HSurfaceTool_VResolution(*args)
75,262
def test_standalone_generic_with_noconfig_2(qtbot, tmpdir): """mimics: sequanix -s path_to_snakefile followed by selection of a working directory in the GUI + forceall + run """ # From the command line argument snakefile = f"{test_dir}/resources/test_generic_noconfig.smk" args = Namesp...
75,263
def test_hit_ovr(red_green): """Zoomed out read hits the overviews""" # GDAL doesn't log overview hits for local files , so we copy the # overviews of green.tif over the red overviews and expect to find # green pixels below. green_ovr = red_green.join("green.tif.ovr") shutil.move(green_ovr, red_...
75,264
def parse_args(): """Parse command-line arguments.""" p = argparse.ArgumentParser(description=__doc__) p.add_argument('-v', '--verbose', action='count', help='increase verbosity') p.add_argument('-f', '--featlist', default='feats.txt') p.add_argument('-s', '--samplelist', default=...
75,265
def enhance_contrast(im, cmap='pink', display_contrast=1): """Enhance contrast of the input image.""" im = ensure_positive(im) color_img = ind2cmap(im, cmap) color_img = color_img * 255 * display_contrast color_img[color_img > 255] = 255 color_img = np.uint8(color_img) return color_img
75,266
def test_get_hash_list(): """Test generating has for nested dict/list""" dict1 = {'1': 2, 3: 4, 'a': [1, -0., '3']} hash1 = get_hash(dict1)[0] dict2 = {'1': 2, 3: 4, 'a': [1, 0., '3']} hash2 = get_hash(dict2)[0] assert hash1 == hash2 dict1 = {'1': 2, 3: 4, 'a': [1, -0., '3', {'1': 0.}]} ...
75,267
def step_props(first, last, specs, night): """ Internal helper function used only in the desi_pipe script to build names of scripts and directories. """ specstr = "" if specs is not None: specstr = " --spectrographs {}".format(",".join([ "{}".format(x) for x in specs ])) rundir = io...
75,268
def run( src, imgpath = NGARO_IMG ): """ run the ngaro interpreter and investigate its state. see module docstring at top of file for dump format """ save_image( assemble( src ), imgpath )
75,269
def drift_stability_ind( missing_recs_drift, drift_tab, missing_recs_stability, stability_tab ): """ This function helps to produce the drift & stability indicator for further processing. Ideally a data with both drift & stability should produce a list of [1,1] Parameters ---------- missing_recs...
75,270
def sample_function(integer1: int, integer2: int): """ This function takes as input two integers (integer1 and integer2) and returns integer1 raised to the power of integer2 Parameters: ----------- integer1 (int) a number greater than or equal to zero intege...
75,271
def get_dfs(path): """ Grabs the different data splits and converts them into dataframes. Expects format from Code Search Net Challenge. """ dfs = [] for split in ["train", "valid", "test"]: files = sorted((path/split).glob("**/*.gz")) df = jsonl_list_to_dataframe(files, ...
75,272
def panorama_request(): """ Gets the details of anomalies from the database, using the URL arguments that are passed in by the :obj:`request.args` to build the MySQL select query string and queries the database, parse the results and creates an array of the anomalies that matched the query and creat...
75,273
def compute_regional_maskfile(meshFile, featureFile, outFile): """ Compute MPAS regional mask file using MPAS-Tool ``compute_mpas_region_masks``. Parameters ---------- meshFile : str Name of the mesh file. featureFile : str Name of the geojson feature file. outFile: st...
75,274
def _get_entropy(data): """ helper function that calculates the entropy of the input array """ H = 0 for value in data: if value > 0: H -= value * np.log2(value) return H
75,275
def make_doc(): """ Only used for sphinx documentation to add the prefix """ doc_app = Flask(__name__) doc_app.register_blueprint(bp, url_prefix='/tmp_dids') return doc_app
75,276
def tf_box_4c_to_box_3d(boxes_4c, ground_plane): """Vectorized box_4c to box_3d conversion Args: boxes_4c: Tensor of boxes_4c (N, 10) ground_plane: Tensor of ground plane coefficients (4,) Returns: Tensor of boxes_3d (N, 7) """ format_checker.check_box_4c_format(boxes_4c) ...
75,277
def timed(function): """ Log how long a function took :param function: Function to time :return: Result of the function """ @wraps(function) def wrapper(*args, **kwargs): start = timer() result = function(*args, **kwargs) print("{} took {} ms".format(function.__name__...
75,278
def tfmatrix2tf(sys): """Convert a matrix of transfer functions to a MIMO transfer function. Parameters ---------- sys: list of (list of control.xferfcn.TransferFunction) The transfer function matrix representing a MIMO system. sys[i][j] is the transfer function from ...
75,279
def active_genes_and_tf(active): """ From differentially expressed genes, return the genes and transcription factors. """ active = list(active) t_factors = list({gene.regulatory_product for gene in active if\ isinstance(gene.regulatory_product, TranscriptionFactor)}) return t_fac...
75,280
def get_cmap(name: str) -> np.ndarray: """Retrieve the given colormap and return RGB values as a uint8 NumPy array of shape (255, 3)""" name = name.lower() if name not in AVAILABLE_CMAPS: raise ValueError(f'Unknown colormap {name}, must be one of {AVAILABLE_CMAPS}') with _get_cmap_data(name) a...
75,281
def _addvFuncNumba( mNrmNext, mNrmGridNext, vNvrsNext, vNvrsPNext, MPCminNvrsNext, hNrmNext, CRRA, PermShkVals_temp, PermGroFac, DiscFacEff, ShkPrbs_temp, EndOfPrdvP, aNrmNow, BoroCnstNat, mNrmGrid, cFuncNow, mNrmMinNow, MPCmaxEff, MPCminNow, )...
75,282
def rename_get_variable(mapping): """ Args: mapping(dict): an old -> new mapping for variable basename. e.g. {'kernel': 'W'} Returns: A context where the variables are renamed. """ def custom_getter(getter, name, *args, **kwargs): splits = name.split('/') basename = s...
75,283
def list_bucket_inventory_configurations(Bucket=None, ContinuationToken=None): """ Returns a list of inventory configurations for the bucket. You can have up to 1,000 analytics configurations per bucket. This operation supports list pagination and does not return more than 100 configurations at a time. Alwa...
75,284
def with_color(color_code: str): """Coloring decorator Arguments: color_code {str} -- e.g.: '\033[91m' """ def wrapper(func): @functools.wraps(func) def inner(args): result = func(f'{color_code}{args}\033[0m') return result return inner return...
75,285
def compute_accuracy(idxR,idx,k): """ # =============================== #----- INPUT # idxR : real labels # idx : estimated labels # k : number of class #----- OUTPUT # ACC_glob : global accuracy # tab_acc : accuracy per class # =============================== """ ...
75,286
def tri_lexique_lemme(corpus,lex_5g,lex_4g,lex_3g,lex_2g,dict_lexique): """ dans un corpus, retrouve les mwes d'un lexique donné en passant par les lemmes entrée : - corpus .conllu (lu par read_file()) - lexiques de mwe ordonnées par tailles de mwe - dico {'mwe' : 'POS associée'} sortie : - dico {phrase : [lis...
75,287
def python_executable(): """Return the real path for the Python executable, if it exists. Return RuntimeError otherwise. Returns: (str): The real path of the current Python executable. """ if not sys.executable: raise RuntimeError( "Failed to retrieve the real path for th...
75,288
def log_n_episodes(log_name, n_episodes): """ Logs number of episodes """ with open_file(_get_log_folder(log_name) + '/n_episodes_log.pickle', 'wb') as f: pickle.dump(n_episodes, f)
75,289
def count_ones(value: bytes) -> int: """Count the number of 1's in the binary string.""" return bin(value).count("1")
75,290
def test_kernel_shap_with_a1a_sparse_nonzero_background(): """ Check with a sparse non zero background matrix. """ np.set_printoptions(threshold=100000) np.random.seed(0) X, y = shap.datasets.a1a() # pylint: disable=unbalanced-tuple-unpacking x_train, x_test, y_train, _ = sklearn.model_selectio...
75,291
def clean_data( data_path: str, save_path: str, text_column: str, weight_column: str ): """Clean the raw data. Only supporting Ahrefs data right now with Search Volume as the weight.""" log.info("Cleaning data.") cols = [text_column, weight_column] ds = pd.read_csv(data_path) da...
75,292
def is_lyrics_content_ok(title, text): """Compare lyrics text to expected lyrics for given title""" setexpected = set(LYRICS_TEXTS[lyrics.slugify(title)].split()) settext = set(text.split()) setinter = setexpected.intersection(settext) # consider lyrics ok if they share 50% or more with the referen...
75,293
def ratio_enum(anchor, ratios): """Enumerate a set of anchors for each aspect ratio wrt an anchor """ base_w, base_h, x_ctr, y_ctr = genwhctrs(anchor) size = base_w * base_h # 16 * 16 size_ratios = size / ratios # (2*16**2, 1*16**2, 0.5*16**2) a_w = np.round(np.sqrt(size_ratios)) a_h = np.round(a_w * ra...
75,294
def escape_value(value: OptionValueType) -> OptionValueType: """Escapes an option value based on its type.""" if isinstance(value, str): return shlex.quote(value) elif isinstance(value, Sequence): return [shlex.quote(v) for v in value] else: return value
75,295
def to_sky(cluster, sortstars=True,): """Calculate on-sky position, proper motion, and radial velocity of cluster - Also changes units to radec Parameters ---------- cluster : class StarCluster sortstars : bool sort star by radius after coordinate change (default: False...
75,296
def over(funcs): """Creates a function that invokes all functions in `funcs` with the arguments it receives and returns their results. Args: funcs (list): List of functions to be invoked. Returns: function: Returns the new pass-thru function. Example: >>> func = over([max...
75,297
def compute_method_overloads_context_by_type(interface, methods): """Computes |method.overload*| template values. Called separately for static and non-static (regular) methods, as these are overloaded separately. Modifies |method| in place for |method| in |methods|. Doesn't change the |methods| lis...
75,298
def get_logger(): """retrieves logger ("singleton"). Returns ------- logging.Logger logger for this module """ global module_name try: get_logger.logger except AttributeError: get_logger.logger = logging.getLogger(module_name) return get_logger.logger
75,299