content
stringlengths
22
815k
id
int64
0
4.91M
def pixelmatch( img1: ImageSequence, img2: ImageSequence, width: int, height: int, output: Optional[MutableImageSequence] = None, threshold: float = 0.1, includeAA: bool = False, alpha: float = 0.1, aa_color: RGBTuple = (255, 255, 0), diff_color: RGBTuple = (255, 0, 0), diff_...
50,900
def test_nemweb_dirlisting_spider_return(aemo_nemweb_dirlisting: Response) -> None: """Checks the return types for a spider""" assert isinstance(aemo_nemweb_dirlisting, Response), "Returns a scrapy response" assert isinstance(aemo_nemweb_dirlisting.body, bytes), "Response body is bytes"
50,901
def test_clean_masked_and_criteria(): """ Check whether removing masked rows and using a criteria work together. """ inp = a_table(masked=True) # Mask the first row. inp['b'].mask = inp['b'] > 0 inp_copy = inp.copy() # This should remove the third row. criteria = {'a': '<=2'} ...
50,902
def binary_search(array, target): """ Does a binary search on to find the index of an element in an array. WARNING - ARRAY HAS TO BE SORTED Keyword arguments: array - the array that contains the target target - the target element for which its index will be returned returns the index...
50,903
def _get_matrix_from_string(string): """Get a network connection matrix from a string. Parameters ---------- string : str String from which to read the matrix. It should have the format of a string representation of a NumPy array. Raises ------ FormatError ...
50,904
def transform_sensu(data): """Decompose a sensu alert into arguments for an alert""" # TODO: maybe calulate a hashed alert ID here? return { 'title': data['attachments'][0]['title'], 'message': data['attachments'][0]['text'], 'username': data['username'], 'icon_emoji': data.g...
50,905
def classification_report(y_true, y_pred, labels=None, target_names=None, sample_weight=None, digits=2, output_dict=False, zero_division="warn"): """Build a text report showing the main classification metrics. Read more in the :ref:`User Guide <classification...
50,906
def links(ctx, lab_path): """ Get EVE-NG lab topology """ client = ctx.obj['CLIENT'] links = client.api.get_lab_topology(lab_path) click.echo(tabulate(links, headers="keys", tablefmt="fancy_grid"))
50,907
def paralog_cn_str(paralog_cn, paralog_qual, min_qual_value=5): """ Returns - paralog CN: string, - paralog qual: tuple of integers, - any_known: bool (any of the values over the threshold). If paralog quality is less than min_qual_value, corresponding CN is replaced with '?' and qua...
50,908
def offbyK(s1,s2,k): """Input: two strings s1,s2, integer k Process: if both strings are of same length, the function checks if the number of dissimilar characters is less than or equal to k Output: returns True when conditions are met otherwise False is returned""" if len(s1)==len(s2): ...
50,909
def unique2(gen): """ given a generator of pairs (x,y), generate one x for each value of y """ memo = set() for x,y in gen: if y not in memo: memo.add(y) yield x
50,910
def register_blueprints(app): """Register Flask blueprints.""" app.register_blueprint(views.blueprint)
50,911
def calc_e_Gx(trainDataArr, trainLabelArr, n, div, rule, D): """计算分类错误率""" e = 0 # 初始化误分类误差率为0 x = trainDataArr[:, n] y = trainLabelArr predict = [] if rule == 'LisOne': L = 1 H = -1 else: L = -1 H = 1 for i in range(trainDataArr.shape[0])...
50,912
def compute_gap( gold_mapping: Dict[str, int], ranked_candidates: List[str], ) -> Union[float, None]: """ Method for computing GAP metric. Args: gold_mapping: Dictionary that maps gold word to its annotators number. ranked_candidates: List of ranked candidates. Returns: ...
50,913
def test_schedule_covid_updates(): """ This test checks that the scheduled covid data updates are running """ schedule_covid_updates(update_interval=10, update_name='update test')
50,914
def SmiNetDate(python_date): """ Date as a string in the format `YYYY-MM-DD` Original xsd documentation: SmiNetLabExporters datumformat (ÅÅÅÅ-MM-DD). """ return python_date.strftime("%Y-%m-%d")
50,915
def get_node_with_children(node, model): """ Return a short list of this top node and all its children. Note, maximum depth of 10. """ if node is None: return model new_model = [node] i = 0 # not really needed, but keep for ensuring an exit from while loop new_model_changed = True w...
50,916
def correct_capitalization(s): """Capitalizes a string with various words, except for prepositions and articles. :param s: The string to capitalize. :return: A new, capitalized, string. """ toret = "" if s: always_upper = {"tic", "i", "ii", "iii", "iv", "v", "vs", "vs.", "2d",...
50,917
def test_umart_html_error(uqcsbot: MockUQCSBot): """ This test covers the case where a search query fails. This is accomplished by mocking the get_search_page function in umart.py """ uqcsbot.post_message(TEST_CHANNEL_ID, "!umart HDD") messages = uqcsbot.test_messages.get(TEST_CHANNEL_ID, []) ...
50,918
def mockedservice(fake_service=None, fake_types=None, address='unix:@test', name=None, vendor='varlink', product='mock', version=1, url='http://localhost'): """ Varlink mocking service To mock a fake service and merely test your varlink client against. ...
50,919
def dsigmoid(x): """ return differential for sigmoid """ ## # D ( e^x ) = ( e^x ) - ( e^x )^2 # - --------- --------- --------- # Dx (1 + e^x) (1 + e^x) (1 + e^x)^2 ## return x * (1 - x)
50,920
def clean(state): """ We do not delete any experiments, only move them to a temporal folder. """ experiment_config = state.experiment_config bin_path = manager.make_and_get_tmp_delete_folder(experiment_config) use_mongo = False if experiment_config['template']["use_mongo"]: raise ...
50,921
def get_filetype(location): """ LEGACY: Return the best filetype for location using multiple tools. """ T = get_type(location) return T.filetype_file.lower()
50,922
def eps_r_op_2s_AA12(x, AA12, A3, A4, op): """Implements the right epsilon map with a non-trivial nearest-neighbour operator. Uses a pre-multiplied tensor for the ket AA12[s, t] = A1[s].dot(A2[t]). See eps_r_op_2s_A(). Parameters ---------- x : ndarray The argument matrix. ...
50,923
def test_single_feature_data(individual_multiply): """ Should return transform each sample individually.""" X = np.array([[1], [2], [3], [4]]) y = np.array([[2], [8], [18], [32]]) y_pred = individual_multiply.transform(X) assert (y == y_pred).all()
50,924
def test_bad_legend_origin_and_size(sphere): """Ensure bad parameters to origin/size raise ValueErrors.""" plotter = pyvista.Plotter() plotter.add_mesh(sphere) legend_labels = [['sphere', 'r']] with pytest.raises(ValueError, match='Invalid loc'): plotter.add_legend(labels=legend_labels, loc=...
50,925
def _bem_specify_coils(bem, coils, coord_frame, n_jobs): """Set up for computing the solution at a set of coils""" # Compute the weighting factors to obtain the magnetic field # in the linear potential approximation coils, coord_frame = _check_coil_frame(coils, coord_frame, bem) # leaving this in i...
50,926
def validate_solidity_compiler(): """ Check the solc prior to running any test. """ from raiden.utils.solc import validate_solc validate_solc()
50,927
def main(): """ Main function to run on sasmodel datasets.""" pfolder = args.folder synthtype = args.synthtype dfolder = pfolder + "\\data_files" if synthtype == "all": xray_synth(dfolder) neutron_synth(dfolder) elif synthtype == "xray": xray_synth(dfolder) elif synt...
50,928
def extract_plate_and_well_names(col_meta, plate_field=PLATE_FIELD, well_field=WELL_FIELD): """ Args: col_meta (pandas df) plate_field (string): metadata field for name of plate well_field (string): metadata field for name of well Returns: plate_names (numpy array of string...
50,929
def check_cli(module, cli): """ This method checks for idempotency using the trunk-show command. If a trunk with given name exists, return TRUNK_EXISTS as True else False. :param module: The Ansible module to fetch input parameters :param cli: The CLI string :return Global Booleans: TRUNK_EXISTS...
50,930
def apply_masked_reduction_along_dim(op, input, *args, **kwargs): """Applies reduction op along given dimension to strided x elements that are valid according to mask tensor. The op is applied to each elementary slice of input with args and kwargs with the following constraints: 1. Prior applying ...
50,931
def index_gen(x): """Index generator. """ indices = np.arange(*x, dtype='int').tolist() inditer = it.product(indices, indices) return inditer
50,932
def pad_xr_dims(input_xr, padded_dims=None): """Takes an xarray and pads it with dimensions of size 1 according to the supplied dims list Inputs input_xr: xarray to pad padded_dims: ordered list of final dims; new dims will be added with size 1. If None, defaults to standard naming ...
50,933
def get_list_projects_xlsx(proposals): """ Excel export of proposals with sharelinks :param proposals: :return: """ wb = Workbook() # grab the active worksheet ws = wb.active ws.title = "BEP Projects" ws['A1'] = 'Projects from {}'.format(settings.NAME_PRETTY) ws['A1'].sty...
50,934
def challenge_bellman_ford(): """Construct a directed, weighted graph to requires 4 iterations of Bellman-Ford""" from ch07.single_source_sp import bellman_ford DG = nx.DiGraph() DG.add_edge('d', 'e', weight=1) DG.add_edge('c', 'd', weight=1) DG.add_edge('b', 'c', weight=1) DG.add_edge('s', ...
50,935
def get(model=None, algorithm=None, trainer=None): """Get an instance of the server.""" if hasattr(Config().server, 'type'): server_type = Config().server.type else: server_type = Config().algorithm.type if server_type in registered_servers: logging.info("Server: %s", server_typ...
50,936
def par_impar(n): """ Par Impar Admite un numero y evalua si es par Parameters ----------- n : int Numero a evaluar Returns ------- bool Resultado de evaluar si es par el numero """ if n%2 == 0 : return Tr...
50,937
def get_attacks_percent (a_data, a_index, dataset= None): """ Return the % for each attack in a_index of the dataset """ percents = {} attacks = {} #for a, index in attacks_map.items(): #percents[a]= 0 for a, index in _attack_classes.items(): percents[a] = 0 total = 0 if dat...
50,938
def test_notify_negative_detection_no_inference(tmpdir, mocker: MockerFixture): """ Expect store to save the image from an inference without any detection but not send a notification for it. """ out_dir = tmpdir context = PipelineContext(unique_pipeline_name="test pipeline") context.data_dir = o...
50,939
def do_login(user, password): """Log-in and return auth token""" login_payload = { "login": { "email": user, "password": password } } login_response = requests.post(URL_LOGIN, json=login_payload) login_ans = json.loads(login_response.text) id_token = log...
50,940
def pow(x, y): """Return x raised to the power y. :type x: numbers.Real :type y: numbers.Real :rtype: float """ return 0.0
50,941
def make_secondary_variables(): """Make secondary variables for modelling""" secondary = read_secondary() secondary_out = secondary.rename(columns={"geography_code": "geo_cd"})[ ["geo_cd", "variable", "value"] ] compl = make_complexity() return pd.concat([secondary_out, compl])
50,942
def normalize_tuple(value, rank): """Repeat the value according to the rank.""" value = nest.flatten(value) if len(value) > rank: return (value[i] for i in range(rank)) else: return tuple([value[i] for i in range(len(value))] + [value[-1] for _ in range(len(value), r...
50,943
async def _dump_data( conn: asyncpg.Connection, table: Table, ids: typing.List[int], out: typing.BinaryIO ): """ Dump data """ logging.log(TRACE, f"Dumping %s rows from table %s", len(ids), table.id) start = time.perf_counter() await conn.execute("CREATE TEMP TABLE _slicedb (_ctid tid) ON ...
50,944
def standard_Purge(*args): """ * Deallocates the storage retained on the free list and clears the list. Returns non-zero if some memory has been actually freed. :rtype: int """ return _Standard.standard_Purge(*args)
50,945
def metrics(label: np.ndarray, pred: np.ndarray, num_class: int): """ :param label: (h, w) :param pred: (h, w) :param num_class: :return: """ label = label.astype(np.uint8) pred = np.round(pred) mat: np.ndarray = np.zeros((num_class, num_class)) [height, width] = label.shape ...
50,946
def to_png(fig, png_name): """Convert image to png directly Parameters ---------- fig : instance of plotly.Figure figure to convert png_name : path path of the file to write (extension should be .png). It overwrites if it exists Notes ----- It crashes easily, es...
50,947
def kbdb(): """Knowledge base database.""" return flags.arg.kbdb
50,948
def apply_cats(df, trn): """Changes any columns of strings in df into categorical variables using trn as a template for the category codes. Parameters: ----------- df: A pandas dataframe. Any columns of strings will be changed to categorical values. The category codes are determined by trn. ...
50,949
def is_transpositionally_related(set1, set2): """ Returns a tuple consisting of a boolean that tells if the two sets are transpositionally related, the transposition that maps set1 to set2, and the transposition that maps set2 to set1. If the boolean is False, the transpositions are None. ...
50,950
def find_dimension_coordinate_mismatch( first_cube: Cube, second_cube: Cube, two_way_mismatch: bool = True ) -> List[str]: """Determine if there is a mismatch between the dimension coordinates in two cubes. Args: first_cube: First cube to compare. second_cube: Se...
50,951
def test_reference_for_bias_preproc_empty(): """Test ``reference_for_bias_preproc``.""" products = { PreprocessorFile({'filename': 10}, {}), PreprocessorFile({'filename': 20}, {}), PreprocessorFile({'filename': 30}, {'trend': {}}), } check.reference_for_bias_preproc(products)
50,952
def vis_detections(im, class_name, dets,ax, thresh=0.5): """This function draws all the detected bounding boxes.""" #returns the index value at which dets > threshold value #considers only the last column as it has values as [[x,y,h,w,thresh]] inds = np.where(dets[:, -1] >= thresh)[0] #if the...
50,953
def patch_python(filename, dart=False, python='PYTHONJS', backend=None): """Rewrite the Python code""" code = patch_assert(filename) ## a main function can not be simply injected like this for dart, ## because dart has special rules about what can be created outside ## of the main function at the m...
50,954
def get_standard_binary_metrics() -> List[Union[AUC, str, BinaryMetric]]: """Return standard list of binary metrics. The set of metrics includes accuracy, balanced accuracy, AUROC, AUPRC, F1 Score, Recall, Specificity, Precision, Miss rate, Fallout and Matthews Correlation Coefficient. """ retu...
50,955
def test_inline_links_507(): """ Test case 507: (part 2) However, if you have unbalanced parentheses, you need to escape or use the <...> form: """ # Arrange source_markdown = """[link](<foo(and(bar)>)""" expected_tokens = [ "[para(1,1):]", "[link(1,1):inline:foo(and(bar):::::l...
50,956
def Xor(n): """Return a DataSet with n examples of 2-input xor.""" return Parity(2, n, name="xor")
50,957
def touchdir_relative(directory: Path): """Make sure a relative directory exists. Args: directory (Path): The directory to touch """ absolute_directory = Config.absolute_path(directory) touchdir_absolute(absolute_directory)
50,958
def bubble_sort(array): """This solution uses two `for` to use first as pointer.""" length = len(array) for i in range(length): # Traverse all elements in array (pointer) for j in range(0, length - i - 1): # All elements until i are already in place if array[j] > array[j + 1]: ...
50,959
async def test_ejv_failure_emails(app, session, stan_server, event_loop, client_id, events_stan, future): """Assert that events can be retrieved and decoded from the Queue.""" # Call back for the subscription from account_mailer.worker import cb_subscription_handler events_subject = 'test_subject' ...
50,960
def feature_selection(dataframe, method, missing_value_threshold=60, variance_threshold=0, correlation_threshold=0.75, target_variable=None, task=None, algorithm='RandomForest', n_features_to_select=5, scoring=None, cv=5, n_jobs=None): """ This function is used for se...
50,961
def plot_box(im, box): """ Plot image and bounding box (coronal and sagittal views) :param im: 3d image :param box: bounding box """ [h_min, h_max, w_min, w_max, d_min, d_max] = box fig, ax = plt.subplots(1, 2, figsize=(8, 8)) ax[0].imshow(np.amax(im, -1), cmap="gray") rect = patche...
50,962
def shaped_reverse_arange(shape, xp=nlcpy, dtype=numpy.float32): """Returns an array filled with decreasing numbers. Args: shape(tuple of int): Shape of returned ndarray. xp(numpy or nlcpy): Array module to use. dtype(dtype): Dtype of returned ndarray. Returns: numpy.nd...
50,963
def then(value): """ Creates an action that ignores the passed state and returns the value. >>> then(1)("whatever") 1 >>> then(1)("anything") 1 """ return lambda _state: value
50,964
def compute_cvm(predictions, masses, n_neighbours=200, step=50): """ Computing Cramer-von Mises (cvm) metric on background events: take average of cvms calculated for each mass bin. In each mass bin global prediction's cdf is compared to prediction's cdf in mass bin. :param predictions: array-like, pred...
50,965
def clear_c(inx: int or tuple or list): """ Deletes the specified columns or columns :param inx: Index of the column or columns to be deleted :return: None """ if inx >= 0: raise Exception("Index is invalid") else: global data global lbels global co...
50,966
def get_pmat(index_df:PandasDf, properties:dict) -> tuple((PandasDf, PandasDf)): """ Run Stft analysis on signals retrieved using rows of index_df. Parameters ---------- index_df : PandasDf, experiment index properties: Dict Returns ------- index_df: PandasDf, experiment index ...
50,967
def jupytext(args=None): """Entry point for the jupytext script""" args = cli_jupytext(args) convert_notebook_files(nb_files=args.notebooks, nb_dest=args.to, test_round_trip=args.test, preserve_outputs=args.update)
50,968
def delete_upload_collection(upload_id: str) -> str: """Delete a multipart upload collection.""" uploads_db = uploads_database(readonly=False) if not uploads_db.has_collection(upload_id): raise UploadNotFound(upload_id) uploads_db.delete_collection(upload_id) return upload_id
50,969
def setup_hull(domain,isDomainFinite,abcissae,hx,hpx,hxparams): """setup_hull: set up the upper and lower hull and everything that comes with that Input: domain - [.,.] upper and lower limit to the domain isDomainFinite - [.,.] is there a lower/upper limit to the domain? abci...
50,970
def get_candidates(arrange_mode_attr): """ According current `arrange_mode` and `condition`, to find out candidates data returns to caller return candidates for displaying Variables: arrange_mode: Different mode has different method to select candidates arrange_condition: The type_id list ...
50,971
def notify(prompt): """ Popup an auto-close notification with instructions about a test """ sg.popup_auto_close(prompt, title="Testing", **sg_kwargs, auto_close_duration=8)
50,972
def img_to_array(model_input: any) -> any: """Converts the incoming image into an array.""" model_input = keras.preprocessing.image.img_to_array(model_input) return model_input
50,973
def batch_works(k): """ batch works """ if k == n_processes - 1: paths = all_paths[k * int(len(all_paths) / n_processes):] else: paths = all_paths[k * int(len(all_paths) / n_processes): (k + 1) * int(len(all_paths) / n_processes)] for path in paths: n4_correction(glob.glob(os.pa...
50,974
def cli(tsv_in: str, tsv_out: str, col_val: str): """ Add a column with a constant value to a TSV file :param tsv_in: :param tsv_out: :param col_name: :param col_val: :return: """ in_frame = pd.read_csv(tsv_in, sep="\t", header=None) in_frame["added"] = col_val in_frame.to_c...
50,975
def add_word_vector_feature(dataset, propositionSet, parsedPropositions, word2VecModel=None, pad_no=35, has_2=True, ): """Add word2vec featur...
50,976
def _bert_add_special_tokens_metadata(metadata, max_length): """ Edit metadata to account for the added special tokens ([CLS] and [SEP]) """ # metadata seq starts from plus 1 metadata[:, 1] = metadata[:, 1] + 1 # clip done to take overflow into account metadata[:, 2] = cp.clip(metadata[:, 2]...
50,977
def analyze_mcmc_file(): """Analyzing the example spectrum MCMC CIV line fit """ # Define Cosmology for cosmological conversions cosmo = FlatLambdaCDM(H0=70, Om0=0.3, Tcmb0=2.725) # Instantiate an empty SpecFit object fit = scfit.SpecFit() # Load the example spectrum fit fit.load('exam...
50,978
def clustering(vertice): """Calcula el coeficiente de clustering de un vertice. Obs: Devuelve -1 si el coeficiente no es calculable. Pre: EL vertice existe y es de clase Vertice. """ # Cuento las conexiones (por duplicado) aristas_entre_vecinos = 0 for vecino in vertice.iter_de_adyacentes(): for segundo_vecino...
50,979
def test_convert_folder_spectra(): """Test that we can convert the "cont_fit" folder contents into pickles properly.""" fdir = 'mattpy/tests/data/' save_dir = fdir + 'test_folder/' assert pahdb_utils.convert_folder_spectra(fdir, sub_dir=None, save_d...
50,980
def main(formato, full=False): """ Get dict of mains and dict of sides. :formato: str (e.g.: "standard" or "modern") :full: bool (True for scraping all decks from /full#paper and False for scraping only first decks from /#paper url) :return: """ url_start = "https://www.mtggoldfish...
50,981
def pipeline(img, mtx, dist): """ The pipeline applies all image pre-processing steps to the image (or video frame). 1) Undistort the image using the given camera matrix and the distortion coefficients 2) Warp the image to a bird's-eye view 3) Apply color space conversion :param img: Input image...
50,982
def table(line, humans): """Вывод скиска людей""" print(line) print( '| {:^4} | {:^20} | {:^15} | {:^16} |'.format( "№", "Ф.И.О.", "Знак зодиака", "Дата рождения")) print(line) for i, num in enumerate(humans, 1): print( '| {...
50,983
def get_coverage_value(coverage_report): """ extract coverage from last line: TOTAL 116 22 81% """ coverage_value = coverage_report.split()[-1].rstrip('%') coverage_value = int(coverage_value) return coverage_value
50,984
def collapse_single_path(digraph, path): """ :param digraph: networkx.DiGraph :param path: list of nodes (simple path of digraph) :return: networkx.DiGraph with only first and last nodes and one edge between them The original graph is an attribute of the edge """ digraph_ordered = digraph....
50,985
def generate_data(train_test_split): """ Generates the training and testing data from the splited data :param train_test_split: train_test_split - array[list[list]]: Contains k arrays of training and test data splices of dataset Example: [[[0.23, 0.34, 0.33, 0.12, 0.45, 0.68], [0.13, 0.35,...
50,986
def vib_g_yor(sleep_speed): """ Cylces through all the colors, white to red. """ PYGLOW.color("white", 100) sleep(sleep_speed) PYGLOW.color("white", 0) PYGLOW.color("blue", 100) sleep(sleep_speed) PYGLOW.color("blue", 0) PYGLOW.color("green", 100) sleep(sleep_speed) PYGLO...
50,987
def process_roses(stations, ncpus, roses_fp, discard_obs_fp): """ For each station we need one trace for each direction. Each direction has a data series containing the frequency of winds within a certain range. Columns: sid - stationid direction_class - number between 0 and 35. 0 repres...
50,988
def find_tsm_marker(content: bytes, initial_key: bytes) -> Tuple[int, int]: """Search binary lua for an attribute start and end location.""" start = content.index(initial_key) brack = 0 bracked = False for _end, char in enumerate(content[start:].decode("ascii")): if char == "{": ...
50,989
def main(): """Evaluate AlexNet on Cats vs. Dogs """ # load the RGB means for the training set means = json.loads(open(config.DATASET_MEAN).read()) # initialize the image preprocessors simple_preprocessor = SimplePreprocessor(227, 227) mean_preprocessor = MeanPreprocessor(means["R"], means["...
50,990
def create_fashion_mnist_dataset(train_transforms, valid_transforms): """ Creates Fashion MNIST train dataset and a test dataset. Args: train_transforms: Transforms to be applied to train dataset. test_transforms: Transforms to be applied to test dataset. """ # This code can be re-used for ot...
50,991
def get_user_profile(request): """Method to get a user Recieves: request, relevant email Returns: httpresponse showing user """ if request.method != "POST": return HttpResponse("only POST calls accepted", status=404) #input validation try: user = User.objects.get(email=reque...
50,992
async def read_product( *, product_id: int, db_product: Product = Depends(get_product_or_404) ): """ Get the product type by id """ # Le righe commentate sotto, sostituite dalla nuova Depends # Nota: il parametro product_id a get_product_or_404 è preso dal path # p = session.get(Product, pro...
50,993
def trip_duration_stats(df): """Calculate & Display statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # Calculate total travel time total_travel_time = df['Trip Duration'].sum() print('Total travel time is : {}'.for...
50,994
def geometry_file_path(prefix, bath, pot): """ geometry file path """ return GEOMETRY_FILE.path([prefix, bath, pot])
50,995
def pop_first_stored(): """Gets the first stored process and delete it from the stored_requests table """ session = get_session() request = session.query(RequestInstance).first() if request: delete_count = session.query(RequestInstance).filter_by(uuid=request.uuid).delete() if delet...
50,996
def get_elements(return_type: str = "name", spectra_folder: str = "spectras"): """Wrapper for retrieving viable elements.""" viable_elements = retrieve_viable_elements(Path(spectra_folder)) for item in viable_elements: print(item[return_type])
50,997
def find_hessian_diag(point, vars=None, model=None): """ Returns Hessian of logp at the point passed. Parameters ---------- model: Model (optional if in `with` context) point: dict vars: list Variables for which Hessian is to be calculated. """ model = modelcontext(model) ...
50,998
def apply_with_random_selector(x, func, num_cases): """Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), wher...
50,999