content
stringlengths
22
815k
id
int64
0
4.91M
def mldivide(A, b): """Solve systems of linear equations Ax = B for x. The matrices A and B must contain the same number of rows. If A is a square n-by-n matrix and B is a matrix with n rows, then x = A\B is a solution to the equation A*x = B, if it exists. Parameters ---------- b : numpy....
78,900
def correlate_subject(func_image: nibabel.brikhead.AFNIImage, data_to_correlate: Iterable, out_path: PathLike) -> None: """ Run a spearman correlation for a list of numbers for every voxel in a func image in 2mm MNI space. The vector of numbers must be the same length as the time domain of the func image. ...
78,901
def precision_at_k(vanilla_topk, fair_topk): """ calculate precision @ K :param vanilla_topk: top K nodes in vanilla mining result :param fair_topk: top K nodes in debiased mining result :return: precision @ K """ topk = set(fair_topk) groundtruth = set(vanilla_topk) return len(topk....
78,902
def includeme_method2(config): """Set **includeme_method2** key on registry.""" config.registry['includeme_method2'] = True
78,903
def update_batch_child_count( batch_execution_job_id, added_count, ): """Updates the status of a given batch_execution_job_id and returns true if completed Parameters ---------- batch_execution_job_id: id of the job to update the status status: BatchExecutionMetadata status to be in add...
78,904
def save_parameter(parameters): """ save the parameters of the simulations in json file :param parameters: dictionary of parameters :return: nothing """ # save the value of all parameters f = open(parameters['path'] + '/parameter.json', "wt") json.dump(parameters, f) f.close()
78,905
def sample(sample_size=5000, noise=0.0): """ return [(s, u, s_next)] """ mdp = PlanarObstaclesMDP(noise=noise) # place holder for data x_data = np.zeros((sample_size, mdp.width, mdp.height), dtype="float32") u_data = np.zeros((sample_size, mdp.action_dim), dtype="float32") x_next_data =...
78,906
def on(): """turn on the display""" z = 0
78,907
def turn_features(turns): """Turn-based features. Parameters ---------- turns: iterable, Sequence of (gap, prev_user, prev_tokens, prev_pos) as returned by the turns_from_chat function. """ turn_features = [] for prev_turn, curr_turn in zip(turns, turns[1:]): featu...
78,908
def initLogMaster(): """Do basic initialization of the logmaster facility. This routine is called whenever the logmaster module is first loaded. It can also be re-called when desired to re- initialize the module.""" global logFormatter, theLoggingContext, mainLogger # In python,...
78,909
def inttools_Parameter(*args): """ :param P: :type P: gp_Pnt :param Curve: :type Curve: Handle_Geom_Curve & :param aParm: :type aParm: float & :rtype: int """ return _IntTools.inttools_Parameter(*args)
78,910
def safe_apply(s: pd.Series, fn) -> pd.Series: """nan以外にのみapply""" return s.apply(lambda x: x if pd.isnull(x) else fn(x))
78,911
def test_get_timebase_small_timebase(): """Test sample rate to timebase conversion for large sampling rates.""" table = { # sample rate [Hz]: timebase as for PicoScope 5e9: 0, 2.5e9: 1, 1.25e9: 2, 625e6: 3, 312.5e6: 4, } # Test exact inputs for sample...
78,912
def test_nbx(dbcursor): """Test that we can parse the NBE.""" utcnow = utc(2020, 7, 22, 14) prod = mosparser(get_test_file("MOS/NBXUSA.txt"), utcnow=utcnow) assert prod.data[0]["model"] == "NBE" assert len(prod.data) == 3 inserts = prod.sql(dbcursor) assert inserts == 18 # Check that we ...
78,913
def flex_colormesh_plot_vs_xy(xvals, yvals, zvals, ax=None, normalize=False, log=False, save_name=None, **kw): """ Add a rectangular block to a color plot using pcolormesh. xvals and yvals should be single vectors with values for the two sweep ...
78,914
def param_to_hash(param_dict): """Generate a hash for a fixed hyperparameter setting""" config_hash = hashlib.md5(json.dumps(param_dict, sort_keys=True).encode("utf-8")).hexdigest() return config_hash
78,915
def print_out(*sigargs): """ This prints out the this will be called in case of Ctrl-C or kill signal :return: """ end_time = time() time_delta = end_time - start_time global monitor output = {'metrics_timeline': monitor.metrics_timeline, 'metric_summaries_timeline': ...
78,916
def evaluate_utterance_sample(sample, model, max_generation_length, name="", gold_forcing=False, metrics=None, total_num=-1, ...
78,917
def lower(series): """Transform all text to lowercase.""" return series.str.lower()
78,918
async def send_push(message=types.Message): """Send push notifications to finish registration for users with status < 6 """ users_to_push = await AirtableAPI.get_users_to_push() if not users_to_push["records"]: return user_ids = [user["fields"]["tg_id"] for user in users_to_push["records...
78,919
def sleep(delay, loop=None): """ Suspends the current task, allowing other tasks to run. Parameters ---------- delay : `float` The time to block sleep in seconds. loop : `None` or ``EventThread``, Optional The event loop to which the returned `future` will be bound to. If no...
78,920
def multihead_self_attention_incremental(query_antecedent, prev_k, prev_v, step_num, name="multihead_attention"): """Incremental self-attention (one decod...
78,921
def system_subset( parameter_key: ParameterGradientKey, force_field: "ForceField", topology: "Topology", scale_amount: Optional[float] = None, ) -> Tuple["openmm.System", "_openmm_unit.Quantity"]: """Produces an OpenMM system containing the minimum number of forces while still containing a speci...
78,922
def gabor_tracked_roi_usis_sess123(sessions, analyspar, sesspar, stimpar, basepar, idxpar, figpar, parallel=False): """ gabor_tracked_roi_usis_sess123(sessions, analyspar, sesspar, stimpar, basepar, idxpar, figpar) Retrieves tracked RO...
78,923
def tensor_to_numpy(data): """Transform torch tensort arrays to numpy arrays.""" if hasattr(data, 'detach'): data = data.detach() if type(data) is torch.Size: return np.array(data) return data.cpu().numpy()
78,924
def coverage_with_data_file(data_file: str) -> Iterator[str]: """This context manager takes the path of a data file and creates a custom coveragerc with the data file path included. The context is yielded the path to the custom rc file. """ parser = ConfigParser() parser.read(".coveragerc") ...
78,925
def request_state_access(state_id: UUID) -> Tuple[Response, int]: """Traverse through the state object linked to the given UUID and look for data ids. Then attempt to load the data into the current session to verify access. :param state_id: The id associated with the saved state. :return: See redire...
78,926
def main(args=None): """Console script for MLlearn.""" click.echo("#1 try scilearn LDA model") MLlearn.tryLDA()
78,927
def get_default_resolution_attribute(attribute_name, default_value=None): """ Internal function that returns value of the given attribute of the default resolution Maya node :param attribute_name: str, name of the attribute to get :param default_value: object, value that is returned if the attribute doe...
78,928
def make_collision_tester(test_method='vdw', test_scale=1.122462048309373): """ Create a function that will test atom overlap based on separation and atomic radii. """ # OH NO MY CAPSLOCK GOT STUCK! test_method = test_method.lower() if test_method == 'cvdw': if _SCIPY_WEAVE == Fal...
78,929
def runAsAdmin(cmdLine=None, wait=True): """ Attempt to relaunch the current script as an admin using the same command line parameters. WARNING: this function only works on Windows. Future support for Posix might be possible. Calling this from other than Windows will raise a RuntimeError. :param c...
78,930
def phrases_from_config(config): """ Identify parenthetical phrases in the documents as they are being imported to the pipeline. import_data_from_config() and phrases_from_config() are the entry points for this step of the pipeline. Args: config: a config file :return: """ ...
78,931
def parse_args(prog): """Parse the command line. Parse the command line, set the program state and return a list of functions to be called for the program's operation, determined from the command line arguments. Args: prog (State): program's state. Returns: list: returns a lis...
78,932
def get_file_references(abs_nb_path, version): """Gets a list of files referenced either in Markdown fenced code blocks or in HTML comments from the notebook. Expands patterns expressed in gitignore syntax (https://git-scm.com/docs/gitignore). Returns the fully expanded list of filenames relative to the...
78,933
async def resolve_subscription_user(event, info, id): """Resolver function for user subscriptions""" user = event["user"] mutation = MutationEnum(event["mutation"]).value return {"user": user, "mutation": mutation}
78,934
def _install(pkgs, pkg_manager): """Return instructions to install system packages.""" installers = { 'apt': _apt_install, 'yum': _yum_install, } if pkg_manager not in installers.keys(): raise ValueError( "package manager '{}' not recognized".format(pkg_manager)) ...
78,935
def gsutil_command(arguments, *args, parallel=True, **kwargs): """Executes a gsutil command with |arguments| and returns the result.""" if environment.get('FUZZ_OUTSIDE_EXPERIMENT'): logger.info('FUZZ_OUTSIDE_EXPERIMENT set, not running \'gsutil %s\'.', ' '.join(arguments)) r...
78,936
def parse_account(s): """ parse entity and account string """ return s.strip().split('.')
78,937
def sbm_adjmat(cluster_sizes, prob_mat_q, directed=False, self_loops=False): """ Generate a graph from the stochastic block model. The list cluster_sizes gives the number of vertices inside each cluster and the matrix Q gives the probability of each edge between pairs of clusters. For two vertices...
78,938
def distribution(Data, N, kernel=False, ccdf=True): """ This function calculates the pdf and ccdf of Data, either by histogram or by gaussian kernels. N: If histogram is used, N is the number of bins to separate the data into. If kernel is used, N gives the number of data points. ccdf: if true, retu...
78,939
def to_pil_image(pic, mode=None): """Convert a tensor or an ndarray to PIL Image. See :class:`~torchvision.transforms.ToPIlImage` for more details. Args: pic (Tensor or numpy.ndarray): Image to be converted to PIL Image. mode (`PIL.Image mode`_): color space and pixel depth of input data (op...
78,940
async def update_issue_pr( db_session: Session, repo_id: uuid.UUID, comments_url: str, terminal_hash: Optional[str] = None, entry_id: Optional[str] = None, comments: Optional[Dict[str, Any]] = None, ) -> GitHubIssuePR: """ Handle Pull Request or Issue hash update. At start we work w...
78,941
def uniqPeptides(peptFile): """ create a fasta-file of non-redundant peptide sequences from peptFile. (return: path to created file) peptFile: peptide sequences (fasta-format) """ outfile = os.path.dirname(peptFile) + "/uniq_" + os.path.basename(peptFile) newls = [] peps = [] n_peps = 0 print "reading pept...
78,942
def run_phenorank(omim_obs, phenotypes_obs=None, nperm=1000, r=0.1, ni=20, gene_mask=None, include_h=True, include_m=True, dir_data="data_phenorank", filename_output="~"): """ run the main PhenoRank function Args: omim_obs: OMIM ID for the disease of interest phenotypes_obs: a list of phenotypes describi...
78,943
def test_LDL_first_missing(ft_mvar, theta_mvar_diffuse, Yt_mvar, Xt_mvar): """ Test when first measurement is missing """ kf = Filter(ft_mvar, Yt_mvar, Xt_mvar, for_smoother=True) kf.init_attr(theta_mvar_diffuse) Y_t, H_t, D_t, R_t, L_t, L_inv = kf._LDL(1) assert kf.n_t[1] == 2 ...
78,944
def mapplot(dataarray, cfg, title_pattern, filename_part, ancestors, **colormesh_args): """Visualize weighted temperature.""" metadata = read_metadata(cfg) metadata_future = metadata['tas_CLIM_future'] start_year = metadata_future[0]['start_year'] end_year = metadata_future[0]['end_year'...
78,945
def http_404_view(request, *args, **kwargs): """View for HTTP 404 page.""" response = render(request, "system/404.html", {}) response.status_code = 404 return response
78,946
def getRecipies(start,end): """ Assuming we expand the Recipes an Agent can hold and work with to more than one, this method would return a visual representation of the Recipes of a certain range in the list that holds them :param start: First Recipe to visually return = list index position :param e...
78,947
def isEquivalentData(values1, values2): """ Determines if two values are equivalent :param Iterable/object values1, values2: :return bool: """ if cell_types.isStr(values1) and cell_types.isStr(values2): result = values1 == values2 elif isinstance(values1, collections.Iterable) \ and isinstance(...
78,948
def init(): """ Initializes module :param dev: bool, Whether tpDcc-core is initialized in dev mode or not """ logger = create_logger() # Get DCC loader module dcc_loader_module = core_dcc.get_dcc_loader_module() logger.info('DCC loader module found: "{}"'.format(dcc_loader_module)) ...
78,949
def default_errorhandler(error): """ Handler function for a logging all errors """ APP.logger.exception() return {'message': error.message}, 500
78,950
def chunk_rays(rays,start,delta): """ rays: a dictionary """ rays_chunk = {} for k,v in rays.items(): if torch.is_tensor(v): v = v.view(-1, v.shape[-1]) rays_chunk[k] = v[start:start+delta] return rays_chunk
78,951
def _get_my_ip(): """Return the actual ip of the local machine. This code figures out what source address would be used if some traffic were to be sent out to some well known address on the Internet. In this case, a Google DNS server is used, but the specific address does not matter much. No traff...
78,952
def _sph2cartMTX(vizMTX): """Converts the spherical vizMTX data to named tuple containing .xs/.ys/.zs. Parameters ---------- vizMTX : array_like [180 x 360] matrix that hold amplitude information over phi and theta Returns ------- V : named_tuple Contains .xs, .ys, .zs cart...
78,953
def Wait(secs_to_wait): """Blocks for specified number of fractional seconds.""" time.sleep(secs_to_wait)
78,954
def insert_receipt_to_mongo(): """ 下载数据文件,插入mongo数据库 :return: """ # market = ['dce', 'czce', 'shfe'] market = ['shfe', 'czce', 'dce'] cursor = conn['receipt'] # transfer_exchange_hq_func = { # 'cffex': transfer_cffex_future_hq, # 'czce': transfer_czce_future_hq, # ...
78,955
def string_to_TaskStatusCode(status): """Converts the given Mesos status string to an integer :param status: The status as a string :type status: string :returns: The status as an integer :rtype: int """ return mesos_pb2.TaskState.Value(status)
78,956
def blank(args): """Default interaction that does absolutely nothing"""
78,957
def concat_data_chunks(*args): """Concatenates data-chunks together based on their keys.""" data_chunk = DataChunk() for k in args[0]: data_chunk[k] = [] for arg in args: for k, v in arg.items(): data_chunk[k].append(v) for k, v in data_chunk.items(): data_chun...
78,958
def normalize_job_id(job_id): """Convert the job id into job_id, array_id.""" job_id = job_id.split('.')[0] if '[' in job_id: job_id, array_id = job_id.split('[') job_id = job_id.strip('[]') array_id = array_id.strip('[]') if not array_id: array_id = None else...
78,959
def get_ingredient(name): """Find an ingredient by its name. Args: name (string): The name of the ingredient. Returns: IngredientDto: The ingredient with the given name, or None. """ ingredient_entity = IngredientEntity.query.filter_by(name=name).first() if ingredient_entity is...
78,960
def get_ydim(da, errors="warn", **kwargs): """Get the dimension of Y type It is a simple call to :func:`get_dims` with ``dim_types="y"`` Parameters ---------- da: xarray.DataArray Array to scan positions: str Default position per type starting from the end. {errors} kwa...
78,961
def test_repeated_time(timezone, serializer): """ Test that if the designated time is repeated during a day due to a backward DST shift, the task is executed on the earlier occurrence of that time. """ trigger = CalendarIntervalTrigger(days=2, hour=2, minute=30, start_date=date(2016, 10, 30), ...
78,962
def create_import_data_json(import_data_dict, event_tree): """ create_import_data_json: This function converts data in event tree into json format. Parameters: import_data_dict: This parameter holds the event tree data event_tree: This parameter holds the event tree data @see #gener...
78,963
def test_Order_POST_request(app): """ with app.test_client() as client: response = client.post( '/orders', data=json.dumps(dict( status='Pedido em andamento', payment_method='dinheiro', products=[], total_price=5.75 ...
78,964
def power_split(y, x, x_max, n): """ Computes the indexes corresponding to equal integral values for a function y and x values :param y: function value array :param x: function x values array :param x_max: maximum x value :param n: number of integral bins :return: indexes of the integral bin...
78,965
def select_ip_from_network(network): """ Randomly selects an IP address from a particular network :param network: Network from which to select the IP address :return: IP address as integer from network """ max_address = network.address | ((1 << (32 - network.prefix)) - 1) return random.randi...
78,966
def ONE_OR_MORE(*grammar, **kwargs): """ This is a synonym for ``REPEAT(*grammar, min=1)`` """ kwargs.update(min=1, max=None) return REPEAT(*grammar, **kwargs)
78,967
def kwtype_to_annotation(kw): """Convert type to a KnownType""" data = {} for name, type in kw.items(): if isinstance(type, str) and ',' in type: for x in type.split(','): data[_clean_name(x.strip())] = _get_type(name) else: data[_clean_name(name)] = ...
78,968
def plot_figure4(): """" Generate fixed height power density plot. """ column_titles = ["5th percentile", "32nd percentile", "50th percentile"] fixed_height_ref = 100. fixed_height_id = list(fixed_heights).index(fixed_height_ref) linspace0 = np.linspace(0, 0.027, 21) # np.linspace(0, .033, 21) ...
78,969
def parse_extinst_instruction(lexer, set_id): """Parse instruction field of OpExtInst instruction.""" assert set_id.inst.op_name == 'OpExtInstImport' _, tag = lexer.get_next_token(peek=True) if tag == 'INT': return parse_literal_number(lexer) elif tag == 'NAME': token, _ = lexer.get_...
78,970
def query(query, experiment_id, host, verify_cert=True): """ Query the MDML for an example of the data structure that your query will return. This is aimed at aiding in development of FuncX functions for use with the MDML. Parameters ---------- query : list Description of the data to send f...
78,971
def load_from_dumps_or_extract(track_ids_requested: set[int], dump_dir=DIR_FEATURES_V1) -> dict[int, list[np.ndarray]]: """ Loads features from dump batches or extracting them from audio :param track_ids_requested: :param dump_dir: :return: """ tracks_features: dict[int, list[np.ndarray]] = ...
78,972
def interlock(word_list, word): """Checks whether a word contains two interleaved words. word_list: list of strings word: string """ evens = word[::2] odds = word[1::2] return in_bisect(word_list, evens) and in_bisect(word_list, odds)
78,973
def reset(): """Reset the cached conf""" global _HIVE_SITE_DICT global _METASTORE_LOC_CACHE _HIVE_SITE_DICT = None _METASTORE_LOC_CACHE = None
78,974
def try_sudachi_import(split_mode="A"): """SudachiPy is required for Japanese support, so check for it. It it's not available blow up and explain how to fix it. split_mode should be one of these values: "A", "B", "C", None->"A".""" try: from sudachipy import dictionary, tokenizer split_m...
78,975
def ask_type(question, ans_type, loop=True): """ Used to ask and assert that the response to the question will be an integer :param question: what to ask :return: the result, of type specified """ answer = ask(question) if loop: # Loops until the user while loop: ...
78,976
def unload_nodenet(nodenet_uid): """ Unload the nodenet. Deletes the instance of this nodenet without deleting it from the storage Arguments: nodenet_uid """ if not nodenet_uid in nodenets: return False if nodenets[nodenet_uid].world: nodenets[nodenet_uid].wo...
78,977
def convert_weights(model: nn.Module): """Convert applicable model parameters to fp16""" def _convert_weights_to_fp16(l): if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): # nn.Conv3d, l.weight.data = l.weight.data.half() if l.bias is not None: l.bias.data ...
78,978
def verifyBundleStructure(expected, actual, currentPath): """ Function to verify if an uploaded bundle follows IBM defined structure @param expected the JSON representation of the IBM defined structure @param actual the JSON representation of the actual structure of the uploaded bundle @p...
78,979
def download_img(cfg, workspace): """download satellite image different api has different RESTful api url, Now we support mapbox/sentinel/bing/custom For mapbox: http://a.tiles.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.jpg?access_token={token} For sentinel: https://services.sentinel-...
78,980
def fix_coordinates(df, cols): """ For coordinate column which require fixing, we it here """ to_fix_or_not_cols = check_if_coordinates_colums_need_fixing(df=df, cols=cols) if to_fix_or_not_cols: fix_col = to_fix_or_not_cols["c...
78,981
def set_ssm_value( session: Session, name: str, value: Any, description: str = "" ) -> None: """Set the ssm parameter. Args: session: The boto3 session. name: The name of the parameter. value: The value of the parameter. description: A description of the parameter. """ ...
78,982
def test_httpretty_should_mock_a_simple_get_with_requests_read(): """HTTPretty should mock a simple GET with requests.get""" httpretty.register_uri( httpretty.GET, "http://yipit.com/", body="Find the best daily deals" ) response = requests.get("http://yipit.com") expect(response.text).to.e...
78,983
def attemptFileClear(fName,later): """ Attempts to remove the file. If not possible, store it in "later". @ In, fName, string, name of file to remove @ In, later, list, list of files to remove later @ Out, later, list, list of files to remove later """ try: os.remove(fName) except OSError: ...
78,984
def word_tokenize(text, engine='newmm',whitespaces=True): """ :param str text: the text to be tokenized :param str engine: the engine to tokenize text :param bool whitespaces: True to output no whitespace, a common mark of sentence or end of phrase in Thai. :Parameters for engine: * newmm - Ma...
78,985
async def test_start(dut): """ Check the design starts up. """ clock = Clock(dut.clk, 25, units="ns") cocotb.fork(clock.start()) dut.RSTB <= 0 dut.power1 <= 0; dut.power2 <= 0; dut.power3 <= 0; dut.power4 <= 0; await ClockCycles(dut.clk, 8) dut.power1 <= 1; await Cl...
78,986
def __reorder_first_headers(headers: List[str], first_headers: List[str]) -> None: """ brings given headers to the head of the list, while preserving their order used for showing important content first. """ for h in reversed(first_headers): if h in headers: headers.insert(0, hea...
78,987
def test_cleaner_scraped_df_not_empty(): """ Test to confirm the output dataframe is not empty """ with raises(ValueError): cleaner.data_cleaner( pd.DataFrame({"price": [], "house_type": [], "listing_url": []}) )
78,988
def choose_best_seqs(dist_matrix, all_genes, groups, medoid): """ Defines the medoid of a distance matrix :param dist_matrix: The numpy array (symmetrical) distance matrix :param groups: sp -> groups of genes :param all_genes: A list of the row/colnames of the distance matrix :param medoid: the ...
78,989
def get_dataset_info_dict(debug): """Get dictionary of dataset info.""" def _tfds_fns(ds_name): fns = [ x # pylint:disable=g-complex-comprehension for s in ('train', 'validation', 'test') for x in audio_to_embeddings_beam_utils._tfds_filenames(ds_name, s)] # pylint:disable=protected-ac...
78,990
def oracle_service_def(): """ Provides the Docker service definitions for running an instance of Oracle Express Edition, result is converted to YAML file and then used to create a Docker compose file. Note this assumes the existence of a container image named 'oracle/database:18.4.0-xe' in a registry th...
78,991
def get_kmsauth_config(region, bless_config): """ Return the kmsauth config values for a given AWS region Args: region (str): the AWS region code (e.g., 'us-east-1') bless_config (BlessConfig): config from BlessConfig Retruns: A dict of configuation values """ alias_code = bl...
78,992
def get_utility_command_execution_order(name): """ Should the given utility command be executed before or after the payload? :param name: utility name (string). :return: execution order constant (UTILITY_BEFORE_PAYLOAD or UTILITY_AFTER_PAYLOAD) """ # example implementation if name == 'moni...
78,993
def bytes_feature(value): """Returns a bytes_list from a string / byte.""" return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
78,994
def int_product(size=DEF_MATRIX, rep=DEF_REP): """ Returns the execution time of performing a product of random integer matrices. Parameters ---------- size : int The dimension of the square matrices that will be used in the operation. rep : i...
78,995
def get_hedgehog_hyperparams(**overrides) -> Tuple: """ Get parameters for Hedgehog agent. If some parameter is not specified in overrides, then it takes a default value. :param overrides: Parameters coming from JSON file. :return: (ac_params, wk_params, si_params, po_params, hh_params, si_class, n...
78,996
def project_waveforms(waveforms, method='pca', selection=None, catalogueconstructor=None, **params): """ """ if selection is None: waveforms2 = waveforms else: waveforms2 = waveforms[selection] if waveforms2.shape[0] == 0: return None, None, None ...
78,997
def high_low_estimator(high, low, window): """ Estimates volatility using Parkinson's method :param high: a series of high prices :param low: a series of low prices :param window: length of the rolling estimation window :return: volatility estimate """ log_high_low = np.log(high / low) ...
78,998
def process_possible_repo(repo: PossibleRepo) -> Optional[Result]: """Process the given possible repo.""" try: slave = Slave(repo) result = slave.run() if result is None: logger.error("Slave returned None result.") return result except BaseException as e: ...
78,999