content
stringlengths
22
815k
id
int64
0
4.91M
def test_data_viewer(dataframe): """Test DataView functions.""" dt_viewer = DataViewer(data=dataframe) check.equal(len(dataframe), len(dt_viewer.filtered_data)) _apply_filter(dt_viewer.data_filter, "Account", "contains", "MSTICAlertsWin1") dt_viewer._apply_filter(btn=None) check.equal(3, len(dt...
5,331,300
def test_query_xdd(): """Assert number of records equals expected hits.""" s.build_query_urls() # Grab first search term s.next_url = s.search_urls[0] s.query_xdd() if s.response_status == "success": assert s.response_hits == len(s.response_data)
5,331,301
def deceptivemultimodal(x: np.ndarray) -> float: """Infinitely many local optima, as we get closer to the optimum.""" assert len(x) >= 2 distance = np.sqrt(x[0]**2 + x[1]**2) if distance == 0.: return 0. angle = np.arctan(x[0] / x[1]) if x[1] != 0. else np.pi / 2. invdistance = int(1. / ...
5,331,302
def get_basins_scores(memory_array, binarized_cluster_dict, basinscore_method="default"): """ Args: - memory_array: i.e. xi matrix, will be N x K (one memory from each cluster) - binarized_cluster_dict: {k: N x M array for k in 0 ... K-1 (i.e. cluster index)} - basinscore_method: options...
5,331,303
def generate_inputs_ph(fixture_sandbox, fixture_localhost, fixture_code, generate_remote_data, generate_kpoints_mesh): """Generate default inputs for a `PhCalculation.""" def _generate_inputs_ph(): """Generate default inputs for a `PhCalculation.""" from aiida.orm import Dict from aiida...
5,331,304
def escape_url(raw): """ Escape urls to prevent code injection craziness. (Hopefully.) """ from urllib.parse import quote return quote(raw, safe="/#:")
5,331,305
def split_sample(labels): """ Split the 'Sample' column of a DataFrame into a list. Parameters ---------- labels: DataFrame The Dataframe should contain a 'Sample' column for splitting. Returns ------- DataFrame Updated DataFrame has 'Sample' column with a list of strin...
5,331,306
def pmi_odds(pnx, pn, nnx, nn): """ Computes the PMI with odds Args: pnx (int): number of POSITIVE news with the term x pn (int): number of POSITIVE news nnx (int): number of NEGATIVE news with the term x nn (int): number of NEGATIVE news Ret...
5,331,307
def berDecodeLength(m, offset=0): """ Return a tuple of (length, lengthLength). m must be atleast one byte long. """ l = ber2int(m[offset + 0:offset + 1]) ll = 1 if l & 0x80: ll = 1 + (l & 0x7F) need(m, offset + ll) l = ber2int(m[offset + 1:offset + ll], signed=0) ...
5,331,308
def hasAspect(obj1, obj2, aspList): """ Returns if there is an aspect between objects considering a list of possible aspect types. """ aspType = aspectType(obj1, obj2, aspList) return aspType != const.NO_ASPECT
5,331,309
def gen_decomposition(denovo_name, basis_names, weights, output_path, project, \ mtype, denovo_plots_dict, basis_plots_dict, reconstruction_plot_dict, \ reconstruction=False, statistics=None, sig_version=None, custom_text=None): """ Generate the correct plot based on mtype. Parameters: ---------- denovo_name: ...
5,331,310
def org(gh): """Creates an Org instance and adds an spy attribute to check for calls""" ret = Organization(gh, name=ORG_NAME) ret._gh = Mock(wraps=ret._gh) ret.spy = ret._gh return ret
5,331,311
def merge_regions( out_path: str, sample1_id: int, regions1_file: File, sample2_id: int, regions2_file: File ) -> File: """ Merge two sorted region files into one. """ def iter_points(regions): for start, end, depth in regions: yield (start, "start", depth) yield (en...
5,331,312
def get_text_hexdigest(data): """returns md5 hexadecimal checksum of string/unicode data NOTE ---- The md5 sum of get_text_hexdigest can differ from get_file_hexdigest. This will occur if the line ending character differs from being read in 'rb' versus 'r' modes. """ data_class = data._...
5,331,313
async def test_get_rdf_turtle(client: Any, fs: Any) -> None: """Should return status 200 OK and RDF as turtle.""" contents = '<http://example.com/drewp> <http://example.com/says> "Hello World" .' fs.create_file( "/srv/www/static-rdf-server/data/ontology-type-1/ontology-1/ontology-1.ttl", con...
5,331,314
def rbInsertFixup(T, z): """给结点重新着色,将其保持为红黑树""" RED = RBTree.COLOR_RED BLACK = RBTree.COLOR_BLACK while z.p.color == RED: if z.p == z.p.p.left: y = z.p.p.right if y.color == RED: z.p.color = BLACK y.color = BLACK z.p.p.color...
5,331,315
def recipe(recipe_id): """ Display the recipe on-page for each recipe id that was requested """ # Update the rating if it's an AJAX call if request.method == "POST": # check if user is login in order to proceed with rating if not session: return json.dumps({'status': 'not...
5,331,316
def api_program_ordering(request, program): """Returns program-wide RF-aware ordering (used after indicator deletion on program page)""" try: data = ProgramPageIndicatorUpdateSerializer.load_for_pk(program).data except Program.DoesNotExist: logger.warning('attempt to access program page orde...
5,331,317
def isinteger(x): """ determine if a string can be converted to an integer """ try: a = int(x) except ValueError: return False else: return True
5,331,318
def unmarshal_tools_pcr_values( buf: bytes, selections: TPML_PCR_SELECTION ) -> Tuple[int, List[bytes]]: """Unmarshal PCR digests from tpm2_quote using the values format. Args: buf (bytes): content of tpm2_quote PCR output. selections (TPML_PCR_SELECTION): The selected PCRs. Returns: ...
5,331,319
def new_topic(request): """添加新主题""" if request.method != 'POST': #未提交数据,创建一个新表单 form = TopicForm() else: #POST提交的数据,对数据进行处理 form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit = False) new_topic.owner = request.user new_topic.save() form.save() return HttpResponse...
5,331,320
def save_model(model, model_filepath): """ Save the classifier model to the location specified Args: model (model) Classifier Model to save model_filepath (string) path to model pickle file """ pickle.dump(model, open(model_filepath, 'wb'))
5,331,321
def two_lot_2bid_2com_2win(self): """ Create tender with 2 lots and 2 bids """ self.create_tender(initial_lots=self.test_lots_data * 2) tenderers = self.create_tenderers(2) # create bid self.app.authorization = ("Basic", ("broker", "")) self.app.post_json( "/tenders/{}/bids".format(self....
5,331,322
def address(lst: Union[List[Any], str], dim: Optional[int] = None) -> Address: """ Similar to :meth:`Address.fromList`, except the name is shorter, and the dimension is inferred if possible. Otherwise, an exception is thrown. Here are some examples: >>> address('*') Address(*, 0) >>> addre...
5,331,323
def import_olx(self, user_id, course_key_string, archive_path, archive_name, language): """ Import a course or library from a provided OLX .tar.gz archive. """ current_step = 'Unpacking' courselike_key = CourseKey.from_string(course_key_string) set_code_owner_attribute_from_module(__name__) ...
5,331,324
async def initialize_agent(request): """ Initialize agent. """ agent = request.app['agent'] data = await request.post() agent.owner = data['agent_name'] agent.endpoint = data['endpoint'] wallet_name = '%s-wallet' % agent.owner # pylint: disable=bare-except # TODO: better handle pot...
5,331,325
def create_scenario_dataframes_geco(scenario): """ Reads GECO dataset and creates a dataframe of the given scenario """ df_sc = pd.read_csv(io["scenario_geco_path"]) df_sc_europe = df_sc.loc[df_sc["Country"] == "EU28"] df_scenario = df_sc_europe.loc[df_sc_europe["Scenario"] == scenario] ret...
5,331,326
def escape_env_var(varname): """ Convert a string to a form suitable for use as an environment variable. The result will be all uppercase, and will have all invalid characters replaced by an underscore. The result will match the following regex: [a-zA-Z_][a-zA-Z0-9_]* Example: "my.pri...
5,331,327
def from_file(handle, output): """ Convert a handle of JSON formatted objects and write a GFF3 file to the given output handle. """ parsed = coord.from_file(handle) features = regions_as_features(parsed) write_gff_text(features, output)
5,331,328
def rms(signal): """ rms(signal) Measures root mean square of a signal Parameters ---------- signal : 1D numpy array """ return np.sqrt(np.mean(np.square(signal)))
5,331,329
def get_template_page(page): """method used to get the a page based on the theme it will check the options.theme defined theme for the page first and if it isnt found it will fallback to options.theme_dir/cling for the template page """ templates = ['%s.html' % os.path.join(options.theme_dir, 'clin...
5,331,330
def named_masks(module, prefix=""): """Returns an iterator over all masks in the network, yielding both the name of a maskable submodule as well as its current mask. Parameters ---------- module : torch.nn.Module The network, which is scanned for variational modules. prefix : string, d...
5,331,331
def handle_with_item(items: List[_T], item_handler: Callable[[_T], _U], result_handler: Callable[[_T, _U], Any], pool: Optional[ThreadPool] = None) -> None: """ Processes all the items in a separate thread using `item_handler` and post-processes ...
5,331,332
def get_config( config_path, trained: bool = False, runner="d2go.runner.GeneralizedRCNNRunner" ): """ Returns a config object for a model in model zoo. Args: config_path (str): config file name relative to d2go's "configs/" directory, e.g., "COCO-InstanceSegmentation/mask_rcnn_R_50_F...
5,331,333
def make_game( width: int = defaults.WIDTH, height: int = defaults.HEIGHT, max_rooms: int = defaults.MAX_ROOMS, seed: Optional[int] = defaults.SEED, slippery_coefficient: float = defaults.SLIPPERY_COEFFICIENT, default_reward: float = defaults.DEFAULT_REWARD, goal_reward: float = defaults.GOA...
5,331,334
def weighted_var(x, weights=None): """Unbiased weighted variance (sample variance) for the components of x. The weights are assumed to be non random (reliability weights). Parameters ---------- x : np.ndarray 1d or 2d with observations in rows weights : np.ndarray or None 1d ar...
5,331,335
def start_detailed_result_worker_route(): """ Add detailed result worker if not exist :return: JSON """ # check if worker already exist if check_worker_result(RABBITMQ_DETAILED_RESULT_QUEUE_NAME) == env.HTML_STATUS.OK.value: return jsonify(status=env.HTML_STATUS.OK.value) if 'db_nam...
5,331,336
def test_get_http_response_querystring_payload(): """Test get_http_response_querystring_payload""" function = { "name": "code_test", "header": "api", "method": "get", "path": "/test/api", "querystring": {}, "payload": {}, } assert functions.get_http_respo...
5,331,337
def _find_next_pickup_item(not_visited_neighbors, array_of_edges_from_node): """ Args: not_visited_neighbors: array_of_edges_from_node: Returns: """ # last node in visited_nodes is where the traveling salesman is. cheapest_path = np.argmin( array_of_edges_from_node[not...
5,331,338
def deformable_conv(input, offset, mask, num_filters, filter_size, stride=1, padding=0, dilation=1, groups=None, deformable_groups=None, ...
5,331,339
def ieee(): """IEEE fixture.""" return t.EUI64.deserialize(b"ieeeaddr")[0]
5,331,340
def test_no_log_none(stdin, capfd): """Allow Ansible to make the decision by matching the argument name against PASSWORD_MATCH.""" arg_spec = { "arg_pass": {} } am = basic.AnsibleModule(arg_spec) # Omitting no_log is only picked up by _log_invocation, so the value never # makes it in...
5,331,341
def is_in(a_list): """Returns a *function* that checks if its argument is in list. Avoids recalculation of list at every comparison.""" def check(arg): return arg in a_list return check
5,331,342
def get_log_record_extra_fields(record): """Taken from `common` repo logging module""" # The list contains all the attributes listed in # http://docs.python.org/library/logging.html#logrecord-attributes skip_list = ( 'args', 'asctime', 'created', 'exc_info', 'exc_text', 'filename', 'func...
5,331,343
def make_ideal(psr): """Adjust the TOAs so that the residuals to zero, then refit.""" psr.stoas[:] -= psr.residuals() / 86400.0 psr.fit()
5,331,344
def test_should_raise_if_wrong_key_dvc_extra_meta(): """ Test raise if not expected keyword in dvc extra meta """ with pytest.raises(MlVToolException): DocstringDvcExtra.from_meta(args=['dvc-wrong'], description='--extra p')
5,331,345
def test_valid_allocation_transfer_agency(database): """If File C (award financial) record has a valid allocation transfer agency, rule always passes.""" cgac = CGACFactory(cgac_code='good') af = AwardFinancialFactory( piid='some_piid', parent_award_id='some_parent_award_id', allocation_transfer_ag...
5,331,346
def test_enum(): """Test manipulating an Enum member. """ e = Enum('a', 'b') assert e.items == ('a', 'b') assert e.default_value_mode[1] == 'a' e_def = e('b') assert e_def is not e assert e_def.default_value_mode[1] == 'b' with pytest.raises(TypeError): e('c') e_add = ...
5,331,347
def ldap_is_intromember(member): """ :param member: A CSHMember instance """ return _ldap_is_member_of_group(member, 'intromembers')
5,331,348
def test_dump_metadata(arterynetwork_def, param): """Test correct execution of dump_metadata. :param arterynetwork_def: Artery network object :param param: Config parameters """ an = arterynetwork_def order, rc, qc, Ru, Rd, L, k1, k2, k3, rho, Re, nu, p0, R1, R2, CT,\ Nt, Nx, T, N_cycles...
5,331,349
def details(request, slug): """ Show product set """ productset = get_object_or_404(models.ProductSet, slug=slug) context = {} response = [] variant_instances = productset.variant_instances() signals.product_view.send( sender=type(productset), instances=variant_instances,...
5,331,350
def applies(platform_string, to='current'): """ Returns True if the given platform string applies to the platform specified by 'to'.""" def _parse_component(component): component = component.strip() parts = component.split("-") if len(parts) == 1: if parts[0] in VALID_PL...
5,331,351
def _GetClassLock(cls): """Returns the lock associated with the class.""" with _CLASS_LOCKS_LOCK: if cls not in _CLASS_LOCKS: _CLASS_LOCKS[cls] = threading.Lock() return _CLASS_LOCKS[cls]
5,331,352
def _get_expression_table_name() -> TableName: """ Get a expression table name. This value will be switched whether current scope is event handler's one or not. Returns ------- table_name : str Target expression table name. """ from apysc._expression import event_handl...
5,331,353
def log(config, results): """ analysis.py plugin: Analyze mongod.log files. :param ConfigDict config: The global config. :param ResultsFile results: Object to add results to. """ LOGGER.info("Checking log files.") reports = config["test_control"]["reports_dir_basename"] perf_json = conf...
5,331,354
def measure_option(mode, number=1, repeat=1, timeout=60, parallel_num=1, pack_size=1, check_correctness=False, build_option=None, replay_db=None, sav...
5,331,355
def get_contributions(user, latest, org=None): """ Traverses the latest array, creates a table if org argument is present only the repos which belong to the org is added to the table and prints the table. """ print("Contributions Today: ") if latest: table = Prett...
5,331,356
def make_inference(input_data, model): """ input_data is assumed to be a pandas dataframe, and model uses standard sklearn API with .predict """ input_data['NIR_V'] = m.calc_NIR_V(input_data) input_data = input_data.replace([np.nan, np.inf, -np.inf, None], np.nan) input_data = input_data.dropna(...
5,331,357
def property_elements(rconn, redisserver, name, device): """Returns a list of dictionaries of element attributes for the given property and device each dictionary will be set in the list in order of label :param rconn: A redis connection :type rconn: redis.client.Redis :param redisserver: The redis...
5,331,358
def run_forever(config: Dict[str, Any]): """ Run and block until a signal is sent to the process. The application, services or gRPC server are all created and initialized when the application starts. """ def run_stuff(config: Dict[str, Any]): resources = initialize_all(config) c...
5,331,359
def _dtype(a, b=None): """Utility for getting a dtype""" return getattr(a, 'dtype', getattr(b, 'dtype', None))
5,331,360
def parse_garmin_tcx(filename): """ Parses tcx activity file from Garmin Connect to Pandas DataFrame object Args: filename (str) - tcx file Returns: a tuple of id(str) and data(DataFrame) DF columns=['time'(datetime.time), 'distance, m'(float), 'HR'(int), 'cadence'(int), 'speed, m/s'(int)] """...
5,331,361
def get_decay_fn(initial_val, final_val, start, stop): """ Returns function handle to use in torch.optim.lr_scheduler.LambdaLR. The returned function supplies the multiplier to decay a value linearly. """ assert stop > start def decay_fn(counter): if counter <= start: return...
5,331,362
async def is_logged(jwt_cookie: Optional[str] = Cookie(None, alias=config.login.jwt_cookie_name)): """ Check if user is logged """ result = False if jwt_cookie: try: token = jwt.decode( jwt_cookie, smart_text(orjson.dumps(config.secret_key)), ...
5,331,363
def cached_query_molecules( client_address: str, molecule_ids: List[str] ) -> List[QCMolecule]: """A cached version of ``FractalClient.query_molecules``. Args: client_address: The address of the running QCFractal instance to query. molecule_ids: The ids of the molecules to query. Retur...
5,331,364
def _domain_to_json(domain): """Translates a Domain object into a JSON dict.""" result = {} # Domain names and bounds are not populated yet if isinstance(domain, sch.IntDomain): result['ints'] = { 'min': str(domain.min_value), 'max': str(domain.max_value), 'isCategorical': domain.is_...
5,331,365
def draw_point(state, x, y, col=COLORS["WHITE"], symb="▓"): """returns a state with a placed point""" state[y][x] = renderObject(symb, col) return state
5,331,366
def remove_read_metadata(meta, field_ids): """Delete any read metadata for remove fields.""" covs = defaultdict(dict) for field_id in field_ids: if field_id.endswith("_cov"): if field_id.endswith("_read_cov"): root = field_id.replace("_read_cov", "") covs[...
5,331,367
def _vars_to_add(new_query_variables, current_query_variables): """ Return list of dicts representing Query Variables not yet persisted Keyword Parameters: new_query_variables -- Dict, representing a new inventory of Query Variables, to be associated with a DWSupport Query current_query_vari...
5,331,368
def Ak(Y2d, H, k): """ Calculate Ak for Sk(x) Parameters ---------- Y2d : list list of y values with the second derived H : list list of h values from spline k : int index from Y2d and H Returns ------- float A...
5,331,369
def cycle_list_next(vlist, current_val): """Return the next element of *current_val* from *vlist*, if approaching the list boundary, starts from begining. """ return vlist[(vlist.index(current_val) + 1) % len(vlist)]
5,331,370
def _cal_hap_stats(gt, hap, pos, src_variants, src_hom_variants, src_het_variants, sample_size): """ Description: Helper function for calculating statistics for a haplotype. Arguments: gt allel.GenotypeArray: Genotype data for all the haplotypes within the same window of the haplotype to be...
5,331,371
def read_cfg(file): """Read configuration file and return list of (start,end) tuples """ result = [] if isfile(file): with open(file) as f: cfg = json.load(f) for entry in cfg: if "start" in entry: filter = (entry["start"], entry.get("end", None)) ...
5,331,372
def test_pragmas_03(): """ Test the case where we specify a 'disable-next-line' pragma, but specify no id to disable. """ # Arrange scanner = MarkdownScanner() supplied_arguments = [ "scan", "test/resources/pragmas/atx_heading_with_multiple_spaces_disable_with_no_id.md", ] ...
5,331,373
def least_l2_affine( source: np.ndarray, target: np.ndarray, shift: bool = True, scale: bool = True ) -> AffineParameters: """Finds the squared-error minimizing affine transform. Args: source: a 1D array consisting of the reward to transform. target: a 1D array consisting of the target to m...
5,331,374
def mark_item_as_read( client: EWSClient, item_ids, operation="read", target_mailbox=None ): """ Marks item as read :param client: EWS Client :param item_ids: items ids to mark as read :param (Optional) operation: operation to execute :param (Optional) target_mailbox: target mailbox ...
5,331,375
def step(state,iidx,arrayTimeIndex,globalTimeStep): """This is the method that will be called by the swept solver. state - 4D numpy array(t,v,x,y (v is variables length)) iidx - an iterable of indexs arrayTimeIndex - the current time step globalTimeStep - a step counter that allows implementation o...
5,331,376
def rerank(args: argparse.Namespace): """ Reranks a list of hypotheses acoording to a sentence-level metric. Writes all output to STDOUT. :param args: Namespace object holding CLI arguments. """ reranker = Reranker(args.metric) with utils.smart_open(args.reference) as reference, utils.smar...
5,331,377
def test_qualbase(): """-q with low qualities, using ascii(quality+64) encoding""" run("-q 10 --quality-base 64 -a XXXXXX", "illumina64.fastq", "illumina64.fastq")
5,331,378
def modeling_viz_examples(df: pd.DataFrame) -> None: """ Purpose: Shows examples for modeling Args: N/A Returns: N/A """ # classification_report example st.write("Classification Report Example") with st.echo(): fancylit.yellowbrick_funcs.show_classificati...
5,331,379
def AIC_score(y_true, y_pred, model=None, df=None): """ calculate Akaike Information Criterion (AIC) Input: y_true: actual values y_pred: predicted values model (optional): predictive model df (optional): degrees of freedom of model One of model or df is requried """ ...
5,331,380
def to_rgb(data, output=None, vmin=None, vmax=None, pmin=2, pmax=98, categorical=False, mask=None, size=None, cmap=None): """Turn some data into a numpy array representing an RGB image. Parameters ---------- data : list of DataArray output : str file path vmin : float or list...
5,331,381
def id_convert(values, idtype=None): """ Get data from the id converter API. https://www.ncbi.nlm.nih.gov/pmc/tools/id-converter-api/ """ base = 'http://www.pubmedcentral.nih.gov/utils/idconv/v1.0/' params = { 'ids': values, 'format': 'json', } if idtype is not None: ...
5,331,382
def testOneSightline(l=0., b=4., Rv=3.1, useCoarse=False): """Try a single sight line""" # Import the bovy et al. map so we don't have to re-initialize it # for each sight-line combined19 = mwdust.Combined19() los = lineofsight(l, b, objBovy=combined19, Rv=Rv) if useCoarse: los.g...
5,331,383
def authenticate_user(): """Authenticate user""" username = request.form['username'] password = request.form['password'] user = User.query.filter_by(username=username, password=password).first() if user is not None: ma_schema = UserSchema() user_data = ma_schema.dump(user) ...
5,331,384
def map_signature( r_func: SignatureTranslatedFunction, is_method: bool = False, map_default: typing.Optional[ typing.Callable[[rinterface.Sexp], typing.Any] ] = _map_default_value ) -> typing.Tuple[inspect.Signature, typing.Optional[int]]: """ Map the signature of an...
5,331,385
def get_random(X): """Get a random sample from X. Parameters ---------- X: array-like, shape (n_samples, n_features) Returns ------- array-like, shape (1, n_features) """ size = len(X) idx = np.random.choice(range(size)) return X[idx]
5,331,386
def _save_update(update): """Save one update in firestore db.""" location = {k: v for k, v in update.items() if k in _location_keys} status = {k: v for k, v in update.items() if k in _update_keys} # Save location in status to enable back referencing location from a status status["location"] = _locat...
5,331,387
def get_secondary_connections(network, user): """ Finds all the secondary connections (i.e. connections of connections) of a given user. Arguments: network: the gamer network data structure. user: a string containing the name of the user. Returns: A list containing the secondary connecti...
5,331,388
def get_regression_function(model, model_code): """ Method which return prediction function for trained regression model :param model: trained model object :return: regression predictor function """ return model.predict
5,331,389
def signal_handler(signal, frame): """Handler for Ctrl-C""" sys.exit(0)
5,331,390
def beam_motion_banding_filter(img, padding=20): """ :param img: numpy.array. 2d projection image or sinogram. The left and right side of the image should be empty. So that `padding` on the left and right will be used to create an beam motion banding image and be ...
5,331,391
def Din(traceFile, cycle, accessType, memAddress): """ Din: prints the memory reference in the "traditional dinero" format used by the DineroIV cache simulator""" traceFile.write("%d 0x%x\n" % (accessType, memAddress))
5,331,392
def i2c(debug=False, reset=20, req=16): """Yield a i2c device.""" try: yield PN532_I2C(debug=debug, reset=reset, req=req) finally: GPIO.cleanup()
5,331,393
def log(session): """Clear nicos log handler content""" handler = session.testhandler handler.clear() return handler
5,331,394
def load_mnist(path, kind='train'): """Load MNIST data from `path`""" labels_path = os.path.join(path, '%s-labels-idx1-ubyte.gz' % kind) images_path = os.path.join(path, '%s-images-idx3-ubyte.gz' % kind) with gzip.open(labels_path, 'rb') as lbpath: lbpath.read(8) buffer = lbpath.read() ...
5,331,395
def add_barostat(system): """Add Monte Carlo barostat""" system.addForce(mm.MonteCarloBarostat(simulation_parameters["pressure"], simulation_parameters["temperature"]))
5,331,396
def calculate_dvh(dose_grid, label, bins=1001): """Calculates a dose-volume histogram Args: dose_grid (SimpleITK.Image): The dose grid. label (SimpleITK.Image): The (binary) label defining a structure. bins (int | list | np.ndarray, optional): Passed to np.histogram, can be ...
5,331,397
def build_target(output, gt_data, H, W): """ Build the training target for output tensor Arguments: output_data -- tuple (delta_pred_batch, conf_pred_batch, class_pred_batch), output data of the yolo network gt_data -- tuple (gt_boxes_batch, gt_classes_batch, num_boxes_batch), ground truth data ...
5,331,398
def dataframe_with_new_calendar(df: pd.DataFrame, new_calendar: pd.DatetimeIndex): """ Returns a new DataFrame where the row data are based on the new calendar (similar to Excel's VLOOKUP with approximate match) :param df: DataFrame :param new_calendar: DatetimeIndex :return: DataFrame """ ...
5,331,399