content
stringlengths
22
815k
id
int64
0
4.91M
def build_package(name: str) -> None: """Build it.""" package_dir = CURR_PATH.joinpath(name) assert package_dir.exists() assert package_dir.joinpath("PKGBUILD").exists() print(f"\tFound directory and PKGBUILD") subprocess.run(["makepkg", "-si", "--noconfirm"], cwd=package_dir) package_file...
5,348,300
def get_module_version(module_name: str) -> str: """Check module version. Raise exception when not found.""" version = None if module_name == "onnxrt": module_name = "onnxruntime" command = [ "python", "-c", f"import {module_name} as module; print(module.__version__)", ...
5,348,301
def _post(url, data): """RESTful API post (insert to database) Parameters ---------- url: str Address for the conftrak server data: dict Entries to be inserted to database """ r = requests.post(url, data=ujson.dumps(data)) r.raise_for_status() ...
5,348,302
def curry(arity_or_fn=None, ignore_kwargs=False, evaluator=None, *args, **kw): """ Creates a function that accepts one or more arguments of a function and either invokes func returning its result if at least arity number of arguments have been provided, or returns a function that accepts the remaini...
5,348,303
def add_to_sys_path(path): """Add a path to the system PATH.""" sys.path.insert(0, path)
5,348,304
def plot_means_std(means, std, list_samples, prev_w=10, nxt_w=10, figsize=(6, 4)): """ Plot mean and standard deviation from the accuracies of each state of each mouse. Parameters ---------- means : dict dictionary containing all the stage changes (e.g. '1-2', '2-3'.....
5,348,305
def filter(args): """ %prog filter fastafile 100 Filter the FASTA file to contain records with size >= or <= certain cutoff. """ p = OptionParser(filter.__doc__) p.add_option( "--less", default=False, action="store_true", help="filter the sizes < certain cutoff [...
5,348,306
def fin_forecast(ratio1, ratio2, sp_df): """used to forecast 3 years of financial forecast/projection """ print("print test line 6") forecast = MCSimulation( portfolio_data = sp_df, weights = [ratio1, ratio2], num_simulation = 500, num_trading_days = 252*3 ) print...
5,348,307
def load_uci_regression_dataset(name, split_seed, train_fraction=0.9, data_dir="uci_datasets"): """Load a UCI dataset from an npz file. Ported from https://github.com/wjmaddox/drbayes/blob/master/experiments/uci_exps/...
5,348,308
def test_check_inputs( student_names, project_names, supervisor_names, capacities, seed, clean ): """ Test that inputs to an instance of SA can be verified. """ _, _, _, game = make_game( student_names, project_names, supervisor_names, capacities, seed, clean ) with warnings.catch_warnings...
5,348,309
def implied_volatility(price, S, K, t, r, q, flag): """Calculate the Black-Scholes-Merton implied volatility. :param S: underlying asset price :type S: float :param K: strike price :type K: float :param sigma: annualized standard deviation, or volatility :type sigma: float :param t: tim...
5,348,310
def clean_hotel_maxpersons(string): """ """ if string is not None: r = int(re.findall('\d+', string)[0]) else: r = 0 return r
5,348,311
def merge_nodes(nodes): """ Merge nodes to deduplicate same-name nodes and add a "parents" attribute to each node, which is a list of Node objects. """ def add_parent(unique_node, parent): if getattr(unique_node, 'parents', None): if parent.name not in unique_node.parents: ...
5,348,312
def offset_add(OFF_par1, OFF_par2, OFF_par3, logpath=None, outdir=None, shellscript=None): """ | Add range and azimuth offset polynomial coefficients | Copyright 2008, Gamma Remote Sensing, v1.1 12-Feb-2008 clw Parameters ---------- OFF_par1: (input) ISP offset/interferogram parameter f...
5,348,313
def getVPCs(account="*", region="*", debug=False, save=False): """Retrieve all data on VPCs from an AWS account and optionally save data on each to a file""" print("Collecting VPC data...", file=sys.stderr) vpclist = {} for vpc in skew.scan("arn:aws:ec2:%s:%s:vpc/*" % (region, account)): if...
5,348,314
def get_cache_timeout(): """Returns timeout according to COOLOFF_TIME.""" cache_timeout = None cool_off = settings.AXES_COOLOFF_TIME if cool_off: if isinstance(cool_off, (int, float)): cache_timeout = timedelta(hours=cool_off).total_seconds() else: cache_timeout =...
5,348,315
def find_records(dataset, search_string): """Retrieve records filtered on search string. Parameters: dataset (list): dataset to be searched search_string (str): query string Returns: list: filtered list of records """ records = [] # empty list (accumulator pattern) for ...
5,348,316
def state_changed(name, address, value, group): """Capture the state change.""" _LOGGER.info("Device %s state %d changed to 0x%02x", address, group, value)
5,348,317
def mood(sentence, **kwargs): """ Returns IMPERATIVE (command), CONDITIONAL (possibility), SUBJUNCTIVE (wish) or INDICATIVE (fact). """ if isinstance(sentence, basestring): try: # A Sentence is expected but a string given. # Attempt to parse the string on-the-fly. ...
5,348,318
def create_script(*args, **kwargs): """Similar to create_file() but will set permission to 777""" mode = kwargs.pop("mode", 777) path = create_file(*args, **kwargs) path.chmod(mode) return path
5,348,319
def unique(x, dim=None): """Unique elements of x and indices of those unique elements https://github.com/pytorch/pytorch/issues/36748#issuecomment-619514810 e.g. unique(tensor([ [1, 2, 3], [1, 2, 4], [1, 2, 3], [1, 2, 5] ]), dim=0) => tensor([0, 1, 3]) ...
5,348,320
def _convert_arg(val, name, type, errmsg=None): """ Convert a Python value in CPO and check its value Args: val: Value to convert name: Argument name type: Expected type errmsg: Optional error message """ val = build_cpo_expr(val) assert val.is_kind_of(type), errmsg ...
5,348,321
def fit_gamma_dist(dataset, model, target_dir): """ - Fit gamma distribution for anomaly scores. - Save the parameters of the distribution. """ data_loader = torch.utils.data.DataLoader( dataset, batch_size=CONFIG["training"]["batch_size"], shuffle=False, drop_last=F...
5,348,322
def into_json(struct): """ Transforms a named tuple into a json object in a nice way. """ return json.dumps(_compile(struct), indent=2)
5,348,323
def atan(*args, **kwargs): """ atan(x) Return the arc tangent (measured in radians) of x. This function has been overriden from math.atan to work element-wise on iterables """ pass
5,348,324
def required_input(data_input, status_code): """check for required fields""" if not data_input in request.get_json(): abort(status_code, "field {0} is required".format(data_input))
5,348,325
def generate_integer_seeds(signature): """Generates a set of seeds. Each seed is supposed to be included as a file for AFL. **NOTE** that this method assumes that the signature only have int types. If a non int type is found, None is returned. Param: (str) signature: fuzzable method si...
5,348,326
def adjust_time(hour: int, minute: int) -> Tuple[int, int]: """Adjust time from sunset using offset in config. Returns: Tuple[int, int]: (hour, minute) of the adjusted time """ today = pendulum.today().at(hour, minute) today = today.add(hours=config.OFFSET_H, minutes=config.OFFSET_M) h...
5,348,327
def read_data_unet(path_images, path_masks, img_dims, norm, stretch, shuffle): """ load, crop and normalize image data option to select images form a folder :param image_path: path of the folder containing the images [string] :param mask_path: path of the folder containing the masks [string] :pa...
5,348,328
def indent(elem, level=0): """ Recursive function to indent an ElementTree._ElementInterface used for pretty printing. Code from U{http://www.effbot.org/zone/element-lib.htm}. To use run indent on elem and then output in the normal way. @param elem: element to be indented. will be modifie...
5,348,329
def flatten(l): """Flatten 2 list """ return reduce(lambda x, y: list(x) + list(y), l, [])
5,348,330
def _rep_t_s(byte4): """ 合成置换T', 由非线性变换和线性变换L'复合而成 """ # 非线性变换 b_array = _non_linear_map(_byte_unpack(byte4)) # 线性变换L' return _linear_map_s(_byte_pack(b_array))
5,348,331
def get_mapping(): """ Returns a dictionary with the mapping of Spacy dependency labels to a numeric value, spacy dependency annotations can be found here https://spacy.io/api/annotation :return: dictionary """ keys = ['acl', 'acomp', 'advcl', 'advmod', 'agent', 'amod', 'appos', 'attr', 'aux', '...
5,348,332
def variable_summaries(var, name): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.name_scope(name): mean = tf.reduce_mean(input_tensor=var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean( ...
5,348,333
def create_root_folder(path: str, name: str) -> int: """ Creates a root folder if folder not in database. Fetches id if folder already in database. Handles paths with both slash and backslash as separator. :param path: The path to the folder in the users file system. :param name: The name of th...
5,348,334
def get_document_term_matrix(all_documents): """ Counts word occurrences by document. Then transform it into a document-term matrix (dtm). Returns a Tf-idf matrix, first count word occurrences by document. This is transformed into a document-term matrix (dtm). This is also just called a term freque...
5,348,335
def f_raw2(coordinate, packedParams): """ The raw function call, performs no checks on valid parameters.. :return: """ gaussParams = packedParams['pack'] res = 0 for p in gaussParams: res += gaussian_2d.f_noravel(coordinate, *p) return res
5,348,336
def example_serving_input_fn(): """Build the serving inputs.""" example_bytestring = tf.placeholder( shape=[None], dtype=tf.string, ) features = tf.parse_example( example_bytestring, tf.feature_column.make_parse_example_spec(INPUT_COLUMNS)) return tf.estimator.export.ServingI...
5,348,337
def emptyentries(targets, headers, dirnames): """ Write genes with no candidate at all to log file """ t = dirnames[1].split('TempFolder')[1] nocandidate = [] for i in range(len(targets)): if not targets[i]: nocandidate.append(i) if len(nocandidate): with open(os.path.joi...
5,348,338
def add_file_uri_to_path(filepath): """Add the file uri preix: "file://" to the beginning of a path""" if not filepath: return False, "The filepath must be specified" if filepath.lower().startswith(FILE_URI_PREFIX): # # return True, filepath updated_fpath = '%s%s' % (FI...
5,348,339
def test_dsm_compute_arg( compute_dsm_default_args, ): # pylint: disable=redefined-outer-name """ Cars compute_dsm arguments test with default and degraded cases """ parser = cars_parser() with tempfile.TemporaryDirectory(dir=temporary_dir()) as directory: compute_dsm_default_args.outd...
5,348,340
def np_slope_diff_spacing(z, xspace, yspace): """ https://github.com/UP-RS-ESP/TopoMetricUncertainty/blob/master/uncertainty.py Provides slope in degrees. """ dy, dx = np.gradient(z, xspace, yspace) return np.arctan(np.sqrt(dx*dx+dy*dy))*180/np.pi
5,348,341
def build_dist( cfg, feat_1, feat_2=None, dist_m=None, verbose=False, ): """Computes distance. Args: input1 (torch.Tensor): 2-D feature matrix. input2 (torch.Tensor): 2-D feature matrix. (optional) Returns: numpy.ndarray: distance matrix. """ if dist_m is None: ...
5,348,342
def write_features( netcdf_file_name, feature_matrix, target_values, num_classes, append_to_file=False): """Writes features (activations of intermediate layer) to NetCDF file. :param netcdf_file_name: Path to output file. :param feature_matrix: numpy array of features. Must have >= 2 dimen...
5,348,343
def call_inverse_cic_single_omp(img_in,yc1,yc2,yi1,yi2,dsi): """ Input: img_in: Magnification Map yc1, yc2: Lens position yi1, yi2: Source position dsi: pixel size on grid """ ny1,ny2 = np.shape(img_in) img_in = np.array(img_in,dtype=ct.c_float) yi1 = np.array(yi1...
5,348,344
def filter_spans(spans): """Filter a sequence of spans and remove duplicates or overlaps. Useful for creating named entities (where one token can only be part of one entity) or when merging spans with `Retokenizer.merge`. When spans overlap, the (first) longest span is preferred over shorter spans. ...
5,348,345
def get_col_names_for_tick(tick='BCHARTS/BITSTAMPUSD'): """ Return the columns available for the tick. Startdate is late by default to avoid getting much data """ return quandl.get(tick, start_date=None).columns
5,348,346
def check_if_needs_inversion(tomodir): """check of we need to run CRTomo in a given tomodir Parameters ---------- tomodir : str Tomodir to check Returns ------- needs_inversion : bool True if not finished yet """ required_files = ( 'grid' + os.sep + 'elem.da...
5,348,347
def check_result(request): """ 通过任务id查询任务结果 :param request: :param task_id: :return: """ task_id = request.data.get('task_id') if task_id is None: return Response({'message': '缺少task_id'}, status=status.HTTP_400_BAD_REQUEST) res = AsyncResult(task_id) if res.ready(): # 检...
5,348,348
def get_debug_device(): """Get the profile to debug from the RIVALCFG_DEVICE environment variable, if any. This device should be selected as the one where the commands will be written, regardless of the selected profile. This is usefull to debug a mouse that have the same command set than an other ...
5,348,349
def make(): """ Runs data processing scripts to turn raw data from (../raw) into cleaned data ready to be analyzed (saved in ../processed). """ logger.info("Nothing implemented yet")
5,348,350
def export_experiment_configuration_to_yml(logger, log_dir, filename, config_interface_obj, user_confirm): """ Dumps the configuration to ``yaml`` file. :param logger: logger object :param log_dir: Directory used to host log files (such as the collected statistics). :type log_dir: str :param ...
5,348,351
def _remove_node(node: int, meta: IntArray, orig_dest: IntArray) -> Tuple[int, int]: """ Parameters ---------- node : int ID of the node to remove meta : ndarray Array with rows containing node, count, and address where address is used to find the first occurrence in orig_des...
5,348,352
def pg(): """ Configures environment variables for running commands on pg, e.g.: fab pg --user=myuser --password=mytopsecretpassword refresh_pg """ env.hosts = ['pg-001.ebi.ac.uk'] env.run = run env.cd = cd
5,348,353
def tfs(parser, xml_parent, data): """yaml: tfs Specifies the Team Foundation Server repository for this job. Requires the Jenkins `Team Foundation Server Plugin. <https://wiki.jenkins-ci.org/display/JENKINS/ Team+Foundation+Server+Plugin>`_ **NOTE**: TFS Password must be entered manually on th...
5,348,354
def forward_many_to_many_without_pr(request): """ Return all the stores with associated books, without using prefetch_related. 100ms overall 8ms on queries 11 queries 1 query to fetch all stores: SELECT "bookstore_store"."id", "bookstore_store"."name" FROM "bookstore_store"...
5,348,355
def generate_combinations (n, rlist): """ from n choose r elements """ combs = [list(itertools.combinations(n, r)) for r in rlist] combs = [item for sublist in combs for item in sublist] return combs
5,348,356
def test_q_control_true(): """ Test that when the Q control is enabled the Q limits are respected """ options = PowerFlowOptions(SolverType.NR, control_q=ReactivePowerControlMode.Direct, retry_with_other_methods=False) fname = os.path.jo...
5,348,357
def conv_datetime(dt, version=2): """Converts dt to string like version 1 = 2014:12:15-00:00:00 version 2 = 2014/12/15 00:00:00 version 3 = 2014/12/15 00:00:00 """ try: if isinstance(dt, six.string_types): if _HAS_PANDAS: dt = pd.to_datetime(dt) fmt =...
5,348,358
def get_description_value(name_of_file): """ :param name_of_file: Source file for function. :return: Description value for particular CVE. """ line = name_of_file.readline() while 'value" :' not in line: line = name_of_file.readline() tmp_list = line.split(':') if len(tmp_list) =...
5,348,359
def octaves(p, fs, density=False, frequencies=NOMINAL_OCTAVE_CENTER_FREQUENCIES, ref=REFERENCE_PRESSURE): """Calculate level per 1/1-octave in frequency domain using the FFT. :param x: Instantaneous signal :math:`x(t)`. :param fs: Sample frequency. :param density: Power density ...
5,348,360
def action_fs_cluster_resize( compute_client, network_client, blob_client, config, storage_cluster_id): # type: (azure.mgmt.compute.ComputeManagementClient, # azure.mgmt.network.NetworkManagementClient, # azure.storage.blob.BlockBlobService, dict, str) -> None """Action: Fs...
5,348,361
def test_online_command(state, config_file: str, url: str) -> None: """Eze run scan remotely on a server""" api_key = os.environ.get("EZE_APIKEY", "") api_url = os.environ.get("EZE_REMOTE_SCAN_ENDPOINT", "") data = {"remote-url": url} try: req = urllib.request.Request( api_url, ...
5,348,362
def test_get_prophet_holidays(): """Tests get_prophet_holidays""" year_list = list(range(2014, 2030+2)) holiday_lookup_countries = ["UnitedStates", "UnitedKingdom", "India", "France", "China"] # Default holidays from get_prophet_holidays actual_holidays = ProphetTemplate().get_prophet_holidays( ...
5,348,363
def build_embed(**kwargs): """Creates a discord embed object.""" return create_embed(**kwargs)
5,348,364
def main(): """ Main """ args = parse_arguments() create_inputs_file(args)
5,348,365
def VAMA(data, period=8, column='close'): """ Volume Adjusted Moving Average :param pd.DataFrame data: pandas DataFrame with open, high, low, close data :param int period: period used for indicator calculation :param str column: column used for indicator calculation (default = "close") :param p...
5,348,366
def link_syscall(oldpath, newpath): """ http://linux.die.net/man/2/link """ # lock to prevent things from changing while we look this up... filesystemmetadatalock.acquire(True) # ... but always release it... try: trueoldpath = _get_absolute_path(oldpath) # is the old path there? if trueo...
5,348,367
def doc_vector(text, stop_words, model): """ 计算文档向量,句子向量求平均 :param text: 需要计算的文档 :param stop_words: 停用词表 :param model: 词向量模型 :return: 文档向量 """ sen_list = get_sentences(text) sen_list = [x[1] for x in sen_list] vector = np.zeros(100, ) length = len(sen_list) for sentence i...
5,348,368
def get_ether_pkt(src, dst, ethertype=ether.ETH_TYPE_IP): """Creates a Ether packet""" return ethernet.ethernet(src=src, dst=dst, ethertype=ethertype)
5,348,369
def _resolve_dependency(param: inspect.Parameter, class_obj: Instantiable , app: App): """ Try to get the instance of a parameter from a bound custom resolver for the class which needs it. if not able to do the above, try to get a registered binding for the parameter's Annotation. if no bin...
5,348,370
def parse_compute_hosts(compute_hosts): """ Transform a coma-separated list of host names into a list. :param compute_hosts: A coma-separated list of host names. :type compute_hosts: str :return: A list of host names. :rtype: list(str) """ return filter(None, re.split('[^a-zA-Z0-9\-_]+',...
5,348,371
def get_bbox(mask_frame): """ get rectangular bounding box for irregular roi Args: mask_frame (np.ndarray): the frame containing the mask Returns: bbox (np.ndarray): numpy array containing the indexes of the bounding box """ bbox = np.zeros(4) bbox[0] = np.min(np.where(np.m...
5,348,372
def view_create_log_entry_verbose(request): """Create a new BehavioralLogEntry. Return the JSON version of the entry""" return view_create_log_entry(request, is_verbose=True)
5,348,373
def read_dictionary(): """ This function reads file "dictionary.txt" stored in FILE and appends words in each line into a Python list """ global dictionary with open(FILE, 'r') as f: for line in f: if len(line.strip()) >= 4: dictionary[line.strip()] = [line.strip()]
5,348,374
def webhook_server_factory(free_port): """For making a server that can accept Onshape webhooks.""" servers = [] threads = [] def _webhook_server_factory(): """ Create a factory to handle webhook notifications coming in. :param on_recieved: function callback to handle the json response ...
5,348,375
def view(args): """Visualize runs in a local web application. Features include: \b - View and filter runs - Compare runs - Browse run files - View run images and other media - View run output Guild View does not currently support starting or modifying runs. For the...
5,348,376
def toggle(): """ Toggle the state of the switch """ is_on = get() if is_on: xbmc.log("WeMo Light: Turn OFF") off() else: xbmc.log("WeMo Light: Turn ON") on()
5,348,377
def test_set_script_coordinates(expected_output, input_atoms_section, positions): """Test that the coordinates are set correctly in the CPMD script.""" # Create temporary directory. # TODO: USE ACTUAL TEMPORARY DIRECTORY. tmp_dir_path = get_tmp_dir() # Create input script. script_file_path = os...
5,348,378
def generator_validator(file_path: Text): """ Validates that the generator module exists and has all the required methods """ if not exists(file_path): raise ArgumentTypeError(f"File {file_path} could not be found") try: module = import_file("generator", file_path) except S...
5,348,379
def main(**kwargs): """ main function """ # logger = logging.getLogger(sys._getframe().f_code.co_name) source = Path(kwargs['source']) destination = Path(kwargs['destination']) with open(source, 'r', encoding='utf-8') as f: j = json.load(f) del f items = [] for orig_id, o...
5,348,380
def from_bytes( data: bytes, idx_list: Optional[List[int]] = None, compression: Optional[str] = "gz" ) -> List[ProgramGraph]: """Deserialize Program Graphs from a byte array. :param data: The serialized Program Graphs. :param idx_list: A zero-based list of graph indices to return. If not provi...
5,348,381
def runTimer(t): """t is timer time in milliseconds""" blinkrow = 500 #in milliseconds eachrow = t // 5 for i in range(5): for _ in range(eachrow//(2*blinkrow)): display.show(Image(hourglassImages[i+1])) sleep(blinkrow) display.show(Image(hourglassImages[i]))...
5,348,382
def ascMoveFormula(note_distance, finger_distance, n1, n2, f1, f2): """This is for situations where direction of notes and fingers are opposite, because either way, you want to add the distance between the fingers. """ # The math.ceil part is so it really hits a value in our moveHash. # This could ...
5,348,383
def create_stomp_connection(garden: Garden) -> Connection: """Create a stomp connection wrapper for a garden Constructs a stomp connection wrapper from the garden's stomp connection parameters. Will ignore subscribe_destination as the router shouldn't be subscribing to anything. Args: gar...
5,348,384
def W_n(S, n_vals, L_vals, J_vals): """ Field-free energy. Includes extra correction terms. -- atomic units -- """ neff = n_vals - get_qd(S, n_vals, L_vals, J_vals) energy = np.array([]) for i, n in enumerate(n_vals): en = -0.5 * (neff[i]**-2.0 - 3.0 * alpha**2.0 / (4.0 * n**4.0) + ...
5,348,385
def page_output(output_string): """Pipe string to a pager. If PAGER is an environment then use that as pager, otherwise use `less`. Args: output_string (str): String to put output. """ output_string = unidecode(output_string.decode('utf-8')) if os.environ.get('__TAUCMDR_DISABLE_PA...
5,348,386
def obter_movimento_manual(tab, peca): # tabuleiro x peca -> tuplo de posicoes """ Recebe uma peca e um tabuleiro e um movimento/posicao introduzidos manualmente, dependendo na fase em que esta o programa. Na fase de colocacao, recebe uma string com uma posicao. Na fase de movimentacao, recebe uma ...
5,348,387
def parse_header(req_header, taint_value): """ 从header头中解析污点的位置 """ import base64 header_raw = base64.b64decode(req_header).decode('utf-8').split('\n') for header in header_raw: _header_list = header.split(':') _header_name = _header_list[0] _header_value = ':'.join(_head...
5,348,388
def filter_and_sort_files( fnames: Union[str, List[str]], return_matches: bool = False ): """Find all timestamped data files and sort them by their timestamps""" if isinstance(fnames, (Path, str)): fnames = os.listdir(fnames) # use the timestamps from all valid timestamped # filenam...
5,348,389
def fake_batch(obs_space, action_space, batch_size=1): """Create a fake SampleBatch compatible with Policy.learn_on_batch.""" samples = { SampleBatch.CUR_OBS: fake_space_samples(obs_space, batch_size), SampleBatch.ACTIONS: fake_space_samples(action_space, batch_size), SampleBatch.REWARDS...
5,348,390
def multi_variant_endpoint(sagemaker_session): """ Sets up the multi variant endpoint before the integration tests run. Cleans up the multi variant endpoint after the integration tests run. """ multi_variant_endpoint.endpoint_name = unique_name_from_base( "integ-test-multi-variant-endpoint" ...
5,348,391
def compute_macro_f1(answer_stats, prefix=''): """Computes F1, precision, recall for a list of answer scores. This computes the *language-wise macro F1*. For minimal answers, we also compute a partial match score that uses F1, which would be included in this computation via `answer_stats`. Args: answer_...
5,348,392
def piecewise_linear(x, rng, NUM_PEOPLE): """ This function samples the piecewise linear viral_load model Args: x ([type]): [description] rng (np.random.RandomState): random number generator NUM_PEOPLE (int): [description] Returns: np.array: [description] """ vi...
5,348,393
def mol_sim_matrix(fingerprints1, fingerprints2, method='cosine', filename=None, max_size=1000, print_progress=True): """Create Matrix of all molecular similarities (based on molecular fingerprints). If filename is n...
5,348,394
def test_load(elf, expected): """Test ELF files that load values from memory into a register. """ elf_filename = os.path.join(elf_dir, elf) revelation = Revelation() with open(elf_filename, 'rb') as elf: revelation.init_state(elf, elf_filename, False, is_test=True) revelation.states[...
5,348,395
def energies_over_delta(syst, p, k_x): """Same as energy_operator(), but returns the square-root of the eigenvalues""" operator = energy_operator(syst, p, k_x) return np.sqrt(np.linalg.eigvalsh(operator))
5,348,396
def subscribe_user_to_basket(instance_id, newsletters=[]): """Subscribe a user to Basket. This task subscribes a user to Basket, if not already subscribed and then updates his data on the Phonebook DataExtension. The task retries on failure at most BASKET_TASK_MAX_RETRIES times and if it finally do...
5,348,397
def browserSelectionRecall(): """try to re-highlight the previously selected item.""" #14.01.13-15.39: implimented selection recall function to prevent losing selected scan while changing file display options for i in range(uist.listBrowser.count()): if uist.listBrowser.item(i).text()==browserSelected: ...
5,348,398
def count_matching(d1: Die, d2: Die, num_rolls: int) -> int: """ Roll the given dice a number of times and count when they match. Args: d1 (Die): One Die object (must not be None) d2 (Die): Another Die object (must not be None) num_rolls (int): Positive number of rolls to toss. ...
5,348,399