content
stringlengths
22
815k
id
int64
0
4.91M
def expand_list(inlist, keyname, expandables, defaults={}, fmt=[]): """[summary] Output is a a dictionary of an element that has an array of elements each has expandables set to the inlist values and for any optional value, revert to the default list. Example: inlist = [{"name": "abc", "writable": True}...
5,304,500
def get_answers(question_id, **params): """获得答案列表""" conditions = list() sort_conditions = list() query = Answer.query if 'ids' in params: conditions.append(Answer.question_id.in_(params['ids'])) if params.get('create_time_sort') is not None: sort_condition = ( Answ...
5,304,501
def p_feature_list(parse): """ features_list : features_list feature POINT_AND_COMMA | feature POINT_AND_COMMA """ if len(parse) == 3: parse[0] = (parse[1],) else: parse[0] = parse[1] + (parse[2],)
5,304,502
def list_all(args): """List all uuid, account_number, name for all environments. :param args: argparser namespace :type args: namespace. """ driver = get_neo4j() with driver.session() as session: cipher = "MATCH (e:Environment)" if (args.missing): cipher += ' WHERE...
5,304,503
def download_gift(gift): """Generates a link allowing the gift file to be downloaded in: test string data out: href string to gift formatted test """ b64 = base64.b64encode(gift.encode()).decode( ) # some strings <-> bytes conversions necessary here href = f'<a href="data:file/txt;base64,{...
5,304,504
def _showFloatDiffs(asserter, expect, actual, **kwargs): """Indicate the differences between two floats. :Parameters: expect, actual The expected and actual float. kwargs ignored. :Return: A string showing why the float values differ. """ ulpDiff = UlpCompare.u...
5,304,505
def is_recovery_active(): """Report whether recovery mode is active.""" return RECOVERY_ACTIVE
5,304,506
def create_icon_score_stub(**kwargs) -> IconScoreInnerStub: """Create IconScoreInnerStub. Note that return value is actually `mock.Mock`. """ task: IconScoreInnerTask = AsyncMock(IconScoreInnerTask) task.validate_transaction.return_value = "result" task.query.return_value = { "result": ...
5,304,507
def wait_message(): """ Wait message from websocket, return the message in the format of a dict. """ try: msg = connection.recv() except websocket._exceptions.WebSocketConnectionClosedException as e: print(e) global connection connection = connect() msg = conn...
5,304,508
def create_classification_for_sample_and_variant_objects( user: User, sample: Sample, variant: Variant, genome_build: GenomeBuild, refseq_transcript_accession: str = None, ensembl_transcript_accession: str = None, annotation_version: str = None): """ Create in...
5,304,509
def bind_operator(operator): """ Binds the specified *build_set* in the currently active target. """ current_target().current_operator = operator
5,304,510
def rectifier(x): """ element-wise ReLU """ return tensor.maximum(0., x)
5,304,511
def unsubChange(doc, API, session): """ Calculate a mailing list unsub request """ diff = "" mls = {} with open("private/json/ml-modsubs.json") as f: mls = json.load(f) f.close() li = doc['listname'] l,d = li.split('@', 2) d = d.replace(".apache.org", "") # Check tha...
5,304,512
def get_wbt_dict(): """Generate a dictionary containing information for all tools. Returns: dict: The dictionary containing information for all tools. """ url = "https://github.com/giswqs/whiteboxgui/raw/master/whiteboxgui/data/whitebox_tools.json" response = urlopen(url) wbt_dict = js...
5,304,513
def abs_path_from_ryven_dir(path_rel_to_ryven_dir: str): """Given a path string relative to the ryven dir '~/.ryven/', return the file/folder absolute path :param path_rel_to_ryven_dir: path relative to ryven dir (e.g. saves) :return: file/folder absolute path """ return abspath(join(ryven_dir_pat...
5,304,514
def get_points(features, fpn_strides): """Get points according to feature map sizes. Args: features (list[Tensor]): Multi-level feature map. Axis 0 represents the number of images `N` in the input data; axes 1-3 are channels, height, and width, which may vary between featu...
5,304,515
def process_status(manager, result): """Supervisor 进程状态""" client = get_supervisor_client() info = client.supervisor.getAllProcessInfo() process_name = "" process_state = "" all_running = True for i in info: state = i.get("statename") desc = i.get("description") if st...
5,304,516
def test_install_read_locked_requeue(install_mockery, monkeypatch, capfd): """Cover basic read lock handling for uninstalled package with requeue.""" orig_fn = inst.PackageInstaller._ensure_locked def _read(installer, lock_type, pkg): tty.msg('{0}->read locked {1}' .format(lock_type, pkg.spec.name)...
5,304,517
def _read(fpath): """Read content of numpy archive file at <fpath>.""" if not pth.__is_file(fpath): log.critical("Numpy file \"{0}\" not found, cannot read data".format(fpath)) log.debug("Reading data from \"{0}\"".format(fpath)) return np.load(fpath)
5,304,518
async def get_proof_request( connection_id: str, schema_id: str, name_proof_request: str, zero_knowledge_proof: List[dict] = None, requested_attrs: List[str] = Query(None), self_attested: List[str] = None, revocation: int = None, exchange_tracing: bool = False, aries_controller: Arie...
5,304,519
def test_get_occweb_dir_fail(cache): """Test get_occweb_dir and get_occweb_page (which is called in the process)""" path = Path('FOT/mission_planning/PRODUCTS/APPR_LOADS/FAIL-NOT-THERE') with pytest.raises(requests.exceptions.HTTPError): occweb.get_occweb_dir(path, cache=cache)
5,304,520
def Dictionary_create_from(nMarkers, markerSize, baseDictionary): """ Dictionary_create_from(nMarkers, markerSize, baseDictionary) -> retval """ pass
5,304,521
def add_saved_albums(auths=None, albums=(None,)): """ Adds/follows albums. :param auths: dict() being the 'destinations'-tree of the auth object as returned from authorize() :param albums: list() containing the albums IDs to add to the 'destinations' accounts :return: True """ for username i...
5,304,522
def unpack_sequence(stream, template): """Unpack data from a sequence, yielding records.""" # is this a sequence or a base type? sequence = isinstance(template, SequenceType) # if there are no children, we use the template as the only column cols = list(template.children()) or [template] # if ...
5,304,523
def get_min(statistical_series): """ Get minimum value for each group :param statistical_series: Multiindex series :return: A series with minimum value for each group """ return statistical_series.groupby(level=0).agg('min')
5,304,524
def now(): """ Get the current time function. :return: Time function. :rtype: function """ if hasattr(time, 'monotonic'): return time.monotonic return time.time
5,304,525
def to_roman(value: int, make_upper: bool = True) -> str: """ The presence of 500 (D) and 50 (L), coupled with the special handling of 400, 900, 40, 90, 4 and 9, make table lookup seem like the best approach. """ if value == 0: return 'Zero' if value > 3999: return f'{value:,}' thousands, value ...
5,304,526
def builtin_increment_overloaded(self, context, looping=False): """ Increment a number by 1. Move the last item of a sequence to the top of the stack. Modify an unary function to have the effect: ( a b -- F(a) F(b) ). """ a = context.pop() if isinstance(a, BNum): # Increment a number by 1 b = type(a)(a.value...
5,304,527
def plot_inventory_chart(remaining): """Update inventory chart. Parameters ---------- remaining : pandas.Series Series object containing the number of remaining items for each product category. Returns ------- fig : plotly.graph_objects.Figure Bar chart showing the ...
5,304,528
def readfile(path, filename): """ Parses a file created by the measurement software (which is based on LabVIEW) :param path: str :param filename: str :return: np.array """ rawfile = open(path + filename) file = csv.reader(rawfile, delimiter="\t") datalist = [] for row in file: ...
5,304,529
def get_isotropic_level(hierarchy_method, x_voxel_size, y_voxel_size, z_voxel_size): """Method to get the resolution level where the data is closest to isotropic Args: hierarchy_method(str): isotropic or anisotropic x_voxel_size(int): voxel size in x dimension y_voxe...
5,304,530
def pearson(exprDF, lMirUser = None, lGeneUser = None, n_core = 2, pval = True): """ Function to calculate the Pearson correlation coefficient, and pval of each pair of miRNA-mRNA, return a matrix of correlation coefficients with columns are miRNAs and rows are mRNAs. Args: exprDF df C...
5,304,531
def detect_mode(editor): """ hook called to detect if this mode should be used for a file, returns True if it should be used, False otherwise """ workfile = editor.getWorkfile() global lexer try: filename = workfile.getFilename() if filename: lexer = get_lexer_for_filename(fi...
5,304,532
def free(v): """Free a scalar.""" check_status(v, lib.GxB_Scalar_free(v))
5,304,533
def find_duplicate(strings: list): """find the first duplicate string from list:strings""" strings = [str(x) for x in strings.split(',')] map = defaultdict(int) duplicate_string = '' for word in strings: if map[word]: duplicate_string = word print(f'The duplicate string is "{word}"') break else: ...
5,304,534
def enemyEnclosed(bo:board, us:snake, snakes:list): """ Returns a list of targets we can enclose the enemy (1) Find squares we can get to first (2) Calcualte enemy chance board, looking for 100% (3) Find intercept of 100% and squares we can get to == bo: boardClass as board ...
5,304,535
def test_app(): """ Creates an instance of the app. session scope """ app.config['TESTING'] = True yield app
5,304,536
def plot_info_plane(MI_object, name, separate_flag, color_l, show_flag, save_flag): """ starts information plane plotting and creates plots for epoch, layer and separated view MI_object: mutual information object name: name of the network color_l: list of colours for different layers show_flag:...
5,304,537
def get_daily_returns(port_val): """Get daily returns of a portfolio value dataframe. Args: port_val (dataframe): daily portfolio value Returns: daily_ret (dataframe): daily returns """ daily_ret = port_val.copy() daily_ret[1:] = (port_val[1:] / port_val[:-1].values)-1 dail...
5,304,538
def get_story(): # type: () -> Story """Get Story in session.""" return session[STORY_KEY]
5,304,539
def align_vector_to_another(a=np.array([0, 0, 1]), b=np.array([1, 0, 0])): """Aligns vector a to vector b with axis angle rotation""" if np.array_equal(a, b): return None, None axis_ = np.cross(a, b) axis_ = axis_ / np.linalg.norm(axis_) angle = np.arccos(np.dot(a, b)) return axis_, ang...
5,304,540
def rand_seq(alphabet, size, p=None): """Generate a random :class:`Sequence` of the given length from the given :class:`Alphabet`. Keyword Args: alphabet (Alphabet) size (int): The length of the randomly generated sequence. p (list): The discrete probability distribution for letters...
5,304,541
def chi2sf_inplace(x, k): """chi squared survival function"""
5,304,542
def en(value): """Returns an RDF literal from the en language for the given value.""" from pymantic.primitives import Literal return Literal(value, language='en')
5,304,543
def minimal_sphinx_app(configuration=None, sourcedir=None): """Create a minimal Sphinx environment; loading sphinx roles, directives, etc. """ class MockSphinx(Sphinx): """Minimal sphinx init to load roles and directives.""" def __init__(self, confoverrides=None, srcdir=None): ...
5,304,544
def plot_alignment(alignment, gs): """Plots the alignment alignments: A list of (numpy) matrix of shape (encoder_steps, decoder_steps) gs : (int) global step """ fig, ax = plt.subplots() im = ax.imshow(alignment) # cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7]) fig.colorbar(im) plt...
5,304,545
def add_sppc_args(parser): """Add args of SPP Container to app.""" parser.add_argument( '--dist-name', type=str, default='ubuntu', help="Name of Linux distribution") parser.add_argument( '--dist-ver', type=str, default='latest', help="Version ...
5,304,546
def update_last_donation(donation, remaining_amount, popular_projects): """ Updates the last donation with the remaining amount of the payment. If the donation is more than the project needs, the project will be filled and the balance will be used to fill the popular projects recursively. """ projec...
5,304,547
def menu(): """Menu Function""" def run(func): """Calls functions""" func() menu() print('\n\t\tYour Personal dictionary!') choice = input("\nDo you want to 'view', 'add', 'delete', 'game', or 'destroy'? Enter 'x' to exit.\n\t=>").lower() if choice == 'view': run(helpers.view) elif choice == 'add': ...
5,304,548
def rank4_naming(proteins_available: Iterable[str], best_match_protein_name: str) -> str: """ Given a list of proteins available as well as the best match name the function returns predicted name In this example the function extracts the first three letter pattern with the number (it can be 3 to 5 digi...
5,304,549
def init_infected_symptomatic_20(): """ Real Name: b'init Infected symptomatic 20' Original Eqn: b'0' Units: b'person' Limits: (None, None) Type: constant b'' """ return 0
5,304,550
def improve_p(time, b, I): """ calculate solution of Kolmogorov equation """ ret = odeint(deriv_improve_kolmog, [1, 0, 0], time, args=(b, I)) P_S, P_I, P_R = ret.T return P_S, P_I, P_R
5,304,551
def flower(ctx, flower_args): """Start the flower instance""" broker = ctx.app.config["CELERY_CONF"]["broker_url"] args = ["celery", "flower", "-b", broker] + list(flower_args) os.execvp(args[0], args[1:])
5,304,552
def has_singularity(order): """ Tests order for a 'Singularity', or a common reduction error resulting in huge counts""" order = order[4:-4] order_c = np.convolve(np.abs(order), [1, 1]) big = np.where(order_c > 500)[0] zero_crossings = np.where(np.diff(np.sign(order)))[0] return True if np.inter...
5,304,553
def get_exact_angle(pt1, pt2): """ Given two cardinal points, returns the corresponding angle in *radians*. Args: * **pt1** (tuple): Point 1 * **pt2** (tuple): Point 2 Returns: float Angle (in radians) Example:: import picwriter.toolkit as tk print(tk....
5,304,554
def _perceptive_hash(file_path, hash_size = 8): """Calculates a hash-value from an image Conversion uses a resized, grayscaled pixel-array of the image, converting the pixel-array to a number-array (differences between neighboring pixels) and finally converting these values to a hex-string of length ha...
5,304,555
def embed(x, vsz, dsz, initializer, finetune=True, scope="LUT"): """Perform a lookup table operation while freezing the PAD vector. Use the initializer to set the weights :param x: The input to this operation :param vsz: The size of the input vocabulary :param dsz: The output size or embedding dimensi...
5,304,556
def test_property(): """Tests properties""" assert ProphetTemplate().allow_model_template_list is False assert ProphetTemplate().allow_model_components_param_list is False template = ProphetTemplate() assert template.DEFAULT_MODEL_TEMPLATE == "PROPHET" assert isinstance(template.estimator, Prop...
5,304,557
def make_drf_request(request: HttpRequest = None, headers: dict = None): """ The request object made by APIRequestFactory is `WSGIRequest` which doesn't have `.query_params` or `.data` method as recommended by DRF. It only gets "upgraded" to DRF `Request` class after passing through the `APIView`, ...
5,304,558
def is_quit_event(event): """ Returns True if provided event is a quit event. :param event: Any pygame event. :return: True if QUIT signal is given, or ESC is pressed, or CMD + Q is pressed, or ALT + F4 is pressed. """ if event.type == pygame.QUIT: return True elif event.type == ...
5,304,559
def split_data(x, y, ratio, seed=1): """split the dataset based on the split ratio.""" # set seed np.random.seed(seed) # generate random indices num_row = len(y) indices = np.random.permutation(num_row) index_split = int(np.floor(ratio * num_row)) index_tr = indices[: index_split] in...
5,304,560
def trace_downstream( input_layer, split_distance=None, split_units="Kilometers", max_distance=None, max_distance_units="Kilometers", bounding_polygon_layer=None, source_database=None, generalize=True, output_name=None, context=None, ...
5,304,561
def get_object_filepath(object: Any) -> str: """ Get object's filepath. """ path = Path(object.__code__.co_filename).absolute() try: filepath = "./" + path.relative_to(Path.cwd()).as_posix() except ValueError: filepath = path.as_posix() return filepath
5,304,562
def linear_timeseries(start_value: float = 0, end_value: float = 1, length: int = 10, freq: str = 'D', start_ts: pd.Timestamp = pd.Timestamp('2000-01-01')) -> TimeSeries: """ Creates a TimeSeries with a starting value of `st...
5,304,563
def get_blog_html(url: str) -> str: """ get the raw html of the blog post """ try: response = requests.get(url) if response.ok: return response.text else: return None except Exception as e: print(f"[!] Failed to get blog html: {str(e)}") return...
5,304,564
def test_resolve_and_filter_bonded_peer(peripheral, central, advertising_type): """Ensure that if the central privacy policy is set to resolve and filter bonded devices show up in scan results as resolved addresses""" perform_bonding_with_privacy_and_disconnect(peripheral, central) advertising_data = s...
5,304,565
def calculate_mwp_mag(peak, epicentral_distance): """ Calculate Mwp magnitude. .. seealso:: [Tsuboi1999]_ and [Tsuboi1995]_ :type peak: float :param peak: Peak value of integral of displacement seismogram. :type epicentral_distance: float :param epicentral_distance: Great-circle epicentral...
5,304,566
def get_all_services(resource_root, cluster_name="default", view=None): """ Get all services @param resource_root: The root Resource object. @param cluster_name: Cluster name @return: A list of ApiService objects. """ return call(resource_root.get, SERVICES_PATH % (cluster_name,), ApiService, ...
5,304,567
def _depgrep_rel_disjunction_action(_s, _l, tokens): """ Builds a lambda function representing a predicate on a tree node from the disjunction of several other such lambda functions. """ # filter out the pipe tokens = [x for x in tokens if x != "|"] # print 'relation disjunction tokens: ', t...
5,304,568
def bibtexToCoNLL(bibpath, writeToDisk = False, outpath = None, encoding = "latex", mapping = None, seqStruct = None): """ The function transforms a bibtex file in a simil-CoNLL dataset. In detail, it parses a bibtex file and returns lists similar to those returned by load_data ...
5,304,569
def get_buff(status): """获取人物指定的BUFF""" dm.use_dict(2) result = dm.find_str(142, 11, 1419, 48, status, color='C1E2DA-3B1D23|E4E0D7-1B1F28', sim=0.8) if result[0] > -1: return True
5,304,570
def get_header_data(header_data_map: dict = {}, ecat_file: str = '', byte_offset: int = 0): """ Collects the header data from an ecat file, by default starts at byte position 0 (aka byte offset) for any header that is not the main header this offset will need to be provided :param header_data_map: The d...
5,304,571
def _disabled_inview_messages(): """Disable in-view help messages during the context""" original = cmds.optionVar(q="inViewMessageEnable") cmds.optionVar(iv=("inViewMessageEnable", 0)) try: yield finally: cmds.optionVar(iv=("inViewMessageEnable", original))
5,304,572
def _find_unused_port(): """ Finds a port that's available. Unfortunately, this port may not be available by the time the subprocess uses it, but this generally works. """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.bind(('127.0.0.1', 0)) sock.listen(socket.SOMAXCONN) _, port = so...
5,304,573
def merge(batch, results): """ Merge clumped results files together """ merger = batch.new_job(name='merge-results') merger.image('ubuntu:18.04') if results: merger.command(f''' head -n 1 {results[0]} > {merger.ofile} for result in {" ".join(results)} do tail -n +2 "$result" >> {merg...
5,304,574
def model_with_buckets(encoder_inputs, decoder_inputs, targets, weights, buckets, seq2seq, softmax_loss_function=None, per_example_loss=False, name=None): """Create a sequence-to-sequence model with support for bucketing. The seq2seq argument is a function that defines ...
5,304,575
def torch_load_state_dict_without_module(ckp_file): """ this function using for load a model without module """ checkpoint = torch.load(ckp_file) state_dict =checkpoint['state_dict'] new_state_dict = OrderedDict() for k, v in state_dict.items(): if 'module.' in k: k = k[...
5,304,576
def resnet50c(config, norm_layer=nn.BatchNorm2D): """resnet50c implement The ResNet-50 [Heet al., 2016] with dilation convolution at last stage, ResNet-50 model Ref, https://arxiv.org/pdf/1512.03385.pdf Args: config (dict): configuration of network norm_layer: normalization layer t...
5,304,577
def set_parameters_in_cookie(response: Response) -> Response: """Set request parameters in the cookie, to use as future defaults.""" if response.status_code == status.HTTP_200_OK: data = {param: request.args[param] for param in PARAMS_TO_PERSIST if param in request.args} response...
5,304,578
def code_list_lengthener(code_list, parameter): """Ensures that code_list is long enough to accept an item in its parameter-th location""" while len(code_list) < parameter+1: code_list.append(0) return code_list
5,304,579
def download_lua(args, download_dir): """Download the Lua tarball to the specified directory.""" full_version = CONFIG["specific_versions"][args.lua_version] if args.lua_version.startswith("luajit"): LOG.info("Downloading LuaJIT %s into `%s`...", full_version, download_dir) response = reque...
5,304,580
def invoice(request): """Returns all invoices""" auth_client = AuthClient( settings.CLIENT_ID, settings.CLIENT_SECRET, settings.REDIRECT_URI, settings.ENVIRONMENT, ) client = QuickBooks( auth_client=auth_client, refresh_token=request.session.get('refres...
5,304,581
def delete_user_account(): """ remove all character blueprint for current user """ if request.is_xhr: char_id = current_user.character_id try: delete_account(current_user) flash("Your account have been deleted.", 'info') return json_response('success', ...
5,304,582
def unaccented_letters(s: str) -> str: """Return the letters of `s` with accents removed.""" s = unicodedata.normalize('NFKD', s) s = re.sub(r'[^\w -]', '', s) return s
5,304,583
def test_apply_channel_kraus(): """ Apply Kraus map. The following test computes PHI(X) where X = [[1, 2], [3, 4]] and where PHI is the superoperator defined by: Phi(X) = [[1,5],[1,0],[0,2]] X [[0,1][2,3][4,5]].conj().T - [[1,0],[0,0],[0,1]] X [[0,0][1,1],[0,0]].conj().T """ test_input_...
5,304,584
def load_ud_english(fpath): """Load a file from the UD English corpus Parameters ---------- fpath : str Path to UD corpus file ending in .conllu Output: Returns a list equal to length of total num of docs with each item contaiing the first index of sentence ...
5,304,585
def smooth_imgs(env: aneurysm_utils.Environment, mr_imgs: list, fwhm=1) -> list: """Smooth images.""" niimg_likes = get_nift_like(env, mr_imgs) smoothed = [] for img in niimg_likes: smoothed.append( nilearn.image.smooth_img(img, fwhm=fwhm).get_data().astype("<f4") ) retu...
5,304,586
def run_averecmd(ssh_client, node_ip, password, method, user='admin', args='', timeout=60): """Run averecmd on the vFXT controller connected via ssh_client.""" cmd = "averecmd --raw --no-check-certificate " + \ "--user {0} --password '{1}' --server {2} {3} {4}".format( use...
5,304,587
def create_bout_ds_list( prefix, lengths=(6, 2, 4, 7), nxpe=4, nype=2, nt=1, guards={}, topology="core", syn_data_type="random", squashed=False, bout_v5=False, metric_3D=False, ): """ Mocks up a set of BOUT-like datasets. Structured as though they were produced b...
5,304,588
def unalign_angles( thetap, Npz, Npr, method='irrational' ) : """ Shift the angles so that the particles are not all aligned along the arms of a star transversely The fact that the particles are all aligned can produce numerical artefacts, especially if the polarization of the laser is aligned ...
5,304,589
def parse_mapping_file(fp): """ """ ensp_to_hgnc = {} with open(fp, "r") as fh: for line in fh: line = line.rstrip() words = line.split() if(len(words) >= 4): ensp_to_hgnc[words[3]] = words[0] return ensp_to_hgnc
5,304,590
def sort_group(indx, column1, column2): """ Parameters ---------- indx : integer column1 : list data type (contains strings of SOC NAMES / WORK STATES which need to be ordered.) column2 : list data type (contains integers which denote numbers of of certified applications.) Returns ------- sort_group : l...
5,304,591
def main(args): """Mix synthetic negative samples into training data. Args: args: command line arguments. """ synthetic_data_file = os.path.expanduser(args.synthetic_data_file) if not os.path.isfile(synthetic_data_file): raise Exception("Synthetic data file not found.") original_data_file =...
5,304,592
def rate_limit(auth, limit, period): """Rate limit main function""" if rate_request(auth, limit, timedelta(seconds=period)): raise exception.too_many_rquests() logging.info('✅ Request is allowed') return True
5,304,593
def unflag_output_id(output_id: str) -> bool: """Sets the flag property of an IOPointer to false.""" store = Store(_db_uri) return store.set_io_pointer_flag(output_id, False)
5,304,594
def fakeimg_gif(fakeimgbytes_gif): """Set up respx to respond to test url with fake image bytes.""" respx.get("http://127.0.0.1/testurl/1").respond(stream=fakeimgbytes_gif)
5,304,595
def make_argument_parser() -> argparse.ArgumentParser: """Generic experiment parser. Generic parser takes the experiment yaml as the main argument, but has some options for reloading, etc. This parser can be easily extended using a wrapper method. Returns: argparse.parser """ parser = argp...
5,304,596
def get_indicator_representation(row): """Convert binary indicator to list of assigned labels Parameters: ----------- row : List[{0,1}] binary indicator list whether i-th label is assigned or not Returns ------- np.array[int] list of assigned labels """ return np.w...
5,304,597
def Uniform(*opts): """Uniform distribution over a finite list of options. Implemented as an instance of :obj:`Options` when the set of options is known statically, and an instance of `UniformDistribution` otherwise. """ if any(isinstance(opt, StarredDistribution) for opt in opts): return UniformDistribution(op...
5,304,598
def _fixed_parameters_to_edata( edata: amici.ExpData, condition_df: pd.DataFrame, fixed_parameter_ids: Sequence[str], condition) -> None: """ Apply fixed parameters for a given simulation condition to the corresponding ExpData. Parameters: edata: ExpData to set fixed...
5,304,599