Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def adaptive_graph_lasso(X, model_selector, method): metric = "log_likelihood" print("Adaptive {} with:".format(model_selector)) print(" adaptive-method: {}".format(method)) if model_selector == "QuicGraphicalLassoCV": print(" metric: {}".for...
[ "Run QuicGraphicalLassoCV or QuicGraphicalLassoEBIC as a two step adaptive fit\n with method of choice (currently: 'binary', 'inverse', 'inverse_squared').\n\n Compare the support and values to the model-selection estimator.\n " ]
Please provide a description of the function:def quic_graph_lasso_ebic_manual(X, gamma=0): print("QuicGraphicalLasso (manual EBIC) with:") print(" mode: path") print(" gamma: {}".format(gamma)) model = QuicGraphicalLasso( lam=1.0, mode="path", init_method="cov", ...
[ "Run QuicGraphicalLasso with mode='path' and gamma; use EBIC criteria for model\n selection.\n\n The EBIC criteria is built into InverseCovarianceEstimator base class\n so we demonstrate those utilities here.\n " ]
Please provide a description of the function:def quic_graph_lasso_ebic(X, gamma=0): print("QuicGraphicalLassoEBIC with:") print(" mode: path") print(" gamma: {}".format(gamma)) model = QuicGraphicalLassoEBIC(lam=1.0, init_method="cov", gamma=gamma) model.fit(X) print(" len(path lams):...
[ "Run QuicGraphicalLassoEBIC with gamma.\n\n QuicGraphicalLassoEBIC is a convenience class. Results should be identical to\n those obtained via quic_graph_lasso_ebic_manual.\n " ]
Please provide a description of the function:def empirical(X): print("Empirical") cov = np.dot(X.T, X) / n_samples return cov, np.linalg.inv(cov)
[ "Compute empirical covariance as baseline estimator.\n " ]
Please provide a description of the function:def sk_ledoit_wolf(X): print("Ledoit-Wolf (sklearn)") lw_cov_, _ = ledoit_wolf(X) lw_prec_ = np.linalg.inv(lw_cov_) return lw_cov_, lw_prec_
[ "Estimate inverse covariance via scikit-learn ledoit_wolf function.\n " ]
Please provide a description of the function:def prototype_adjacency(self, n_block_features, alpha): return make_sparse_spd_matrix( n_block_features, alpha=np.abs(1.0 - alpha), smallest_coef=self.spd_low, largest_coef=self.spd_high, random_sta...
[ "Build a new graph.\n\n Doc for \".create(n_features, alpha)\"\n\n Parameters\n -----------\n n_features : int\n\n alpha : float (0,1)\n The complexity / sparsity factor.\n This is (1 - alpha_0) in sklearn.datasets.make_sparse_spd_matrix\n where al...
Please provide a description of the function:def prototype_adjacency(self, n_block_features, alpha=None): return -np.ones((n_block_features, n_block_features)) * 0.5 + self.prng.uniform( low=self.low, high=self.high, size=(n_block_features, n_block_features) )
[ "Build a new graph.\n\n Doc for \".create(n_features, alpha)\"\n\n Parameters\n -----------\n n_features : int\n\n [alpha] : float (0,1)\n Unused.\n\n Each graph will have a minimum of\n\n (n_blocks * n_block_features**2 - n_blocks) / 2\n\n edge...
Please provide a description of the function:def _nonzero_intersection(m, m_hat): n_features, _ = m.shape m_no_diag = m.copy() m_no_diag[np.diag_indices(n_features)] = 0 m_hat_no_diag = m_hat.copy() m_hat_no_diag[np.diag_indices(n_features)] = 0 m_hat_nnz = len(np.nonzero(m_hat_no_diag.fl...
[ "Count the number of nonzeros in and between m and m_hat.\n\n Returns\n ----------\n m_nnz : number of nonzeros in m (w/o diagonal)\n\n m_hat_nnz : number of nonzeros in m_hat (w/o diagonal)\n\n intersection_nnz : number of nonzeros in intersection of m/m_hat\n (w/o diagonal)\n ...
Please provide a description of the function:def support_false_positive_count(m, m_hat): m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat) return int((m_hat_nnz - intersection_nnz) / 2.0)
[ "Count the number of false positive support elements in\n m_hat in one triangle, not including the diagonal.\n " ]
Please provide a description of the function:def support_false_negative_count(m, m_hat): m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat) return int((m_nnz - intersection_nnz) / 2.0)
[ "Count the number of false negative support elements in\n m_hat in one triangle, not including the diagonal.\n " ]
Please provide a description of the function:def support_difference_count(m, m_hat): m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat) return int((m_nnz + m_hat_nnz - (2 * intersection_nnz)) / 2.0)
[ "Count the number of different elements in the support in one triangle,\n not including the diagonal.\n " ]
Please provide a description of the function:def has_exact_support(m, m_hat): m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat) return int((m_nnz + m_hat_nnz - (2 * intersection_nnz)) == 0)
[ "Returns 1 if support_difference_count is zero, 0 else.\n " ]
Please provide a description of the function:def has_approx_support(m, m_hat, prob=0.01): m_nz = np.flatnonzero(np.triu(m, 1)) m_hat_nz = np.flatnonzero(np.triu(m_hat, 1)) upper_diagonal_mask = np.flatnonzero(np.triu(np.ones(m.shape), 1)) not_m_nz = np.setdiff1d(upper_diagonal_mask, m_nz) int...
[ "Returns 1 if model selection error is less than or equal to prob rate,\n 0 else.\n\n NOTE: why does np.nonzero/np.flatnonzero create so much problems?\n " ]
Please provide a description of the function:def _compute_error(comp_cov, covariance_, precision_, score_metric="frobenius"): if score_metric == "frobenius": return np.linalg.norm(np.triu(comp_cov - covariance_, 1), ord="fro") elif score_metric == "spectral": error = comp_cov - covariance_ ...
[ "Computes the covariance error vs. comp_cov.\n\n Parameters\n ----------\n comp_cov : array-like, shape = (n_features, n_features)\n The precision to compare with.\n This should normally be the test sample covariance/precision.\n\n scaling : bool\n If True, the squared error norm is...
Please provide a description of the function:def _validate_path(path): if path is None: return None new_path = np.array(sorted(set(path), reverse=True)) if new_path[0] != path[0]: print("Warning: Path must be sorted largest to smallest.") return new_path
[ "Sorts path values from largest to smallest.\n\n Will warn if path parameter was not already sorted.\n " ]
Please provide a description of the function:def init_coefs(self, X): self.n_samples_, self.n_features_ = X.shape self.sample_covariance_, self.lam_scale_ = _init_coefs( X, method=self.init_method ) if not self.auto_scale: self.lam_scale_ = 1.0
[ "Computes ...\n\n Initialize the following values:\n self.n_samples\n self.n_features\n self.sample_covariance_\n self.lam_scale_\n " ]
Please provide a description of the function:def score(self, X_test, y=None): if isinstance(self.precision_, list): print("Warning: returning a list of scores.") S_test, lam_scale_test = _init_coefs(X_test, method=self.init_method) error = self.cov_error(S_test, score_metri...
[ "Computes the score between cov/prec of sample covariance of X_test\n and X via 'score_metric'.\n\n Note: We want to maximize score so we return the negative error.\n\n Parameters\n ----------\n X_test : array-like, shape = [n_samples, n_features]\n Test data of which w...
Please provide a description of the function:def cov_error(self, comp_cov, score_metric="frobenius"): if not isinstance(self.precision_, list): return _compute_error( comp_cov, self.covariance_, self.precision_, score_metric ) path_errors = [] fo...
[ "Computes the covariance error vs. comp_cov.\n\n May require self.path_\n\n Parameters\n ----------\n comp_cov : array-like, shape = (n_features, n_features)\n The precision to compare with.\n This should normally be the test sample covariance/precision.\n\n ...
Please provide a description of the function:def ebic(self, gamma=0): if not self.is_fitted_: return if not isinstance(self.precision_, list): return metrics.ebic( self.sample_covariance_, self.precision_, self.n_samples_,...
[ "Compute EBIC scores for each model. If model is not \"path\" then\n returns a scalar score value.\n\n May require self.path_\n\n See:\n Extended Bayesian Information Criteria for Gaussian Graphical Models\n R. Foygel and M. Drton\n NIPS 2010\n\n Parameters\n ...
Please provide a description of the function:def ebic_select(self, gamma=0): if not isinstance(self.precision_, list): raise ValueError("EBIC requires multiple models to select from.") return if not self.is_fitted_: return ebic_scores = self.ebic(ga...
[ "Uses Extended Bayesian Information Criteria for model selection.\n\n Can only be used in path mode (doesn't really make sense otherwise).\n\n See:\n Extended Bayesian Information Criteria for Gaussian Graphical Models\n R. Foygel and M. Drton\n NIPS 2010\n\n Parameters\n ...
Please provide a description of the function:def quic_graph_lasso(X, num_folds, metric): print("QuicGraphicalLasso + GridSearchCV with:") print(" metric: {}".format(metric)) search_grid = { "lam": np.logspace(np.log10(0.01), np.log10(1.0), num=100, endpoint=True), "init_method": ["cov...
[ "Run QuicGraphicalLasso with mode='default' and use standard scikit\n GridSearchCV to find the best lambda.\n\n Primarily demonstrates compatibility with existing scikit tooling.\n " ]
Please provide a description of the function:def quic_graph_lasso_cv(X, metric): print("QuicGraphicalLassoCV with:") print(" metric: {}".format(metric)) model = QuicGraphicalLassoCV( cv=2, # cant deal w more folds at small size n_refinements=6, n_jobs=1, init_method="...
[ "Run QuicGraphicalLassoCV on data with metric of choice.\n\n Compare results with GridSearchCV + quic_graph_lasso. The number of\n lambdas tested should be much lower with similar final lam_ selected.\n " ]
Please provide a description of the function:def model_average(X, penalization): n_trials = 100 print("ModelAverage with:") print(" estimator: QuicGraphicalLasso (default)") print(" n_trials: {}".format(n_trials)) print(" penalization: {}".format(penalization)) # if penalization is r...
[ "Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion\n matrix.\n\n NOTE: This returns precision_ proportions, not cov, prec estimates, so we\n return the raw proportions for \"cov\" and the threshold support\n estimate for prec.\n " ]
Please provide a description of the function:def adaptive_model_average(X, penalization, method): n_trials = 100 print("Adaptive ModelAverage with:") print(" estimator: QuicGraphicalLasso (default)") print(" n_trials: {}".format(n_trials)) print(" penalization: {}".format(penalization)) ...
[ "Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion\n matrix.\n\n NOTE: Only method = 'binary' really makes sense in this case.\n " ]
Please provide a description of the function:def graph_lasso(X, num_folds): print("GraphLasso (sklearn)") model = GraphLassoCV(cv=num_folds) model.fit(X) print(" lam_: {}".format(model.alpha_)) return model.covariance_, model.precision_, model.alpha_
[ "Estimate inverse covariance via scikit-learn GraphLassoCV class.\n " ]
Please provide a description of the function:def prototype_adjacency(self, n_block_features, alpha): return lattice( self.prng, n_block_features, alpha, random_sign=self.random_sign, low=self.low, high=self.high, )
[ "Build a new graph.\n\n Doc for \".create(n_features, alpha)\"\n\n Parameters\n -----------\n n_features : int\n\n alpha : float (0,1)\n The complexity / sparsity factor.\n\n Each graph will have a minimum of\n\n n_blocks * ceil(alpha * n_block...
Please provide a description of the function:def quic( S, lam, mode="default", tol=1e-6, max_iter=1000, Theta0=None, Sigma0=None, path=None, msg=0, ): assert mode in ["default", "path", "trace"], "mode = 'default', 'path' or 'trace'." Sn, Sm = S.shape if Sn != Sm: ...
[ "Fits the inverse covariance model according to the given training\n data and parameters.\n\n Parameters\n -----------\n S : 2D ndarray, shape (n_features, n_features)\n Empirical covariance or correlation matrix.\n\n Other parameters described in `class InverseCovariance`.\n\n Returns\n ...
Please provide a description of the function:def _quic_path( X, path, X_test=None, lam=0.5, tol=1e-6, max_iter=1000, Theta0=None, Sigma0=None, method="quic", verbose=0, score_metric="log_likelihood", init_method="corrcoef", ): S, lam_scale_ = _init_coefs(X, metho...
[ "Wrapper to compute path for example X.\n " ]
Please provide a description of the function:def fit(self, X, y=None, **fit_params): # quic-specific outputs self.opt_ = None self.cputime_ = None self.iters_ = None self.duality_gap_ = None # these must be updated upon self.fit() self.sample_covariance_...
[ "Fits the inverse covariance model according to the given training\n data and parameters.\n\n Parameters\n -----------\n X : 2D ndarray, shape (n_features, n_features)\n Input data.\n\n Returns\n -------\n self\n " ]
Please provide a description of the function:def lam_at_index(self, lidx): if self.path_ is None: return self.lam * self.lam_scale_ return self.lam * self.lam_scale_ * self.path_[lidx]
[ "Compute the scaled lambda used at index lidx.\n " ]
Please provide a description of the function:def fit(self, X, y=None): # quic-specific outputs self.opt_ = None self.cputime_ = None self.iters_ = None self.duality_gap_ = None # these must be updated upon self.fit() self.sample_covariance_ = None ...
[ "Fits the GraphLasso covariance model to X.\n\n Closely follows sklearn.covariance.graph_lasso.GraphLassoCV.\n\n Parameters\n ----------\n X : ndarray, shape (n_samples, n_features)\n Data from which to compute the covariance estimate\n " ]
Please provide a description of the function:def fit(self, X, y=None, **fit_params): # quic-specific outputs self.opt_ = None self.cputime_ = None self.iters_ = None self.duality_gap_ = None # these must be updated upon self.fit() self.path_ = None ...
[ "Fits the inverse covariance model according to the given training\n data and parameters.\n\n Parameters\n -----------\n X : 2D ndarray, shape (n_features, n_features)\n Input data.\n\n Returns\n -------\n self\n " ]
Please provide a description of the function:def _compute_ranks(X, winsorize=False, truncation=None, verbose=True): n_samples, n_features = X.shape Xrank = np.zeros(shape=X.shape) if winsorize: if truncation is None: truncation = 1 / ( 4 * np.power(n_samples, 0.25) ...
[ "\n Transform each column into ranked data. Tied ranks are averaged.\n Ranks can optionally be winsorized as described in Liu 2009 otherwise\n this returns Tsukahara's scaled rank based Z-estimator.\n\n Parameters\n ----------\n X : array-like, shape = (n_samples, n_features)\n The data mat...
Please provide a description of the function:def spearman_correlation(X, rowvar=False): Xrank = _compute_ranks(X) rank_correlation = np.corrcoef(Xrank, rowvar=rowvar) return 2 * np.sin(rank_correlation * np.pi / 6)
[ "\n Computes the spearman correlation estimate.\n This is effectively a bias corrected pearson correlation\n between rank transformed columns of X.\n\n Parameters\n ----------\n X: array-like, shape = [n_samples, n_features]\n Data matrix using which we compute the empirical\n correl...
Please provide a description of the function:def kendalltau_correlation(X, rowvar=False, weighted=False): if rowvar: X = X.T _, n_features = X.shape rank_correlation = np.eye(n_features) for row in np.arange(n_features): for col in np.arange(1 + row, n_features): if we...
[ "\n Computes kendall's tau correlation estimate.\n The option to use scipy.stats.weightedtau is not recommended\n as the implementation does not appear to handle ties correctly.\n\n Parameters\n ----------\n X: array-like, shape = [n_samples, n_features]\n Data matrix using which we compute...
Please provide a description of the function:def version(self): request_params = dict(self.request_params) request_url = str(self.request_url) result = self.do_http_request( 'get', request_url, data=request_params, custom_header=str(self....
[ "\n This attribute retrieve the API version.\n\n >>> Works().version\n '1.0.0'\n " ]
Please provide a description of the function:def count(self): request_params = dict(self.request_params) request_url = str(self.request_url) request_params['rows'] = 0 result = self.do_http_request( 'get', request_url, data=request_params, ...
[ "\n This method retrieve the total of records resulting from a given query.\n\n This attribute can be used compounded with query, filter,\n sort, order and facet methods.\n\n Examples:\n >>> from crossref.restful import Works\n >>> Works().query('zika').count()\n ...
Please provide a description of the function:def url(self): request_params = self._escaped_pagging() sorted_request_params = sorted([(k, v) for k, v in request_params.items()]) req = requests.Request( 'get', self.request_url, params=sorted_request_params).prepare() ...
[ "\n This attribute retrieve the url that will be used as a HTTP request to\n the Crossref API.\n\n This attribute can be used compounded with query, filter,\n sort, order and facet methods.\n\n Examples:\n >>> from crossref.restful import Works\n >>> Works()....
Please provide a description of the function:def order(self, order='asc'): context = str(self.context) request_url = build_url_endpoint(self.ENDPOINT, context) request_params = dict(self.request_params) if order not in self.ORDER_VALUES: raise UrlSyntaxError( ...
[ "\n This method retrieve an iterable object that implements the method\n __iter__. The arguments given will compose the parameters in the\n request url.\n\n This method can be used compounded with query, filter,\n sort and facet methods.\n\n kwargs: valid SORT_VALUES argume...
Please provide a description of the function:def select(self, *args): context = str(self.context) request_url = build_url_endpoint(self.ENDPOINT, context) request_params = dict(self.request_params) select_args = [] invalid_select_args = [] for item in args: ...
[ "\n This method retrieve an iterable object that implements the method\n __iter__. The arguments given will compose the parameters in the\n request url.\n\n This method can be used compounded with query, filter,\n sort and facet methods.\n\n args: valid FIELDS_SELECT argume...
Please provide a description of the function:def sort(self, sort='score'): context = str(self.context) request_url = build_url_endpoint(self.ENDPOINT, context) request_params = dict(self.request_params) if sort not in self.SORT_VALUES: raise UrlSyntaxError( ...
[ "\n This method retrieve an iterable object that implements the method\n __iter__. The arguments given will compose the parameters in the\n request url.\n\n This method can be used compounded with query, filter,\n order and facet methods.\n\n kwargs: valid SORT_VALUES argum...
Please provide a description of the function:def filter(self, **kwargs): context = str(self.context) request_url = build_url_endpoint(self.ENDPOINT, context) request_params = dict(self.request_params) for fltr, value in kwargs.items(): decoded_fltr = fltr.replace('_...
[ "\n This method retrieve an iterable object that implements the method\n __iter__. The arguments given will compose the parameters in the\n request url.\n\n This method can be used compounded and recursively with query, filter,\n order, sort and facet methods.\n\n kwargs: v...
Please provide a description of the function:def query(self, *args, **kwargs): context = str(self.context) request_url = build_url_endpoint(self.ENDPOINT, context) request_params = dict(self.request_params) if args: request_params['query'] = ' '.join([str(i) for i i...
[ "\n This method retrieve an iterable object that implements the method\n __iter__. The arguments given will compose the parameters in the\n request url.\n\n This method can be used compounded and recursively with query, filter,\n order, sort and facet methods.\n\n args: str...
Please provide a description of the function:def sample(self, sample_size=20): context = str(self.context) request_url = build_url_endpoint(self.ENDPOINT, context) request_params = dict(self.request_params) try: if sample_size > 100: raise UrlSyntaxE...
[ "\n This method retrieve an iterable object that implements the method\n __iter__. The arguments given will compose the parameters in the\n request url.\n\n kwargs: sample_size (Integer) between 0 and 100.\n\n return: iterable object of Works metadata\n\n Example:\n ...
Please provide a description of the function:def doi(self, doi, only_message=True): request_url = build_url_endpoint( '/'.join([self.ENDPOINT, doi]) ) request_params = {} result = self.do_http_request( 'get', request_url, data=req...
[ "\n This method retrieve the DOI metadata related to a given DOI\n number.\n\n args: Crossref DOI id (String)\n\n return: JSON\n\n Example:\n >>> from crossref.restful import Works\n >>> works = Works()\n >>> works.doi('10.1590/S0004-28032013005000...
Please provide a description of the function:def doi_exists(self, doi): request_url = build_url_endpoint( '/'.join([self.ENDPOINT, doi]) ) request_params = {} result = self.do_http_request( 'get', request_url, data=request_params,...
[ "\n This method retrieve a boolean according to the existence of a crossref\n DOI number. It returns False if the API results a 404 status code.\n\n args: Crossref DOI id (String)\n\n return: Boolean\n\n Example 1:\n >>> from crossref.restful import Works\n >...
Please provide a description of the function:def works(self, funder_id): context = '%s/%s' % (self.ENDPOINT, str(funder_id)) return Works(context=context)
[ "\n This method retrieve a iterable of Works of the given funder.\n\n args: Crossref allowed document Types (String)\n\n return: Works()\n " ]
Please provide a description of the function:def query(self, *args): context = str(self.context) request_url = build_url_endpoint(self.ENDPOINT) request_params = dict(self.request_params) if args: request_params['query'] = ' '.join([str(i) for i in args]) r...
[ "\n This method retrieve an iterable object that implements the method\n __iter__. The arguments given will compose the parameters in the\n request url.\n\n args: strings (String)\n\n return: iterable object of Members metadata\n\n Example:\n >>> from crossref.re...
Please provide a description of the function:def works(self, member_id): context = '%s/%s' % (self.ENDPOINT, str(member_id)) return Works(context=context)
[ "\n This method retrieve a iterable of Works of the given member.\n\n args: Member ID (Integer)\n\n return: Works()\n " ]
Please provide a description of the function:def all(self): request_url = build_url_endpoint(self.ENDPOINT, self.context) request_params = dict(self.request_params) result = self.do_http_request( 'get', request_url, data=request_params, c...
[ "\n This method retrieve an iterator with all the available types.\n\n return: iterator of crossref document types\n\n Example:\n >>> from crossref.restful import Types\n >>> types = Types()\n >>> [i for i in types.all()]\n [{'label': 'Book Section', ...
Please provide a description of the function:def works(self, type_id): context = '%s/%s' % (self.ENDPOINT, str(type_id)) return Works(context=context)
[ "\n This method retrieve a iterable of Works of the given type.\n\n args: Crossref allowed document Types (String)\n\n return: Works()\n " ]
Please provide a description of the function:def works(self, prefix_id): context = '%s/%s' % (self.ENDPOINT, str(prefix_id)) return Works(context=context)
[ "\n This method retrieve a iterable of Works of the given prefix.\n\n args: Crossref Prefix (String)\n\n return: Works()\n " ]
Please provide a description of the function:def works(self, issn): context = '%s/%s' % (self.ENDPOINT, str(issn)) return Works(context=context)
[ "\n This method retrieve a iterable of Works of the given journal.\n\n args: Journal ISSN (String)\n\n return: Works()\n " ]
Please provide a description of the function:def register_doi(self, submission_id, request_xml): endpoint = self.get_endpoint('deposit') files = { 'mdFile': ('%s.xml' % submission_id, request_xml) } params = { 'operation': 'doMDUpload', 'lo...
[ "\n This method registry a new DOI number in Crossref or update some DOI\n metadata.\n\n submission_id: Will be used as the submission file name. The file name\n could be used in future requests to retrieve the submission status.\n\n request_xml: The XML with the document metadata...
Please provide a description of the function:def request_doi_status_by_filename(self, file_name, data_type='result'): endpoint = self.get_endpoint('submissionDownload') params = { 'usr': self.api_user, 'pwd': self.api_key, 'file_name': file_name, ...
[ "\n This method retrieve the DOI requests status.\n\n file_name: Used as unique ID to identify a deposit.\n\n data_type: [contents, result]\n contents - retrieve the XML submited by the publisher\n result - retrieve a JSON with the status of the submission\n " ]
Please provide a description of the function:def request_doi_status_by_batch_id(self, doi_batch_id, data_type='result'): endpoint = self.get_endpoint('submissionDownload') params = { 'usr': self.api_user, 'pwd': self.api_key, 'doi_batch_id': doi_batch_id, ...
[ "\n This method retrieve the DOI requests status.\n\n file_name: Used as unique ID to identify a deposit.\n\n data_type: [contents, result]\n contents - retrieve the XML submited by the publisher\n result - retrieve a XML with the status of the submission\n " ]
Please provide a description of the function:def asbool(s): if s is None: return False if isinstance(s, bool): return s s = str(s).strip() return s.lower() in truthy
[ " Return the boolean value ``True`` if the case-lowered value of string\n input ``s`` is a :term:`truthy string`. If ``s`` is already one of the\n boolean values ``True`` or ``False``, return it." ]
Please provide a description of the function:def rule_from_pattern(pattern, base_path=None, source=None): if base_path and base_path != abspath(base_path): raise ValueError('base_path must be absolute') # Store the exact pattern for our repr and string functions orig_pattern = pattern # Early returns follow # ...
[ "\n\tTake a .gitignore match pattern, such as \"*.py[cod]\" or \"**/*.bak\",\n\tand return an IgnoreRule suitable for matching against files and\n\tdirectories. Patterns which do not match files, such as comments\n\tand blank lines, will return None.\n\tBecause git allows for nested .gitignore files, a base_path va...
Please provide a description of the function:def _find_plugin_dir(module_type): '''Find the directory containing the plugin definition for the given type. Do this by searching all the paths where plugins can live for a dir that matches the type name.''' for install_dir in _get_plugin_install_dirs(): ...
[]
Please provide a description of the function:def _get_plugin_install_dirs(): '''Return all the places on the filesystem where we should look for plugin definitions. Order is significant here: user-installed plugins should be searched first, followed by system-installed plugins, and last of all peru buil...
[]
Please provide a description of the function:def unglobbed_prefix(glob): '''Returns all the path components, starting from the beginning, up to the first one with any kind of glob. So for example, if glob is 'a/b/c*/d', return 'a/b'.''' parts = [] for part in PurePosixPath(glob).parts: if co...
[]
Please provide a description of the function:def split_on_stars_interpreting_backslashes(s): r'''We don't want to do in-place substitutions of a regex for *, because we need to be able to regex-escape the rest of the string. Instead, we split the string on *'s, so that the rest can be regex-escaped and then...
[]
Please provide a description of the function:def glob_to_path_regex(glob): '''Supports * and **. Backslashes can escape stars or other backslashes. As in pathlib, ** may not adjoin any characters other than slash. Unlike pathlib, because we're not talking to the actual filesystem, ** will match files as...
[]
Please provide a description of the function:def force_utf8_in_ascii_mode_hack(): '''In systems without a UTF8 locale configured, Python will default to ASCII mode for stdout and stderr. This causes our fancy display to fail with encoding errors. In particular, you run into this if you try to run peru i...
[]
Please provide a description of the function:async def parse_target(self, runtime, target_str): '''A target is a pipeline of a module into zero or more rules, and each module and rule can itself be scoped with zero or more module names.''' pipeline_parts = target_str.split(RULE_SEPARATOR) ...
[]
Please provide a description of the function:def _maybe_quote(val): '''All of our values should be strings. Usually those can be passed in as bare words, but if they're parseable as an int or float we need to quote them.''' assert isinstance(val, str), 'We should never set non-string values.' needs_...
[]
Please provide a description of the function:async def gather_coalescing_exceptions(coros, display, *, verbose): '''The tricky thing about running multiple coroutines in parallel is what we're supposed to do when one of them raises an exception. The approach we're using here is to catch exceptions and keep ...
[]
Please provide a description of the function:async def create_subprocess_with_handle(command, display_handle, *, shell=False, cwd, ...
[]
Please provide a description of the function:async def safe_communicate(process, input=None): '''Asyncio's communicate method has a bug where `communicate(input=b"")` is treated the same as `communicate(). That means that child processes can hang waiting for input, when their stdin should be closed. See ...
[]
Please provide a description of the function:def raises_gathered(error_type): '''For use in tests. Many tests expect a single error to be thrown, and want it to be of a specific type. This is a helper method for when that type is inside a gathered exception.''' container = RaisesGatheredContainer() ...
[]
Please provide a description of the function:async def merge_imports_tree(cache, imports, target_trees, base_tree=None): '''Take an Imports struct and a dictionary of resolved trees and merge the unified imports tree. If base_tree is supplied, merge that too. There are a couple reasons for structuring this ...
[]
Please provide a description of the function:def get_request_filename(request): '''Figure out the filename for an HTTP download.''' # Check to see if a filename is specified in the HTTP headers. if 'Content-Disposition' in request.info(): disposition = request.info()['Content-Disposition'] p...
[]
Please provide a description of the function:def _extract_optional_list_field(blob, name): '''Handle optional fields that can be either a string or a list of strings.''' value = _optional_list(typesafe_pop(blob, name, [])) if value is None: raise ParserError( '"{}" field must be a st...
[]
Please provide a description of the function:def _extract_multimap_field(blob, name): '''Extracts multimap fields. Values can either be a scalar string or a list of strings. We need to parse both. For example: example: a: foo/ b: - bar/ - baz/''' message =...
[]
Please provide a description of the function:def _optional_list(value): '''Convert a value that may be a scalar (str) or list into a tuple. This produces uniform output for fields that may supply a single value or list of values, like the `imports` field.''' if isinstance(value, str): return (va...
[]
Please provide a description of the function:def pop_all(self): new_stack = type(self)() new_stack._exit_callbacks = self._exit_callbacks self._exit_callbacks = deque() return new_stack
[ "Preserve the context stack by transferring it to a new instance." ]
Please provide a description of the function:def push(self, exit): # We use an unbound method rather than a bound method to follow # the standard lookup behaviour for special methods. _cb_type = type(exit) try: exit_method = _cb_type.__exit__ except Attribut...
[ "Registers a callback with the standard __exit__ method signature.\n Can suppress exceptions the same way __exit__ method can.\n Also accepts any object with an __exit__ method (registering a call\n to the method instead of the object itself).\n " ]
Please provide a description of the function:def enter_context(self, cm): # We look up the special methods on the type to match the with # statement. _cm_type = type(cm) _exit = _cm_type.__exit__ result = _cm_type.__enter__(cm) self._push_cm_exit(cm, _exit) ...
[ "Enters the supplied context manager.\n If successful, also pushes its __exit__ method as a callback and\n returns the result of the __enter__ method.\n " ]
Please provide a description of the function:def callback(self, callback, *args, **kwds): _exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. ...
[ "Registers an arbitrary callback and arguments.\n Cannot suppress exceptions.\n " ]
Please provide a description of the function:def _push_cm_exit(self, cm, cm_exit): _exit_wrapper = self._create_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, True)
[ "Helper to correctly register callbacks to __exit__ methods." ]
Please provide a description of the function:async def enter_async_context(self, cm): _cm_type = type(cm) _exit = _cm_type.__aexit__ result = await _cm_type.__aenter__(cm) self._push_async_cm_exit(cm, _exit) return result
[ "Enters the supplied async context manager.\n If successful, also pushes its __aexit__ method as a callback and\n returns the result of the __aenter__ method.\n " ]
Please provide a description of the function:def push_async_exit(self, exit): _cb_type = type(exit) try: exit_method = _cb_type.__aexit__ except AttributeError: # Not an async context manager, so assume it's a coroutine function self._push_exit_callba...
[ "Registers a coroutine function with the standard __aexit__ method\n signature.\n Can suppress exceptions the same way __aexit__ method can.\n Also accepts any object with an __aexit__ method (registering a call\n to the method instead of the object itself).\n " ]
Please provide a description of the function:def push_async_callback(self, callback, *args, **kwds): _exit_wrapper = self._create_async_cb_wrapper(callback, *args, **kwds) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with intr...
[ "Registers an arbitrary coroutine function and arguments.\n Cannot suppress exceptions.\n " ]
Please provide a description of the function:def _push_async_cm_exit(self, cm, cm_exit): _exit_wrapper = self._create_async_exit_wrapper(cm, cm_exit) self._push_exit_callback(_exit_wrapper, False)
[ "Helper to correctly register coroutine function to __aexit__\n method." ]
Please provide a description of the function:async def Runtime(args, env): 'This is the async constructor for the _Runtime class.' r = _Runtime(args, env) await r._init_cache() return r
[]
Please provide a description of the function:def find_project_file(start_dir, basename): '''Walk up the directory tree until we find a file of the given name.''' prefix = os.path.abspath(start_dir) while True: candidate = os.path.join(prefix, basename) if os.path.isfile(candidate): ...
[]
Please provide a description of the function:def delete_if_error(path): '''If any exception is raised inside the context, delete the file at the given path, and allow the exception to continue.''' try: yield except Exception: if os.path.exists(path): os.remove(path) r...
[]
Please provide a description of the function:def _format_file_lines(files): '''Given a list of filenames that we're about to print, limit it to a reasonable number of lines.''' LINES_TO_SHOW = 10 if len(files) <= LINES_TO_SHOW: lines = '\n'.join(files) else: lines = ('\n'.join(files[...
[]
Please provide a description of the function:def dotperu_exclude_case_insensitive_git_globs(): globs = [] for capitalization in DOTPERU_CAPITALIZATIONS: globs.append(capitalization + '/**') globs.append('**/' + capitalization + '/**') return globs
[ "These use the glob syntax accepted by `git ls-files` (NOT our own\n glob.py). Note that ** must match at least one path component, so we have\n to use separate globs for matches at the root and matches below." ]
Please provide a description of the function:def git_env(self): 'Set the index file and prevent git from reading global configs.' env = dict(os.environ) for var in ["HOME", "XDG_CONFIG_HOME"]: env.pop(var, None) env["GIT_CONFIG_NOSYSTEM"] = "true" # Weirdly, GIT_INDEX...
[]
Please provide a description of the function:async def read_tree_updating_working_copy(self, tree, force): '''This method relies on the current working copy being clean with respect to the current index. The benefit of this over checkout_missing_files_from_index(), is that is clean up files that...
[]
Please provide a description of the function:async def export_tree(self, tree, dest, previous_tree=None, *, force=False, previous_index_file=None): '''This ...
[]
Please provide a description of the function:async def modify_tree(self, tree, modifications): '''The modifications are a map of the form, {path: TreeEntry}. The tree can be None to indicate an empty starting tree. The entries can be either blobs or trees, or None to indicate a deletion. The ret...
[]
Please provide a description of the function:def load_states(): from pkg_resources import resource_stream # load state data from pickle file with resource_stream(__name__, 'states.pkl') as pklfile: for s in pickle.load(pklfile): state = State(**s) # create state object ...
[ " Load state data from pickle file distributed with this package.\n\n Creates lists of states, territories, and combined states and\n territories. Also adds state abbreviation attribute access\n to the package: us.states.MD\n " ]
Please provide a description of the function:def lookup(val, field=None, use_cache=True): import jellyfish if field is None: if FIPS_RE.match(val): field = 'fips' elif ABBR_RE.match(val): val = val.upper() field = 'abbr' else: val = ...
[ " Semi-fuzzy state lookup. This method will make a best effort\n attempt at finding the state based on the lookup value provided.\n\n * two digits will search for FIPS code\n * two letters will search for state abbreviation\n * anything else will try to match the metaphone of state...
Please provide a description of the function:def query(searchstr, outformat=FORMAT_BIBTEX, allresults=False): logger.debug("Query: {sstring}".format(sstring=searchstr)) searchstr = '/scholar?q='+quote(searchstr) url = GOOGLE_SCHOLAR_URL + searchstr header = HEADERS header['Cookie'] = "GSP=CF=%d...
[ "Query google scholar.\n\n This method queries google scholar and returns a list of citations.\n\n Parameters\n ----------\n searchstr : str\n the query\n outformat : int, optional\n the output format of the citations. Default is bibtex.\n allresults : bool, optional\n return ...
Please provide a description of the function:def get_links(html, outformat): if outformat == FORMAT_BIBTEX: refre = re.compile(r'<a href="https://scholar.googleusercontent.com(/scholar\.bib\?[^"]*)') elif outformat == FORMAT_ENDNOTE: refre = re.compile(r'<a href="https://scholar.googleuserc...
[ "Return a list of reference links from the html.\n\n Parameters\n ----------\n html : str\n outformat : int\n the output format of the citations\n\n Returns\n -------\n List[str]\n the links to the references\n\n " ]
Please provide a description of the function:def convert_pdf_to_txt(pdf, startpage=None): if startpage is not None: startpageargs = ['-f', str(startpage)] else: startpageargs = [] stdout = subprocess.Popen(["pdftotext", "-q"] + startpageargs + [pdf, "-"], s...
[ "Convert a pdf file to text and return the text.\n\n This method requires pdftotext to be installed.\n\n Parameters\n ----------\n pdf : str\n path to pdf file\n startpage : int, optional\n the first page we try to convert\n\n Returns\n -------\n str\n the converted text...
Please provide a description of the function:def pdflookup(pdf, allresults, outformat, startpage=None): txt = convert_pdf_to_txt(pdf, startpage) # remove all non alphanumeric characters txt = re.sub("\W", " ", txt) words = txt.strip().split()[:20] gsquery = " ".join(words) bibtexlist = quer...
[ "Look a pdf up on google scholar and return bibtex items.\n\n Paramters\n ---------\n pdf : str\n path to the pdf file\n allresults : bool\n return all results or only the first (i.e. best one)\n outformat : int\n the output format of the citations\n startpage : int\n f...
Please provide a description of the function:def _get_bib_element(bibitem, element): lst = [i.strip() for i in bibitem.split("\n")] for i in lst: if i.startswith(element): value = i.split("=", 1)[-1] value = value.strip() while value.endswith(','): ...
[ "Return element from bibitem or None.\n\n Paramteters\n -----------\n bibitem :\n element :\n\n Returns\n -------\n\n " ]