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 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_e131(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_e131
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_long_line_physically(self, result): """Try to make lines fit within --max-line-length characters.""" line_index = result['line'] - 1 target = self.source[line_index] previous_line = get_item(self.source, line_index - 1, default='') next_line = get_item(self.source, line_...
Try to make lines fit within --max-line-length characters.
fix_long_line_physically
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
def has_arithmetic_operator(line): """Return True if line contains any arithmetic operators.""" for operator in pycodestyle.ARITHMETIC_OP: if operator in line: return True return False
Return True if line contains any arithmetic operators.
has_arithmetic_operator
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def count_unbalanced_brackets(line): """Return number of unmatched open/close brackets.""" count = 0 for opening, closing in ['()', '[]', '{}']: count += abs(line.count(opening) - line.count(closing)) return count
Return number of unmatched open/close brackets.
count_unbalanced_brackets
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def split_at_offsets(line, offsets): """Split line at offsets. Return list of strings. """ result = [] previous_offset = 0 current_offset = 0 for current_offset in sorted(offsets): if current_offset < len(line) and previous_offset != current_offset: result.append(line[...
Split line at offsets. Return list of strings.
split_at_offsets
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def match_file(filename, exclude): """Return True if file is okay for modifying/recursing.""" base_name = os.path.basename(filename) if base_name.startswith('.'): return False for pattern in exclude: if fnmatch.fnmatch(base_name, pattern): return False if fnmatch.fn...
Return True if file is okay for modifying/recursing.
match_file
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def _fix_file(parameters): """Helper function for optionally running fix_file() in parallel.""" if parameters[1].verbose: print('[file:{}]'.format(parameters[0]), file=sys.stderr) try: return fix_file(*parameters) except IOError as error: print(str(error), file=sys.stderr) ...
Helper function for optionally running fix_file() in parallel.
_fix_file
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def fix_multiple_files(filenames, options, output=None): """Fix list of files. Optionally fix files recursively. """ results = [] filenames = find_files(filenames, options.recursive, options.exclude) if options.jobs > 1: import multiprocessing pool = multiprocessing.Pool(option...
Fix list of files. Optionally fix files recursively.
fix_multiple_files
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def is_python_file(filename): """Return True if filename is Python file.""" if filename.endswith('.py'): return True try: with open_with_encoding( filename, limit_byte_check=MAX_PYTHON_FILE_DETECTION_BYTES) as f: text = f.read(MAX_PYTHON_FILE_DETE...
Return True if filename is Python file.
is_python_file
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def is_probably_part_of_multiline(line): """Return True if line is likely part of a multiline string. When multiline strings are involved, pep8 reports the error as being at the start of the multiline string, which doesn't work for us. """ return ( '"""' in line or "'''" in line or...
Return True if line is likely part of a multiline string. When multiline strings are involved, pep8 reports the error as being at the start of the multiline string, which doesn't work for us.
is_probably_part_of_multiline
python
hhatto/autopep8
autopep8.py
https://github.com/hhatto/autopep8/blob/master/autopep8.py
MIT
def run(filename, command, max_line_length=79, ignore='', check_ignore='', verbose=False, comparison_function=None, aggressive=0, experimental=False, line_range=None, random_range=False, pycodestyle=True): """Run autopep8 on file at filename. Return True on success. """ ...
Run autopep8 on file at filename. Return True on success.
run
python
hhatto/autopep8
test/acid.py
https://github.com/hhatto/autopep8/blob/master/test/acid.py
MIT
def check_syntax(filename, raise_error=False): """Return True if syntax is okay.""" with autopep8.open_with_encoding(filename) as input_file: try: compile(input_file.read(), '<string>', 'exec', dont_inherit=True) return True except (SyntaxError, TypeError, UnicodeDecodeEr...
Return True if syntax is okay.
check_syntax
python
hhatto/autopep8
test/acid.py
https://github.com/hhatto/autopep8/blob/master/test/acid.py
MIT
def process_args(): """Return processed arguments (options and positional arguments).""" compare_bytecode_ignore = 'E71,E721,W' parser = argparse.ArgumentParser() parser.add_argument( '--command', default='{} {}'.format(sys.executable, os.path.join(ROOT_PA...
Return processed arguments (options and positional arguments).
process_args
python
hhatto/autopep8
test/acid.py
https://github.com/hhatto/autopep8/blob/master/test/acid.py
MIT
def check(paths, args): """Run recursively run autopep8 on directory of files. Return False if the fix results in broken syntax. """ if paths: dir_paths = paths else: dir_paths = [path for path in sys.path if os.path.isdir(path)] filenames = dir_paths ...
Run recursively run autopep8 on directory of files. Return False if the fix results in broken syntax.
check
python
hhatto/autopep8
test/acid.py
https://github.com/hhatto/autopep8/blob/master/test/acid.py
MIT
def latest_packages(last_hours): """Return names of latest released packages on PyPI.""" process = subprocess.Popen( ['yolk', '--latest-releases={hours}'.format(hours=last_hours)], stdout=subprocess.PIPE) for line in process.communicate()[0].decode('utf-8').split('\n'): if line: ...
Return names of latest released packages on PyPI.
latest_packages
python
hhatto/autopep8
test/acid_pypi.py
https://github.com/hhatto/autopep8/blob/master/test/acid_pypi.py
MIT
def get(self): """ Returns a simple HTML form for login """ if self.user: self.redirect_to('home', id=self.user_id) params = {} return self.render_template('boilerplate_login.html', **params)
Returns a simple HTML form for login
get
python
hhatto/autopep8
test/e101_example.py
https://github.com/hhatto/autopep8/blob/master/test/e101_example.py
MIT
def post(self): """ username: Get the username from POST dict password: Get the password from POST dict """ if not self.form.validate(): return self.get() username = self.form.username.data.lower() try: if utils.is_email_valid(username): ...
username: Get the username from POST dict password: Get the password from POST dict
post
python
hhatto/autopep8
test/e101_example.py
https://github.com/hhatto/autopep8/blob/master/test/e101_example.py
MIT
def get(self): """ Returns a simple HTML form for create a new user """ if self.user: self.redirect_to('home', id=self.user_id) params = {} return self.render_template('boilerplate_register.html', **params)
Returns a simple HTML form for create a new user
get
python
hhatto/autopep8
test/e101_example.py
https://github.com/hhatto/autopep8/blob/master/test/e101_example.py
MIT
def get(self): """ Returns a simple HTML for contact form """ if self.user: user_info = models.User.get_by_id(long(self.user_id)) if user_info.name or user_info.last_name: self.form.name.data = user_info.name + " " + user_info.last_name if user_info.e...
Returns a simple HTML for contact form
get
python
hhatto/autopep8
test/e101_example.py
https://github.com/hhatto/autopep8/blob/master/test/e101_example.py
MIT
def get(self): """ Returns a simple HTML form for edit profile """ params = {} if self.user: user_info = models.User.get_by_id(long(self.user_id)) self.form.username.data = user_info.username self.form.name.data = user_info.name self.form.last_nam...
Returns a simple HTML form for edit profile
get
python
hhatto/autopep8
test/e101_example.py
https://github.com/hhatto/autopep8/blob/master/test/e101_example.py
MIT
def get(self): """ Returns a simple HTML form for editing password """ params = {} return self.render_template('boilerplate_edit_password.html', **params)
Returns a simple HTML form for editing password
get
python
hhatto/autopep8
test/e101_example.py
https://github.com/hhatto/autopep8/blob/master/test/e101_example.py
MIT
def get(self): """ Returns a simple HTML form for edit email """ params = {} if self.user: user_info = models.User.get_by_id(long(self.user_id)) self.form.new_email.data = user_info.email return self.render_template('boilerplate_edit_email.html', **params)
Returns a simple HTML form for edit email
get
python
hhatto/autopep8
test/e101_example.py
https://github.com/hhatto/autopep8/blob/master/test/e101_example.py
MIT
def get(self): """ Returns a simple HTML form for home """ params = {} return self.render_template('boilerplate_home.html', **params)
Returns a simple HTML form for home
get
python
hhatto/autopep8
test/e101_example.py
https://github.com/hhatto/autopep8/blob/master/test/e101_example.py
MIT
def ismethoddescriptor(object): """Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, bu...
Return true if the object is a method descriptor. But not if ismethod() or isclass() or isfunction() are true. This is new in Python 2.2, and, for example, is true of int.__add__. An object passing this test has a __get__ attribute but not a __set__ attribute, but beyond that the set of attributes var...
ismethoddescriptor
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def isdatadescriptor(object): """Return true if the object is a data descriptor. Data descriptors have both a __get__ and a __set__ attribute. Examples are properties (defined in Python) and getsets and members (defined in C). Typically, data descriptors will also have __name__ and __doc__ attributes ...
Return true if the object is a data descriptor. Data descriptors have both a __get__ and a __set__ attribute. Examples are properties (defined in Python) and getsets and members (defined in C). Typically, data descriptors will also have __name__ and __doc__ attributes (properties, getsets, and members...
isdatadescriptor
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def isgeneratorfunction(object): """Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See help(isfunction) for attributes listing.""" return bool((isfunction(object) or ismethod(object)) and object.__code__...
Return true if the object is a user-defined generator function. Generator function objects provides same attributes as functions. See help(isfunction) for attributes listing.
isgeneratorfunction
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddescriptor(object))
Return true if the object is any kind of function or method.
isroutine
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" if isclass(object): mro = (object,) + getmro(object) else: mro = () results = [] processed = set() ...
Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.
getmembers
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def classify_class_attrs(cls): """Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via cla...
Return list of attribute-descriptor tuples. For each name in dir(cls), the return list contains a 4-tuple with these elements: 0. The name (a string). 1. The kind of attribute this is, one of these strings: 'class method' created via classmethod() 'static meth...
classify_class_attrs
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def unwrap(func, *, stop=None): """Get the object wrapped by *func*. Follows the chain of :attr:`__wrapped__` attributes returning the last object in the chain. *stop* is an optional callback accepting an object in the wrapper chain as its sole argument that allows the unwrapping to be terminated earl...
Get the object wrapped by *func*. Follows the chain of :attr:`__wrapped__` attributes returning the last object in the chain. *stop* is an optional callback accepting an object in the wrapper chain as its sole argument that allows the unwrapping to be terminated early if the callback returns a true val...
unwrap
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def indentsize(line): """Return the indent size, in spaces, at the start of a line of text.""" expline = line.expandtabs() return len(expline) - len(expline.lstrip())
Return the indent size, in spaces, at the start of a line of text.
indentsize
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def getdoc(object): """Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.""" try: doc = object.__doc__ ...
Get the documentation string for an object. All tabs are expanded to spaces. To clean up docstrings that are indented to line up with blocks of code, any whitespace than can be uniformly removed from the second line onwards is removed.
getdoc
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT
def cleandoc(doc): """Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed.""" try: lines = doc.expandtabs().split('\n') except UnicodeError: return None else: # Find minimum indentation of any non-bla...
Clean up indentation from docstrings. Any whitespace that can be uniformly removed from the second line onwards is removed.
cleandoc
python
hhatto/autopep8
test/inspect_example.py
https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py
MIT