content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def app_validate_batch(app_name_or_id, alias=None, input_params={}, always_retry=True, **kwargs): """ Invokes the /app-xxxx/validateBatch API method. For more info, see: https://documentation.dnanexus.com/developer/api/running-analyses/apps#api-method-app-xxxx-yyyy-validatebatch """ fully_qualified...
07ea5f856749e578d66f0138acf86d4a9f46ae7c
47,400
import collections def build_dataset(words, vocabulary_size=50000): """Returns: data: list of the same length as words, with each word replaced by a unique numeric ID. count: counters for the vocabulary_size most common words in 'words'. dictionary: maps word->ID r...
149f72d18a1304fe4414a95ed1491a7e6bd6c4de
47,401
import shutil import os def build_wheel(wheel_directory, config_settings, metadata_directory=None): """Invoke the mandatory build_wheel hook. If a wheel was already built in the prepare_metadata_for_build_wheel fallback, this will copy it rather than rebuilding the wheel. """ prebuilt_...
683633757d26f7b6d6c0015992d747995d360da0
47,402
import os def check_folder(folder): """ Test if folder exists and is absolute """ if os.path.isdir(folder): if os.path.isabs(folder): return True else: raise ValueError("The path to the folder must be absolute") else: raise OSError("Can't find the pa...
e2d606ab5bb68e104c8896da753d2e76d6ac7697
47,403
def used_voltage_params(): """ Returns a list of qdac voltage parameters for the used channels """ station = qc.Station.default qdac = station['qdac'] chans = sorted(used_channels()) voltages = [qdac.channels[ii - 1] for ii in chans] return voltages
4fde688214c98ca92a9f6b640e484ac713c5f7b8
47,404
def get_config_files(): """Get the config file for dataduct Note: The order of precedence is: 1. /etc/dataduct.cfg 2. ~/.dataduct/dataduct.cfg 3. DATADUCT_CONFIG_PATH environment variable, if it exists Returns: A list of file paths of dataduct config file locations,...
f043cbed27d3b49f50cb2c235931fdbdc49b5d27
47,405
from typing import Dict from datetime import datetime def make_epoch_log(seconds: float, metric_data: Dict[str, AverageValueMeter], epoch: int) -> str: """Create the log message basen on input parameters. Args: seconds (float): Time spent on train and valid epoch...
23e3931133944ce2ec588180f4898a3fef4f32d2
47,406
def _error_matches_criteria(error, criteria): """ Check if an error matches a set of criteria. Args: error: The error to check. criteria: A list of key value pairs to check for in the error. Returns: A boolean indicating if the provided error matches the...
8f52f7288fdefa496084b4faf689ed269360050a
47,407
import torch def eval(device, model, datas, criterion): """Eval the model""" losses = 0 model.eval() with torch.no_grad(): for data, target in datas: output = model(data.to(device)).flatten() losses += criterion(output.flatten(), target.to(device)).item() return los...
bf9d71640922e3c3a9d9bcd0fc83bc37f6c2da7d
47,408
def find_first_link(content: str) -> Link: """Metin içerisindeki ilk bağlantıyı bulur Arguments: content {str} -- Metin Returns: Link -- Bulunan bağlantı objesi Examles: >>> find_first_link('[name1](path1) [name2](path2)') Link(name='name1', path='path1') """ r...
7b6b437b8ff407b0244b9c5f067b1d524e9eed9c
47,409
import asyncio def create_rfxtrx_tcp_dsmr_reader(host, port, dsmr_version, telegram_callback, loop=None, keep_alive_interval=None): """Creates a DSMR asyncio protocol coroutine using a RFXtrx TCP connection.""" if not loop: loop = asy...
18254fb10a422a9c63255a64832ad457dbf43651
47,410
from lifelines import KaplanMeierFitter def find_mean_differential_survival(outcomes, interventions): """ Given outcomes and interventions, find the maximum restricted mean survival time """ treated_km = KaplanMeierFitter().fit(outcomes['uncensored time treated'].values, np.ones(len(outcomes)).astype...
9d0fca74ec4ee8a8fbdd59e7a08f67e1ccd49f9e
47,411
import os def get_engine(onnx_file_path, engine_file_path=""): """Attempts to load a serialized engine if available, otherwise builds a new TensorRT engine and saves it.""" def build_engine(): """Takes an ONNX file and creates a TensorRT engine to run inference with""" with trt.Builder(TRT_LOG...
d4648a6f2b5bbe6b1b39be06f36300884f64987e
47,412
def check_if_git_is_installed(): """Check if GIT is installed by calling 'git --version'.""" try: git_version = check_output(["git", "--version"]).decode('utf-8') if git_version.startswith("git version"): return True raise Exception('Git not installed') except: re...
6702e1302c361954f557fec468b2d89e78c19fb1
47,413
def try_replace_with_core_lstm(op): """ Inputs: op (Operation): op.op_type must be 'tf_lstm_block_cell' or `tf_lstm_block` Returns: True if op can be represented by mb.lstm op in SSA. False otherwise """ if op.op_type == "tf_lstm_block_cell": batch = op.x.shape[0] else: # tf_...
35a1071c71e4c2e4500799d96295c7b9eee672cb
47,414
import re def pad_punctuation_w_space(text: str) -> str: """Pad punctuation marks with space for separate tokenization.""" result = re.sub(r'([:;"*.,!?()/\=-])', r" \1 ", text) result = re.sub(r"[^a-zA-Z]", " ", result) result = re.sub(r"\s{2,}", " ", result) # code for removing single characters ...
8bdb82865d5e127e32d483f83246f4ad1b96b0be
47,415
from typing import Type def get_fastx_flag_extractor(fmt: FastxFormats) -> Type[ABCFlagExtractor]: """Retrieves appropriate flag extractor class.""" if FastxFormats.FASTA == fmt: return FastaFlagExtractor elif FastxFormats.FASTQ == fmt: return FastqFlagExtractor else: return AB...
009698de417857cd9254527e74f6e7ac12eabad8
47,416
def mu_post(xs, xs_train, ys_train, kernel, hparams): """ Posterior mean conditioned on xs. Note: a numerical jitter term of 1e-9 is added to avoid nans when inverting """ # TODO: use cholesky decomposition for inversion cov_train = kernels.cov_map(kernel, hparams, xs_train, xs_train) \ ...
847329a0a421bb77f749c9280e5137b4e5ccf836
47,417
def tensors2classlist(tensor, seq_lens): """ Converts a 3d tensor (max(seq_len), batch_size, output_dim=1) to a 2d class list (list[batch_size * list[seq_len]]) Arguments: tensor (torch.tensor) : 3d padded tensor of different sequence lengths of shape (max(seq_lens), batch_size, output_...
52de31050a32ce54b2733f4c4dd348044e3da259
47,418
def skippable_exons(exons): """ Determine which exon(s) can be skipped For each exon (except the first and second, which cannot be skipped), we want to find the minimum number of exons which together have a size that can be divided by 3. >>> list(skippable_exons([30])) [] >>> list(skippable...
f96ec0da6d72191d252cfe0ba5cdbeb21bc4388c
47,419
from typing import Callable from typing import Any def not_pf(predicate: Callable[[Any], bool]): """ Negates the predicate * **predicate**: predicate to be tested * **return**: a predicate that is the negation of the passed predicate >>> p = not_pf(true_p) >>> p(1) False >>> p = not_...
50d3993c4a83e5794a63134b65c732d1aa0ca1fa
47,420
def _ShouldSkip(commit_check, modified_lines, line, rule, test_class=False): """Returns whether an error on a given line should be skipped. Args: commit_check: Whether Checkstyle is being run on a specific commit. modified_lines: A list of lines that has been modified. line: The line that has a rule vi...
7f7cd6410f6c8357d1cd465b11445cf49bd500b5
47,421
def monte_carlo(cycles, precision, concunique, bottom_temp_est, dp, por, por_fit, seddepths, sedtimes, temp_d, bottom_temp, z, advection, leg, site, solute_db, ds, por_error, conc_fit, runtime_errors, line_fit): """ Monte Carlo simulation of flux_model output to f...
d7a435fd982f525b74ee05d377e9ee8a1f7eecda
47,422
from typing import List def getViewsAlias()->List[str]: """获取所有views.py的别名""" obj = getEnvXmlObj() return obj.get_childnode_lists('alias/file[name=views]')
3dc5a38e44f8eef707beb9361fcbca8b16476b52
47,423
from typing import Optional def get_logs(experiment_name: Optional[str] = None, save: bool = False) -> pd.DataFrame: """ Returns a table of experiment logs. Only works when ``log_experiment`` is True when initializing the ``setup`` function. Example ------- >>> from pycaret.datasets import ...
6f1b55864361098ac9d5c8bd843d5405d59765ac
47,424
def filter_genes(centroids): """returns genes that have std > 0""" return centroids.index[(centroids.std(axis=1) != 0).tolist()]
fcfbd18b6d657d6758feb324642c4118b80aecfd
47,425
def multivariate_t_logpdf(x, m, S, df=np.inf): """calculate log pdf for each value Parameters ---------- x : array_like, shape=(n_samples, n_features) m : array_like, shape=(n_features,) S : array_like, shape=(n_features, n_features) covariance matrix df : int or float de...
8a53d603b6e91fbc2e74e5f444d024b38af38d23
47,426
def get_iou_score(class_weights=1., smooth=SMOOTH, per_image=True, threshold=None): """Change default parameters of IoU/Jaccard score Args: class_weights: 1. or list of class weights, len(weights) = C smooth: value to avoid division by zero per_image: if ``True``, metric is calculated a...
03123ab38dad5ff1d8efaa44a0b4fd00cd3d47dd
47,427
from .ctwrapper import IVIVisaLibrary def _get_default_wrapper() -> str: """Return an available default VISA wrapper as a string ('ivi' or 'py'). Use IVI if the binary is found, else try to use pyvisa-py. 'ni' VISA wrapper is NOT used since version > 1.10.0 and will be removed in 1.12 Raises ...
95527140a935996fb2453835395f5a0199de9320
47,428
from typing import List from typing import Tuple def make_flfacts_mach_sweep(alt: float, machs: List[float], eas_limit: float=1000., alt_units: str='m', velocity_units: str='m/s', density_units: str='kg/m^3', ...
fd31ad68da7f5a3167457370e4e78ecda66235fd
47,429
def create_rnn_numpy_batches( array, batch_size=500, timesteps=TIMESTEPS, features=1, array_type="X" ): """Transform a numpy array, so that it can be fed into an RNN. RNNs require all batches to be the exact same length. This function removes excess elements from the array and so ensures all batches ar...
5ba4d1c23fb1e9e2040e075a02d78f872545ef05
47,430
def nll_loss(input, label, weight=None, ignore_index=-100, reduction='mean', name=None): """ This api returns negative log likelihood. See more detail in :ref:`api_nn_loss_NLLLoss` . Parameters: input (Tensor): Input tensor, the ...
2b22c63a2c3847bf259ff579782df0316ae7665d
47,431
def image_to_string( image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0, ): """ Returns the result of a Tesseract OCR run on the provided image to string """ args = [image, 'txt', lang, config, nice, timeout] return { Output.BYTES: lambda: run_...
d2ccb74f2cc9dceb3036e234af4cc541f82255bf
47,432
def organic_pdf_to_img(pdf_file, pdf_dim=None): """ Converts pdf file into image :param pdf_file: path to the pdf file :return: wand image object """ if not pdf_dim: pdf_dim = get_pdf_dim(pdf_file) page_width, page_height = pdf_dim print('read pdf {}'.format(pdf_file)) # img ...
3c355edc017d19662ed11647ba9f176272daa851
47,433
import os def correct_bias(in_file, out_file, image_type=sitk.sitkFloat64): """ Corrects the bias using ANTs N4BiasFieldCorrection. If this fails, will then attempt to correct bias using SimpleITK :param in_file: input file path :param out_file: output file path :return: file path to the bias corr...
b7ff6023688a4ebd0d6a966a474fba139c188954
47,434
import io import zipfile import os def download_contest(request, contest_id): """Download all submissions of the contest as zip file.""" contest = get_object_or_404(Contest, pk=contest_id) buffer = io.BytesIO() zip_archive = zipfile.ZipFile(buffer, mode='w') for theme in Theme.objects.filter(con...
c2ea1f00d53604268c1a2d9f9c60777ac9f5f919
47,435
from typing import Dict from typing import List def list_keys(bucket: str, prefix: str, suffix: str, delta_to: Dict[str, str] = None) -> List[str]: """ Lists all the keys belonging to a give key prefix in object storage :param bucket: The object storage bucket :param prefix: The key prefix :param ...
9db7dfa842d721a6285b87a27448e5cdbfe88fee
47,436
def info_panel_factory(db): """ Returns: The factory class used to generate info panels for testing. """ return InfoPanelFactory
e43aa05f28d1ebead281f6caa5faf46a1b2b8b27
47,437
import numpy def brier_score(survival_train, survival_test, estimate, times): """Estimate the time-dependent Brier score for right censored data. The time-dependent Brier score is the mean squared error at time point :math:`t`: .. math:: \\mathrm{BS}^c(t) = \\frac{1}{n} \\sum_{i=1}^n I(y_i \\le...
02c4568451b054838b203ed037677f015a9a10b6
47,438
from operator import mul def dot(A, B): """ Dot product between two arrays. A -> n_dim = 1 B -> n_dim = 2 """ arr = [] for i in range(len(B)): if isinstance(A, dict): val = sum([v * B[i][k] for k, v in A.items()]) else: val = sum(map(mul, A, B[i])) ...
9ea609f78e27eb3046507db3e366531090b26d6d
47,439
def get_invocation_command(toolset, tool, user_provided_command = [], additional_paths = [], path_last = False): """ Same as get_invocation_command_nodefault, except that if no tool is found, returns either the user-provided-command, if present, or the 'tool' parameter. """ ...
7fd76a04468de1764e234183f758640de00e6141
47,440
def decoding_layer(dec_input, encoder_state, target_sequence_length, max_target_sequence_length, rnn_size, num_layers, target_vocab_to_int, target_vocab_size, batch_size, keep_prob, decoding_embedding_size): """ Create decoding layer ...
2d832771359c7af2443629f488b03aa386e0cbe5
47,441
def create_interaction(principal_id, **kw): """ Create a new interaction for the given principal ID, make it the :func:`current interaction <zope.security.management.newInteraction>`, and return the :class:`Principal` object. """ principal = Principal(principal_id, **kw) participation = ...
ef7c5eb7045e3504bdd00cc9420c1a0402c2bcce
47,442
from datetime import datetime import uuid def python_type(type_description): """Return object representing the Python type. Args: type_description (str): Arc-style type description/code. Returns: Python object representing the type. """ instance = { "date": datetime.datet...
007367c9b7852c0d24c9bfddb8bf710afcd3f89f
47,443
def openedx_extract_transform_factory(get_config): """ Factory for generating OpenEdx extract and transform functions based on the configuration Args: get_config (callable): callable to get configuration for the openedx backend Returns: OpenEdxExtractTransform: the generated extract an...
73c1231fdcd6208f29af00d0a38aaafba59468e2
47,444
def _mint(challenge, bits): """Answer a 'generalized hashcash' challenge' Hashcash requires stamps of form 'ver:bits:date:res:ext:rand:counter' This internal function accepts a generalized prefix 'challenge', and returns only a suffix that produces the requested SHA leading zeros. NOTE: Number of ...
691631769f09413b8257a92c7831ab8953bbcb6b
47,445
def product(A, B, p_name): """ Computes the product automaton of two DFAs. Args ---- A, B : variables referencing a DFA. p_name : name of the product automaton. Returns ------- An DFA which is a product automaton of input DFA or A and B with name "p_name". Testable Code ...
3dd06d21f3659c2c17c270a729d9a1fa751902a5
47,446
def load_data(dataset_str): """ Loads input data from gcn/data directory ind.dataset_str.x => the feature vectors of the training instances as scipy.sparse.csr.csr_matrix object; ind.dataset_str.tx => the feature vectors of the test instances as scipy.sparse.csr.csr_matrix object; ind.dataset_str.al...
4611a50d4d7fde4659b766ce13d1363e35fcdc8c
47,447
from typing import OrderedDict def dense_video_sampling(videos, annotations=None, bckg_label=201, t_res=16, t_stride=16, drop_video=True): """Sample clips to extract C3D. Parameters ---------- videos : pandas.DataFrame Table with info about videos in dataset i.e. uniq...
7bb9d4ae4de3868e63b5ad2afc308c026f98dd28
47,448
import os def dem_quality_check(gdir): """Run a simple quality check on the rgitopo DEMs Parameters ---------- gdir : GlacierDirectory the glacier directory Returns ------- a dict of DEMSOURCE:frac pairs, where frac is the percentage of valid DEM grid points on the glacier. ...
4ed19aac77dc8c48663ccbb6636172b9e9ced945
47,449
def IsImage(a): """Return if the object is of Image type. Args: a: object whose type needs to be checked Returns: True if |a| is of Image type, False otherwise """ return isinstance(a, Image)
fe43e6ef7d25d0f7e470507540d10a1e935beacb
47,450
def upload_to_object_store( client, bucket, full_path_to_filename, object_name=None, content_type="binary/octet-stream", ): """Uploads the specified file to the object store Parameters: client: str, the boto3 client object bucket: str, target bucket location full_pat...
1652a69341664e8cfa5b5e32787808f9022004e8
47,451
def set_autocommit(autocommit, using=None): """Set the autocommit status of the connection.""" return get_connection(using).set_autocommit(autocommit)
792cb38ec8f31b3390489742dceef67bc52dc70f
47,452
import copy def copy_attributes_from_object(in_config, in_object, attr_list): """Clones a object and copies attributes from an object to it.""" config = copy.deepcopy(in_config) for item in attr_list: if hasattr(in_object, item): value = getattr(in_object, item) else: raise ValueError('attr_...
6751c947ef77c51909632a366d09fa35cc82f859
47,453
def get_frame_size(*args): """get_frame_size(func_t pfn) -> asize_t""" return _idaapi.get_frame_size(*args)
a5e08be1463e808107e84fce1f1c049b7815a424
47,454
from operator import index def z_decode(p): """ 调用方式, while p: v,p=z_decode(p) #v:值 p:bytes(每次z_decode计算偏移量) params = v 递归地取字符串p,每次取一些到v,剩下的更新为p,继续迭代 decode php param from string to python 根据php serialize p: str """ #print(p) if p[0]=='N': #NULL 0x4e-'N' return None,p[2:] elif p[0]=='b':...
1038dcf8a356e53574fb6eab6a9842bec78a5db6
47,455
def scaling_aligned_one_dim_cascade( time, x, y, z, track_azimuth, track_zenith, ): """Cascade with topology defined by a cascade at `SCALING_CASCADE_ENERGY`, and changing energy only modifies number of photons produced""" return aligned_one_dim_cascade( time=time, x=...
81d6e23a6c3bd7308a32c24311db47a063df7e81
47,456
def GetParsedDeps(deps_file): """Returns the full parsed DEPS file dictionary, and merged deps. Arguments: deps_file: Path to the .DEPS.git file. Returns: An (x,y) tuple. x is a dictionary containing the contents of the DEPS file, and y is a dictionary containing the result of merging unix and comm...
cfa7c4dd3134b131063e4cf288be730fd93b0c19
47,457
def _parse_option(line): """ Parses option line. Returns (name, value). Raises ValueError on invalid syntax or unknown option. """ match = _OPTION_REGEX.match(line) if not match: raise ValueError('Invalid syntax') for name, type_ in _OPTIONS: if name == match.group(1): ...
bf8f7e71c2a5d0ed61fdbecb8f8ac033e8771c43
47,458
def convert(from_unit, to_unit, *args, **kwargs): """ Convert the value from one unit to another :param from_unit: Source unit :param to_unit: Target unit :param args: Additional parameters (values) :param kwargs: Additional parameters (additional values like for conversion watts to ohms) :r...
233c16fda7943ae15093a8e455f6634bd75bbd4a
47,459
def hex_validator(length=0): """ Returns a function to be used as a model validator for a hex-encoded CharField. This is useful for secret keys of all kinds:: def key_validator(value): return hex_validator(20)(value) key = models.CharField(max_length=40, validators=[key_validat...
6ab272ab19f3b801ec612309ab41c845154a1eae
47,460
def bytes_feature(value): """Create a multi-valued bytes feature from a single value.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
f3b7ec25baca436fae7851fecbcd29787e6cc639
47,461
import os import torch def setup_model(args): """Setup model and optimizer.""" model = get_model(args) # if args.deepspeed: # print_rank_0("DeepSpeed is enabled.") # # model, _, _, _ = deepspeed.initialize( # model=model, # model_parameters=model.parameters(),...
664531b31fab4cc33be68145ee09e363b938a62f
47,462
def mkmatrix(m, n): """ Return a random invalid correlation matrix of order `m+n` with a positive definite top left block of order `m`. """ while True: A = randcorr(m) #B = randcorr(n) B = np.identity(n) Y = np.matrix(np.random.randn(m, n) / (m+n)**1.2) M0 = ...
a8d45f0b99adc08b43ca3a5f4c740edaab1e95de
47,463
def remove_last_range(some_list): """ Returns a given list with its last range removed. list -> list """ return some_list[:-1]
ea2063c901d3aaf67caad97f1760f6fb6afb31c1
47,464
import torch def lazy_bind(concrete_type, unbound_method): """ Returns a function that lazily binds `unbound_method` to a provided Module IValue, then invokes the method. We do this so that any Python shenanigans that will poison type sharing are impossible at compile time. """ def lazy_bi...
2d483782772bd1d4dc8b81dd621bc029d5876c38
47,465
import six def FigureToSummary(name, fig): """Create tf.Summary proto from matplotlib.figure.Figure. Args: name: Summary name. fig: A matplotlib figure object. Returns: A `tf.Summary` proto containing the figure rendered to an image. """ canvas = backend_agg.FigureCanvasAgg(fig) fig.canvas.d...
6182c127bd05003ff40a324240dfd5e8ffb3c679
47,466
from typing import Optional from typing import Dict from typing import Any from typing import cast def require_dict(value: Optional[Dict[Any, Any]], key_type: Any=None, value_type: Any=None, allow_none: bool=False) -> Any: """Make sure a value is a Dict[key_type, value_type]. Used when deali...
31611fa58de5a09b4bf9833cf22be1e151df00df
47,467
def reconstructTimestamp(currentTimestamp, lsbTimestamp): """ Reconstructs a timestamp from a partial timestamp, that only has the least significant bytes. :param currentTimestamp: Current time, obtained with time.time(). :param lsbTimestamp: Partial (least significant) timestamp, as a uint16. :retu...
df8836b3e849051fe62b8d2105fd46f9c1211bc1
47,468
def get_date_print_format(date_filter): """ Utility for returning the date format for a given date filter in human readable format @param date filter : the given date filter @return the date format for a given filter """ vals = { 'day': '[YYYY-MM-DD]', 'hour': '[YYYY-MM-DD : HH]' } return vals[date_filter]
a7b15f944905c44c6bff1ed65514fdb0133d150b
47,469
import os import json def loadTempTranscript(tempFileName): """ Load a temp transcript file by name """ # todo lot of copy/paste from above if os.path.exists(tempFileName): with open(tempFileName, 'rb') as tempFile: try: return [m for line in tempFile.readlines(...
4368d3dee4aa98ffe5e8a556daf12c325c7d8a7f
47,470
def pre_submission(*args, **kwargs): """ Perform a presubmit of a list of local files. This is the first stage for a batch submit of files. Variables: None Arguments: None Data Block (REQUIRED): { "1": # File ID {"sh...
fa68404d833145a3a44fe1a0dd1be09fd1b3cbb9
47,471
from typing import List def _historical_user_data_for_decisions(user: User, days: int) -> List: """ Return public data regarding the clicked Statements for a certain user :param days: The number of days ending with today for which the data shall be procured. :param user: The user for which the data s...
6536c474fa90a388cf2d599c5e147017dfe62427
47,472
import os import pickle def OptimiseGuestPositionAtWindow(xnDataset,hostData,hostCrystal,arGuestAtomFracPositions,lsGuestAtomChemSymbols,sHostGuestName,sRootOutputDir,bReloadWindowState): """Optimise guest molecule position at the window position using global optimiser. [xnDataset]: XML node, config 'dataset' node ...
65c8a3455389b4569dafaebd1d807cd86e3387d0
47,473
def collapse_locations(obj_list, keyname): """ Given a CustomQuerySet object, filter/aggregate it down so we just have one item per country or city. keyname is 'country' or 'city'. Also drop the 'privacy_country' or 'privacy_city' field. On input, we might have: country privacy_coun...
75586dc7fbd180ff6db031a0a706ea2221ced387
47,474
def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that letter in it. Updates the hand: uses up the letters in the given word and returns the new ha...
767aec56bec10900a3ccd67e2772355baf7886d0
47,475
def is_sciobj_valid_for_create(): """When RESOURCE_MAP_CREATE == 'reserve', objects that are created and that are also aggregated in one or more resource maps can only be created by a DataONE subject that has write or changePermission on the resource map.""" # TODO return True
2a57bb1295791d4f67652c3fb2477da2d9733462
47,476
def filter_by_indices(good_indices, vals): """ 从分段算法得到的下标集合中得到 对应的轨迹点集合 :param good_indices: 下标集合 :param vals: 原始点数据(未分段) 集合 :return: 分段后的点集合 """ vals_iter = iter(vals) good_indices_iter = iter(good_indices) out_vals = [] num_vals = 0 for i in good_indices_iter: if i != ...
c38dd76a90452cdbe96c92c8850752f56cc9882f
47,477
import logging def match_func(cor, exc, tolerance): """ Check if coordinate matches expected coordinate within a given tolerance. cor - coordinate exc - expected coordinate tolerance - error rate float coordinate elements will be checked based on this value list/tu...
b2ee7b41e2d56cee14c2078ef51f0900b1f4b617
47,478
def transform_tabular_data(xml_input): """ Converts table data (xml) from BambooHR into a dictionary with employee id as key and a list of dictionaries. Each field is a dict with the id as the key and inner text as the value e.g. <table> <row id="321" employeeId="123"> ...
025831e3192a9a7ce6b8130b76e4e1bf827a1744
47,479
import numpy as np import os def gen_index_noddi(in_bval, b0_index): """ This is a function to generate the index file for FSL eddy :param in_bval: :param b0_index: :return: """ out_file = os.path.abspath('index.txt') bvals = np.loadtxt(in_bval) vols = len(bvals) index_list = [...
84ac37def63d1714030d797930e3de958b8ff6a4
47,480
def create_workflow(name=None, namespace=None, bucket=None, **kwargs): # pylint: disable=too-many-statements """Create workflow returns an Argo workflow to test kfctl upgrades. Args: name: Name to give to the workflow. This can also be used to name things associated with the workflow. """ builder = B...
62e967e6e767fbdbfd3aec1151dc1213fe95212d
47,481
def create_annotation_model(table_name: str, annotation_columns: dict, with_crud_columns: bool=True): """ Create an declarative sqlalchemy annotation model. Parameters ---------- table_name : str Specified table_name. annotation_colum...
c33af504cc921537474574a8f30948b772498ce4
47,482
def speed_control(target, current, Kp=1.0): """ Proportional control for the speed. :param target: target speed (m/s) :param current: current speed (m/s) :param Kp: speed proportional gain :return: controller output (m/ss) """ return Kp * (target - current)
ce01369dc9445f65249a82cfb7882223ded38f36
47,483
def value_to_name(klass): """ Generate a function to convert an IntEnum value to its name. :param type klass: the class defining the IntEnum :returns: a function to convert a single number to a name :rtype: int -> str """ def the_func(num, terse_unknown=False): """ Convert ...
69e45e9e07388dacc27d5cc5b4d3822d6d716d3d
47,484
def np_ortho(shape, random_state): """ Builds a theano variable filled with orthonormal random values """ g = random_state.randn(*shape) o_g = linalg.svd(g)[0] return o_g.astype(theano.config.floatX)
f5762934c902cd6118aaec6a43f0856c0992702d
47,485
def force_func(biorbd_model: biorbd.Model, use_excitation: bool = False): """ Define the casadi function that compute the muscle force. Parameters ---------- biorbd_model : biorbd.Model Model of the system. use_excitation : bool If True, use the excitation of the muscles. R...
23866a48b0501d86612e85835ec177730d89d47c
47,486
import os import json def geolocalize_map(request): """ Args: request (flask.Request): HTTP request object JSON example: {"uri": "https://i.stack.imgur.com/WiDpa.jpg"} """ request_json = request.get_json() if request.args and 'uri' in request.args: uri = request.args.get('u...
9923f0b7e2e8b96ad401403b1953653b72cb0fb9
47,487
def ReLU(x, alpha): """ Wrapper for using a ReLU activation function TODO: Implement an option for choosing between relu, leaky relu and prelu. """ # return tf.nn.relu(x) # return leakyReLU(x, 0.001) # return parametricReLU(x, alpha) return tf.nn.elu(x) # return tf.tanh(x)
3b66a945a38b17225718168690328cae45aad17a
47,488
def _is_valid_case(obj): """Returns True if ``obj`` is a valid test case Criteria for being a valid test case: - Is a class and a subclass of :class:`WebDriverTestCase <webdriver_test_tools.testcase.webdriver.WebDriverTestCase>` - Is not :class:`WebDriverTestCase <webdriver...
09d7d07af46e24354f81256430b21e0cb6462fce
47,489
def cajeroExist(): """ Verifica la existencia de un registro en CajaCajero :return: """ try: movimientoid = CajaCajero.objects.latest('id_movimiento') except CajaCajero.DoesNotExist: movimientoid = None pass return movimientoid
74ff2c0a6c8fedeb8b1e2b819e07f397dc4bb775
47,490
def get_reaktor(): """Returns the reaktor instance from the app globals.""" if not hasattr(g, '_reaktor'): g._reaktor = Reaktor(**current_app.config['REAKTOR_CONFIG']) return g._reaktor
eeaefb7f7eb2498a0bac8d4cbc3e3399fe69fc78
47,491
import os def get_outpath(filename, outdir): """Get output filepath. :filename: name of music file :outdir: path of output directory :returns: path of converted music file """ outname = '{}.mp3'.format(os.path.splitext(filename)[0]) outpath = os.path.join(outdir, outname) return outp...
048c1ce65c21a0a561f928eb42882eaa60ee8b1a
47,492
def _Bezier3Seg(p1, p2, c1, c2, gs): """Return a 'B' segment, transforming coordinates. Args: p1: (float, float) - start point p2: (float, float) - end point c1: (float, float) - first control point c2: (float, float) - second control point gs: _SState - used to transform coordina...
f4d661bdcf0e9b294d4c428c54ed1c5d682a1ed7
47,493
import torch def gather( v: torch.Tensor, split_in: qp.utils.TaskDivision, comm: qp.MPI.Comm, dim: int, ) -> torch.Tensor: """Return the contents of v, changed from split based on split_in on communicator comm and dimension dim, to not-split i.e. fully available on all processes.""" # ...
8c54dc42e7fae4bc75ad151737f5b40fd0d96aed
47,494
def match_nans(x, y): """Performs pairwise matching of nans between ``x`` and ``y``. Args: x, y (ndarray or xarray object): Array-like objects to pairwise match nans over. Returns: x, y (ndarray or xarray object): If either ``x`` or ``y`` has missing data, adds nans in the same...
8bbeba78210d9344c4b8faa57454462e7b761ad8
47,495
def index(): """User's homepage after logging or signing in""" # Fetch posts of user and whoever the user follows. posts = Posts.query.all() return render_template("index.html", posts=posts)
74a4f72231fd3ccb8e3b03aa5f9ed37250c75e7c
47,496
def calculator_post(): """index_get""" return CalculatorController.post()
413b31a61c85139415c7a69fc7788e9121c57d99
47,497
import numpy import random def randomPairs(n_records, sample_size): """ Return random combinations of indices for a square matrix of size n records. For a discussion of how this works see http://stackoverflow.com/a/14839010/98080 """ n = int(n_records * (n_records - 1) / 2) if sample_siz...
378634b99a83c8f18c9c137737c32e6d12816ae7
47,498
def is_parsed_result_successful(parsed_result): """Returns True if a parsed result is successful""" return parsed_result['ResponseMetadata']['HTTPStatusCode'] < 300
717f8aa88b814405a5a008e9706338fd0f91a7ff
47,499