content
stringlengths
22
815k
id
int64
0
4.91M
def acknowledge_task(task): """Acknowledge a given task.""" import googleapiclient.discovery # Create a client. client = googleapiclient.discovery.build('cloudtasks', 'v2beta2') body = {'scheduleTime': task['scheduleTime']} client.projects().locations().queues().tasks().acknowledge( n...
5,322,300
def remove_metrics(metrics_in, metric_collection, reduced_set=False, portraitplot=False): """ Removes some metrics from given list Inputs: ------ :param metrics_in: list of string List of metrics. :param metric_collection: string Name of a metric collection. **Optional argum...
5,322,301
def help_package_prompt(help_list, on_select, on_cancel=None): """ Given a list of loaded help indexes, prompt the user to select one of the packages. on_select is invoked with the name of the selected package, while on_cancel is invoked if the user cancels the selection. """ if not help_list: ...
5,322,302
async def test_get_available_devices1(emulator: Emulator, kaleidescape: Kaleidescape): """Test get available devices with single device.""" device = Device(kaleidescape) fields = await device.get_available_devices() assert fields == [LOCAL_CPDID]
5,322,303
def main (args): """usage: promoteParameters.py input-filename output-filename """ if len(args) != 3: print(main.__doc__) sys.exit(1) infile = args[1] outfile = args[2] if not os.path.exists(infile): print("[Error] %s : No such file." % (infile)) sys.exit(1) reader = libsbml.SBMLReade...
5,322,304
def exponential_function(X): """ Benchmark exponential function f(x) = exp(-3x) """ return np.exp(-3 * X)
5,322,305
def _get_firebase_db_url(): """Grabs the databaseURL from the Firebase config snippet. Regex looks scary, but all it is doing is pulling the 'databaseURL' field from the Firebase javascript snippet""" regex = re.compile(r'\bdatabaseURL\b.*?["\']([^"\']+)') cwd = os.path.dirname(__file__) try: ...
5,322,306
def get_user_by_name(name): """通过 name/oname 获取 user 对象,用于导入评论者 Comment只接受User对象 Args: name/oname Returns: user<object>: 用户对象 user_type: 用户类型 """ try: return NaturalPerson.objects.get(name=name).person_id, UTYPE_PER except: pass try: return Organization.objects.ge...
5,322,307
def gen_html(length=10, include_tags=True): """Return a random string made up of html characters. :param int length: Length for random data. :returns: A random string made up of html characters. :rtype: str """ random.seed() html_tag = random.choice(HTML_TAGS) if not include_tags: ...
5,322,308
def format_coco(chip_dfs: Dict, patch_size: int, row_name: str): """ Format train and test chip geometries to COCO json format. COCO train and val set have specific ids. """ chip_height, chip_width = patch_size, patch_size cocojson = { "info": {}, "licenses": [], "categor...
5,322,309
def robust_optimize(ydata, fitfunc, arg_dict, maxiter=10, inmask=None, invvar=None, lower=None, upper=None, maxdev=None, maxrej=None, groupdim=None, groupsize=None, groupbadpix=False, grow=0, sticky=True, use_mad=False, verbose=False, **kwa...
5,322,310
def DAGcon(G, N): """A method to construct a Directed Acyclic graph Parameters ---------- G : The subsumption set. N : The number of nodes. Returns ------- Returns the DAG as a list. """ l = list() caches = list() l_g = sorted(G, key=lambda x: G[x], reverse = True) ...
5,322,311
def authenticate_owner_password(password : 'bytes', encryption_dict : 'dict', id_array : 'list'): """ Authenticate the owner password. Parameters ---------- password : bytes The password to be authenticated as owner password. encryption_dict : dict The dictionary containing ...
5,322,312
def next_neighbors(p, ps, k): """ Function to find the next neighbors for a non-periodic setup This function gives for a value p the k points next to it which are found in in the vector ps Args: p: the current point ps (np.ndarray): the grid with the potential neighbors k (...
5,322,313
def parse_date(datestring): """ Return a datetime for a date string """ try: dt = datetime.strptime(datestring, TIME_FORMAT_FINE) except ValueError: dt = datetime.strptime(datestring, TIME_FORMAT_COARSE) return dt.replace(tzinfo=timezone.utc)
5,322,314
def eigval2(k,aee,aeiaie,aii,see,sei,sii,tau=1,alpha=0): """ smaller eigenvalue of recurrently connected network of E,I units, analytically determined input: k: spatial frequency aee: ampltidue E to E connectivity aeiaie: product of amplitudes of E to I and I to E connectivity aii: ampltidue I to I connectivity...
5,322,315
def test_properties_facade_get_properties_under_at_sub_level(): """ Test calling the `property_names_under` function specifying none of the top level. """ # Arrange config_map = { "upper": { "new_top_level": { "feature": {"enabled": True}, "other_...
5,322,316
def randomize_censored_values(x, lower_bound=None, lower_threshold=None, upper_bound=None, upper_threshold=None, inplace=False, inverse=False, seed=None, lower_power=1., upper_power=1.): """ Randomizes values beyond threshold in x or de-randomizes such formerly randomized val...
5,322,317
def read_fits(filename, params): """ read in the polynomial fit fits file (saved from Extract_Orders.py) and extract using polynomial fits :param filename: string, location and file name of the file containing the polynomial fits (params['poly_fits_file'] by default) :param pa...
5,322,318
def test_status() -> None: """Test status method.""" connect = Connect(connect_url="http://localhost:8083") result = connect.status("influxdb-sink") assert "RUNNING" in result
5,322,319
def cli(ctx, log: bool, interactive: bool): """ Main entry point to micone """ spinner = Spinner(text="Starting up...", spinner="dots", interactive=interactive) spinner.start() ctx.obj["SPINNER"] = spinner spinner.succeed("Successfully initialized micone") if log: LOG.enable() cl...
5,322,320
def IntCurve_PConicTool_NbSamples(*args): """ :param C: :type C: IntCurve_PConic & :rtype: int :param C: :type C: IntCurve_PConic & :param U0: :type U0: float :param U1: :type U1: float :rtype: int """ return _IntCurve.IntCurve_PConicTool_NbSamples(*args)
5,322,321
def nearest_neighbor(graph, restarts=10, weight='weight'): """ Recursive Nearest-Neighbor algorithm to solve the traveling salesman problem. These are the steps of the algorithm for each restart: #. Start on a random node as current node; #. Find the shortest edge connecting the current node with an unvisit...
5,322,322
def update_metrics(metrics, losses, mode, src_seq, tracking_loss=None, batch_level=True): """ Records relevant metrics in the metrics data structure while training. If batch_level is true, this means the loss for the current batch is recorded in addition to the running epoch loss. Parameters --...
5,322,323
def dmet_low_rdm(active_fock, number_active_electrons): """Construct the one-particle RDM from low-level calculation. Args: active_fock (numpy.array): Fock matrix from low-level calculation (float64). number_active_electrons (int): Number of electrons in the entire system. Returns: ...
5,322,324
def reversed_complement(string): """Find the reverse complement of a DNA string. Given: A DNA string Pattern. Return: Pattern, the reverse complement of Pattern.""" complements = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A' } return "".join([complements[string[i]] for i in...
5,322,325
def create_service(scopes): """ Creates a Gmail service based on the credentials.json found in the current directory. """ creds = None if os.path.exists("modules/token.pickle"): with open("modules/token.pickle", "rb") as token: creds = pickle.load(token) if not creds or not...
5,322,326
def package_positions_images(image, position_arr): """ 获取 背包 位置图片 :param image: :param position_arr: :return: """ res = [] for position in position_arr: x1, x2, y1, y2 = position if image is None: res.append(image_util.capture((x1, y1, x2, y2))) else:...
5,322,327
def save(operator, context, filepath, apply_modifiers, separator, default_texture_flag, flip_uv, alt_color, matrix, scale, f15_rot_space, obj=None, **kwargs): """ :param bpy.types.Operator operator: :param context: :param str filepath: :param bool apply_modifiers: :param str s...
5,322,328
def get_checkpoint_path(train_dir, num_iters_ckpt): """ Finds the checkpoint path that corresponds to the num_iters_ckpt. Args: train_dir: string: path to the directory where the checkpoints files are saved. num_iters_ckpt: int: number of training iterations performed when the check...
5,322,329
def CurDatalistCreate(): """ 初始化当前更新列表 """ #todo 加个错误处理 buff_dr_result=ts.get_today_all() cwd = os.getcwd() txtFile = cwd + '\\data\\'+'today_all_data.csv' buff_dr_result.to_csv(txtFile) ''' #UNDEFINE1226 cwd = os.getcwd() txtFile1 = cwd + '\\data\\'+'initli...
5,322,330
def save_to_file(filecontent: str, filename: Path, mode: Optional[str] = 'w') -> None: """Saves string to file.""" with open(filename, mode) as output: output.write(filecontent)
5,322,331
def merge_masks(masks): """ Merge masks for each organ into one ndimage, overlapped pixels will be override by the later class value contours: [num_class, D, H, W] return: merged contour of shape [D, H, W] """ num_class, D, H, W = masks.shape merged_masks = np.zeros((D, H, W), dtype...
5,322,332
def print_subheader(object_type): """ Print out a subheader for a text file. """ return """ ################################################################# # {0} ################################################################# """.format(object_type)
5,322,333
def downloader(download_link, destino,lista=False): """ Função juntando ambas possibilidades de download. """ if lista == False: downloader_file(download_link, destino) else: downloader_lista(download_link,destino)
5,322,334
def get_virtualenv_version(args, python): # type: (EnvironmentConfig, str) -> t.Optional[t.Tuple[int, ...]] """Get the virtualenv version for the given python intepreter, if available, otherwise return None.""" try: cache = get_virtualenv_version.cache except AttributeError: cache = get_vir...
5,322,335
def require_data(PWState, TheAnalyzer): """Defines the transition targets for each involved state. """ variable_db.require("path_iterator") def __door_adr_sequences(PWState): result = ["{\n"] length = 0 for path_id, door_id_sequence in enumerate(PWState.door_id_sequence_lis...
5,322,336
def pad_batch_data(insts, pad_idx=0, return_pos=False, return_input_mask=False, return_max_len=False, return_num_token=False): """ Pad the instances to the max sequence length in batch, and generate the correspond...
5,322,337
def tuisavefile(filename): """ Save the Energyplus file """ global data Prompt='Would you like to save this file ?' Action = tui1.RadioButtons("Choose an action",( ("Save",1),("Save As",2),("Quit",3) )) if Action==3: return if Action==1: mylib1.writeStr2File(filename,`data`) return Prompt='Choose new fil...
5,322,338
def test_create_affiliation_exists(session, auth_mock): # pylint:disable=unused-argument """Assert that an Affiliation can not be created affiliation exists.""" entity_service1 = factory_entity_service(entity_info=TestEntityInfo.entity_lear_mock) entity_dictionary1 = entity_service1.as_dict() business_...
5,322,339
def push2d(inp, g, shape: Optional[List[int]], bound: List[Bound], extrapolate: int = 1): """ inp: (B, C, iX, iY) tensor g: (B, iX, iY, 2) tensor shape: List{2}[int], optional bound: List{2}[Bound] tensor extrapolate: ExtrapolateType returns: (B, C, *shape) tensor """ dim ...
5,322,340
def weightfunction(obs_id, local_time, date, weight): """ Show plot of target weighting function with respect to tot_time. Parameters ---------- obs_id : string Unique observation identifier local_time : array of strings or 'astropy.tot_time.core.Time' array Time grid of local ...
5,322,341
def _iter_folder(folder: Path, recursive: bool) -> Iterator[Path]: """Yield .py files and subfolders (packages) in a folder. We do a breadth-first search so parents are imported first. """ folders = deque([folder]) while folders: for path in folders.popleft().iterdir(): if path....
5,322,342
def condor_tables(sqlContext, hdir='hdfs:///project/monitoring/archive/condor/raw/metric', date=None, verbose=False): """ Parse HTCondor records Example of HTCondor recornd on HDFS {"data":{"AccountingGroup":"analysis.wverbeke","Badput":0.0,"CMSGroups":"[\"/cms\"]","CMSPrimaryDataTier":...
5,322,343
def generate_pddl_problems(args): """Generate randomly sampled pick and place PDDL problems as per the specified args parameters. """ # PDDLGym domain parser domain = PDDLDomainParser(args.domain, expect_action_preds=False, operators_as_actions=True) domain_version = domain.domain_name.replace('task...
5,322,344
def _contiguous_groups( length: int, comparator: Callable[[int, int], bool] ) -> List[Tuple[int, int]]: """Splits range(length) into approximate equivalence classes. Args: length: The length of the range to split. comparator: Determines if two indices have approximately equal it...
5,322,345
def datatype_derive(times, series): """ returns series converted to datatype derive store only differeces between two subsequent values parameters: series <tuple> of <float> returns: <tuple> of <float> """ new_series = [0.0, ] for index in range(1, len(series)): new_ser...
5,322,346
def ajax_delete_entry(request): """Asynchronously deletes an entry This method is for RUSERs who wish to delete a single entry from their TrackingEntries. This method is only available via ajax and obviously requires that users be logged in. We then create our json_data map to hold our success sta...
5,322,347
def mni152_to_civet(img, civet_density='41k', method='linear'): """ Projects `img` in MNI152 space to CIVET surface Parameters ---------- img : str or os.PathLike or niimg_like Image in MNI152 space to be projected civet_density : {'41k'}, optional Desired output density of CIVE...
5,322,348
def main(output_path=None): """Writes out new python build system This is needed because CircleCI does not support build matrices nor parameterisation of cache paths or other aspects of their config There's also the added bonus of validating the yaml as we go. Additionally, we template and wr...
5,322,349
def get_rotational_part(trans): """ Get the :math:`d×d` rotational part of a :math:`(d+1)×(d+1)` transformation matrix. Parameters ---------- trans : array_like The given transformation matrix. Returns ------- numpy.ndarray The rotational part, with potential scaling re...
5,322,350
def imitation_terminal_condition(env, dist_fail_threshold=1.0, rot_fail_threshold=0.5 * np.pi): """A terminal condition for motion imitation task. Args: env: An instance of MinitaurGymEnv dist_fail_threshold: Max distance the simulated chara...
5,322,351
def main(): """ Syncs users from Google Workspace to Fresh Service(adds new, deletes old). Adds users to their respective requester groups in FreshService """ # create Google service for API calls creds = authorize() service = build('admin', 'directory_v1', credentials=creds) # create ...
5,322,352
def polySubdivideEdge(q=1,e=1,cch=1,ch=1,dv="int",n="string",nds="int",s="linear",ws=1): """ http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/polySubdivideEdge.html ----------------------------------------- polySubdivideEdge is undoable, queryable, and editable. Subdivides an edge into...
5,322,353
def iproute2_is_vrf_capable(): """ Checks if the iproute2 version installed on the system is capable of handling VRFs by interpreting the output of the 'ip' utility found in PATH. Returns True if capability can be detected, returns False otherwise. """ if is_linux(): try: s...
5,322,354
def cleanRepl(matchobj): """ Clean up a directory name so that it can be written to a matplotlib title without encountering LaTeX escape sequences Replace backslashes with forward slashes replace underscores (subscript) with escaped underscores """ if matchobj.group(0) == r'\...
5,322,355
def bitcoinAddress2bin(btcAddress): """convert a bitcoin address to binary data capable of being put in a CScript""" # chop the version and checksum out of the bytes of the address if ":" in btcAddress: pfx, addr = btcAddress.split(":") decoded = cashaddrutil.b32decode(addr) if not c...
5,322,356
def StartITMAgent(TargetServerIP,TargetServerUsername,TargetServerPasswd,StartCommand=r'/itm/bin/itmcmd agent start ux um'): """ Start ITM Agent return: exitCode: 0: success 1: connection error 2: command error commandOutput: output """ ...
5,322,357
def final_plot_beam_values(surveys,zDMgrid, zvals,dmvals,pset,binset,names,logsigma,logmean,outdir): """ For each survey, get the beamshape, and plot it vs the dots on the one plot """ # hard-coded best values method=2 thresh=0 # does this for each survey # for lat50, FE, and Parkes ...
5,322,358
def remove_setuptools(): """ Remove setuptools from the current environment. """ print("Removing setuptools") cmd = [sys.executable, '-m', 'pip', 'uninstall', '-y', 'setuptools'] # set cwd to something other than '.' to avoid detecting # '.' as the installed package. subprocess.check_cal...
5,322,359
def table_check(self, arithmetic_func, expected_result, int_type, min, max, node=None): """Check that arithmetic functions work using tables with Int128, UInt128, Int256, and UInt256. """ if node is None: node = self.context.node table_name = f'table_{getuid()}' with Given(f"I have a tabl...
5,322,360
def metadata(ctx,_overwrite=False): """ update all metadata xml files """ print ("Importing Categories") category_dict={} with open(ctx.category, 'r')as category_file: category_csv = csv.DictReader(category_file,dialect='excel',delimiter=';') for row in category_csv: ...
5,322,361
def set_submission_error_msg(config, submission_id, error_msg): """ Set submission message error Parameters ---------- config : dict configuration submission_id : int id of the requested submission error_msg : str message error """ # Create database url ...
5,322,362
def parse_arguments(): """ Parse command line argument and construct the DNN :return: a dictionary comprising the command-line arguments """ # define the program description text = 'Coverage Analyzer for DNNs' # initiate the parser parser = argparse.ArgumentParser(description=text) ...
5,322,363
def cost_matrix(gdf, dist_3d_matrix, line_bc,resolution,Rivers_option): """ Creates the cost matrix in €/km by finding the average weight between two points and then multiplying by the distance and the line base cost. :param gdf: Geodataframe being analyzed :param dist_3d_matrix: 3D distance matrix ...
5,322,364
def test_append_different_priorities_2(pq): """Value at first position should be 0.""" pq.insert(1, 2) pq.insert(0, 10) assert pq._priority[0].head.val == 0
5,322,365
def test_output_lists_equal(): """check that the length of the first list is equal to the output of the second list""" stats = shapiro_wilk(data) assert len(stats[0]) == len(stats[1])
5,322,366
def home(): """ The home page that asks for user input. """ return render_template('index.html')
5,322,367
def info(ctx): """Print current edition information""" config = get_configuration_or_quit(ctx.obj['settings_path']) try: metadata = EditionMetaData.from_existed_project(config.get_project_root()) except MetadataNotFound: logger.critical("No metadata file found in project root, please act...
5,322,368
def tanh(x): """ Computes hyperbolic tangent of x element-wise. Parameters ---------- x : tensor Must be one of the following types: bfloat16, half, float32, float64, complex64, complex128. Returns ------- A Tensor. Has the same type as x. """ _tanh = ms.ops.Tanh()...
5,322,369
def all_directions(): """ :return: Returns all the available directions. """ return dt.groups.keys()
5,322,370
def determine_result(image, reference, result): """ Determine a test result against a reference and thresholds. Args: image (TestImage): The image being compressed. reference (Record): The reference result to compare against. result (Record): The test result. Returns: R...
5,322,371
def save_as_qdp(arrays, errors=None, filename="out.qdp"): """Save arrays in a QDP file. Saves an array of variables, and possibly their errors, to a QDP file. Parameters ---------- arrays: [array1, array2] List of variables. All variables must be arrays and of the same length. errors: ...
5,322,372
def str2period(x, tostring=False): """ Convert string into pandas.Period ex) 99991231 -> 9999-12-31 """ if x is not None: ret = pd.Period(year=x // 10000, month=x // 100 % 100, day=x % 100, freq='D') else: ret = None if tostring and ret is not None: ret = str(ret) ...
5,322,373
def webauthn_begin_assertion(): """ This url is called when the authentication process begins """ username = request.form.get("login_username") if not util.validate_username(username): return make_response(jsonify({"fail": "Invalid username."}), 401) credentials = database.get_credentia...
5,322,374
def add_new_repository(user, full_name, githubprofile_service, commit_service): """ Register a new repository and all your commits from last month Raises: github.UnknownObjectException GitHubProfile.DoesNotExists RepositoryNotBelongToUserException Returns: (Repository) created ...
5,322,375
def register_omitted_classes(models): """ Register classes that don't have an own admin yet. Example: register_omitted_classes(some_app.models) """ # This can be improved for fields that are only not creatable but are updateable or viceversa. for mdl in models.__dict__.values(): ...
5,322,376
def project(ctx, name, file_path, verbose): """ Creates a new FTL project """ if verbose: click.echo(YELLOW(f'<-->\nname:{name}\nfile_path:{file_path}\n<-->')) proj_path_root = os.path.join(file_path, name) click.echo(f'proj_path_root:{proj_path_root}') try: os.makedirs(proj_...
5,322,377
def case_copy(request): """ 复制case :param request: :return: """ user_id = request.session.get('user_id', '') if not get_user(user_id): request.session['login_from'] = '/base/case/' return HttpResponseRedirect('/login/') else: if request.method == 'GET': ...
5,322,378
def get_node_config(node_dir, key): """ This function retrieves a setting from the indigo node configuration. """ return exec_node_command(node_dir, "config", "get", key)
5,322,379
def get_argparser(): """ Returns an argument parser for this script """ parser = ArgumentParser(description='Fit a U-Time model defined in' ' a project folder. Invoke ' '"ut init" to start a new project.') parser.add_arg...
5,322,380
def _deep_different(left, right, entry): """ checks that entry is identical between ZipFile instances left and right """ left = chunk_zip_entry(left, entry) right = chunk_zip_entry(right, entry) for ldata, rdata in izip_longest(left, right): if ldata != rdata: return Tr...
5,322,381
def _save_as_pickle(to_pickle, path): """Save features as pickle""" with open(path, 'wb') as f: pickle.dump(to_pickle, f)
5,322,382
def plot_pointingtable(pt_list, plot_file, title, **kwargs): """ Standard plot of pointing table :param pt_list: :param plot_file: :param title: :param kwargs: :return: """ plt.clf() r2a = 180.0 * 3600.0 / numpy.pi rms_az = 0.0 rms_el = 0.0 num = 0 for pt in pt_l...
5,322,383
def test_xscov_asymmetric(text_cov_lb5_asym): """Check that `XsCov` raises error because matrix non symmetric""" tape = sandy.formats.endf6.Endf6.from_text(text_cov_lb5_asym) with pytest.raises(Exception): return sandy.XsCov.from_endf6(tape)
5,322,384
def segment(img, img_bg, img0_sigma=5, img0_min_size=300, img0_min_distance=50, img0_thresh_bg=500, img0_min_size_bg=10_000, img0_dilation=5): """Standard DAPI / nuclear based cellular segmentation. Args: img (np.array): Image array with nuclear labeling. img_bg (np.array): Image to be used for...
5,322,385
def get_parsing_function(input_format: Optional[str], filename: str) -> Callable: """Return appropriate parser function based on input format of file. :param input_format: File format :param filename: Filename :raises Exception: Unknown file format :return: Appropriate 'read' function """ i...
5,322,386
def process_proto_file(proto_file) -> Iterable[OutputFile]: """Generates code for a single .proto file.""" _, package_root = build_node_tree(proto_file) output_filename = _proto_filename_to_generated_header(proto_file.name) generator = RawCodeGenerator(output_filename) codegen.generate_package(pro...
5,322,387
def custom_resampler(array_like): """calculating heat index using monthly values of temperature.""" return np.sum(np.power(np.divide(array_like, 5.0), 1.514))
5,322,388
def make_nhwc(batch, c=3): """Makes a NxHxW(x1) tensor NxHxWxC, written in graph mode. """ # Assert 3D or 4D n_dims = tf.rank(batch) assert_op = tf.debugging.Assert( tf.logical_or(tf.equal(n_dims, 3), tf.equal(n_dims, 4)), [n_dims]) # If necessary, 3D to 4D wit...
5,322,389
def review_bkdata_data_id(): """ 检测采集项bkdata_id: 处理未同步到数据平台的data_id """ toggle_switch = FeatureToggleObject.switch(name=FEATURE_BKDATA_DATAID) if not toggle_switch: return collector_configs = CollectorConfig.objects.filter(bkdata_data_id__isnull=True) for collector_config in collecto...
5,322,390
def word_window(sequence: str, target: str, size: int) -> Union[Tuple[List[str], List[str]], None]: """ Retrieves word windows of 'size' to the left and 'size' to the right. If size == 0: Take the entire sequence as window """ assert size >= 0 tokens = word_tokenize(sequence.lower()) if targ...
5,322,391
def get_pheonix_restaurants(): """ Get All Phoenix restaurant. Returns: All Phoenix restaurants as a list of restaurant dictionaries objects. """ return get_restaurants("Phoenix", PHOENIX_RESTAURANTS_PATH)
5,322,392
def get_p_detect_small_jurisdictions(end_date): """ Apply a scaling to the daily reported cases by accounting for a ~75% detection probability pre 15/12/2021 and 0.5 following that. To improve the transition, we assume that detection probability decreases from 0.75 to 0.5 over 7 days beginning 9/12/202...
5,322,393
def f(x): """ Compute function value. """ return np.sin(x)
5,322,394
def _arnoldi_step(j, V_v, H_s, A, A_inv, precision): """ Performs an iteration of the Arnoldi process: - A new Krylov vector new_v = (A @ A_inv) @ V_v[:, j] is computed. - new_v is orthogonalized against the columns of V_v, yielding the orthogonalized vector orth_v along with new overlaps. - orth_v ...
5,322,395
def get_papers(): """Get papers discussing COVID-19 treatments Returns ------- DataFrame dataframe of treatment documents """ def count_treatments(df): # TODO: normalize by text length? return df["text"].str.count(RE_TOPIC) return filter_docs_by_count(count_treatmen...
5,322,396
def calculate_speed(ds): """Calculate speed on the central (T) grid. First, interpolate U and V to the central grid, then square, add, and take root. Parameters ---------- ds : xarray dataset A grid-aware dataset as produced by `xorca.lib.preprocess_orca`. Returns ------- ...
5,322,397
def image_preprocessing(image_path, preprocess_input, target_size): """ Read and preprocess an image from disk. Args: image_path (str): path to the image. preprocess_input (funciton): a preprocessing function. target_size (tuple): image target size. Returns: np.ndarray:...
5,322,398
def publish_host_update(instance): """ Publish information about DC Host updates using DCHost API serializer. """ if settings.HERMES_HOST_UPDATE_TOPIC_NAME: logger.info( 'Publishing host update for {}'.format(instance), extra={ 'type': 'PUBLISH_HOST_UPDATE...
5,322,399