code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def MultivariateNormal(inv_mass_matrix): """Potential and kinetic energy for a multivariate normal distribution.""" def log_density(q): q, _ = ravel_pytree(q) return stats.multivariate_normal.logpdf(q, jnp.zeros_like(q), inv_mass_matrix) def kinetic_energy(p, position=None): del po...
Potential and kinetic energy for a multivariate normal distribution.
MultivariateNormal
python
blackjax-devs/blackjax
tests/mcmc/test_integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_integrators.py
Apache-2.0
def test_esh_momentum_update(self, dims): """ Test the numerically efficient version of the momentum update currently implemented match the naive implementation according to the Equation 16 in :cite:p:`robnik2023microcanonical` """ step_size = 1e-3 key0, key1 = ja...
Test the numerically efficient version of the momentum update currently implemented match the naive implementation according to the Equation 16 in :cite:p:`robnik2023microcanonical`
test_esh_momentum_update
python
blackjax-devs/blackjax
tests/mcmc/test_integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_integrators.py
Apache-2.0
def test_non_separable(self): """Test the integration of a non-separable Hamiltonian with a known closed-form solution, as defined in https://arxiv.org/abs/1609.02212. """ def neg_potential(q): return -0.5 * (q**2 + 1) def kinetic_energy(p, position=None): ...
Test the integration of a non-separable Hamiltonian with a known closed-form solution, as defined in https://arxiv.org/abs/1609.02212.
test_non_separable
python
blackjax-devs/blackjax
tests/mcmc/test_integrators.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_integrators.py
Apache-2.0
def test_invalid(self, shape, is_inv): """Test formatting raises error for invalid shapes""" mass_matrix = jnp.zeros(shape=shape) with self.assertRaisesRegex( ValueError, "The mass matrix has the wrong number of dimensions" ): metrics._format_covariance(mass_matri...
Test formatting raises error for invalid shapes
test_invalid
python
blackjax-devs/blackjax
tests/mcmc/test_metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_metrics.py
Apache-2.0
def test_gaussian_euclidean_ndim_invalid(self, shape): """Test Gaussian Euclidean Function returns correct function invalid ndim""" x = jnp.ones(shape=shape) with self.assertRaisesRegex( ValueError, "The mass matrix has the wrong number of dimensions" ): _ = metri...
Test Gaussian Euclidean Function returns correct function invalid ndim
test_gaussian_euclidean_ndim_invalid
python
blackjax-devs/blackjax
tests/mcmc/test_metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_metrics.py
Apache-2.0
def test_gaussian_euclidean_dim_1(self): """Test Gaussian Euclidean Function with ndim 1""" inverse_mass_matrix = jnp.asarray([1 / 4], dtype=self.dtype) momentum, kinetic_energy, _, scale = metrics.gaussian_euclidean( inverse_mass_matrix ) arbitrary_position = jnp.as...
Test Gaussian Euclidean Function with ndim 1
test_gaussian_euclidean_dim_1
python
blackjax-devs/blackjax
tests/mcmc/test_metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_metrics.py
Apache-2.0
def test_gaussian_euclidean_dim_2(self): """Test Gaussian Euclidean Function with ndim 2""" inverse_mass_matrix = jnp.asarray( [[2 / 3, 0.5], [0.5, 3 / 4]], dtype=self.dtype ) momentum, kinetic_energy, _, scale = metrics.gaussian_euclidean( inverse_mass_matrix ...
Test Gaussian Euclidean Function with ndim 2
test_gaussian_euclidean_dim_2
python
blackjax-devs/blackjax
tests/mcmc/test_metrics.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_metrics.py
Apache-2.0
def test_normal_univariate(self, initial_position): """ Move samples are generated in the univariate case, with std following sigma, and independently of the position. """ keys = jax.random.split(self.key, 200) proposal = normal(sigma=jnp.array([1.0])) samples = [...
Move samples are generated in the univariate case, with std following sigma, and independently of the position.
test_normal_univariate
python
blackjax-devs/blackjax
tests/mcmc/test_proposal.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_proposal.py
Apache-2.0
def test_one_step_addition(self): """New position is an addition to previous position. Since the density == 1, the proposal is accepted. The random step may depend on the previous position """ rng_key = jax.random.key(0) initial_position = jnp.array([50.0]) def r...
New position is an addition to previous position. Since the density == 1, the proposal is accepted. The random step may depend on the previous position
test_one_step_addition
python
blackjax-devs/blackjax
tests/mcmc/test_random_walk_without_chex.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_random_walk_without_chex.py
Apache-2.0
def test_proposal_is_independent_of_position(self): """New position does not depend on previous position""" rng_key = jax.random.key(0) initial_position = jnp.array([50.0]) other_position = jnp.array([15000.0]) step = build_irmh() for previous_position in [initial_posit...
New position does not depend on previous position
test_proposal_is_independent_of_position
python
blackjax-devs/blackjax
tests/mcmc/test_random_walk_without_chex.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_random_walk_without_chex.py
Apache-2.0
def test_non_symmetric_proposal(self): """ Given that proposal_logdensity_fn is included, thus the proposal is non-symmetric. When computing the acceptance of the proposed state Then proposal_logdensity_fn value is taken into account """ rng_key = jax.random.key(0...
Given that proposal_logdensity_fn is included, thus the proposal is non-symmetric. When computing the acceptance of the proposed state Then proposal_logdensity_fn value is taken into account
test_non_symmetric_proposal
python
blackjax-devs/blackjax
tests/mcmc/test_random_walk_without_chex.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_random_walk_without_chex.py
Apache-2.0
def test_generate_reject(self): """ Steps from previous state, Builds a proposal from the new state and given that the sampling rule rejects, the prev_state is proposed again """ rng_key = jax.random.key(0) prev_state = RWState(jnp.array([30.0]), 15.0) ...
Steps from previous state, Builds a proposal from the new state and given that the sampling rule rejects, the prev_state is proposed again
test_generate_reject
python
blackjax-devs/blackjax
tests/mcmc/test_random_walk_without_chex.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_random_walk_without_chex.py
Apache-2.0
def test_window_adaptation( self, case, is_mass_matrix_diagonal, window_adapt_config ): """Test the HMC kernel and the Stan warmup.""" rng_key, init_key0, init_key1 = jax.random.split(self.key, 3) x_data = jax.random.normal(init_key0, shape=(1000, 1)) y_data = 3 * x_data + ja...
Test the HMC kernel and the Stan warmup.
test_window_adaptation
python
blackjax-devs/blackjax
tests/mcmc/test_sampling.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_sampling.py
Apache-2.0
def __init__(self, d, condition_number): """numpy_seed is used to generate a random rotation for the covariance matrix. If None, the covariance matrix is diagonal.""" self.ndims = d self.name = "IllConditionedGaussian" self.condition_numbe...
numpy_seed is used to generate a random rotation for the covariance matrix. If None, the covariance matrix is diagonal.
__init__
python
blackjax-devs/blackjax
tests/mcmc/test_sampling.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_sampling.py
Apache-2.0
def test_meads(self): """Test the MEADS adaptation w/ GHMC kernel.""" rng_key, init_key0, init_key1 = jax.random.split(self.key, 3) x_data = jax.random.normal(init_key0, shape=(1000, 1)) y_data = 3 * x_data + jax.random.normal(init_key1, shape=x_data.shape) logposterior_fn_ = fu...
Test the MEADS adaptation w/ GHMC kernel.
test_meads
python
blackjax-devs/blackjax
tests/mcmc/test_sampling.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_sampling.py
Apache-2.0
def test_chees(self, jitter_generator): """Test the ChEES adaptation w/ HMC kernel.""" rng_key, init_key0, init_key1 = jax.random.split(self.key, 3) x_data = jax.random.normal(init_key0, shape=(1000, 1)) y_data = 3 * x_data + jax.random.normal(init_key1, shape=x_data.shape) logp...
Test the ChEES adaptation w/ HMC kernel.
test_chees
python
blackjax-devs/blackjax
tests/mcmc/test_sampling.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_sampling.py
Apache-2.0
def generate_multivariate_target(self, rng=None): """Genrate a Multivariate Normal distribution as target.""" if rng is None: loc = jnp.array([0.0, 3]) scale = jnp.array([1.0, 2.0]) rho = jnp.array(0.75) else: loc_rng, scale_rng, rho_rng = jax.rand...
Genrate a Multivariate Normal distribution as target.
generate_multivariate_target
python
blackjax-devs/blackjax
tests/mcmc/test_sampling.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_sampling.py
Apache-2.0
def test_mcse(self, algorithm, parameters, is_mass_matrix_diagonal): """Test convergence using Monte Carlo CLT across multiple chains.""" pos_init_key, sample_key = jax.random.split(self.key) ( logdensity_fn, true_loc, true_scale, true_rho, ...
Test convergence using Monte Carlo CLT across multiple chains.
test_mcse
python
blackjax-devs/blackjax
tests/mcmc/test_sampling.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/mcmc/test_sampling.py
Apache-2.0
def test_dual_averaging(self): """We test the dual averaging algorithm by searching for the point that minimizes the gradient of a simple function. """ # we need to wrap the gradient in a namedtuple as we optimize for a target # acceptance probability in the context of HMC. ...
We test the dual averaging algorithm by searching for the point that minimizes the gradient of a simple function.
test_dual_averaging
python
blackjax-devs/blackjax
tests/optimizers/test_optimizers.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/optimizers/test_optimizers.py
Apache-2.0
def test_minimize_lbfgs(self, maxiter, maxcor): """Test if dot product between approximate inverse hessian and gradient is the same between two loop recursion algorthm of LBFGS and formulas of the pathfinder paper""" def regression_logprob(log_scale, coefs, preds, x): """Lin...
Test if dot product between approximate inverse hessian and gradient is the same between two loop recursion algorthm of LBFGS and formulas of the pathfinder paper
test_minimize_lbfgs
python
blackjax-devs/blackjax
tests/optimizers/test_optimizers.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/optimizers/test_optimizers.py
Apache-2.0
def test_recover_diag_inv_hess(self): "Compare inverse Hessian estimation from LBFGS with known groundtruth." nd = 5 mean = np.linspace(3.0, 50.0, nd) cov = np.diag(np.linspace(1.0, 10.0, nd)) def loss_fn(x): return -stats.multivariate_normal.logpdf(x, mean, cov) ...
Compare inverse Hessian estimation from LBFGS with known groundtruth.
test_recover_diag_inv_hess
python
blackjax-devs/blackjax
tests/optimizers/test_optimizers.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/optimizers/test_optimizers.py
Apache-2.0
def test_recover_posterior(self, ndim): """Test if pathfinder is able to estimate well enough the posterior of a normal-normal conjugate model""" def logp_posterior_conjugate_normal_model( x, observed, prior_mu, prior_prec, true_prec ): n = observed.shape[0] ...
Test if pathfinder is able to estimate well enough the posterior of a normal-normal conjugate model
test_recover_posterior
python
blackjax-devs/blackjax
tests/optimizers/test_pathfinder.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/optimizers/test_pathfinder.py
Apache-2.0
def test_scale_when_aceptance_below_optimal(self): """ Given that the acceptance rate is below optimal, the scale gets reduced. """ np.testing.assert_allclose( update_scale_from_acceptance_rate( scales=jnp.array([0.5]), acceptance_rates=jnp.array([0.2]...
Given that the acceptance rate is below optimal, the scale gets reduced.
test_scale_when_aceptance_below_optimal
python
blackjax-devs/blackjax
tests/smc/test_inner_kernel_tuning.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_inner_kernel_tuning.py
Apache-2.0
def test_scale_when_aceptance_above_optimal(self): """ Given that the acceptance rate is above optimal the scale increases ------- """ np.testing.assert_allclose( update_scale_from_acceptance_rate( scales=jnp.array([0.5]), acceptance_rates=jnp....
Given that the acceptance rate is above optimal the scale increases -------
test_scale_when_aceptance_above_optimal
python
blackjax-devs/blackjax
tests/smc/test_inner_kernel_tuning.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_inner_kernel_tuning.py
Apache-2.0
def test_scale_mean_smoothes(self): """ The end result depends on the mean acceptance rate, smoothing the results """ np.testing.assert_allclose( update_scale_from_acceptance_rate( scales=jnp.array([0.5, 0.5]), acceptance_rates=jnp.array([0.3, 0.2]) ...
The end result depends on the mean acceptance rate, smoothing the results
test_scale_mean_smoothes
python
blackjax-devs/blackjax
tests/smc/test_inner_kernel_tuning.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_inner_kernel_tuning.py
Apache-2.0
def test_tuning_pretuning(self): """ Tests that we can apply tuning on some parameters and pretuning in some others at the same time. """ ( init_particles, logprior_fn, loglikelihood_fn, ) = self.particles_prior_loglikelihood() ...
Tests that we can apply tuning on some parameters and pretuning in some others at the same time.
test_tuning_pretuning
python
blackjax-devs/blackjax
tests/smc/test_inner_kernel_tuning.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_inner_kernel_tuning.py
Apache-2.0
def test_measure_of_chain_mixing_identity(self): """ Given identity matrix and 1. acceptance probability then the mixing is the square of norm 2. """ m = np.eye(2) acceptance_probabilities = np.array([1.0, 1.0]) chain_mixing = esjd(m)( self.previous_p...
Given identity matrix and 1. acceptance probability then the mixing is the square of norm 2.
test_measure_of_chain_mixing_identity
python
blackjax-devs/blackjax
tests/smc/test_pretuning.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_pretuning.py
Apache-2.0
def test_measure_of_chain_mixing_with_non_1_acceptance_rate(self): """ Given identity matrix then the mixing is the square of norm 2. multiplied by the acceptance rate """ m = np.eye(2) acceptance_probabilities = np.array([0.5, 0.2]) chain_mixing = esjd(m)( ...
Given identity matrix then the mixing is the square of norm 2. multiplied by the acceptance rate
test_measure_of_chain_mixing_with_non_1_acceptance_rate
python
blackjax-devs/blackjax
tests/smc/test_pretuning.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_pretuning.py
Apache-2.0
def test_update_param_distribution(self): """ Given an extremely good mixing on one chain, and that the alpha parameter is 0, then the parameters of that chain with a slight mutation due to noise are reused. """ ( new_parameter_distribution, chain...
Given an extremely good mixing on one chain, and that the alpha parameter is 0, then the parameters of that chain with a slight mutation due to noise are reused.
test_update_param_distribution
python
blackjax-devs/blackjax
tests/smc/test_pretuning.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_pretuning.py
Apache-2.0
def test_update_multi_sigmas(self): """ When we have multiple parameters, the performance is attached to its combination so sampling must work accordingly. """ ( new_parameter_distribution, chain_mixing_measurement, ) = update_parameter_distributio...
When we have multiple parameters, the performance is attached to its combination so sampling must work accordingly.
test_update_multi_sigmas
python
blackjax-devs/blackjax
tests/smc/test_pretuning.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_pretuning.py
Apache-2.0
def test_ess_solver_multivariate(self, target_ess): """ Posterior with more than one variable. Let's assume we want to sample from P(x) x ~ N(mean, cov) x in R^{2} """ num_particles = 1000 mean = jnp.zeros((1, 2)) cov = jnp.diag(jnp.array([1, 1])) _logdens...
Posterior with more than one variable. Let's assume we want to sample from P(x) x ~ N(mean, cov) x in R^{2}
test_ess_solver_multivariate
python
blackjax-devs/blackjax
tests/smc/test_smc_ess.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_smc_ess.py
Apache-2.0
def test_ess_solver_posterior_signature(self, target_ess): """ Posterior with more than one variable. Let's assume we want to sample from P(x,y) x ~ N(mean, cov) y ~ N(mean, cov) """ num_particles = 1000 mean = jnp.zeros((1, 2)) cov = jnp.diag(jnp.array([1, 1])) ...
Posterior with more than one variable. Let's assume we want to sample from P(x,y) x ~ N(mean, cov) y ~ N(mean, cov)
test_ess_solver_posterior_signature
python
blackjax-devs/blackjax
tests/smc/test_smc_ess.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_smc_ess.py
Apache-2.0
def normal_logdensity_fn(x, chol_cov): """minus log-density of a centered multivariate normal distribution""" dim = chol_cov.shape[0] y = jax.scipy.linalg.solve_triangular(chol_cov, x, lower=True) normalizing_constant = ( np.sum(np.log(np.abs(np.diag(chol_cov)))) + dim * np.log(2 * np.pi) / 2.0 ...
minus log-density of a centered multivariate normal distribution
normal_logdensity_fn
python
blackjax-devs/blackjax
tests/smc/test_tempered_smc.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_tempered_smc.py
Apache-2.0
def test_update_waste_free_multivariate_particles(self): """ Given resampled multivariate particles, when updating with waste free, they are joined by the result of iterating the MCMC chain to get a bigger set of particles. """ resampled_particles = np.ones((50, 3...
Given resampled multivariate particles, when updating with waste free, they are joined by the result of iterating the MCMC chain to get a bigger set of particles.
test_update_waste_free_multivariate_particles
python
blackjax-devs/blackjax
tests/smc/test_waste_free_smc.py
https://github.com/blackjax-devs/blackjax/blob/master/tests/smc/test_waste_free_smc.py
Apache-2.0
def detect_language(cls, code: str) -> str: """Scan the Mnemonic until the language becomes unambiguous, including as abbreviation prefixes. Unfortunately, there are valid words that are ambiguous between languages, which are complete words in one language and are prefixes in another: ...
Scan the Mnemonic until the language becomes unambiguous, including as abbreviation prefixes. Unfortunately, there are valid words that are ambiguous between languages, which are complete words in one language and are prefixes in another: english: abandon ... about french: aba...
detect_language
python
trezor/python-mnemonic
src/mnemonic/mnemonic.py
https://github.com/trezor/python-mnemonic/blob/master/src/mnemonic/mnemonic.py
MIT
def generate(self, strength: int = 128) -> str: """ Create a new mnemonic using a random generated number as entropy. As defined in BIP39, the entropy must be a multiple of 32 bits, and its size must be between 128 and 256 bits. Therefore the possible values for `strength` are 128, 160,...
Create a new mnemonic using a random generated number as entropy. As defined in BIP39, the entropy must be a multiple of 32 bits, and its size must be between 128 and 256 bits. Therefore the possible values for `strength` are 128, 160, 192, 224 and 256. If not provided, the default en...
generate
python
trezor/python-mnemonic
src/mnemonic/mnemonic.py
https://github.com/trezor/python-mnemonic/blob/master/src/mnemonic/mnemonic.py
MIT
def open_with_encoding(filename, mode='r', encoding=None, limit_byte_check=-1): """Return opened file with a specific encoding.""" if not encoding: encoding = detect_encoding(filename, limit_byte_check=limit_byte_check) return io.open(filename, mode=mode, encoding=encoding, newli...
Return opened file with a specific encoding.
open_with_encoding
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def extended_blank_lines(logical_line, blank_lines, blank_before, indent_level, previous_logical): """Check for missing blank lines after class declaration.""" if previous_logical.startswith(('def ', 'async def '...
Check for missing blank lines after class declaration.
extended_blank_lines
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def continued_indentation(logical_line, tokens, indent_level, hang_closing, indent_char, noqa): """Override pycodestyle's function to provide indentation information.""" first_row = tokens[0][2][0] nrows = 1 + tokens[-1][2][0] - first_row if noqa or nrows == 1: return ...
Override pycodestyle's function to provide indentation information.
continued_indentation
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _check_affected_anothers(self, result) -> bool: """Check if the fix affects the number of lines of another remark.""" line_index = result['line'] - 1 target = self.source[line_index] original_target = self.original_source[line_index] return target != original_target
Check if the fix affects the number of lines of another remark.
_check_affected_anothers
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix(self): """Return a version of the source code with PEP 8 violations fixed.""" pep8_options = { 'ignore': self.options.ignore, 'select': self.options.select, 'max_line_length': self.options.max_line_length, 'hang_closing': self.options.hang_closing,...
Return a version of the source code with PEP 8 violations fixed.
fix
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _fix_reindent(self, result): """Fix a badly indented line. This is done by adding or removing from its initial indent only. """ num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] self.source[l...
Fix a badly indented line. This is done by adding or removing from its initial indent only.
_fix_reindent
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e125(self, result): """Fix indentation undistinguish from the next logical line.""" num_indent_spaces = int(result['info'].split()[1]) line_index = result['line'] - 1 target = self.source[line_index] spaces_to_add = num_indent_spaces - len(_get_indentation(target)) ...
Fix indentation undistinguish from the next logical line.
fix_e125
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e262(self, result): """Fix spacing after inline comment hash.""" target = self.source[result['line'] - 1] offset = result['column'] code = target[:offset].rstrip(' \t#') comment = target[offset:].lstrip(' \t#') fixed = code + (' # ' + comment if comment.strip()...
Fix spacing after inline comment hash.
fix_e262
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e265(self, result): """Fix spacing after block comment hash.""" target = self.source[result['line'] - 1] indent = _get_indentation(target) line = target.lstrip(' \t') pos = next((index for index, c in enumerate(line) if c != '#')) hashes = line[:pos] comm...
Fix spacing after block comment hash.
fix_e265
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e266(self, result): """Fix too many block comment hashes.""" target = self.source[result['line'] - 1] # Leave stylistic outlined blocks alone. if target.strip().endswith('#'): return indentation = _get_indentation(target) fixed = indentation + '# ' +...
Fix too many block comment hashes.
fix_e266
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e304(self, result): """Remove blank line following function decorator.""" line = result['line'] - 2 if not self.source[line].strip(): self.source[line] = ''
Remove blank line following function decorator.
fix_e304
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e305(self, result): """Add missing 2 blank lines after end of function or class.""" add_delete_linenum = 2 - int(result['info'].split()[-1]) cnt = 0 offset = result['line'] - 2 modified_lines = [] if add_delete_linenum < 0: # delete cr add_...
Add missing 2 blank lines after end of function or class.
fix_e305
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_long_line_logically(self, result, logical): """Try to make lines fit within --max-line-length characters.""" if ( not logical or len(logical[2]) == 1 or self.source[result['line'] - 1].lstrip().startswith('#') ): return self.fix_long_line_p...
Try to make lines fit within --max-line-length characters.
fix_long_line_logically
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e701(self, result): """Put colon-separated compound statement on separate lines.""" line_index = result['line'] - 1 target = self.source[line_index] c = result['column'] fixed_source = (target[:c] + '\n' + _get_indentation(target) + self.indent_wo...
Put colon-separated compound statement on separate lines.
fix_e701
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e702(self, result, logical): """Put semicolon-separated compound statement on separate lines.""" if not logical: return [] # pragma: no cover logical_lines = logical[2] # Avoid applying this when indented. # https://docs.python.org/reference/compound_stmts.h...
Put semicolon-separated compound statement on separate lines.
fix_e702
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e704(self, result): """Fix multiple statements on one line def""" (line_index, _, target) = get_index_offset_contents(result, self.source) match = STARTSWITH_DEF_REGEX.match(target) if match: self.source[line...
Fix multiple statements on one line def
fix_e704
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e712(self, result): """Fix (trivial case of) comparison with boolean.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # Handle very easy "not" special cases. if re.match(r'^\s*if [\...
Fix (trivial case of) comparison with boolean.
fix_e712
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e713(self, result): """Fix (trivial case of) non-membership check.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # to convert once 'not in' -> 'in' before_target = target[:offset]...
Fix (trivial case of) non-membership check.
fix_e713
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e714(self, result): """Fix object identity should be 'is not' case.""" (line_index, offset, target) = get_index_offset_contents(result, self.source) # to convert once 'is not' -> 'is' before_target = target[:offset...
Fix object identity should be 'is not' case.
fix_e714
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_e731(self, result): """Fix do not assign a lambda expression check.""" (line_index, _, target) = get_index_offset_contents(result, self.source) match = LAMBDA_REGEX.search(target) if match: end = match.end() ...
Fix do not assign a lambda expression check.
fix_e731
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def get_module_imports_on_top_of_file(source, import_line_index): """return import or from keyword position example: > 0: import sys 1: import os 2: 3: def function(): """ def is_string_literal(line): if line[0] in 'uUbB': line = line[1:] if lin...
return import or from keyword position example: > 0: import sys 1: import os 2: 3: def function():
get_module_imports_on_top_of_file
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def get_fixed_long_line(target, previous_line, original, indent_word=' ', max_line_length=79, aggressive=0, experimental=False, verbose=False): """Break up long line and return result. Do this by generating multiple reformatted candidates and then ranking ...
Break up long line and return result. Do this by generating multiple reformatted candidates and then ranking the candidates to heuristically select the best option.
get_fixed_long_line
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def join_logical_line(logical_line): """Return single line based on logical line input.""" indentation = _get_indentation(logical_line) return indentation + untokenize_without_newlines( generate_tokens(logical_line.lstrip())) + '\n'
Return single line based on logical line input.
join_logical_line
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def untokenize_without_newlines(tokens): """Return source code based on tokens.""" text = '' last_row = 0 last_column = -1 for t in tokens: token_string = t[1] (start_row, start_column) = t[2] (end_row, end_column) = t[3] if start_row > last_row: last_co...
Return source code based on tokens.
untokenize_without_newlines
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _get_logical(source_lines, result, logical_start, logical_end): """Return the logical line corresponding to the result. Assumes input is already E702-clean. """ row = result['line'] - 1 col = result['column'] - 1 ls = None le = None for i in range(0, len(logical_start), 1): ...
Return the logical line corresponding to the result. Assumes input is already E702-clean.
_get_logical
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def code_almost_equal(a, b): """Return True if code is similar. Ignore whitespace when comparing specific line. """ split_a = split_and_strip_non_empty_lines(a) split_b = split_and_strip_non_empty_lines(b) if len(split_a) != len(split_b): return False for (index, _) in enumerate(...
Return True if code is similar. Ignore whitespace when comparing specific line.
code_almost_equal
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def find_newline(source): """Return type of newline used in source. Input is a list of lines. """ assert not isinstance(source, str) counter = collections.defaultdict(int) for line in source: if line.endswith(CRLF): counter[CRLF] += 1 elif line.endswith(CR): ...
Return type of newline used in source. Input is a list of lines.
find_newline
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def get_diff_text(old, new, filename): """Return text of unified diff between old and new.""" newline = '\n' diff = difflib.unified_diff( old, new, 'original/' + filename, 'fixed/' + filename, lineterm=newline) text = '' for line in diff: text += line ...
Return text of unified diff between old and new.
get_diff_text
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _priority_key(pep8_result): """Key for sorting PEP8 results. Global fixes should be done first. This is important for things like indentation. """ priority = [ # Fix multiline colon-based before semicolon based. 'e701', # Break multiline statements early. 'e702'...
Key for sorting PEP8 results. Global fixes should be done first. This is important for things like indentation.
_priority_key
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def shorten_line(tokens, source, indentation, indent_word, max_line_length, aggressive=0, experimental=False, previous_line=''): """Separate line at OPERATOR. Multiple candidates will be yielded. """ for candidate in _shorten_line(tokens=tokens, sour...
Separate line at OPERATOR. Multiple candidates will be yielded.
shorten_line
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _shorten_line(tokens, source, indentation, indent_word, aggressive=0, previous_line=''): """Separate line at OPERATOR. The input is expected to be free of newlines except for inside multiline strings and at the end. Multiple candidates will be yielded. """ in_string = Fa...
Separate line at OPERATOR. The input is expected to be free of newlines except for inside multiline strings and at the end. Multiple candidates will be yielded.
_shorten_line
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def current_size(self): """The size of the current line minus the indentation.""" size = 0 for item in reversed(self._lines): size += item.size if isinstance(item, self._LineBreak): break return size
The size of the current line minus the indentation.
current_size
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _add_item(self, item, indent_amt): """Add an item to the line. Reflow the line to get the best formatting after the item is inserted. The bracket depth indicates if the item is being inserted inside of a container or not. """ if item.is_fstring_start: se...
Add an item to the line. Reflow the line to get the best formatting after the item is inserted. The bracket depth indicates if the item is being inserted inside of a container or not.
_add_item
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _prevent_default_initializer_splitting(self, item, indent_amt): """Prevent splitting between a default initializer. When there is a default initializer, it's best to keep it all on the same line. It's nicer and more readable, even if it goes over the maximum allowable line length. T...
Prevent splitting between a default initializer. When there is a default initializer, it's best to keep it all on the same line. It's nicer and more readable, even if it goes over the maximum allowable line length. This goes back along the current line to determine if we have a default ...
_prevent_default_initializer_splitting
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _enforce_space(self, item): """Enforce a space in certain situations. There are cases where we will want a space where normally we wouldn't put one. This just enforces the addition of a space. """ if isinstance(self._lines[-1], (self._Space, self._Line...
Enforce a space in certain situations. There are cases where we will want a space where normally we wouldn't put one. This just enforces the addition of a space.
_enforce_space
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _delete_whitespace(self): """Delete all whitespace from the end of the line.""" while isinstance(self._lines[-1], (self._Space, self._LineBreak, self._Indent)): del self._lines[-1]
Delete all whitespace from the end of the line.
_delete_whitespace
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _get_extent(self, index): """The extent of the full element. E.g., the length of a function call or keyword. """ extent = 0 prev_item = get_item(self._items, index - 1) seen_dot = prev_item and str(prev_item) == '.' while index < len(self._items): ...
The extent of the full element. E.g., the length of a function call or keyword.
_get_extent
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _parse_container(tokens, index, for_or_if=None): """Parse a high-level container, such as a list, tuple, etc.""" # Store the opening bracket. items = [Atom(Token(*tokens[index]))] index += 1 num_tokens = len(tokens) while index < num_tokens: tok = Token(*tokens[index]) if ...
Parse a high-level container, such as a list, tuple, etc.
_parse_container
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _parse_tokens(tokens): """Parse the tokens. This converts the tokens into a form where we can manipulate them more easily. """ index = 0 parsed_tokens = [] num_tokens = len(tokens) while index < num_tokens: tok = Token(*tokens[index]) assert tok.token_type != tok...
Parse the tokens. This converts the tokens into a form where we can manipulate them more easily.
_parse_tokens
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _reflow_lines(parsed_tokens, indentation, max_line_length, start_on_prefix_line): """Reflow the lines so that it looks nice.""" if str(parsed_tokens[0]) == 'def': # A function definition gets indented a bit more. continued_indent = indentation + ' ' * 2 * DEFAULT_INDENT_SI...
Reflow the lines so that it looks nice.
_reflow_lines
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _shorten_line_at_tokens_new(tokens, source, indentation, max_line_length): """Shorten the line taking its length into account. The input is expected to be free of newlines except for inside multiline strings and at the end. """ # Yield the original source so to ...
Shorten the line taking its length into account. The input is expected to be free of newlines except for inside multiline strings and at the end.
_shorten_line_at_tokens_new
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _shorten_line_at_tokens(tokens, source, indentation, indent_word, key_token_strings, aggressive): """Separate line by breaking at tokens in key_token_strings. The input is expected to be free of newlines except for inside multiline strings and at the end. """ offset...
Separate line by breaking at tokens in key_token_strings. The input is expected to be free of newlines except for inside multiline strings and at the end.
_shorten_line_at_tokens
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def normalize_multiline(line): """Normalize multiline-related code that will cause syntax error. This is for purposes of checking syntax. """ if line.startswith(('def ', 'async def ')) and line.rstrip().endswith(':'): return line + ' pass' elif line.startswith('return '): return 'd...
Normalize multiline-related code that will cause syntax error. This is for purposes of checking syntax.
normalize_multiline
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_whitespace(line, offset, replacement): """Replace whitespace at offset and return fixed line.""" # Replace escaped newlines too left = line[:offset].rstrip('\n\r \t\\') right = line[offset:].lstrip('\n\r \t\\') if right.startswith('#'): return line return left + replacement + ri...
Replace whitespace at offset and return fixed line.
fix_whitespace
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _execute_pep8(pep8_options, source): """Execute pycodestyle via python method calls.""" class QuietReport(pycodestyle.BaseReport): """Version of checker that does not print.""" def __init__(self, options): super(QuietReport, self).__init__(options) self.__full_error...
Execute pycodestyle via python method calls.
_execute_pep8
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def run(self, indent_size=DEFAULT_INDENT_SIZE): """Fix indentation and return modified line numbers. Line numbers are indexed at 1. """ if indent_size < 1: return self.input_text try: stats = _reindent_stats(tokenize.generate_tokens(self.getline)) ...
Fix indentation and return modified line numbers. Line numbers are indexed at 1.
run
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _reindent_stats(tokens): """Return list of (lineno, indentlevel) pairs. One for each stmt and comment line. indentlevel is -1 for comment lines, as a signal that tokenize doesn't know what to do about them; indeed, they're our headache! """ find_stmt = 1 # Next token begins a fresh stmt? ...
Return list of (lineno, indentlevel) pairs. One for each stmt and comment line. indentlevel is -1 for comment lines, as a signal that tokenize doesn't know what to do about them; indeed, they're our headache!
_reindent_stats
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _leading_space_count(line): """Return number of leading spaces in line.""" i = 0 while i < len(line) and line[i] == ' ': i += 1 return i
Return number of leading spaces in line.
_leading_space_count
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def check_syntax(code): """Return True if syntax is okay.""" try: return compile(code, '<string>', 'exec', dont_inherit=True) except (SyntaxError, TypeError, ValueError): return False
Return True if syntax is okay.
check_syntax
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def find_with_line_numbers(pattern, contents): """A wrapper around 're.finditer' to find line numbers. Returns a list of line numbers where pattern was found in contents. """ matches = list(re.finditer(pattern, contents)) if not matches: return [] end = matches[-1].start() # -1 so...
A wrapper around 're.finditer' to find line numbers. Returns a list of line numbers where pattern was found in contents.
find_with_line_numbers
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def get_disabled_ranges(source): """Returns a list of tuples representing the disabled ranges. If disabled and no re-enable will disable for rest of file. """ enable_line_nums = find_with_line_numbers(ENABLE_REGEX, source) disable_line_nums = find_with_line_numbers(DISABLE_REGEX, source) total...
Returns a list of tuples representing the disabled ranges. If disabled and no re-enable will disable for rest of file.
get_disabled_ranges
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def filter_disabled_results(result, disabled_ranges): """Filter out reports based on tuple of disabled ranges. """ line = result['line'] for disabled_range in disabled_ranges: if disabled_range[0] <= line <= disabled_range[1]: return False return True
Filter out reports based on tuple of disabled ranges.
filter_disabled_results
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def filter_results(source, results, aggressive): """Filter out spurious reports from pycodestyle. If aggressive is True, we allow possibly unsafe fixes (E711, E712). """ non_docstring_string_line_numbers = multiline_string_lines( source, include_docstrings=False) all_string_line_numbers = ...
Filter out spurious reports from pycodestyle. If aggressive is True, we allow possibly unsafe fixes (E711, E712).
filter_results
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def multiline_string_lines(source, include_docstrings=False): """Return line numbers that are within multiline strings. The line numbers are indexed at 1. Docstrings are ignored. """ line_numbers = set() previous_token_type = '' _check_target_tokens = [tokenize.STRING] if IS_SUPPORT_T...
Return line numbers that are within multiline strings. The line numbers are indexed at 1. Docstrings are ignored.
multiline_string_lines
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def commented_out_code_lines(source): """Return line numbers of comments that are likely code. Commented-out code is bad practice, but modifying it just adds even more clutter. """ line_numbers = [] try: for t in generate_tokens(source): token_type = t[0] token_...
Return line numbers of comments that are likely code. Commented-out code is bad practice, but modifying it just adds even more clutter.
commented_out_code_lines
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def shorten_comment(line, max_line_length, last_comment=False): """Return trimmed or split long comment line. If there are no comments immediately following it, do a text wrap. Doing this wrapping on all comments in general would lead to jagged comment text. """ assert len(line) > max_line_len...
Return trimmed or split long comment line. If there are no comments immediately following it, do a text wrap. Doing this wrapping on all comments in general would lead to jagged comment text.
shorten_comment
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def normalize_line_endings(lines, newline): """Return fixed line endings. All lines will be modified to use the most common line ending. """ line = [line.rstrip('\n\r') + newline for line in lines] if line and lines[-1] == lines[-1].rstrip('\n\r'): line[-1] = line[-1].rstrip('\n\r') ret...
Return fixed line endings. All lines will be modified to use the most common line ending.
normalize_line_endings
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_code(source, options=None, encoding=None, apply_config=False): """Return fixed source code. "encoding" will be used to decode "source" if it is a byte string. """ options = _get_options(options, apply_config) # normalize options.ignore = [opt.upper() for opt in options.ignore] opti...
Return fixed source code. "encoding" will be used to decode "source" if it is a byte string.
fix_code
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def apply_global_fixes(source, options, where='global', filename='', codes=None): """Run global fixes on source code. These are fixes that only need be done once (unlike those in FixPEP8, which are dependent on pycodestyle). """ if codes is None: codes = [] if an...
Run global fixes on source code. These are fixes that only need be done once (unlike those in FixPEP8, which are dependent on pycodestyle).
apply_global_fixes
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _parser_error_with_code( parser: argparse.ArgumentParser, code: int, msg: str, ) -> None: """wrap parser.error with exit code""" parser.print_usage(sys.stderr) parser.exit(code, f"{msg}\n")
wrap parser.error with exit code
_parser_error_with_code
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def read_config(args, parser): """Read both user configuration and local configuration.""" config = SafeConfigParser() try: if args.verbose and os.path.exists(args.global_config): print("read config path: {}".format(args.global_config)) config.read(args.global_config) i...
Read both user configuration and local configuration.
read_config
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def read_pyproject_toml(args, parser): """Read pyproject.toml and load configuration.""" if sys.version_info >= (3, 11): import tomllib else: import tomli as tomllib config = None if os.path.exists(args.global_config): with open(args.global_config, "rb") as fp: ...
Read pyproject.toml and load configuration.
read_pyproject_toml
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def supported_fixes(): """Yield pep8 error codes that autopep8 fixes. Each item we yield is a tuple of the code followed by its description. """ yield ('E101', docstring_summary(reindent.__doc__)) instance = FixPEP8(filename=None, options=None, contents='') for attribute in dir(instance):...
Yield pep8 error codes that autopep8 fixes. Each item we yield is a tuple of the code followed by its description.
supported_fixes
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def line_shortening_rank(candidate, indent_word, max_line_length, experimental=False): """Return rank of candidate. This is for sorting candidates. """ if not candidate.strip(): return 0 rank = 0 lines = candidate.rstrip().split('\n') offset = 0 if ( ...
Return rank of candidate. This is for sorting candidates.
line_shortening_rank
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT