content
stringlengths
22
815k
id
int64
0
4.91M
async def async_get_maker_for_service(hass, service): """Get coffee maker to be used for specified service.""" device_id = None key = 'device_id' if key in service.data: device_id = service.data.get(key)[0] _LOGGER.info(f'Found target: {device_id}') device = None if device_id is...
5,320,000
def make_deferred_related(factory, fixture, attr): """Make deferred function for the related factory declaration. :param factory: Factory class. :param fixture: Object fixture name e.g. "book". :param attr: Declaration attribute name e.g. "publications". :note: Deferred function name results in "b...
5,320,001
def triple_grad_check(x, y, x_init=None, y_grads=None, x_grads_grads=None, place=None, program=None, eps=1e-6, atol=1e-5, ...
5,320,002
def test_shifted_within_year_ffill(): """Test for this.""" pass
5,320,003
def getbrowser(): """ Get the name of the browser currently being used """ # Try to find the browser try: # Get the browser name webbrowser.get(using=None) # Catch an error except RuntimeError: # Return nothing return None
5,320,004
def minimize_bias_geodetic(x, gd_mb=None, mb_geodetic=None, h=None, w=None, pf=2.5, absolute_bias=False, ys=np.arange(2000, 2019, 1), oggm_default_mb = False, **kwargs): """ calibra...
5,320,005
def turn_on_win_ops_with_associated_p(): """Turn on the global state of win operations with associated p. If it is state is on, all win ops such as put, update, accumulate also apply on the associated p value as well. The default state is off. """ mpi_lib.bluefog_torch_set_win_ops_with_associat...
5,320,006
def unpack_big_integer(binary_string): """ Convert a byte string into an integer. Akin to a base-256 decode, big-endian. """ if len(binary_string) <= 8: return unpack_big_integer_by_struct(binary_string) # NOTE: 1.1 to 4 times as fast as unpack_big_integer_by_brute() else: ...
5,320,007
def test_compare_convert_dims(dim1, dim2, is_equal): """Tests __eq__ function for comparing 2 SharedDims.""" dim1 = SharedDim.from_tiledb_dim(dim1) dim2 = SharedDim.from_tiledb_dim(dim2) if is_equal: assert dim1 == dim2 else: assert dim1 != dim2
5,320,008
def ndrange(slice_list): """ Generator that creates an N-dimensional for loop in Python. :param slice_list: Slice or list of slices (as tuples or `slice`s) to loop over. :return: N-dimensional loop index generator. """ if not isinstance(slice_list, list): n...
5,320,009
def file_uploader_helper(file) -> tuple: """ file upload helper function :param file: :return: """ temp_folder = os.path.join(os.getcwd(), 'temp') if not os.path.isdir(temp_folder): try: os.mkdir(temp_folder) except OSError: raise OSError(f'Cannot crea...
5,320,010
def extractLineFromTarget(**kwargs): """ based on the corridor and the related points, extract lines from original point clouds. """ img_buffer = kwargs['img_buffer'] min_xyz = kwargs['min_xyz'] cellsize = kwargs['cellsize'] pts_target = kwargs['pts_target'] # deep copy of the original data ...
5,320,011
def contract_expanded_and_prob_pattern_nodes( product: ProductNode ) -> ProductNode: # P(A and B) = P(A when B) * P(B) """Contract expanded And Probability pattern nodes ` P(Y) * P(X when Y) = P(X and Y)` in `product` >>> contract_expanded_and_prob_pattern_nodes(1.5 * N(P(A when B)) * N(P(B))) ...
5,320,012
def get_api_data(quote, date_range): """request to API with error check Error message if any of query params are invaild Note if API call limit is reached""" print(API_URL.format(date_range, quote)) data = requests.get(API_URL.format(date_range, quote)).json() if "Error Message" in data: ...
5,320,013
def find_module_path_and_all(module: str, pyversion: Tuple[int, int], no_import: bool, search_path: List[str], interpreter: str) -> Optional[Tuple[str, Optional[List[st...
5,320,014
def test_lfs_hook_can_be_avoided(runner, project, subdirectory, large_file): """Test committing large files to Git.""" result = runner.invoke( cli, [ '--no-external-storage', 'dataset', 'add', '-c', 'my-dataset', str(large_file) ] ) assert 0 == result.exit_code ...
5,320,015
def solve_TLS_Ab(A, b): """Solve an overdetermined TLS system by singular value decomposition. """ ## solve by SVD U, W, Vt = linalg.singular_value_decomposition(A, full_matrices=0) V = numpy.transpose(Vt) Ut = numpy.transpose(U) ## analyze singular values and generate smallness cutoff ...
5,320,016
def FixCentralTensorCalculateAuxiliaryTensor(ori_tensor_set, ori_matrix, mpo_input_shape, mpo_output_shape, ranks): """ In put tensor set product by matrix2MPO, and New_matrix. return the central tensor when auxiliary tensor was fixed. We assumes n = 5 """ ori_matrix = torch.from_numpy(ori_matr...
5,320,017
def AddEntryPoint(ordinal, ea, name, makecode): """ Add entry point @param ordinal: entry point number if entry point doesn't have an ordinal number, 'ordinal' should be equal to 'ea' @param ea: address of the entry point @param name: name of the entry point. If null...
5,320,018
def goodsEditSkuChannel(skuId,regionId): """ :param skuId: :param regionId: :return: """ reqUrl = req_url('goods', "/sku/updateGroup") if reqUrl: url = reqUrl else: return "服务host匹配失败" headers = { 'Content-Type': 'application/json', 'X-Region-Id': re...
5,320,019
def poly(x, y, order, rej_lo, rej_hi, niter): """linear least square polynomial fit with sigma-clipping""" # x = list of x data # y = list of y data # order = polynomial order # rej_lo = lower rejection threshold (units=sigma) # rej_hi = upper rejection threshold (units=sugma) # niter = num...
5,320,020
def check_watched_dir(): """ A celery task that runs and moves files in WATCHED_DIR via the blind_media_move function :return: None """ media_files = recursive_extract_files(WATCHED_DIR) if len(media_files) > 0: for item in media_files: item_path = os.path.join(WATCHED_DIR, i...
5,320,021
def on_step_start(func): """A function decorator that wraps a Callable inside the NeMoCallback object and runs the function with the on_step_start callback event. """ class NeMoCallbackWrapper(NeMoCallback): def __init__(self, my_func): self._func = my_func def on_step_star...
5,320,022
def training_helper(sim, generator): """A Helper function to fine-tune MNIST model""" g = sim.session.graph sess = sim.session with g.as_default(): x = sim.session.graph.get_tensor_by_name("reshape_input:0") y = g.get_tensor_by_name("labels:0") fc1_w = g.get_tensor_by_name("dense...
5,320,023
def create_image(disk_format, path, size): """Create a disk image :param disk_format: Disk image format (as known by qemu-img) :param path: Desired location of the disk image :param size: Desired size of disk image. May be given as an int or a string. If given as an int, it will be int...
5,320,024
def to_npy(csv_path): """ Convert csv to npy; save it and a np array containing the indexes. Inputs: csv_path : path to the csv with the node degree Return: None Files generated: npy files : np.array containing the transposed csv converted to npy, stored in .../np...
5,320,025
def reindent_docstring(node, indent_level=1, smart=True): """ Reindent the docstring :param node: AST node :type node: ```ast.AST``` :param indent_level: docstring indentation level whence: 0=no_tabs, 1=one tab; 2=two tabs :type indent_level: ```int``` :param smart: Smart indent mode, if ...
5,320,026
def test_calculate_bonds_with_constant_delta_method_with_default_param(): """ Calculate bonds with the constant_delta method without providing a value for param and check the expected failure. """ molecule = mogli.read('examples/dna.xyz')[0] with pytest.raises(ValueError): molecule.calcu...
5,320,027
def _set_mofa_data_from_mudata( model, mdata, groups_label=None, use_raw=False, use_layer=None, likelihoods=None, features_subset=None, save_metadata=None, use_obs=None, ): """ Input the data in MuData format PARAMETERS ---------- model: MOFA+ model entry point o...
5,320,028
def xyz(x, y, z): """Construct a Toyplot color from CIE XYZ values, using observer = 2 deg and illuminant = D65.""" x = x / 100.0 y = y / 100.0 z = z / 100.0 r = x * 3.2406 + y * -1.5372 + z * -0.4986 g = x * -0.9689 + y * 1.8758 + z * 0.0415 b = x * 0.0557 + y * -0.2040 + z * 1.0570 r...
5,320,029
def pydantic_input_validation( action_input: Dict[str, Any], validator: Type[BaseModel] ) -> None: """ Validate input using the pydantic model itself. Raises a BadActionRequest exception if the input is incorrect. """ try: validator(**action_input) except ValidationError as ve: ...
5,320,030
def model_fit(df, city, target, outlier=False, remove_features=False, classifier=False): """ plot n importante feature of a model INPUT: df - DataFrame city - city to subset target - target variable outlie...
5,320,031
def _is_large_prime(num): """Inefficient primality test, but we can get away with this simple implementation because we don't expect users to be running print_fizzbuzz(n) for Fib(n) > 514229""" if not num % 2 or not num % 5: return False test = 5 while test*test <= num: if not nu...
5,320,032
def cleanup_code(content: str): """Automatically removes code blocks from the code.""" # remove ```py\n``` if content.startswith('```') and content.endswith('```'): return '\n'.join(content.split('\n')[1:-1]) # remove `foo` return content.strip('` \n')
5,320,033
def name_generator(identifier: str= "") -> str: """ Generates a unique name. :param identifier: identifier to add to the name :return: the generated name """ return f"thrifty-builder-test-{identifier}{uuid4()}"
5,320,034
def merge_fcs(fcs, merged_fc, gdb): """combines like geometries into a feature class""" desc = arcpy.Describe(os.path.join(gdb, fcs[0])) if arcpy.Exists(merged_fc): arcpy.Delete_management(merged_fc) ifc = arcpy.CreateFeatureclass_management(out_path=os.path.dirname(merged_fc), ...
5,320,035
def _ssim_for_multi_scale(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, k1=0.01, k2=0.03): """Calculate SSIM (structural similarity) and contrast s...
5,320,036
def index(request): """ :param request: :return: """ panel = True # auto login for test users user = authenticate(username='admin', password='Aa1234567890') login(request, user) return render(request, "back/index.html", locals())
5,320,037
def test_load_problem(tmp_path: str, square: Problem[int]) -> None: """Test that load_problem loads square correctly.""" path = pathjoin(tmp_path, "problem.pckl") with open(path, "wb") as file: dump(square, file) square_loaded: Problem[int] = load_problem(tmp_path, "problem.pckl") square_l...
5,320,038
def _check_positive(name: str, value: int) -> bool: """Checks that `value` is positive.""" if value <= 0: raise ValueError(f'Expected a positive value for {name}, found {value}.')
5,320,039
def membersof(parser, token): """ Given a collection and a content type, sets the results of :meth:`collection.members.with_model <.CollectionMemberManager.with_model>` as a variable in the context. Usage:: {% membersof <collection> with <app_label>.<model_name> as <var> %} """ params=token.split_contents(...
5,320,040
def ext_s(variable, value, substitution): """ext_s is a helper function for eq, without checking for duplicates or contradiction it adds a variable/value pair to the given substitution. `unify` deals with all of the related verification. @param variable: A LogicVariable @param value: A value that c...
5,320,041
def sc_fermi_sub_wrap( calc, non_native, native, stoich, non_native_limit, native_limit, im_cor, charge ): """ sc_fermi_sub_wrap determines the formation energy of a substitutional defect, and formats a 'ChargeState' object to be fed into sc_fermi args: calc = DFT calculation summary of the defective materi...
5,320,042
def _include_matcher(keyword="#include", delim="<>"): """Match an include statement and return a (keyword, file, extra) duple, or a touple of None values if there isn't a match.""" rex = re.compile(r'^(%s)\s*%s(.*)%s(.*)$' % (keyword, delim[0], delim[1])) def matcher(context, line): m = rex.ma...
5,320,043
def cod_converter(cod_decimal_string): """ From a decimal value of CoD, map and retrieve the corresponding major class of a Bluetooth device :param cod_decimal_string: numeric string corresponding to the class of device :return: list of class(es) """ if not cod_decimal_string or cod_decimal_string...
5,320,044
def get_params(ntrain, EXP_NAME, order, Nside, architecture="FCN", verbose=True): """Parameters for the cgcnn and cnn2d defined in deepsphere/models.py""" n_classes = 2 params = dict() params['dir_name'] = EXP_NAME # Types of layers. params['conv'] = 'chebyshev5' # Graph convolution: chebysh...
5,320,045
def add_newdoc(name: str, value: str, doc: str) -> None: """Append ``_docstrings_list`` with a docstring for `name`. Parameters ---------- name : str The name of the object. value : str A string-representation of the object. doc : str The docstring of the objec...
5,320,046
def historify( X: np.ndarray, history_len: int, ): """Generate (num_histories, history_len, input_dim) history from time series data Todo: * Implement striding Warning: * This converts back and forth between jnp and np, which is fine for CPU, but may cause issues if we need to ...
5,320,047
def _gen_snapshot(queue, timeout=0.1, max_get_attempts=3): """ Yield a list of all items currently on the queue. Wait timeout seconds to avoid hammering the cpu. Repeat unless queue was empty max_get_attempts times in a row. """ n_get_attempts = 0 while True: n_get_attempts += 1 ...
5,320,048
def test_remote(): """ Grabs a path from the web paths queue, add it to the target website's base path, and then attempt to retrieve it. If the file is successfully retrieved, the HTTP status code and full path to the file is outputted. """ while not web_paths.empty(): path = web_paths.g...
5,320,049
def do_insert(csvfile, sqlitedb): """ Connects to the database and inserts all the data of the csvfile. """ con = sqlite3.connect(sqlitedb) data = pd.read_csv(csvfile, skiprows=1) for index, row in data.iterrows(): mapped_row = map_to_existing_names(row) insert_into_sqlite...
5,320,050
def test_service__init__service_can_be_constructed_with_just_service_path(): """ Make sure the only thing the Service Class needs is a service_path. """ service = Service(DO_NOTHING_PATH) service.run_service() service.stop_service()
5,320,051
def lcs(l1, l2, eq=operator.eq): """Finds the longest common subsequence of l1 and l2. Returns a list of common parts and a list of differences. >>> lcs([1, 2, 3], [2]) ([2], [1, 3]) >>> lcs([1, 2, 3, 3, 4], [2, 3, 4, 5]) ([2, 3, 4], [1, 3, 5]) >>> lcs('banana', 'baraban') (['b', 'a', '...
5,320,052
def get_data_sequences(project_dir, hparams, logger, args): """ Loads training and validation data as specified in the hyperparameter file. Returns a batch sequencer object for each dataset, not the ImagePairLoader dataset itself. The preprocessing function may make changes to the hparams dictionar...
5,320,053
def __give_team_number(df: pd.DataFrame): """Adds the number to the team names""" stats = df.groupby("Team")["Amount"].sum() for team, amount in stats.iteritems(): df.Team.replace("^" + team + "$", f"{team} ({amount})", inplace=True, regex=True)
5,320,054
def request_factory(environ): """Factory function that adds the headers necessary for Cross-domain calls. Adapted from: http://stackoverflow.com/questions/21107057/pyramid-cors-for-ajax-requests Copied from mtholder/pyraphyletic """ request = Request(environ) _LOG.debug('trunctated reque...
5,320,055
def tick_payload(): """ Payload for tick """ data = TickEvent(tick_type=TickType.FULL).json() return { "context": { "eventId": "some-eventId", "timestamp": "some-timestamp", "eventType": "some-eventType", "resource": "some-resource", }, ...
5,320,056
def calc_sparsity(optimizer, total_params, total_quant_params): """ Returns the sparsity of the overall network and the sparsity of quantized layers only. Parameters: ----------- optimizer: An optimizer containing quantized model layers in param_groups[1]['params'] and non-quantized...
5,320,057
def get_pck_normalized_joint_distances(gt_array: np.ndarray, pred_array: np.ndarray, visible_array: np.array, threshold, ref_distances): """ n = number of records :param gt_array: (n, num_joints, 2) :param pred_array: (n, num_joints, 2) :param visible_array: (n, num_joints) # 0 if invisible, 1 if vi...
5,320,058
def dict_to_header_arrays(header=None, byteorder='='): """ Returns null hf, hi, hs arrays, optionally filled with values from a dictionary. No header checking. :param header: SAC header dictionary. :type header: dict :param byteorder: Desired byte order of initialized arrays (little, nativ...
5,320,059
def swapKeys(d,keySwapDict): """ Swap keys in dictionary according to keySwap dictionary """ dNew = {} for key, keyNew in keySwapDict.iteritems(): if key in d: dNew[keyNew] = d[key] for key in d: if key not in keySwapDict: dNew[key] = d[key] return dN...
5,320,060
def render_pyramid(pyr, levels): """ Renders a big image of horizontally stacked pyramid levels :param pyr: Gaussian or Laplacian pyramid :param levels: number of levels to present in the result <= max_levels :return: single black image with pyramid levels stacked horizontally """ pyr[0] = (...
5,320,061
def test_scatter_plot(): """ Test plot of predicted electric conductivity as a function of the mole fractions. Input ----- x_vals : numpy vector x-axis (mole fractions) y_vals : numpy vector y-axis (predicted conductivities) x_variable : string for labeling the x-axis Returns -...
5,320,062
def add_steam_appid_txt(ctx): """Add steam_appid.txt for testing.""" osx_app = ctx['osx_app'] steam_appid = ctx['steam_appid'] osx_steam_appid_txt = f'{osx_app}/Contents/MacOS/steam_appid.txt' with open(osx_steam_appid_txt, 'wt') as f: f.write(f'{steam_appid}') old = {k for k in ctx} ...
5,320,063
def networkx2pandas(current_graph, input_type): """Converting current graph into a pandas data frame :param: current_graph: a python dict containing all paths :param: input_type: the semantic type of the input """ data = [] for paths in current_graph.values(): for path in paths: ...
5,320,064
def test_collection_pages_are_list_of_page_objects_if_paginated_is_False(): """If a collection.paginated is false, then collection.pages should be a flat list""" page_1 = page_2 = page_3 = page_4 = page_5 = Page() not_paginated = [page_1, page_2, page_3, page_4, page_5] class TestCollection(Colle...
5,320,065
def assemble_matrix(form: _fem.FormMetaClass, constraint: Union[MultiPointConstraint, Sequence[MultiPointConstraint]], bcs: Sequence[_fem.DirichletBCMetaClass] = [], diagval: _PETSc.ScalarType = 1, A: _...
5,320,066
def getLayers(model): """ get each layer's name and its module :param model: :return: each layer's name and its module """ layers = {} root = '' def unfoldLayer(model, root): """ unfold each layer :param model: the given model or a single layer ...
5,320,067
def usage(script_name): """Print basic usage help""" print """ Usage: %s -m MM -y YYYY Produces .pdf reports for all clients of all threats found during the month specified. Mandatory arguments to long options are mandatory to short form as well. -m, --month=MM Desired month in two digit format, i.e....
5,320,068
def redeploy(): """ Implements redeploy handle Runs docker-compose pull and up commands for specified service Service must be preconfigured with yml file in SERVICES_DIR Docker URL can be configured with DOCKER_URL option """ service = request.args.get("service", type=str) if not service...
5,320,069
def unittests(): """ Short tests. Runs on CircleCI on every commit. Returns everything in the tests root directory. """ test_loader = unittest.TestLoader() test_suite = test_loader.discover('tests') test_suite = _circleci_parallelism(test_suite) return test_suite
5,320,070
def get_weekly_forecasts(country_code, zip_code): #for the web app examining trends """ Fetches the weekly data from the Weather.gov API, for a given country and zip code. Params: country_code (str) the requested country, like "US" zip_code (str) the requested postal code, like "20057" ...
5,320,071
def parse_nml(string, ignore_comments=False): """ parse a string namelist, and returns a list of param bundles with four attrs: name, value, help, group """ group_re = re.compile(r'&([^&]+)/', re.DOTALL) # allow blocks to span multiple lines array_re = re.compile(r'(\w+)\((\d+)\)') # string_re ...
5,320,072
def glo2loc_2D(c,s): """ Build rotation matrix from global to local 2D coordinate system. ------- Inputs: c: cosine in radian of the angle from global to local coordinate system s: sine in radian of the angle from global to local coordinate system ------- Output: R_m: rotation matrix...
5,320,073
def model_scatter_2d(c=1500, dc=150, freq=25, dx=5, dt=0.0001, nx=[50, 50], propagator=None, prop_kwargs=None): """Create a point scatterer model, and the expected waveform at point, and the forward propagated wave. """ nx = np.array(nx) model = np.ones(nx, dtype=np.float32) ...
5,320,074
def contours_and_bounding_boxes(bw_image, rgb_image): """Extract contours and bounding_boxes. Parameters ---------- bw_image: np.uint8 Input thresholded image rgb_image: np.uint8 Input rgb image Returns ------- image_label_overlay: label """ cleare...
5,320,075
def sparsify_axis_labels(ax, n=2): """ Sparsify tick labels on the given matplotlib axis, keeping only those whose index is divisible by n """ for idx, label in enumerate(ax.xaxis.get_ticklabels()): if idx % n != 0: label.set_visible(False)
5,320,076
def Compute_RHS_and_LHS(functional, testfunc, dofs, do_simplifications = False): """ This computes the LHS matrix and the RHS vector Keyword arguments: functional -- The functional to derivate testfunc -- The test functions dofs -- The dofs vectors do_simplifications -- If apply simplifications...
5,320,077
def init_logging_yaml(config_file): """initialize logging configuration via a dict specified from a YAML file """ # https://docs.python.org/3/library/logging.config.html#logging-config-api global log_root, log_file, log_dir yaml=YAML(typ='safe') # default, if not specfied, is 'rt' (round-trip) wi...
5,320,078
def test_apache2_config(host): """ Check if Apache2 is configured """ assert not host.file('/etc/apache2/mods-enabled/mpm_event.load').exists assert not host.file('/etc/apache2/mods-enabled/mpm_prefork.load').exists assert host.file('/etc/apache2/mods-enabled/proxy.load').is_symlink assert host.fi...
5,320,079
def main(): """Parse the command line arguments and write the corresponding XDMF file.""" parser = ArgumentParser( description="Write an XDMF file for post-processing results in HDF5.") parser.add_argument(dest="file_name", metavar="<filename>", help="path to an HDF5 file for...
5,320,080
def buscaVizinhos(matrizCapacidades): """Função para buscar os vizihos de cada vertice""" vizinhos = {} for v in range(len(matrizCapacidades)): vizinhos[v] = [] for v, fluxos in enumerate(matrizCapacidades): for vizinho, fluxo in enumerate(fluxos): if fluxo > 0: ...
5,320,081
def get_server_numeric_version(ami_env, is_local_run=False): """ Gets the current server version Arguments: ami_env: (str) AMI version name. is_local_run: (bool) when running locally, assume latest version. Returns: (str) Server numeric version """ ...
5,320,082
def get_all_images(): """ :return: all data from db, except db id's """ return list(cursor.find({}, {'_id': False}))
5,320,083
def historical_market_capitalization( apikey: str, symbol: str, limit: int = DEFAULT_LIMIT ) -> typing.List[typing.Dict]: """ Query FMP /historical-market-capitalization/ API. :param apikey: Your API key. :param symbol: Company ticker. :param limit: Number of rows to return. :return: A list...
5,320,084
def get_search_url(query=None, start=None, end=None, page=None): # type: (str, int, int, int) -> str """Constructs a search URL based on the given parameters""" query = "+" if query is None else query start = "+" if start is None else start end = "+" if end is None else end page = 1 if page is N...
5,320,085
def test_corner_case_for_power_at_1(metric_class=TweedieDevianceScore): """Test that corner case for power=1.0 produce valid result.""" metric = TweedieDevianceScore() targets = torch.tensor([0, 1, 0, 1]) preds = torch.tensor([0.1, 0.1, 0.1, 0.1]) val = metric(preds, targets) assert val != 0.0 ...
5,320,086
def init(ctx): """Install production dependencies""" ctx.run("pipenv install --deploy")
5,320,087
def run_parallel_cmd(cmd_list, timeout_s = 999): """Run a list of commands in parallel Args: cmd_list: command list Returns: command output """ children = [] for cmd in cmd_list: ps = subprocess.Popen(cmd, shell=True, universal_newlines=True,...
5,320,088
def test_insertion_get_method(flask_app): """Test get request""" response = flask_app.get(case_api_url, data=json.dumps(data), content_type='application/json') assert response.status_code == 405 assert response.mimetype == 'application/json'
5,320,089
def hash_file(path: PathType, algo: str, enc: str = "utf-8", bsize: int = 65536) -> str: """ Hash the name and contents of a file. Parameters ---------- path : PathType file to hash. algo : str hash algorithm name supported by haslib Python module. enc : str, optional ...
5,320,090
def visualizePrecRecFscoreByBetas(re): """ 展示不同的beta下,模型的Precision, Recall和F1-score """ betas = np.arange(0, 10, 0.1) precs = [] recs = [] fscores = [] pred = re.apply(lambda x: 1 if x["pred_proba"] > 0.5 else 0, axis=1) label = re["label"] for beta in betas: prec, rec, f...
5,320,091
def run(ctx, user, function, repeats=1): """ Execute a specific function """ args = [user, function] if repeats: args.append(str(repeats)) run_command("simple_runner", args)
5,320,092
def _check_json(out_file, status, hold_file): """Function: _check_json Description: Private function for file_check function. Arguments: (input) out_file -> Path and file name of output file. (input) status -> Status of check. (input) hold_file -> Name of file if file check fail...
5,320,093
def test_n_mod_m4(): """ Test that noninteger m fails """ with pytest.raises(ValueError): n_mod_m(1, 3 / 2)
5,320,094
def _guess_z_grid_shape(x, y): """Guess the shape of a grid from (x, y) coordinates. The grid might contain more elements than x and y, as the last line might be partly filled. :param numpy.ndarray x: :paran numpy.ndarray y: :returns: (order, (height, width)) of the regular grid, or No...
5,320,095
def get_hosts_with_state(state): """Helper function to check the maintenance status and return all hosts listed as being in a current state :param state: State we are interested in ('down_machines' or 'draining_machines') :returns: A list of hostnames in the specified state or an empty list if no machi...
5,320,096
def load_category_index(label_map_path, num_classes): """ load the category index from the lablemap with the given path for example, a cateory index is like the following CATEGORORY_INDEX = { 1 : {'id':1, 'name':'Green'}, 2 : {'id':2, 'name':'Red'}, 3 : {'id':3, 'name':'Yellow'} ...
5,320,097
def test_in_order_with_empty_input(): """To test in_order method with an empty tree.""" tree_new = BST() with pytest.raises(TypeError) as err: tree_new.in_order_traversal(tree_new.root) assert str(err.value) == (f'There is no node to traverse.')
5,320,098
def create_mask(M, N, path, radius): """ Fill a square block with values Parameters ---------- M: int Number of points in the first trajectory N: int Number of points in the second trajectory p: list of [i, j] A warping path one level up radius: int Half ...
5,320,099