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 getfile(object):
"""Work out which source or compiled file an object was defined in."""
if ismodule(object):
if hasattr(object, '__file__'):
return object.__file__
raise TypeError('{!r} is a built-in module'.format(object))
if isclass(object):
if hasattr(object, '__module__'):
object = sys.modules.get(object.__module__)
if hasattr(object, '__file__'):
return object.__file__
raise TypeError('{!r} is a built-in class'.format(object))
if ismethod(object):
object = object.__func__
if isfunction(object):
object = object.__code__
if istraceback(object):
object = object.tb_frame
if isframe(object):
object = object.f_code
if iscode(object):
return object.co_filename
raise TypeError('{!r} is not a module, class, method, '
'function, traceback, frame, or code object'.format(object)) | Work out which source or compiled file an object was defined in. | getfile | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getmodulename(path):
"""Return the module name for a given file, or None."""
fname = os.path.basename(path)
# Check for paths that look like an actual module file
suffixes = [(-len(suffix), suffix)
for suffix in importlib.machinery.all_suffixes()]
suffixes.sort() # try longest suffixes first, in case they overlap
for neglen, suffix in suffixes:
if fname.endswith(suffix):
return fname[:neglen]
return None | Return the module name for a given file, or None. | getmodulename | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getsourcefile(object):
"""Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
"""
filename = getfile(object)
all_bytecode_suffixes = importlib.machinery.DEBUG_BYTECODE_SUFFIXES[:]
all_bytecode_suffixes += importlib.machinery.OPTIMIZED_BYTECODE_SUFFIXES[:]
if any(filename.endswith(s) for s in all_bytecode_suffixes):
filename = (os.path.splitext(filename)[0] +
importlib.machinery.SOURCE_SUFFIXES[0])
elif any(filename.endswith(s) for s in
importlib.machinery.EXTENSION_SUFFIXES):
return None
if os.path.exists(filename):
return filename
# only return a non-existent filename if the module has a PEP 302 loader
if getattr(getmodule(object, filename), '__loader__', None) is not None:
return filename
# or it is in the linecache
if filename in linecache.cache:
return filename | Return the filename that can be used to locate an object's source.
Return None if no way can be identified to get the source.
| getsourcefile | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getabsfile(object, _filename=None):
"""Return an absolute path to the source or compiled file for an object.
The idea is for each object to have a unique origin, so this routine
normalizes the result as much as possible."""
if _filename is None:
_filename = getsourcefile(object) or getfile(object)
return os.path.normcase(os.path.abspath(_filename)) | Return an absolute path to the source or compiled file for an object.
The idea is for each object to have a unique origin, so this routine
normalizes the result as much as possible. | getabsfile | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getmodule(object, _filename=None):
"""Return the module an object was defined in, or None if not found."""
if ismodule(object):
return object
if hasattr(object, '__module__'):
return sys.modules.get(object.__module__)
# Try the filename to modulename cache
if _filename is not None and _filename in modulesbyfile:
return sys.modules.get(modulesbyfile[_filename])
# Try the cache again with the absolute file name
try:
file = getabsfile(object, _filename)
except TypeError:
return None
if file in modulesbyfile:
return sys.modules.get(modulesbyfile[file])
# Update the filename to module name cache and check yet again
# Copy sys.modules in order to cope with changes while iterating
for modname, module in list(sys.modules.items()):
if ismodule(module) and hasattr(module, '__file__'):
f = module.__file__
if f == _filesbymodname.get(modname, None):
# Have already mapped this module, so skip it
continue
_filesbymodname[modname] = f
f = getabsfile(module)
# Always map to the name the module knows itself by
modulesbyfile[f] = modulesbyfile[
os.path.realpath(f)] = module.__name__
if file in modulesbyfile:
return sys.modules.get(modulesbyfile[file])
# Check the main module
main = sys.modules['__main__']
if not hasattr(object, '__name__'):
return None
if hasattr(main, object.__name__):
mainobject = getattr(main, object.__name__)
if mainobject is object:
return main
# Check builtins
builtin = sys.modules['builtins']
if hasattr(builtin, object.__name__):
builtinobject = getattr(builtin, object.__name__)
if builtinobject is object:
return builtin | Return the module an object was defined in, or None if not found. | getmodule | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def findsource(object):
"""Return the entire source file and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. An OSError
is raised if the source code cannot be retrieved."""
file = getsourcefile(object)
if file:
# Invalidate cache if needed.
linecache.checkcache(file)
else:
file = getfile(object)
# Allow filenames in form of "<something>" to pass through.
# `doctest` monkeypatches `linecache` module to enable
# inspection, so let `linecache.getlines` to be called.
if not (file.startswith('<') and file.endswith('>')):
raise OSError('source code not available')
module = getmodule(object, file)
if module:
lines = linecache.getlines(file, module.__dict__)
else:
lines = linecache.getlines(file)
if not lines:
raise OSError('could not get source code')
if ismodule(object):
return lines, 0
if isclass(object):
name = object.__name__
pat = re.compile(r'^(\s*)class\s*' + name + r'\b')
# make some effort to find the best matching class definition:
# use the one with the least indentation, which is the one
# that's most probably not inside a function definition.
candidates = []
for i in range(len(lines)):
match = pat.match(lines[i])
if match:
# if it's at toplevel, it's already the best one
if lines[i][0] == 'c':
return lines, i
# else add whitespace to candidate list
candidates.append((match.group(1), i))
if candidates:
# this will sort by whitespace, and by line number,
# less whitespace first
candidates.sort()
return lines, candidates[0][1]
else:
raise OSError('could not find class definition')
if ismethod(object):
object = object.__func__
if isfunction(object):
object = object.__code__
if istraceback(object):
object = object.tb_frame
if isframe(object):
object = object.f_code
if iscode(object):
if not hasattr(object, 'co_firstlineno'):
raise OSError('could not find function definition')
lnum = object.co_firstlineno - 1
pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
while lnum > 0:
if pat.match(lines[lnum]): break
lnum = lnum - 1
return lines, lnum
raise OSError('could not find code object') | Return the entire source file and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of all the lines
in the file and the line number indexes a line in that list. An OSError
is raised if the source code cannot be retrieved. | findsource | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getcomments(object):
"""Get lines of comments immediately preceding an object's source code.
Returns None when source can't be found.
"""
try:
lines, lnum = findsource(object)
except (OSError, TypeError):
return None
if ismodule(object):
# Look for a comment block at the top of the file.
start = 0
if lines and lines[0][:2] == '#!': start = 1
while start < len(lines) and lines[start].strip() in ('', '#'):
start = start + 1
if start < len(lines) and lines[start][:1] == '#':
comments = []
end = start
while end < len(lines) and lines[end][:1] == '#':
comments.append(lines[end].expandtabs())
end = end + 1
return ''.join(comments)
# Look for a preceding block of comments at the same indentation.
elif lnum > 0:
indent = indentsize(lines[lnum])
end = lnum - 1
if end >= 0 and lines[end].lstrip()[:1] == '#' and \
indentsize(lines[end]) == indent:
comments = [lines[end].expandtabs().lstrip()]
if end > 0:
end = end - 1
comment = lines[end].expandtabs().lstrip()
while comment[:1] == '#' and indentsize(lines[end]) == indent:
comments[:0] = [comment]
end = end - 1
if end < 0: break
comment = lines[end].expandtabs().lstrip()
while comments and comments[0].strip() == '#':
comments[:1] = []
while comments and comments[-1].strip() == '#':
comments[-1:] = []
return ''.join(comments) | Get lines of comments immediately preceding an object's source code.
Returns None when source can't be found.
| getcomments | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getblock(lines):
"""Extract the block of code at the top of the given list of lines."""
blockfinder = BlockFinder()
try:
tokens = tokenize.generate_tokens(iter(lines).__next__)
for _token in tokens:
blockfinder.tokeneater(*_token)
except (EndOfBlock, IndentationError):
pass
return lines[:blockfinder.last] | Extract the block of code at the top of the given list of lines. | getblock | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getsourcelines(object):
"""Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file the first line of code was found. An OSError is
raised if the source code cannot be retrieved."""
lines, lnum = findsource(object)
if ismodule(object): return lines, 0
else: return getblock(lines[lnum:]), lnum + 1 | Return a list of source lines and starting line number for an object.
The argument may be a module, class, method, function, traceback, frame,
or code object. The source code is returned as a list of the lines
corresponding to the object and the line number indicates where in the
original source file the first line of code was found. An OSError is
raised if the source code cannot be retrieved. | getsourcelines | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getclasstree(classes, unique=False):
"""Arrange the given list of classes into a hierarchy of nested lists.
Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list. Each entry is a 2-tuple
containing a class and a tuple of its base classes. If the 'unique'
argument is true, exactly one entry appears in the returned structure
for each class in the given list. Otherwise, classes using multiple
inheritance and their descendants will appear multiple times."""
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if not parent in children:
children[parent] = []
if c not in children[parent]:
children[parent].append(c)
if unique and parent in classes: break
elif c not in roots:
roots.append(c)
for parent in children:
if parent not in classes:
roots.append(parent)
return walktree(roots, children, None) | Arrange the given list of classes into a hierarchy of nested lists.
Where a nested list appears, it contains classes derived from the class
whose entry immediately precedes the list. Each entry is a 2-tuple
containing a class and a tuple of its base classes. If the 'unique'
argument is true, exactly one entry appears in the returned structure
for each class in the given list. Otherwise, classes using multiple
inheritance and their descendants will appear multiple times. | getclasstree | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getargs(co):
"""Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where
'args' is the list of argument names. Keyword-only arguments are
appended. 'varargs' and 'varkw' are the names of the * and **
arguments or None."""
args, varargs, kwonlyargs, varkw = _getfullargs(co)
return Arguments(args + kwonlyargs, varargs, varkw) | Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where
'args' is the list of argument names. Keyword-only arguments are
appended. 'varargs' and 'varkw' are the names of the * and **
arguments or None. | getargs | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def _getfullargs(co):
"""Get information about the arguments accepted by a code object.
Four things are returned: (args, varargs, kwonlyargs, varkw), where
'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
and 'varkw' are the names of the * and ** arguments or None."""
if not iscode(co):
raise TypeError('{!r} is not a code object'.format(co))
nargs = co.co_argcount
names = co.co_varnames
nkwargs = co.co_kwonlyargcount
args = list(names[:nargs])
kwonlyargs = list(names[nargs:nargs+nkwargs])
step = 0
nargs += nkwargs
varargs = None
if co.co_flags & CO_VARARGS:
varargs = co.co_varnames[nargs]
nargs = nargs + 1
varkw = None
if co.co_flags & CO_VARKEYWORDS:
varkw = co.co_varnames[nargs]
return args, varargs, kwonlyargs, varkw | Get information about the arguments accepted by a code object.
Four things are returned: (args, varargs, kwonlyargs, varkw), where
'args' and 'kwonlyargs' are lists of argument names, and 'varargs'
and 'varkw' are the names of the * and ** arguments or None. | _getfullargs | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getargspec(func):
"""Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names.
'args' will include keyword-only argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
Use the getfullargspec() API for Python-3000 code, as annotations
and keyword arguments are supported. getargspec() will raise ValueError
if the func has either annotations or keyword arguments.
"""
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \
getfullargspec(func)
if kwonlyargs or ann:
raise ValueError("Function has keyword-only arguments or annotations"
", use getfullargspec() API which can support them")
return ArgSpec(args, varargs, varkw, defaults) | Get the names and default values of a function's arguments.
A tuple of four things is returned: (args, varargs, varkw, defaults).
'args' is a list of the argument names.
'args' will include keyword-only argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
Use the getfullargspec() API for Python-3000 code, as annotations
and keyword arguments are supported. getargspec() will raise ValueError
if the func has either annotations or keyword arguments.
| getargspec | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getfullargspec(func):
"""Get the names and default values of a callable object's arguments.
A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
'kwonlyargs' is a list of keyword-only argument names.
'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
'annotations' is a dictionary mapping argument names to annotations.
The first four items in the tuple correspond to getargspec().
"""
try:
# Re: `skip_bound_arg=False`
#
# There is a notable difference in behaviour between getfullargspec
# and Signature: the former always returns 'self' parameter for bound
# methods, whereas the Signature always shows the actual calling
# signature of the passed object.
#
# To simulate this behaviour, we "unbind" bound methods, to trick
# inspect.signature to always return their first parameter ("self",
# usually)
# Re: `follow_wrapper_chains=False`
#
# getfullargspec() historically ignored __wrapped__ attributes,
# so we ensure that remains the case in 3.3+
sig = _signature_internal(func,
follow_wrapper_chains=False,
skip_bound_arg=False)
except Exception as ex:
# Most of the times 'signature' will raise ValueError.
# But, it can also raise AttributeError, and, maybe something
# else. So to be fully backwards compatible, we catch all
# possible exceptions here, and reraise a TypeError.
raise TypeError('unsupported callable') from ex
args = []
varargs = None
varkw = None
kwonlyargs = []
defaults = ()
annotations = {}
defaults = ()
kwdefaults = {}
if sig.return_annotation is not sig.empty:
annotations['return'] = sig.return_annotation
for param in sig.parameters.values():
kind = param.kind
name = param.name
if kind is _POSITIONAL_ONLY:
args.append(name)
elif kind is _POSITIONAL_OR_KEYWORD:
args.append(name)
if param.default is not param.empty:
defaults += (param.default,)
elif kind is _VAR_POSITIONAL:
varargs = name
elif kind is _KEYWORD_ONLY:
kwonlyargs.append(name)
if param.default is not param.empty:
kwdefaults[name] = param.default
elif kind is _VAR_KEYWORD:
varkw = name
if param.annotation is not param.empty:
annotations[name] = param.annotation
if not kwdefaults:
# compatibility with 'func.__kwdefaults__'
kwdefaults = None
if not defaults:
# compatibility with 'func.__defaults__'
defaults = None
return FullArgSpec(args, varargs, varkw, defaults,
kwonlyargs, kwdefaults, annotations) | Get the names and default values of a callable object's arguments.
A tuple of seven things is returned:
(args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults annotations).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the default values of the last n arguments.
'kwonlyargs' is a list of keyword-only argument names.
'kwonlydefaults' is a dictionary mapping names from kwonlyargs to defaults.
'annotations' is a dictionary mapping argument names to annotations.
The first four items in the tuple correspond to getargspec().
| getfullargspec | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getargvalues(frame):
"""Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame."""
args, varargs, varkw = getargs(frame.f_code)
return ArgInfo(args, varargs, varkw, frame.f_locals) | Get information about arguments passed into a particular frame.
A tuple of four things is returned: (args, varargs, varkw, locals).
'args' is a list of the argument names.
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals dictionary of the given frame. | getargvalues | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def formatargspec(args, varargs=None, varkw=None, defaults=None,
kwonlyargs=(), kwonlydefaults={}, annotations={},
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
formatreturns=lambda text: ' -> ' + text,
formatannotation=formatannotation):
"""Format an argument spec from the values returned by getargspec
or getfullargspec.
The first seven arguments are (args, varargs, varkw, defaults,
kwonlyargs, kwonlydefaults, annotations). The other five arguments
are the corresponding optional formatting functions that are called to
turn names and values into strings. The last argument is an optional
function to format the sequence of arguments."""
def formatargandannotation(arg):
result = formatarg(arg)
if arg in annotations:
result += ': ' + formatannotation(annotations[arg])
return result
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i, arg in enumerate(args):
spec = formatargandannotation(arg)
if defaults and i >= firstdefault:
spec = spec + formatvalue(defaults[i - firstdefault])
specs.append(spec)
if varargs is not None:
specs.append(formatvarargs(formatargandannotation(varargs)))
else:
if kwonlyargs:
specs.append('*')
if kwonlyargs:
for kwonlyarg in kwonlyargs:
spec = formatargandannotation(kwonlyarg)
if kwonlydefaults and kwonlyarg in kwonlydefaults:
spec += formatvalue(kwonlydefaults[kwonlyarg])
specs.append(spec)
if varkw is not None:
specs.append(formatvarkw(formatargandannotation(varkw)))
result = '(' + ', '.join(specs) + ')'
if 'return' in annotations:
result += formatreturns(formatannotation(annotations['return']))
return result | Format an argument spec from the values returned by getargspec
or getfullargspec.
The first seven arguments are (args, varargs, varkw, defaults,
kwonlyargs, kwonlydefaults, annotations). The other five arguments
are the corresponding optional formatting functions that are called to
turn names and values into strings. The last argument is an optional
function to format the sequence of arguments. | formatargspec | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value)):
"""Format an argument spec from the 4 values returned by getargvalues.
The first four arguments are (args, varargs, varkw, locals). The
next four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments."""
def convert(name, locals=locals,
formatarg=formatarg, formatvalue=formatvalue):
return formatarg(name) + formatvalue(locals[name])
specs = []
for i in range(len(args)):
specs.append(convert(args[i]))
if varargs:
specs.append(formatvarargs(varargs) + formatvalue(locals[varargs]))
if varkw:
specs.append(formatvarkw(varkw) + formatvalue(locals[varkw]))
return '(' + ', '.join(specs) + ')' | Format an argument spec from the 4 values returned by getargvalues.
The first four arguments are (args, varargs, varkw, locals). The
next four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional function to format the sequence of arguments. | formatargvalues | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getcallargs(*func_and_positional, **named):
"""Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'."""
func = func_and_positional[0]
positional = func_and_positional[1:]
spec = getfullargspec(func)
args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec
f_name = func.__name__
arg2value = {}
if ismethod(func) and func.__self__ is not None:
# implicit 'self' (or 'cls' for classmethods) argument
positional = (func.__self__,) + positional
num_pos = len(positional)
num_args = len(args)
num_defaults = len(defaults) if defaults else 0
n = min(num_pos, num_args)
for i in range(n):
arg2value[args[i]] = positional[i]
if varargs:
arg2value[varargs] = tuple(positional[n:])
possible_kwargs = set(args + kwonlyargs)
if varkw:
arg2value[varkw] = {}
for kw, value in named.items():
if kw not in possible_kwargs:
if not varkw:
raise TypeError("%s() got an unexpected keyword argument %r" %
(f_name, kw))
arg2value[varkw][kw] = value
continue
if kw in arg2value:
raise TypeError("%s() got multiple values for argument %r" %
(f_name, kw))
arg2value[kw] = value
if num_pos > num_args and not varargs:
_too_many(f_name, args, kwonlyargs, varargs, num_defaults,
num_pos, arg2value)
if num_pos < num_args:
req = args[:num_args - num_defaults]
for arg in req:
if arg not in arg2value:
_missing_arguments(f_name, req, True, arg2value)
for i, arg in enumerate(args[num_args - num_defaults:]):
if arg not in arg2value:
arg2value[arg] = defaults[i]
missing = 0
for kwarg in kwonlyargs:
if kwarg not in arg2value:
if kwonlydefaults and kwarg in kwonlydefaults:
arg2value[kwarg] = kwonlydefaults[kwarg]
else:
missing += 1
if missing:
_missing_arguments(f_name, kwonlyargs, False, arg2value)
return arg2value | Get the mapping of arguments to values.
A dict is returned, with keys the function argument names (including the
names of the * and ** arguments, if any), and values the respective bound
values from 'positional' and 'named'. | getcallargs | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getclosurevars(func):
"""
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
"""
if ismethod(func):
func = func.__func__
if not isfunction(func):
raise TypeError("'{!r}' is not a Python function".format(func))
code = func.__code__
# Nonlocal references are named in co_freevars and resolved
# by looking them up in __closure__ by positional index
if func.__closure__ is None:
nonlocal_vars = {}
else:
nonlocal_vars = {
var : cell.cell_contents
for var, cell in zip(code.co_freevars, func.__closure__)
}
# Global and builtin references are named in co_names and resolved
# by looking them up in __globals__ or __builtins__
global_ns = func.__globals__
builtin_ns = global_ns.get("__builtins__", builtins.__dict__)
if ismodule(builtin_ns):
builtin_ns = builtin_ns.__dict__
global_vars = {}
builtin_vars = {}
unbound_names = set()
for name in code.co_names:
if name in ("None", "True", "False"):
# Because these used to be builtins instead of keywords, they
# may still show up as name references. We ignore them.
continue
try:
global_vars[name] = global_ns[name]
except KeyError:
try:
builtin_vars[name] = builtin_ns[name]
except KeyError:
unbound_names.add(name)
return ClosureVars(nonlocal_vars, global_vars,
builtin_vars, unbound_names) |
Get the mapping of free variables to their current values.
Returns a named tuple of dicts mapping the current nonlocal, global
and builtin references as seen by the body of the function. A final
set of unbound names that could not be resolved is also provided.
| getclosurevars | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getframeinfo(frame, context=1):
"""Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
The optional second argument specifies the number of lines of context
to return, which are centered around the current line."""
if istraceback(frame):
lineno = frame.tb_lineno
frame = frame.tb_frame
else:
lineno = frame.f_lineno
if not isframe(frame):
raise TypeError('{!r} is not a frame or traceback object'.format(frame))
filename = getsourcefile(frame) or getfile(frame)
if context > 0:
start = lineno - 1 - context//2
try:
lines, lnum = findsource(frame)
except OSError:
lines = index = None
else:
start = max(start, 1)
start = max(0, min(start, len(lines) - context))
lines = lines[start:start+context]
index = lineno - 1 - start
else:
lines = index = None
return Traceback(filename, lineno, frame.f_code.co_name, lines, index) | Get information about a frame or traceback object.
A tuple of five things is returned: the filename, the line number of
the current line, the function name, a list of lines of context from
the source code, and the index of the current line within that list.
The optional second argument specifies the number of lines of context
to return, which are centered around the current line. | getframeinfo | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getouterframes(frame, context=1):
"""Get a list of records for a frame and all higher (calling) frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context."""
framelist = []
while frame:
framelist.append((frame,) + getframeinfo(frame, context))
frame = frame.f_back
return framelist | Get a list of records for a frame and all higher (calling) frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context. | getouterframes | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getinnerframes(tb, context=1):
"""Get a list of records for a traceback's frame and all lower frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context."""
framelist = []
while tb:
framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
tb = tb.tb_next
return framelist | Get a list of records for a traceback's frame and all lower frames.
Each record contains a frame object, filename, line number, function
name, a list of lines of context, and index within the context. | getinnerframes | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getattr_static(obj, attr, default=_sentinel):
"""Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
and may find attributes that getattr can't (like descriptors
that raise AttributeError). It can also return descriptor objects
instead of instance members in some cases. See the
documentation for details.
"""
instance_result = _sentinel
if not _is_type(obj):
klass = type(obj)
dict_attr = _shadowed_dict(klass)
if (dict_attr is _sentinel or
type(dict_attr) is types.MemberDescriptorType):
instance_result = _check_instance(obj, attr)
else:
klass = obj
klass_result = _check_class(klass, attr)
if instance_result is not _sentinel and klass_result is not _sentinel:
if (_check_class(type(klass_result), '__get__') is not _sentinel and
_check_class(type(klass_result), '__set__') is not _sentinel):
return klass_result
if instance_result is not _sentinel:
return instance_result
if klass_result is not _sentinel:
return klass_result
if obj is klass:
# for types we check the metaclass too
for entry in _static_getmro(type(klass)):
if _shadowed_dict(type(entry)) is _sentinel:
try:
return entry.__dict__[attr]
except KeyError:
pass
if default is not _sentinel:
return default
raise AttributeError(attr) | Retrieve attributes without triggering dynamic lookup via the
descriptor protocol, __getattr__ or __getattribute__.
Note: this function may not be able to retrieve all attributes
that getattr can fetch (like dynamically created attributes)
and may find attributes that getattr can't (like descriptors
that raise AttributeError). It can also return descriptor objects
instead of instance members in some cases. See the
documentation for details.
| getattr_static | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getgeneratorstate(generator):
"""Get current state of a generator-iterator.
Possible states are:
GEN_CREATED: Waiting to start execution.
GEN_RUNNING: Currently being executed by the interpreter.
GEN_SUSPENDED: Currently suspended at a yield expression.
GEN_CLOSED: Execution has completed.
"""
if generator.gi_running:
return GEN_RUNNING
if generator.gi_frame is None:
return GEN_CLOSED
if generator.gi_frame.f_lasti == -1:
return GEN_CREATED
return GEN_SUSPENDED | Get current state of a generator-iterator.
Possible states are:
GEN_CREATED: Waiting to start execution.
GEN_RUNNING: Currently being executed by the interpreter.
GEN_SUSPENDED: Currently suspended at a yield expression.
GEN_CLOSED: Execution has completed.
| getgeneratorstate | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def getgeneratorlocals(generator):
"""
Get the mapping of generator local variables to their current values.
A dict is returned, with the keys the local variable names and values the
bound values."""
if not isgenerator(generator):
raise TypeError("'{!r}' is not a Python generator".format(generator))
frame = getattr(generator, "gi_frame", None)
if frame is not None:
return generator.gi_frame.f_locals
else:
return {} |
Get the mapping of generator local variables to their current values.
A dict is returned, with the keys the local variable names and values the
bound values. | getgeneratorlocals | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def _signature_strip_non_python_syntax(signature):
"""
Takes a signature in Argument Clinic's extended signature format.
Returns a tuple of three things:
* that signature re-rendered in standard Python syntax,
* the index of the "self" parameter (generally 0), or None if
the function does not have a "self" parameter, and
* the index of the last "positional only" parameter,
or None if the signature has no positional-only parameters.
"""
if not signature:
return signature, None, None
self_parameter = None
last_positional_only = None
lines = [l.encode('ascii') for l in signature.split('\n')]
generator = iter(lines).__next__
token_stream = tokenize.tokenize(generator)
delayed_comma = False
skip_next_comma = False
text = []
add = text.append
current_parameter = 0
OP = token.OP
ERRORTOKEN = token.ERRORTOKEN
# token stream always starts with ENCODING token, skip it
t = next(token_stream)
assert t.type == tokenize.ENCODING
for t in token_stream:
type, string = t.type, t.string
if type == OP:
if string == ',':
if skip_next_comma:
skip_next_comma = False
else:
assert not delayed_comma
delayed_comma = True
current_parameter += 1
continue
if string == '/':
assert not skip_next_comma
assert last_positional_only is None
skip_next_comma = True
last_positional_only = current_parameter - 1
continue
if (type == ERRORTOKEN) and (string == '$'):
assert self_parameter is None
self_parameter = current_parameter
continue
if delayed_comma:
delayed_comma = False
if not ((type == OP) and (string == ')')):
add(', ')
add(string)
if (string == ','):
add(' ')
clean_signature = ''.join(text)
return clean_signature, self_parameter, last_positional_only |
Takes a signature in Argument Clinic's extended signature format.
Returns a tuple of three things:
* that signature re-rendered in standard Python syntax,
* the index of the "self" parameter (generally 0), or None if
the function does not have a "self" parameter, and
* the index of the last "positional only" parameter,
or None if the signature has no positional-only parameters.
| _signature_strip_non_python_syntax | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def replace(self, *, name=_void, kind=_void,
annotation=_void, default=_void):
'''Creates a customized copy of the Parameter.'''
if name is _void:
name = self._name
if kind is _void:
kind = self._kind
if annotation is _void:
annotation = self._annotation
if default is _void:
default = self._default
return type(self)(name, kind, default=default, annotation=annotation) | Creates a customized copy of the Parameter. | replace | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def __init__(self, parameters=None, *, return_annotation=_empty,
__validate_parameters__=True):
'''Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
'''
if parameters is None:
params = OrderedDict()
else:
if __validate_parameters__:
params = OrderedDict()
top_kind = _POSITIONAL_ONLY
kind_defaults = False
for idx, param in enumerate(parameters):
kind = param.kind
name = param.name
if kind < top_kind:
msg = 'wrong parameter order: {!r} before {!r}'
msg = msg.format(top_kind, kind)
raise ValueError(msg)
elif kind > top_kind:
kind_defaults = False
top_kind = kind
if kind in (_POSITIONAL_ONLY, _POSITIONAL_OR_KEYWORD):
if param.default is _empty:
if kind_defaults:
# No default for this parameter, but the
# previous parameter of the same kind had
# a default
msg = 'non-default argument follows default ' \
'argument'
raise ValueError(msg)
else:
# There is a default for this parameter.
kind_defaults = True
if name in params:
msg = 'duplicate parameter name: {!r}'.format(name)
raise ValueError(msg)
params[name] = param
else:
params = OrderedDict(((param.name, param)
for param in parameters))
self._parameters = types.MappingProxyType(params)
self._return_annotation = return_annotation | Constructs Signature from the given list of Parameter
objects and 'return_annotation'. All arguments are optional.
| __init__ | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def from_function(cls, func):
'''Constructs Signature for the given python function'''
is_duck_function = False
if not isfunction(func):
if _signature_is_functionlike(func):
is_duck_function = True
else:
# If it's not a pure Python function, and not a duck type
# of pure function:
raise TypeError('{!r} is not a Python function'.format(func))
Parameter = cls._parameter_cls
# Parameter information.
func_code = func.__code__
pos_count = func_code.co_argcount
arg_names = func_code.co_varnames
positional = tuple(arg_names[:pos_count])
keyword_only_count = func_code.co_kwonlyargcount
keyword_only = arg_names[pos_count:(pos_count + keyword_only_count)]
annotations = func.__annotations__
defaults = func.__defaults__
kwdefaults = func.__kwdefaults__
if defaults:
pos_default_count = len(defaults)
else:
pos_default_count = 0
parameters = []
# Non-keyword-only parameters w/o defaults.
non_default_count = pos_count - pos_default_count
for name in positional[:non_default_count]:
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD))
# ... w/ defaults.
for offset, name in enumerate(positional[non_default_count:]):
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_POSITIONAL_OR_KEYWORD,
default=defaults[offset]))
# *args
if func_code.co_flags & CO_VARARGS:
name = arg_names[pos_count + keyword_only_count]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_POSITIONAL))
# Keyword-only parameters.
for name in keyword_only:
default = _empty
if kwdefaults is not None:
default = kwdefaults.get(name, _empty)
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_KEYWORD_ONLY,
default=default))
# **kwargs
if func_code.co_flags & CO_VARKEYWORDS:
index = pos_count + keyword_only_count
if func_code.co_flags & CO_VARARGS:
index += 1
name = arg_names[index]
annotation = annotations.get(name, _empty)
parameters.append(Parameter(name, annotation=annotation,
kind=_VAR_KEYWORD))
# Is 'func' is a pure Python function - don't validate the
# parameters list (for correct order and defaults), it should be OK.
return cls(parameters,
return_annotation=annotations.get('return', _empty),
__validate_parameters__=is_duck_function) | Constructs Signature for the given python function | from_function | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def replace(self, *, parameters=_void, return_annotation=_void):
'''Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
'''
if parameters is _void:
parameters = self.parameters.values()
if return_annotation is _void:
return_annotation = self._return_annotation
return type(self)(parameters,
return_annotation=return_annotation) | Creates a customized copy of the Signature.
Pass 'parameters' and/or 'return_annotation' arguments
to override them in the new copy.
| replace | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def _main():
""" Logic for inspecting an object given at command line """
import argparse
import importlib
parser = argparse.ArgumentParser()
parser.add_argument(
'object',
help="The object to be analysed. "
"It supports the 'module:qualname' syntax")
parser.add_argument(
'-d', '--details', action='store_true',
help='Display info about the module rather than its source code')
args = parser.parse_args()
target = args.object
mod_name, has_attrs, attrs = target.partition(":")
try:
obj = module = importlib.import_module(mod_name)
except Exception as exc:
msg = "Failed to import {} ({}: {})".format(mod_name,
type(exc).__name__,
exc)
print(msg, file=sys.stderr)
exit(2)
if has_attrs:
parts = attrs.split(".")
obj = module
for part in parts:
obj = getattr(obj, part)
if module.__name__ in sys.builtin_module_names:
print("Can't get info for builtin modules.", file=sys.stderr)
exit(1)
if args.details:
print('Target: {}'.format(target))
print('Origin: {}'.format(getsourcefile(module)))
print('Cached: {}'.format(module.__cached__))
if obj is module:
print('Loader: {}'.format(repr(module.__loader__)))
if hasattr(module, '__path__'):
print('Submodule search path: {}'.format(module.__path__))
else:
try:
__, lineno = findsource(obj)
except Exception:
pass
else:
print('Line: {}'.format(lineno))
print('\n')
else:
print(getsource(obj)) | Logic for inspecting an object given at command line | _main | python | hhatto/autopep8 | test/inspect_example.py | https://github.com/hhatto/autopep8/blob/master/test/inspect_example.py | MIT |
def test_readlines_from_file_with_bad_encoding(self):
"""Bad encoding should not cause an exception."""
self.assertEqual(
['# -*- coding: zlatin-1 -*-\n'],
autopep8.readlines_from_file(
os.path.join(ROOT_DIR, 'test', 'bad_encoding.py'))) | Bad encoding should not cause an exception. | test_readlines_from_file_with_bad_encoding | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_readlines_from_file_with_bad_encoding2(self):
"""Bad encoding should not cause an exception."""
# This causes a warning on Python 3.
with warnings.catch_warnings(record=True):
self.assertTrue(autopep8.readlines_from_file(
os.path.join(ROOT_DIR, 'test', 'bad_encoding2.py'))) | Bad encoding should not cause an exception. | test_readlines_from_file_with_bad_encoding2 | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_fix_code_byte_string(self):
"""This feature is here for friendliness to Python 2."""
self.assertEqual(
'print(123)\n',
autopep8.fix_code(b'print( 123 )\n')) | This feature is here for friendliness to Python 2. | test_fix_code_byte_string | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_e231_should_only_do_ws_comma_once(self):
"""If we don't check appropriately, we end up doing ws_comma multiple
times and skipping all other fixes."""
line = """\
print( 1 )
foo[0,:]
bar[zap[0][0]:zig[0][0],:]
"""
fixed = """\
print(1)
foo[0, :]
bar[zap[0][0]:zig[0][0], :]
"""
with autopep8_context(line) as result:
self.assertEqual(fixed, result) | If we don't check appropriately, we end up doing ws_comma multiple
times and skipping all other fixes. | test_e231_should_only_do_ws_comma_once | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_e501_with_aggressive_and_massive_number_of_logical_lines(self):
"""We do not care about results here.
We just want to know that it doesn't take a ridiculous amount of
time. Caching is currently required to avoid repeately trying
the same line.
"""
line = """\
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from provider.compat import user_model_label
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Client'
db.create_table('oauth2_client', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_model_label])),
('url', self.gf('django.db.models.fields.URLField')(max_length=200)),
('redirect_uri', self.gf('django.db.models.fields.URLField')(max_length=200)),
('client_id', self.gf('django.db.models.fields.CharField')(default='37b581bdc702c732aa65', max_length=255)),
('client_secret', self.gf('django.db.models.fields.CharField')(default='5cf90561f7566aa81457f8a32187dcb8147c7b73', max_length=255)),
('client_type', self.gf('django.db.models.fields.IntegerField')()),
))
db.send_create_signal('oauth2', ['Client'])
# Adding model 'Grant'
db.create_table('oauth2_grant', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_model_label])),
('client', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2.Client'])),
('code', self.gf('django.db.models.fields.CharField')(default='f0cda1a5f4ae915431ff93f477c012b38e2429c4', max_length=255)),
('expires', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2012, 2, 8, 10, 43, 45, 620301))),
('redirect_uri', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('scope', self.gf('django.db.models.fields.IntegerField')(default=0)),
))
db.send_create_signal('oauth2', ['Grant'])
# Adding model 'AccessToken'
db.create_table('oauth2_accesstoken', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_model_label])),
('token', self.gf('django.db.models.fields.CharField')(default='b10b8f721e95117cb13c', max_length=255)),
('client', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2.Client'])),
('expires', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime(2013, 2, 7, 10, 33, 45, 618854))),
('scope', self.gf('django.db.models.fields.IntegerField')(default=0)),
))
db.send_create_signal('oauth2', ['AccessToken'])
# Adding model 'RefreshToken'
db.create_table('oauth2_refreshtoken', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm[user_model_label])),
('token', self.gf('django.db.models.fields.CharField')(default='84035a870dab7c820c2c501fb0b10f86fdf7a3fe', max_length=255)),
('access_token', self.gf('django.db.models.fields.related.OneToOneField')(related_name='refresh_token', unique=True, to=orm['oauth2.AccessToken'])),
('client', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['oauth2.Client'])),
('expired', self.gf('django.db.models.fields.BooleanField')(default=False)),
))
db.send_create_signal('oauth2', ['RefreshToken'])
def backwards(self, orm):
# Deleting model 'Client'
db.delete_table('oauth2_client')
# Deleting model 'Grant'
db.delete_table('oauth2_grant')
# Deleting model 'AccessToken'
db.delete_table('oauth2_accesstoken')
# Deleting model 'RefreshToken'
db.delete_table('oauth2_refreshtoken')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
user_model_label: {
'Meta': {'object_name': user_model_label.split('.')[-1]},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'oauth2.accesstoken': {
'Meta': {'object_name': 'AccessToken'},
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2.Client']"}),
'expires': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2013, 2, 7, 10, 33, 45, 624553)'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'scope': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'token': ('django.db.models.fields.CharField', [], {'default': "'d5c1f65020ebdc89f20c'", 'max_length': '255'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label})
},
'oauth2.client': {
'Meta': {'object_name': 'Client'},
'client_id': ('django.db.models.fields.CharField', [], {'default': "'306fb26cbcc87dd33cdb'", 'max_length': '255'}),
'client_secret': ('django.db.models.fields.CharField', [], {'default': "'7e5785add4898448d53767f15373636b918cf0e3'", 'max_length': '255'}),
'client_type': ('django.db.models.fields.IntegerField', [], {}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'redirect_uri': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'url': ('django.db.models.fields.URLField', [], {'max_length': '200'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label})
},
'oauth2.grant': {
'Meta': {'object_name': 'Grant'},
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2.Client']"}),
'code': ('django.db.models.fields.CharField', [], {'default': "'310b2c63e27306ecf5307569dd62340cc4994b73'", 'max_length': '255'}),
'expires': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime(2012, 2, 8, 10, 43, 45, 625956)'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'redirect_uri': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'scope': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label})
},
'oauth2.refreshtoken': {
'Meta': {'object_name': 'RefreshToken'},
'access_token': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'refresh_token'", 'unique': 'True', 'to': "orm['oauth2.AccessToken']"}),
'client': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['oauth2.Client']"}),
'expired': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'token': ('django.db.models.fields.CharField', [], {'default': "'ef0ab76037f17769ab2975a816e8f41a1c11d25e'", 'max_length': '255'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['%s']" % user_model_label})
}
}
complete_apps = ['oauth2']
"""
with autopep8_context(line, options=['-aa']) as result:
self.assertEqual(''.join(line.split()),
''.join(result.split())) | We do not care about results here.
We just want to know that it doesn't take a ridiculous amount of
time. Caching is currently required to avoid repeately trying
the same line.
| test_e501_with_aggressive_and_massive_number_of_logical_lines | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_e501_avoid_breaking_at_opening_slice(self):
"""Prevents line break on slice notation, dict access in this example:
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw[
'abc'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
"""
line = """\
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
"""
fixed = """\
GYakymOSMc = GYakymOSMW(GYakymOSMJ, GYakymOSMA, GYakymOSMr,
GYakymOSMw['abc'], GYakymOSMU, GYakymOSMq, GYakymOSMH, GYakymOSMl, svygreNveyvarf=GYakymOSME)
"""
with autopep8_context(line) as result:
self.assertEqual(fixed, result) | Prevents line break on slice notation, dict access in this example:
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw[
'abc'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
| test_e501_avoid_breaking_at_opening_slice | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_e501_avoid_breaking_at_multi_level_slice(self):
"""Prevents line break on slice notation, dict access in this example:
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc'][
'def'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
"""
line = """\
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc']['def'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
"""
fixed = """\
GYakymOSMc = GYakymOSMW(GYakymOSMJ, GYakymOSMA, GYakymOSMr,
GYakymOSMw['abc']['def'], GYakymOSMU, GYakymOSMq, GYakymOSMH, GYakymOSMl, svygreNveyvarf=GYakymOSME)
"""
with autopep8_context(line) as result:
self.assertEqual(fixed, result) | Prevents line break on slice notation, dict access in this example:
GYakymOSMc=GYakymOSMW(GYakymOSMJ,GYakymOSMA,GYakymOSMr,GYakymOSMw['abc'][
'def'],GYakymOSMU,GYakymOSMq,GYakymOSMH,GYakymOSMl,svygreNveyvarf=GYakymOSME)
| test_e501_avoid_breaking_at_multi_level_slice | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def test_execfile_in_lambda_should_not_be_modified(self):
"""Modifying this to the exec() form is invalid in Python 2."""
line = 'lambda: execfile("foo.py")\n'
with autopep8_context(line, options=['--aggressive']) as result:
self.assertEqual(line, result) | Modifying this to the exec() form is invalid in Python 2. | test_execfile_in_lambda_should_not_be_modified | python | hhatto/autopep8 | test/test_autopep8.py | https://github.com/hhatto/autopep8/blob/master/test/test_autopep8.py | MIT |
def check(expected_filename, input_filename, aggressive):
"""Test and compare output.
Return True on success.
"""
got = autopep8.fix_file(
input_filename,
options=autopep8.parse_args([''] + aggressive * ['--aggressive']))
try:
with autopep8.open_with_encoding(expected_filename) as expected_file:
expected = expected_file.read()
except IOError:
expected = None
if expected == got:
return True
else:
got_filename = expected_filename + '.err'
encoding = autopep8.detect_encoding(input_filename)
with autopep8.open_with_encoding(got_filename,
encoding=encoding,
mode='w') as got_file:
got_file.write(got)
print(
'{begin}{got} does not match expected {expected}{end}'.format(
begin=RED,
got=got_filename,
expected=expected_filename,
end=END),
file=sys.stdout)
return False | Test and compare output.
Return True on success.
| check | python | hhatto/autopep8 | test/test_suite.py | https://github.com/hhatto/autopep8/blob/master/test/test_suite.py | MIT |
def run(filename, aggressive):
"""Test against a specific file.
Return True on success.
Expected output should have the same base filename, but live in an "out"
directory:
foo/bar.py
foo/out/bar.py
Failed output will go to:
foo/out/bar.py.err
"""
return check(
expected_filename=os.path.join(
os.path.dirname(filename),
'out',
os.path.basename(filename)
),
input_filename=filename,
aggressive=aggressive
) | Test against a specific file.
Return True on success.
Expected output should have the same base filename, but live in an "out"
directory:
foo/bar.py
foo/out/bar.py
Failed output will go to:
foo/out/bar.py.err
| run | python | hhatto/autopep8 | test/test_suite.py | https://github.com/hhatto/autopep8/blob/master/test/test_suite.py | MIT |
def __eq__(self, other):
'''Vectors can be checked for equality.
Uses epsilon floating comparison; tiny differences are still equal.
'''
for i in range(len(self._v)):
if not equal(self._v[i], other._v[i]):
return False
return True | Vectors can be checked for equality.
Uses epsilon floating comparison; tiny differences are still equal.
| __eq__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __cmp__(self, other):
'''Vectors can be compared, returning -1,0,+1.
Elements are compared in order, using epsilon floating comparison.
'''
for i in range(len(self._v)):
if not equal(self._v[i], other._v[i]):
if self._v[i] > other._v[i]: return 1
return -1
return 0 | Vectors can be compared, returning -1,0,+1.
Elements are compared in order, using epsilon floating comparison.
| __cmp__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __neg__(self):
'''The inverse of a vector is a negative in all elements.'''
v = V(self)
for i in range(len(v._v)):
v[i] = -v[i]
v._l = self._l
return v | The inverse of a vector is a negative in all elements. | __neg__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __nonzero__(self):
'''A vector is nonzero if any of its elements are nonzero.'''
for i in range(len(self._v)):
if self._v[i]: return True
return False | A vector is nonzero if any of its elements are nonzero. | __nonzero__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def random(cls, order=3):
'''Returns a unit vector in a random direction.'''
# distribution is not without bias, need to use polar coords?
v = V(range(order))
v._l = None
short = True
while short:
for i in range(order):
v._v[i] = 2.0*random.random() - 1.0
if not zero(v._v[i]): short = False
return v.normalize() | Returns a unit vector in a random direction. | random | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __iadd__(self, other):
'''Vectors can be added to each other, or a scalar added to them.'''
if isinstance(other, V):
if len(other._v) != len(self._v):
raise ValueError, 'mismatched dimensions'
for i in range(len(self._v)):
self._v[i] += other._v[i]
else:
for i in range(len(self._v)):
self._v[i] += other
self._l = None
return self | Vectors can be added to each other, or a scalar added to them. | __iadd__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __isub__(self, other):
'''Vectors can be subtracted, or a scalar subtracted from them.'''
if isinstance(other, V):
if len(other._v) != len(self._v):
raise ValueError, 'mismatched dimensions'
for i in range(len(self._v)):
self._v[i] -= other._v[i]
else:
for i in range(len(self._v)):
self._v[i] -= other
self._l = None
return self | Vectors can be subtracted, or a scalar subtracted from them. | __isub__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __imul__(self, other):
'''Vectors can be multipled by a scalar. Two 3d vectors can cross.'''
if isinstance(other, V):
self._v = self.cross(other)._v
else:
for i in range(len(self._v)):
self._v[i] *= other
self._l = None
return self | Vectors can be multipled by a scalar. Two 3d vectors can cross. | __imul__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __idiv__(self, other):
'''Vectors can be divided by scalars; each element is divided.'''
other = 1.0 / other
for i in range(len(self._v)):
self._v[i] *= other
self._l = None
return self | Vectors can be divided by scalars; each element is divided. | __idiv__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def cross(self, other):
'''Find the vector cross product between two 3d vectors.'''
if len(self._v) != 3 or len(other._v) != 3:
raise ValueError, 'cross multiplication only for 3d vectors'
p, q = self._v, other._v
r = [ p[1] * q[2] - p[2] * q[1],
p[2] * q[0] - p[0] * q[2],
p[0] * q[1] - p[1] * q[0] ]
return V(r) | Find the vector cross product between two 3d vectors. | cross | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def dot(self, other):
'''Find the scalar dot product between this vector and another.'''
s = 0
for i in range(len(self._v)):
s += self._v[i] * other._v[i]
return s | Find the scalar dot product between this vector and another. | dot | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def magnitude(self, value=None):
'''Find the magnitude (spatial length) of this vector.
With a value, return a vector with same direction but of given length.
'''
mag = self.__mag()
if value is None: return mag
if zero(mag):
raise ValueError, 'Zero-magnitude vector cannot be scaled.'
v = self.__class__(self)
v.__imul__(value / mag)
v._l = value
return v | Find the magnitude (spatial length) of this vector.
With a value, return a vector with same direction but of given length.
| magnitude | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def order(self, order):
'''Remove elements from the end, or extend with new elements.'''
order = int(order)
if order < 1:
raise ValueError, 'cannot reduce a vector to zero elements'
v = V(self)
while order < len(v._v):
v._v.pop()
while order > len(v._v):
v._v.append(1.0)
v._l = None
return v | Remove elements from the end, or extend with new elements. | order | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def conjugate(self):
'''The conjugate of a quaternion has its X, Y and Z negated.'''
twin = Q(self)
for i in range(3):
twin._v[i] = -twin._v[i]
twin._l = twin._l
return twin | The conjugate of a quaternion has its X, Y and Z negated. | conjugate | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def inverse(self):
'''The quaternion inverse is the conjugate with reciprocal W.'''
twin = self.conjugate()
if twin._v[3] != 1.0:
twin._v[3] = 1.0 / twin._v[3]
twin._l = None
return twin | The quaternion inverse is the conjugate with reciprocal W. | inverse | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def rotate(cls, axis, theta):
'''Prepare a quaternion that represents a rotation on a given axis.'''
if isinstance(axis, str):
if axis in ('x','X'): axis = V.X
elif axis in ('y','Y'): axis = V.Y
elif axis in ('z','Z'): axis = V.Z
axis = axis.normalize()
s = math.sin(theta / 2.)
c = math.cos(theta / 2.)
return Q( axis._v[0] * s, axis._v[1] * s, axis._v[2] * s, c ) | Prepare a quaternion that represents a rotation on a given axis. | rotate | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __init__(self, *args):
'''Constructs a new 4x4 matrix.
If no arguments are given, an identity matrix is constructed.
Any combination of V vectors, tuples, lists or scalars may be given,
but taken together in order, they must have 16 number values total.
'''
# no args gives identity matrix
# 16 scalars collapsed from any combination of lists, tuples, vectors
if not args:
args = (1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1)
if len(args) == 4: args = collapse(*args)
a = args[0]
if isinstance(a, V):
if len(a) != 16: raise TypeError, 'M() takes exactly 16 elements'
self._v = list(a._v[:])
elif isseq(a):
if len(a) != 16: raise TypeError, 'M() takes exactly 16 elements'
self._v = map(float, a)
else:
if len(args) != 16: raise TypeError, 'M() takes exactly 16 elements'
self._v = map(float, args) | Constructs a new 4x4 matrix.
If no arguments are given, an identity matrix is constructed.
Any combination of V vectors, tuples, lists or scalars may be given,
but taken together in order, they must have 16 number values total.
| __init__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __str__(self):
'''Returns a multiple-line string representation of the matrix.'''
# prettier on multiple lines
n = self.__class__.__name__
ns = ' '*len(n)
t = n+'('+', '.join([ repr(self._v[i]) for i in 0,1,2,3 ])+',\n'
t += ns+' '+', '.join([ repr(self._v[i]) for i in 4,5,6,7 ])+',\n'
t += ns+' '+', '.join([ repr(self._v[i]) for i in 8,9,10,11 ])+',\n'
t += ns+' '+', '.join([ repr(self._v[i]) for i in 12,13,14,15 ])+')'
return t | Returns a multiple-line string representation of the matrix. | __str__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def __setitem__(self, rc, value):
'''Injects a single element into the matrix.
May index 0-15, or with tuples of (row,column) 0-3 each.
Indexing goes across first, so m[3] is m[0,3] and m[7] is m[1,3].
'''
if not isinstance(rc, tuple): return V.__getitem__(self, rc)
self._v[rc[0]*4+rc[1]] = float(value) | Injects a single element into the matrix.
May index 0-15, or with tuples of (row,column) 0-3 each.
Indexing goes across first, so m[3] is m[0,3] and m[7] is m[1,3].
| __setitem__ | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def row(self, r, v=None):
'''Returns or replaces a vector representing a row of the matrix.
Rows are counted 0-3. If given, new vector must be four numbers.
'''
if r < 0 or r > 3: raise IndexError, 'row index out of range'
if v is None: return V(self._v[r*4:(r+1)*4])
e = v
if isinstance(v, V): e = v._v
if len(e) != 4: raise ValueError, 'new row must include 4 values'
self._v[r*4:(r+1)*4] = e
return v | Returns or replaces a vector representing a row of the matrix.
Rows are counted 0-3. If given, new vector must be four numbers.
| row | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def col(self, c, v=None):
'''Returns or replaces a vector representing a column of the matrix.
Columns are counted 0-3. If given, new vector must be four numbers.
'''
if c < 0 or c > 3: raise IndexError, 'column index out of range'
if v is None: return V([ self._v[c+4*i] for i in range(4) ])
e = v
if isinstance(v, V): e = v._v
if len(e) != 4: raise ValueError, 'new row must include 4 values'
for i in range(4): self._v[c+4*i] = e[i]
return v | Returns or replaces a vector representing a column of the matrix.
Columns are counted 0-3. If given, new vector must be four numbers.
| col | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def translation(self):
'''Extracts the translation component from this matrix.'''
(a,b,c,d,
e,f,g,h,
i,j,k,l,
m,n,o,p) = self._v
return V(m,n,o) | Extracts the translation component from this matrix. | translation | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def rotation(self):
'''Extracts Euler angles of rotation from this matrix.
This attempts to find alternate rotations in case of gimbal lock,
but all of the usual problems with Euler angles apply here.
All Euler angles are in radians.
'''
(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p) = self._v
rotY = D = math.asin(c)
C = math.cos(rotY)
if (abs(C) > 0.005):
trX = k/C ; trY = -g/C ; rotX = math.atan2(trY, trX)
trX = a/C ; trY = -b/C ; rotZ = math.atan2(trY, trX)
else:
rotX = 0
trX = f ; trY = e ; rotZ = math.atan2(trY, trX)
return V(rotX,rotY,rotZ) | Extracts Euler angles of rotation from this matrix.
This attempts to find alternate rotations in case of gimbal lock,
but all of the usual problems with Euler angles apply here.
All Euler angles are in radians.
| rotation | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def angle(a, b):
'''Find the angle (scalar value in radians) between two 3d vectors.'''
a = a.normalize()
b = b.normalize()
if a == b: return 0.0
return math.acos(a.dot(b)) | Find the angle (scalar value in radians) between two 3d vectors. | angle | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def track(v):
'''Find the track (direction in positive radians) of a 2d vector.
E.g., track(V(1,0)) == 0 radians; track(V(0,1) == math.pi/2 radians;
track(V(-1,0)) == math.pi radians; and track(V(0,-1) is math.pi*3/2.
'''
t = math.atan2(v[1], v[0])
if t < 0:
return t + 2.*math.pi
return t | Find the track (direction in positive radians) of a 2d vector.
E.g., track(V(1,0)) == 0 radians; track(V(0,1) == math.pi/2 radians;
track(V(-1,0)) == math.pi radians; and track(V(0,-1) is math.pi*3/2.
| track | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def quangle(a, b):
'''Find a quaternion that rotates one 3d vector to parallel another.'''
x = a.cross(b)
w = a.magnitude() * b.magnitude() + a.dot(b)
return Q(x[0], x[1], x[2], w) | Find a quaternion that rotates one 3d vector to parallel another. | quangle | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def dsquared(one, two):
'''Find the square of the distance between two points.'''
# working with squared distances is common to avoid slow sqrt() calls
m = 0
for i in range(len(one._v)):
d = one._v[i] - two._v[i]
m += d * d
return m | Find the square of the distance between two points. | dsquared | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def nearest(point, neighbors):
'''Find the nearest neighbor point to a given point.'''
best = None
for other in neighbors:
d = dsquared(point, other)
if best is None or d < best[1]:
best = (other, d)
return best[0] | Find the nearest neighbor point to a given point. | nearest | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def farthest(point, neighbors):
'''Find the farthest neighbor point to a given point.'''
best = None
for other in neighbors:
d = dsquared(point, other)
if best is None or d > best[1]:
best = (other, d)
return best[0] | Find the farthest neighbor point to a given point. | farthest | python | hhatto/autopep8 | test/vectors_example.py | https://github.com/hhatto/autopep8/blob/master/test/vectors_example.py | MIT |
def test_keys(self):
"""areas.json - All regions are accounted for."""
expected = set([
u'Norrbotten',
u'V\xe4sterbotten',
]) | areas.json - All regions are accounted for. | test_keys | python | hhatto/autopep8 | test/suite/E10.py | https://github.com/hhatto/autopep8/blob/master/test/suite/E10.py | MIT |
def qualify_by_address(
self, cr, uid, ids, context=None,
params_to_check=frozenset(QUALIF_BY_ADDRESS_PARAM)):
""" This gets called by the web server """ | This gets called by the web server | qualify_by_address | python | hhatto/autopep8 | test/suite/E12.py | https://github.com/hhatto/autopep8/blob/master/test/suite/E12.py | MIT |
def qualify_by_address(self, cr, uid, ids, context=None,
params_to_check=frozenset(QUALIF_BY_ADDRESS_PARAM)):
""" This gets called by the web server """ | This gets called by the web server | qualify_by_address | python | hhatto/autopep8 | test/suite/E12.py | https://github.com/hhatto/autopep8/blob/master/test/suite/E12.py | MIT |
def test_keys(self):
"""areas.json - All regions are accounted for."""
expected = set([
u'Norrbotten',
u'V\xe4sterbotten',
]) | areas.json - All regions are accounted for. | test_keys | python | hhatto/autopep8 | test/suite/W19.py | https://github.com/hhatto/autopep8/blob/master/test/suite/W19.py | MIT |
def test_keys(self):
"""areas.json - All regions are accounted for."""
expected = set([
u'Norrbotten',
u'V\xe4sterbotten',
]) | areas.json - All regions are accounted for. | test_keys | python | hhatto/autopep8 | test/suite/out/E10.py | https://github.com/hhatto/autopep8/blob/master/test/suite/out/E10.py | MIT |
def qualify_by_address(
self, cr, uid, ids, context=None,
params_to_check=frozenset(QUALIF_BY_ADDRESS_PARAM)):
""" This gets called by the web server """ | This gets called by the web server | qualify_by_address | python | hhatto/autopep8 | test/suite/out/E12.py | https://github.com/hhatto/autopep8/blob/master/test/suite/out/E12.py | MIT |
def qualify_by_address(self, cr, uid, ids, context=None,
params_to_check=frozenset(QUALIF_BY_ADDRESS_PARAM)):
""" This gets called by the web server """ | This gets called by the web server | qualify_by_address | python | hhatto/autopep8 | test/suite/out/E12.py | https://github.com/hhatto/autopep8/blob/master/test/suite/out/E12.py | MIT |
def test_keys(self):
"""areas.json - All regions are accounted for."""
expected = set([
u'Norrbotten',
u'V\xe4sterbotten',
]) | areas.json - All regions are accounted for. | test_keys | python | hhatto/autopep8 | test/suite/out/W19.py | https://github.com/hhatto/autopep8/blob/master/test/suite/out/W19.py | MIT |
def return_random_from_word(word):
"""
This function receives a TextMobject,
obtains its length:
len(TextMobject("Some text"))
and returns a random list, example:
INPUT: word = TextMobjecT("Hello")
length = len(word) # 4
rango = list(range(length)) # [0,1,2,3]
OUTPUT: [3,0,2,1] # Random list
"""
rango = list(range(len(word)))
random.shuffle(rango)
return rango |
This function receives a TextMobject,
obtains its length:
len(TextMobject("Some text"))
and returns a random list, example:
INPUT: word = TextMobjecT("Hello")
length = len(word) # 4
rango = list(range(length)) # [0,1,2,3]
OUTPUT: [3,0,2,1] # Random list
| return_random_from_word | python | manim-kindergarten/manim_sandbox | utils/animations/RandomScene.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/animations/RandomScene.py | MIT |
def get_random_coord(r_x, r_y, step_x, step_y):
"""
Given two ranges (a, b) and (c, d), this function returns an
intermediate array (x, y) such that "x" belongs to (a, c)
and "y" belongs to (b, d).
"""
range_x = list(range(r_x[0], r_x[1], step_x))
range_y = list(range(r_y[0], r_y[1], step_y))
select_x = random.choice(range_x)
select_y = random.choice(range_y)
return np.array([select_x, select_y, 0]) |
Given two ranges (a, b) and (c, d), this function returns an
intermediate array (x, y) such that "x" belongs to (a, c)
and "y" belongs to (b, d).
| get_random_coord | python | manim-kindergarten/manim_sandbox | utils/animations/RandomScene.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/animations/RandomScene.py | MIT |
def return_random_coords(word, r_x, r_y, step_x, step_y):
"""
This function returns a random coordinate array,
given the length of a TextMobject
"""
rango = range(len(word))
return [word.get_center() + get_random_coord(r_x, r_y, step_x, step_y) for _ in rango] |
This function returns a random coordinate array,
given the length of a TextMobject
| return_random_coords | python | manim-kindergarten/manim_sandbox | utils/animations/RandomScene.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/animations/RandomScene.py | MIT |
def get_formatter(self, **kwargs):
"""
Configuration is based first off instance attributes,
but overwritten by any kew word argument. Relevant
key words:
- include_sign
- group_with_commas
- num_decimal_places
- field_name (e.g. 0 or 0.real)
"""
config = dict([
(attr, getattr(self, attr))
for attr in [
"include_sign",
"group_with_commas",
"num_decimal_places",
]
])
config.update(kwargs)
return "".join([
"{",
config.get("field_name", ""),
":",
"+" if config["include_sign"] else "",
"," if config["group_with_commas"] else "",
".", str(config["num_decimal_places"]), "f",
"}",
]) |
Configuration is based first off instance attributes,
but overwritten by any kew word argument. Relevant
key words:
- include_sign
- group_with_commas
- num_decimal_places
- field_name (e.g. 0 or 0.real)
| get_formatter | python | manim-kindergarten/manim_sandbox | utils/mobjects/ColorText.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/mobjects/ColorText.py | MIT |
def apply_edge(self):
'''
(private)
Finally apply the edge.
Appies the edge
'''
for (u,v) in self.edgeQ:
if u==v:
continue
self.adde(u,v) |
(private)
Finally apply the edge.
Appies the edge
| apply_edge | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def adde(self, u, v):
'''
(private)
Add an edge applied on arraies inside.
'''
if self.verbose:
print("Added edge from and to"+str(u)+" "+str(v))
self.hasone[u] = True
self.hasone[v] = True
self.out[u]=self.out[u]+1
self.cnt = self.cnt+1
self.edg[self.cnt].nxt = self.head[u]
self.edg[self.cnt].to = v
self.edg[self.cnt].top = 0
self.edg[self.head[u]].top = self.cnt
self.edg[self.cnt].bot = self.head[u]
self.head[u] = self.cnt |
(private)
Add an edge applied on arraies inside.
| adde | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def dfs(self, x,layer,fat):
'''
(private)
Get the basic arguments of the tree.
'''
self.dfsord.append(x)
self.dep[x] = layer
self.fa[x] = fat
i = self.head[x]
if i==0:
self.size[x]=1
while i != int(0):
v = self.edg[i].to
if v != fat:
self.dfs(self.edg[i].to,layer+1,x)
self.size[x]=self.size[x]+self.size[self.edg[i].to]
i = self.edg[i].nxt |
(private)
Get the basic arguments of the tree.
| dfs | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def getpos(self,v):
'''
(private)
Get the x-y crood position between of a tree.
'''
if v!= self.treeroot:
u=self.fa[v]
self.pos[v] = self.pos[u]+2*np.array([math.cos(self.tau[v]+self.omega[v]/2),math.sin(self.tau[v]+self.omega[v]/2),0])
yita = self.tau[v]
i = self.head[v]
while i != int(0):
w = self.edg[i].to
self.omega[w] = self.size[w]/self.size[1]*-self.factor*PI
self.tau[w] = yita
yita = yita+self.omega[w]
if w!=self.fa[v]:
self.getpos(self.edg[i].to)
i = self.edg[i].nxt
if self.verbose:
print(i) |
(private)
Get the x-y crood position between of a tree.
| getpos | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def getxy(self):
'''
(private)
Get the position between of a tree.
'''
self.getpos(self.treeroot)
for i in range(1,self.edgnum):
if self.hasone[i]:
p=Circle(fill_color=GREEN,radius=0.25,fill_opacity=0.8,color=GREEN)
p.move_to(self.pos[i])
self.tree.add(p)
else:
p=Circle(fill_color=GREEN,radius=0.25,fill_opacity=0.8,color=GREEN)
p.move_to(8*DOWN)
self.tree.add(p)
return self.tree |
(private)
Get the position between of a tree.
| getxy | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def get_id(self):
'''
(private)
Get the id between of a tree.
'''
for i in range(1,self.edgnum):
if self.hasone[i]==True:
ics=TextMobject(str(i))
ics.move_to(self.pos[i]).shift((self.radius+0.1)*DOWN).scale(0.6)
self.ids.add(ics)
return self.ids |
(private)
Get the id between of a tree.
| get_id | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def get_connection(self,x,fa):
'''
(private)
Get the lines between of a tree.
'''
ln = Line(self.pos[self.fa[x]],self.pos[self.fa[x]],color=BLUE)
ln = Line(self.pos[self.fa[x]],self.pos[x],color=BLUE)
self.lines.add(ln)
txt=TextMobject(str(len(self.lines)-1),color=WHITE)
txt.move_to(ln).scale(0.5)
self.edgemk.add(txt)
self.sidecnt.append((fa,x))
i = self.head[x]
while i != int(0):
w = self.edg[i].to
if w != self.fa[x]:
self.get_connection(self.edg[i].to,self.fa[x])
i = self.edg[i].nxt
return self.lines |
(private)
Get the lines between of a tree.
| get_connection | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def highlight_edge(self,frm,to):
"""
Focuses on an edge to stress
"""
for i in range(0,len(self.sidecnt)):
u = self.sidecnt[i][0]
v = self.sidecnt[i][1]
if u!=0 and v!=0:
if frm==u and to==v:
self.play(FocusOn(self.lines[i-1]))
break |
Focuses on an edge to stress
| highlight_edge | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def get_instance_of_edge(self,x):
'''
Returns a instance of edge which you can apply methods on.
'''
for i in range(0,len(self.sidecnt)):
u = self.sidecnt[i][0]
v = self.sidecnt[i][1]
if u!=0 and v!=0:
if frm==u and to==v:
return (self.lines[i-1])
break |
Returns a instance of edge which you can apply methods on.
| get_instance_of_edge | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def get_arguments(self):
'''
(private)
Get the datas of a tree.
'''
self.apply_edge()
self.dfs(self.treeroot,self.treeroot,0)
self.treeMobject.add(self.getxy())
self.treeMobject.add(self.get_nodes())
self.treeMobject.add(self.get_id())
self.treeMobject.add(self.get_connection(self.treeroot,0)) |
(private)
Get the datas of a tree.
| get_arguments | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def restart(self):
'''
(private)
Restart the tree. Clear all the mobjects and datas.
'''
self.cnt = 0
self.edg = [Edge(0,0)]
self.head = [0]*self.edgnum
self.dep = [0]*self.edgnum
self.sidecnt = [(0,0)]
self.fa = [0]*self.edgnum
self.pos = [np.array([0,self.shiftup,0])]
self.out = [0]*self.edgnum
self.dfsord=[0]
self.hasone=[False]*self.edgnum
self.omega = [2*PI]*self.edgnum
self.tau = [0]*self.edgnum
self.size=[1]*self.edgnum
for i in range(self.edgnum):
x=Edge(0,0)
self.edg.append(x)
for i in range(self.edgnum):
x=np.array([0,self.shiftup,0])
self.pos.append(x)
self.lines = VMobject()
self.tree = VMobject()
self.ids = VMobject()
self.treeMobject = VGroup() |
(private)
Restart the tree. Clear all the mobjects and datas.
| restart | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def draw_tree(self):
'''
Show up the tree onto the screen.
'''
self.apply_edge()
self.dfs(self.treeroot,self.treeroot,0)
self.treeMobject.add(self.getxy())
self.treeMobject.add(self.get_nodes())
self.treeMobject.add(self.get_id())
self.treeMobject.add(self.get_connection(self.treeroot,0))
self.play(Write(self.treeMobject)) |
Show up the tree onto the screen.
| draw_tree | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def update_transform(self):
'''
Update the tree on the screen, which uses the latest data to
reposition and rebuild the tree.
'''
utter = self.treeMobject.copy()
self.remove(self.treeMobject)
self.restart()
self.get_arguments()
self.play(Transform(utter,self.treeMobject))
self.add(self.treeMobject)
self.remove(utter)
#self.play(Write(self.treeMobject)) |
Update the tree on the screen, which uses the latest data to
reposition and rebuild the tree.
| update_transform | python | manim-kindergarten/manim_sandbox | utils/scenes/OITree.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/utils/scenes/OITree.py | MIT |
def get_formatter(self, **kwargs):
"""
Configuration is based first off instance attributes,
but overwritten by any kew word argument. Relevant
key words:
- include_sign
- group_with_commas
- num_decimal_places
- field_name (e.g. 0 or 0.real)
"""
config = dict([
(attr, getattr(self, attr))
for attr in [
"include_sign",
"group_with_commas",
"num_decimal_places",
]
])
config.update(kwargs)
return "".join([
"{",
config.get("field_name", ""),
":",
"+" if config["include_sign"] else "",
"," if config["group_with_commas"] else "",
".", str(config["num_decimal_places"]), "f",
"}",
]) |
Configuration is based first off instance attributes,
but overwritten by any kew word argument. Relevant
key words:
- include_sign
- group_with_commas
- num_decimal_places
- field_name (e.g. 0 or 0.real)
| get_formatter | python | manim-kindergarten/manim_sandbox | videos/manimTutorial/part3_Color.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/videos/manimTutorial/part3_Color.py | MIT |
def capture(self, mobjects, write_current_frame=True):
"""
Capture mobjects on the current frame, write to movie if possible.
:param mobjects: instance of Mobject to be captured.
:param write_current_frame: boolean value, whether to write current frame to movie.
"""
self.update_frame(mobjects, self.get_frame())
if write_current_frame:
self.write_current_frame()
return self |
Capture mobjects on the current frame, write to movie if possible.
:param mobjects: instance of Mobject to be captured.
:param write_current_frame: boolean value, whether to write current frame to movie.
| capture | python | manim-kindergarten/manim_sandbox | videos/Solitaire/raw_frame_scene.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/videos/Solitaire/raw_frame_scene.py | MIT |
def tear_down(self):
"""
Finish method for RawFrameScene. A must call after using this scene.
"""
self.file_writer.close_movie_pipe()
setattr(self, "msg_flag", False)
self.msg_thread.join()
self.print_frame_message(msg_end="\n")
self.num_plays += 1 |
Finish method for RawFrameScene. A must call after using this scene.
| tear_down | python | manim-kindergarten/manim_sandbox | videos/Solitaire/raw_frame_scene.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/videos/Solitaire/raw_frame_scene.py | MIT |
def play(*args, **kwargs):
"""
'self.play' method fails in this scene. Do not use it.
"""
raise Exception("""
'self.play' method is not allowed to use in this scene
Use 'self.capture(...)' instead
""") |
'self.play' method fails in this scene. Do not use it.
| play | python | manim-kindergarten/manim_sandbox | videos/Solitaire/raw_frame_scene.py | https://github.com/manim-kindergarten/manim_sandbox/blob/master/videos/Solitaire/raw_frame_scene.py | MIT |
async def async_update_worker(worker_id, q, notification_q, app, datastore):
"""
Async worker function that processes watch check jobs from the queue.
Args:
worker_id: Unique identifier for this worker
q: AsyncSignalPriorityQueue containing jobs to process
notification_q: Standard queue for notifications
app: Flask application instance
datastore: Application datastore
"""
# Set a descriptive name for this task
task = asyncio.current_task()
if task:
task.set_name(f"async-worker-{worker_id}")
logger.info(f"Starting async worker {worker_id}")
while not app.config.exit.is_set():
update_handler = None
watch = None
try:
# Use asyncio wait_for to make queue.get() cancellable
queued_item_data = await asyncio.wait_for(q.get(), timeout=1.0)
except asyncio.TimeoutError:
# No jobs available, continue loop
continue
except Exception as e:
logger.error(f"Worker {worker_id} error getting queue item: {e}")
await asyncio.sleep(0.1)
continue
uuid = queued_item_data.item.get('uuid')
fetch_start_time = round(time.time())
# Mark this UUID as being processed
from changedetectionio import worker_handler
worker_handler.set_uuid_processing(uuid, processing=True)
try:
if uuid in list(datastore.data['watching'].keys()) and datastore.data['watching'][uuid].get('url'):
changed_detected = False
contents = b''
process_changedetection_results = True
update_obj = {}
# Clear last errors
datastore.data['watching'][uuid]['browser_steps_last_error_step'] = None
datastore.data['watching'][uuid]['last_checked'] = fetch_start_time
watch = datastore.data['watching'].get(uuid)
logger.info(f"Worker {worker_id} processing watch UUID {uuid} Priority {queued_item_data.priority} URL {watch['url']}")
try:
watch_check_update.send(watch_uuid=uuid)
# Processor is what we are using for detecting the "Change"
processor = watch.get('processor', 'text_json_diff')
# Init a new 'difference_detection_processor'
processor_module_name = f"changedetectionio.processors.{processor}.processor"
try:
processor_module = importlib.import_module(processor_module_name)
except ModuleNotFoundError as e:
print(f"Processor module '{processor}' not found.")
raise e
update_handler = processor_module.perform_site_check(datastore=datastore,
watch_uuid=uuid)
# All fetchers are now async, so call directly
await update_handler.call_browser()
# Run change detection (this is synchronous)
changed_detected, update_obj, contents = update_handler.run_changedetection(watch=watch)
except PermissionError as e:
logger.critical(f"File permission error updating file, watch: {uuid}")
logger.critical(str(e))
process_changedetection_results = False
except ProcessorException as e:
if e.screenshot:
watch.save_screenshot(screenshot=e.screenshot)
if e.xpath_data:
watch.save_xpath_data(data=e.xpath_data)
datastore.update_watch(uuid=uuid, update_obj={'last_error': e.message})
process_changedetection_results = False
except content_fetchers_exceptions.ReplyWithContentButNoText as e:
extra_help = ""
if e.has_filters:
has_img = html_tools.include_filters(include_filters='img',
html_content=e.html_content)
if has_img:
extra_help = ", it's possible that the filters you have give an empty result or contain only an image."
else:
extra_help = ", it's possible that the filters were found, but contained no usable text."
datastore.update_watch(uuid=uuid, update_obj={
'last_error': f"Got HTML content but no text found (With {e.status_code} reply code){extra_help}"
})
if e.screenshot:
watch.save_screenshot(screenshot=e.screenshot, as_error=True)
if e.xpath_data:
watch.save_xpath_data(data=e.xpath_data)
process_changedetection_results = False
except content_fetchers_exceptions.Non200ErrorCodeReceived as e:
if e.status_code == 403:
err_text = "Error - 403 (Access denied) received"
elif e.status_code == 404:
err_text = "Error - 404 (Page not found) received"
elif e.status_code == 407:
err_text = "Error - 407 (Proxy authentication required) received, did you need a username and password for the proxy?"
elif e.status_code == 500:
err_text = "Error - 500 (Internal server error) received from the web site"
else:
extra = ' (Access denied or blocked)' if str(e.status_code).startswith('4') else ''
err_text = f"Error - Request returned a HTTP error code {e.status_code}{extra}"
if e.screenshot:
watch.save_screenshot(screenshot=e.screenshot, as_error=True)
if e.xpath_data:
watch.save_xpath_data(data=e.xpath_data, as_error=True)
if e.page_text:
watch.save_error_text(contents=e.page_text)
datastore.update_watch(uuid=uuid, update_obj={'last_error': err_text})
process_changedetection_results = False
except FilterNotFoundInResponse as e:
if not datastore.data['watching'].get(uuid):
continue
err_text = "Warning, no filters were found, no change detection ran - Did the page change layout? update your Visual Filter if necessary."
datastore.update_watch(uuid=uuid, update_obj={'last_error': err_text})
# Filter wasnt found, but we should still update the visual selector so that they can have a chance to set it up again
if e.screenshot:
watch.save_screenshot(screenshot=e.screenshot)
if e.xpath_data:
watch.save_xpath_data(data=e.xpath_data)
# Only when enabled, send the notification
if watch.get('filter_failure_notification_send', False):
c = watch.get('consecutive_filter_failures', 0)
c += 1
# Send notification if we reached the threshold?
threshold = datastore.data['settings']['application'].get('filter_failure_notification_threshold_attempts', 0)
logger.debug(f"Filter for {uuid} not found, consecutive_filter_failures: {c} of threshold {threshold}")
if c >= threshold:
if not watch.get('notification_muted'):
logger.debug(f"Sending filter failed notification for {uuid}")
await send_filter_failure_notification(uuid, notification_q, datastore)
c = 0
logger.debug(f"Reset filter failure count back to zero")
datastore.update_watch(uuid=uuid, update_obj={'consecutive_filter_failures': c})
else:
logger.trace(f"{uuid} - filter_failure_notification_send not enabled, skipping")
process_changedetection_results = False
except content_fetchers_exceptions.checksumFromPreviousCheckWasTheSame as e:
# Yes fine, so nothing todo, don't continue to process.
process_changedetection_results = False
changed_detected = False
except content_fetchers_exceptions.BrowserConnectError as e:
datastore.update_watch(uuid=uuid,
update_obj={'last_error': e.msg})
process_changedetection_results = False
except content_fetchers_exceptions.BrowserFetchTimedOut as e:
datastore.update_watch(uuid=uuid,
update_obj={'last_error': e.msg})
process_changedetection_results = False
except content_fetchers_exceptions.BrowserStepsStepException as e:
if not datastore.data['watching'].get(uuid):
continue
error_step = e.step_n + 1
from playwright._impl._errors import TimeoutError, Error
# Generally enough info for TimeoutError (couldnt locate the element after default seconds)
err_text = f"Browser step at position {error_step} could not run, check the watch, add a delay if necessary, view Browser Steps to see screenshot at that step."
if e.original_e.name == "TimeoutError":
# Just the first line is enough, the rest is the stack trace
err_text += " Could not find the target."
else:
# Other Error, more info is good.
err_text += " " + str(e.original_e).splitlines()[0]
logger.debug(f"BrowserSteps exception at step {error_step} {str(e.original_e)}")
datastore.update_watch(uuid=uuid,
update_obj={'last_error': err_text,
'browser_steps_last_error_step': error_step})
if watch.get('filter_failure_notification_send', False):
c = watch.get('consecutive_filter_failures', 0)
c += 1
# Send notification if we reached the threshold?
threshold = datastore.data['settings']['application'].get('filter_failure_notification_threshold_attempts', 0)
logger.error(f"Step for {uuid} not found, consecutive_filter_failures: {c}")
if threshold > 0 and c >= threshold:
if not watch.get('notification_muted'):
await send_step_failure_notification(watch_uuid=uuid, step_n=e.step_n, notification_q=notification_q, datastore=datastore)
c = 0
datastore.update_watch(uuid=uuid, update_obj={'consecutive_filter_failures': c})
process_changedetection_results = False
except content_fetchers_exceptions.EmptyReply as e:
# Some kind of custom to-str handler in the exception handler that does this?
err_text = "EmptyReply - try increasing 'Wait seconds before extracting text', Status Code {}".format(e.status_code)
datastore.update_watch(uuid=uuid, update_obj={'last_error': err_text,
'last_check_status': e.status_code})
process_changedetection_results = False
except content_fetchers_exceptions.ScreenshotUnavailable as e:
err_text = "Screenshot unavailable, page did not render fully in the expected time or page was too long - try increasing 'Wait seconds before extracting text'"
datastore.update_watch(uuid=uuid, update_obj={'last_error': err_text,
'last_check_status': e.status_code})
process_changedetection_results = False
except content_fetchers_exceptions.JSActionExceptions as e:
err_text = "Error running JS Actions - Page request - "+e.message
if e.screenshot:
watch.save_screenshot(screenshot=e.screenshot, as_error=True)
datastore.update_watch(uuid=uuid, update_obj={'last_error': err_text,
'last_check_status': e.status_code})
process_changedetection_results = False
except content_fetchers_exceptions.PageUnloadable as e:
err_text = "Page request from server didnt respond correctly"
if e.message:
err_text = "{} - {}".format(err_text, e.message)
if e.screenshot:
watch.save_screenshot(screenshot=e.screenshot, as_error=True)
datastore.update_watch(uuid=uuid, update_obj={'last_error': err_text,
'last_check_status': e.status_code,
'has_ldjson_price_data': None})
process_changedetection_results = False
except content_fetchers_exceptions.BrowserStepsInUnsupportedFetcher as e:
err_text = "This watch has Browser Steps configured and so it cannot run with the 'Basic fast Plaintext/HTTP Client', either remove the Browser Steps or select a Chrome fetcher."
datastore.update_watch(uuid=uuid, update_obj={'last_error': err_text})
process_changedetection_results = False
logger.error(f"Exception (BrowserStepsInUnsupportedFetcher) reached processing watch UUID: {uuid}")
except Exception as e:
logger.error(f"Worker {worker_id} exception processing watch UUID: {uuid}")
logger.error(str(e))
datastore.update_watch(uuid=uuid, update_obj={'last_error': "Exception: " + str(e)})
process_changedetection_results = False
else:
if not datastore.data['watching'].get(uuid):
continue
update_obj['content-type'] = update_handler.fetcher.get_all_headers().get('content-type', '').lower()
if not watch.get('ignore_status_codes'):
update_obj['consecutive_filter_failures'] = 0
update_obj['last_error'] = False
cleanup_error_artifacts(uuid, datastore)
if not datastore.data['watching'].get(uuid):
continue
if process_changedetection_results:
# Extract title if needed
if datastore.data['settings']['application'].get('extract_title_as_title') or watch['extract_title_as_title']:
if not watch['title'] or not len(watch['title']):
try:
update_obj['title'] = html_tools.extract_element(find='title', html_content=update_handler.fetcher.content)
logger.info(f"UUID: {uuid} Extract <title> updated title to '{update_obj['title']}")
except Exception as e:
logger.warning(f"UUID: {uuid} Extract <title> as watch title was enabled, but couldn't find a <title>.")
try:
datastore.update_watch(uuid=uuid, update_obj=update_obj)
if changed_detected or not watch.history_n:
if update_handler.screenshot:
watch.save_screenshot(screenshot=update_handler.screenshot)
if update_handler.xpath_data:
watch.save_xpath_data(data=update_handler.xpath_data)
# Ensure unique timestamp for history
if watch.newest_history_key and int(fetch_start_time) == int(watch.newest_history_key):
logger.warning(f"Timestamp {fetch_start_time} already exists, waiting 1 seconds")
fetch_start_time += 1
await asyncio.sleep(1)
watch.save_history_text(contents=contents,
timestamp=int(fetch_start_time),
snapshot_id=update_obj.get('previous_md5', 'none'))
empty_pages_are_a_change = datastore.data['settings']['application'].get('empty_pages_are_a_change', False)
if update_handler.fetcher.content or (not update_handler.fetcher.content and empty_pages_are_a_change):
watch.save_last_fetched_html(contents=update_handler.fetcher.content, timestamp=int(fetch_start_time))
# Send notifications on second+ check
if watch.history_n >= 2:
logger.info(f"Change detected in UUID {uuid} - {watch['url']}")
if not watch.get('notification_muted'):
await send_content_changed_notification(uuid, notification_q, datastore)
except Exception as e:
logger.critical(f"Worker {worker_id} exception in process_changedetection_results")
logger.critical(str(e))
datastore.update_watch(uuid=uuid, update_obj={'last_error': str(e)})
# Always record attempt count
count = watch.get('check_count', 0) + 1
# Record server header
try:
server_header = update_handler.fetcher.headers.get('server', '').strip().lower()[:255]
datastore.update_watch(uuid=uuid, update_obj={'remote_server_reply': server_header})
except Exception as e:
pass
datastore.update_watch(uuid=uuid, update_obj={'fetch_time': round(time.time() - fetch_start_time, 3),
'check_count': count})
except Exception as e:
logger.error(f"Worker {worker_id} unexpected error processing {uuid}: {e}")
logger.error(f"Worker {worker_id} traceback:", exc_info=True)
# Also update the watch with error information
if datastore and uuid in datastore.data['watching']:
datastore.update_watch(uuid=uuid, update_obj={'last_error': f"Worker error: {str(e)}"})
finally:
# Always cleanup - this runs whether there was an exception or not
if uuid:
try:
# Mark UUID as no longer being processed
worker_handler.set_uuid_processing(uuid, processing=False)
# Send completion signal
if watch:
#logger.info(f"Worker {worker_id} sending completion signal for UUID {watch['uuid']}")
watch_check_update.send(watch_uuid=watch['uuid'])
update_handler = None
logger.debug(f"Worker {worker_id} completed watch {uuid} in {time.time()-fetch_start_time:.2f}s")
except Exception as cleanup_error:
logger.error(f"Worker {worker_id} error during cleanup: {cleanup_error}")
# Brief pause before continuing to avoid tight error loops (only on error)
if 'e' in locals():
await asyncio.sleep(1.0)
else:
# Small yield for normal completion
await asyncio.sleep(0.01)
# Check if we should exit
if app.config.exit.is_set():
break
# Check if we're in pytest environment - if so, be more gentle with logging
import sys
in_pytest = "pytest" in sys.modules or "PYTEST_CURRENT_TEST" in os.environ
if not in_pytest:
logger.info(f"Worker {worker_id} shutting down") |
Async worker function that processes watch check jobs from the queue.
Args:
worker_id: Unique identifier for this worker
q: AsyncSignalPriorityQueue containing jobs to process
notification_q: Standard queue for notifications
app: Flask application instance
datastore: Application datastore
| async_update_worker | python | dgtlmoon/changedetection.io | changedetectionio/async_update_worker.py | https://github.com/dgtlmoon/changedetection.io/blob/master/changedetectionio/async_update_worker.py | Apache-2.0 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.