code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
for pid in self.get_process_ids():
aProcess = self.get_process(pid)
if not aProcess.is_being_debugged():
self._del_process(aProcess) | def clear_unattached_processes(self) | Removes Process objects from the snapshot
referring to processes not being debugged. | 4.308913 | 3.255199 | 1.323702 |
for pid in self.get_process_ids():
aProcess = self.get_process(pid)
try:
aProcess.close_handle()
except Exception:
e = sys.exc_info()[1]
try:
msg = "Cannot close process handle %s, reason: %s"
... | def close_process_handles(self) | Closes all open handles to processes in this snapshot. | 3.156181 | 2.994868 | 1.053863 |
for aProcess in self.iter_processes():
aProcess.close_thread_handles()
try:
aProcess.close_handle()
except Exception:
e = sys.exc_info()[1]
try:
msg = "Cannot close process handle %s, reason: %s"
... | def close_process_and_thread_handles(self) | Closes all open handles to processes and threads in this snapshot. | 3.37349 | 3.25511 | 1.036367 |
#self.close_process_and_thread_handles()
for aProcess in self.iter_processes():
aProcess.clear()
self.__processDict = dict() | def clear_processes(self) | Removes all L{Process}, L{Thread} and L{Module} objects in this snapshot. | 9.84796 | 8.978211 | 1.096873 |
found = list()
filename = filename.lower()
if PathOperations.path_is_absolute(filename):
for aProcess in self.iter_processes():
imagename = aProcess.get_filename()
if imagename and imagename.lower() == filename:
found.ap... | def __find_processes_by_filename(self, filename) | Internally used by L{find_processes_by_filename}. | 2.792007 | 2.683535 | 1.040421 |
found = self.__find_processes_by_filename(fileName)
if not found:
fn, ext = PathOperations.split_extension(fileName)
if not ext:
fileName = '%s.exe' % fn
found = self.__find_processes_by_filename(fileName)
return found | def find_processes_by_filename(self, fileName) | @type fileName: str
@param fileName: Filename to search for.
If it's a full pathname, the match must be exact.
If it's a base filename only, the file part is matched,
regardless of the directory where it's located.
@note: If the process is not found and the file ext... | 4.084288 | 4.167641 | 0.98 |
## if not isinstance(aProcess, Process):
## if hasattr(aProcess, '__class__'):
## typename = aProcess.__class__.__name__
## else:
## typename = str(type(aProcess))
## msg = "Expected Process, got %s instead" % typename
## raise Ty... | def _add_process(self, aProcess) | Private method to add a process object to the snapshot.
@type aProcess: L{Process}
@param aProcess: Process object. | 2.274499 | 2.429559 | 0.936178 |
try:
aProcess = self.__processDict[dwProcessId]
del self.__processDict[dwProcessId]
except KeyError:
aProcess = None
msg = "Unknown process ID %d" % dwProcessId
warnings.warn(msg, RuntimeWarning)
if aProcess:
aProce... | def _del_process(self, dwProcessId) | Private method to remove a process object from the snapshot.
@type dwProcessId: int
@param dwProcessId: Global process ID. | 3.19214 | 3.365895 | 0.948378 |
dwProcessId = event.get_pid()
dwThreadId = event.get_tid()
hProcess = event.get_process_handle()
## if not self.has_process(dwProcessId): # XXX this would trigger a scan
if dwProcessId not in self.__processDict:
aProcess = Process(dwProcessId, hProcess)
... | def _notify_create_process(self, event) | Notify the creation of a new process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{CreateProcessEvent}
@param event: Create process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{Fal... | 3.676282 | 3.944426 | 0.932019 |
dwProcessId = event.get_pid()
## if self.has_process(dwProcessId): # XXX this would trigger a scan
if dwProcessId in self.__processDict:
self._del_process(dwProcessId)
return True | def _notify_exit_process(self, event) | Notify the termination of a process.
This is done automatically by the L{Debug} class, you shouldn't need
to call it yourself.
@type event: L{ExitProcessEvent}
@param event: Exit process event.
@rtype: bool
@return: C{True} to call the user-defined handle, C{False} o... | 8.282318 | 10.498484 | 0.788906 |
if key is None:
key_callback = _natural_keys
else:
def key_callback(item):
return _natural_keys(key(item))
return sorted(to_sort, key=key_callback) | def nsorted(to_sort, key=None) | Returns a naturally sorted list | 2.815373 | 2.818323 | 0.998953 |
return (hasattr(object, "__get__")
and not hasattr(object, "__set__") # else it's a data descriptor
and not ismethod(object) # mutual exclusion
and not isfunction(object)
and not isclass(object)) | def ismethoddescriptor(object) | Return true if the object is a method descriptor.
But not if ismethod() or isclass() or isfunction() are true.
This is new in Python 2.2, and, for example, is true of int.__add__.
An object passing this test has a __get__ attribute but not a __set__
attribute, but beyond that the set of attributes var... | 4.530145 | 4.540532 | 0.997712 |
return (isbuiltin(object)
or isfunction(object)
or ismethod(object)
or ismethoddescriptor(object)) | def isroutine(object) | Return true if the object is any kind of function or method. | 3.38058 | 3.305263 | 1.022787 |
results = []
for key in dir(object):
value = getattr(object, key)
if not predicate or predicate(value):
results.append((key, value))
results.sort()
return results | def getmembers(object, predicate=None) | Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate. | 2.322089 | 2.208951 | 1.051218 |
mro = getmro(cls)
names = dir(cls)
result = []
for name in names:
# Get the object associated with the name.
# Getting an obj from the __dict__ sometimes reveals more than
# using getattr. Static and class methods are dramatic examples.
if name in cls.__dict__:
... | def classify_class_attrs(cls) | Return list of attribute-descriptor tuples.
For each name in dir(cls), the return list contains a 4-tuple
with these elements:
0. The name (a string).
1. The kind of attribute this is, one of these strings:
'class method' created via classmethod()
'static meth... | 3.467771 | 3.019666 | 1.148396 |
"Return tuple of base classes (including cls) in method resolution order."
if hasattr(cls, "__mro__"):
return cls.__mro__
else:
result = []
_searchbases(cls, result)
return tuple(result) | def getmro(cls) | Return tuple of base classes (including cls) in method resolution order. | 3.901086 | 3.002476 | 1.29929 |
expline = string.expandtabs(line)
return len(expline) - len(string.lstrip(expline)) | def indentsize(line) | Return the indent size, in spaces, at the start of a line of text. | 4.915469 | 4.05492 | 1.212223 |
try:
doc = object.__doc__
except AttributeError:
return None
if not isinstance(doc, (str, unicode)):
return None
try:
lines = string.split(string.expandtabs(doc), '\n')
except UnicodeError:
return None
else:
margin = None
for line in l... | def getdoc(object) | Get the documentation string for an object.
All tabs are expanded to spaces. To clean up docstrings that are
indented to line up with blocks of code, any whitespace than can be
uniformly removed from the second line onwards is removed. | 2.385582 | 2.250756 | 1.059903 |
if ismodule(object):
if hasattr(object, '__file__'):
return object.__file__
raise TypeError, 'arg is a built-in module'
if isclass(object):
object = sys.modules.get(object.__module__)
if hasattr(object, '__file__'):
return object.__file__
rais... | def getfile(object) | Work out which source or compiled file an object was defined in. | 1.86801 | 1.824911 | 1.023617 |
filename = os.path.basename(path)
suffixes = map(lambda (suffix, mode, mtype):
(-len(suffix), suffix, mode, mtype), imp.get_suffixes())
suffixes.sort() # try longest suffixes first, in case they overlap
for neglen, suffix, mode, mtype in suffixes:
if filename[neglen:] == ... | def getmoduleinfo(path) | Get the module name, suffix, mode, and module type for a given file. | 3.74101 | 3.200359 | 1.168935 |
filename = getfile(object)
if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
filename = filename[:-4] + '.py'
for suffix, mode, kind in imp.get_suffixes():
if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
# Looks like a binary file. We want to only retu... | def getsourcefile(object) | Return the Python source file an object was defined in, if it exists. | 3.577219 | 3.472527 | 1.030149 |
return os.path.normcase(
os.path.abspath(getsourcefile(object) or getfile(object))) | def getabsfile(object) | 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. | 4.307209 | 4.554081 | 0.945791 |
if ismodule(object):
return object
if isclass(object):
return sys.modules.get(object.__module__)
try:
file = getabsfile(object)
except TypeError:
return None
if modulesbyfile.has_key(file):
return sys.modules[modulesbyfile[file]]
for module in sys.mod... | def getmodule(object) | Return the module an object was defined in, or None if not found. | 1.985756 | 2.013845 | 0.986052 |
try:
file = open(getsourcefile(object))
except (TypeError, IOError):
raise IOError, 'could not get source code'
lines = file.readlines()
file.close()
if ismodule(object):
return lines, 0
if isclass(object):
name = object.__name__
pat = re.compile(r'... | 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 IOError
is raised if th... | 2.231485 | 2.090632 | 1.067373 |
try: lines, lnum = findsource(object)
except IOError: 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 string.strip(lines[start]) in ['', '#']:
... | def getcomments(object) | Get lines of comments immediately preceding an object's source code. | 2.300539 | 2.288925 | 1.005074 |
try:
tokenize.tokenize(ListReader(lines).readline, BlockFinder().tokeneater)
except EndOfBlock, eob:
return lines[:eob.args[0]]
# Fooling the indent/dedent logic implies a one-line definition
return lines[:1] | def getblock(lines) | Extract the block of code at the top of the given list of lines. | 20.46225 | 18.694036 | 1.094587 |
lines, lnum = findsource(object)
if ismodule(object): return lines, 0
else: return getblock(lines[lnum:]), lnum + 1 | 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 ... | 6.200649 | 7.866007 | 0.788284 |
results = []
classes.sort(lambda a, b: cmp(a.__name__, b.__name__))
for c in classes:
results.append((c, c.__bases__))
if children.has_key(c):
results.append(walktree(children[c], children, c))
return results | def walktree(classes, children, parent) | Recursive helper function for getclasstree(). | 2.524449 | 2.451838 | 1.029615 |
children = {}
roots = []
for c in classes:
if c.__bases__:
for parent in c.__bases__:
if not children.has_key(parent):
children[parent] = []
children[parent].append(c)
if unique and parent in classes: break
... | def getclasstree(classes, unique=0) | 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 ... | 2.989315 | 2.876592 | 1.039187 |
if not iscode(co): raise TypeError, 'arg is not a code object'
nargs = co.co_argcount
names = co.co_varnames
args = list(names[:nargs])
step = 0
# The following acrobatics are for anonymous (tuple) arguments.
if not sys.platform.startswith('java'):#Jython doesn't have co_code
... | def getargs(co) | Get information about the arguments accepted by a code object.
Three things are returned: (args, varargs, varkw), where 'args' is
a list of argument names (possibly containing nested lists), and
'varargs' and 'varkw' are the names of the * and ** arguments or None. | 2.713702 | 2.665538 | 1.018069 |
if ismethod(func):
func = func.im_func
if not isfunction(func): raise TypeError, 'arg is not a Python function'
args, varargs, varkw = getargs(func.func_code)
return args, varargs, varkw, func.func_defaults | 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 (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'defaults' is an n-tuple of the ... | 2.816647 | 3.32719 | 0.846554 |
args, varargs, varkw = getargs(frame.f_code)
return args, varargs, varkw, frame.f_locals | 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 (it may contain nested lists).
'varargs' and 'varkw' are the names of the * and ** arguments or None.
'locals' is the locals diction... | 3.238284 | 3.81266 | 0.84935 |
if type(object) in [types.ListType, types.TupleType]:
return join(map(lambda o, c=convert, j=join: strseq(o, c, j), object))
else:
return convert(object) | def strseq(object, convert, join=joinseq) | Recursively walk a sequence, stringifying each element. | 2.47673 | 2.38536 | 1.038305 |
specs = []
if defaults:
firstdefault = len(args) - len(defaults)
for i in range(len(args)):
spec = strseq(args[i], formatarg, join)
if defaults and i >= firstdefault:
spec = spec + formatvalue(defaults[i - firstdefault])
specs.append(spec)
if varargs:
... | def formatargspec(args, varargs=None, varkw=None, defaults=None,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq) | Format an argument spec from the 4 values returned by getargspec.
The first four arguments are (args, varargs, varkw, defaults). The
other four arguments are the corresponding optional formatting functions
that are called to turn names and values into strings. The ninth
argument is an optional functi... | 2.005505 | 2.30841 | 0.868782 |
def convert(name, locals=locals,
formatarg=formatarg, formatvalue=formatvalue):
return formatarg(name) + formatvalue(locals[name])
specs = []
for i in range(len(args)):
specs.append(strseq(args[i], convert, join))
if varargs:
specs.append(formatvarargs(vararg... | def formatargvalues(args, varargs, varkw, locals,
formatarg=str,
formatvarargs=lambda name: '*' + name,
formatvarkw=lambda name: '**' + name,
formatvalue=lambda value: '=' + repr(value),
join=joinseq) | 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 functio... | 2.537031 | 2.715275 | 0.934355 |
# Written by Marc-Andr Lemburg; revised by Jim Hugunin and Fredrik Lundh.
lineno = frame.f_lineno
code = frame.f_code
if hasattr(code, 'co_lnotab'):
table = code.co_lnotab
lineno = code.co_firstlineno
addr = 0
for i in range(0, len(table), 2):
addr = addr... | def getlineno(frame) | Get the line number from a frame object, allowing for optimization. | 5.178144 | 4.853429 | 1.066904 |
framelist = []
while frame:
framelist.append((frame,) + getframeinfo(frame, context))
frame = frame.f_back
return framelist | 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. | 2.962605 | 2.718958 | 1.089611 |
framelist = []
while tb:
framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
tb = tb.tb_next
return framelist | 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. | 2.868107 | 2.903995 | 0.987642 |
type, value, context, children = raw_node
if children or type in gr.number2symbol:
# If there's exactly one child, return that child instead of
# creating a new node.
if len(children) == 1:
return children[0]
return Node(type, children, context=context)
else:... | def convert(gr, raw_node) | Convert raw node information to a Node or Leaf instance.
This is passed to the parser driver which calls it whenever a reduction of a
grammar rule produces a new complete node, so that the tree is build
strictly bottom-up. | 4.741285 | 4.458591 | 1.063404 |
if not patterns:
yield 0, {}
else:
p, rest = patterns[0], patterns[1:]
for c0, r0 in p.generate_matches(nodes):
if not rest:
yield c0, r0
else:
for c1, r1 in generate_matches(rest, nodes[c0:]):
r = {}
... | def generate_matches(patterns, nodes) | Generator yielding matches for a sequence of patterns and nodes.
Args:
patterns: a sequence of patterns
nodes: a sequence of nodes
Yields:
(count, results) tuples where:
count: the entire sequence of patterns matches nodes[:count];
results: dict containing named submatc... | 2.467096 | 2.326223 | 1.060559 |
warnings.warn("set_prefix() is deprecated; use the prefix property",
DeprecationWarning, stacklevel=2)
self.prefix = prefix | def set_prefix(self, prefix) | Set the prefix for the node (see Leaf class).
DEPRECATED; use the prefix property directly. | 4.085094 | 2.930784 | 1.393857 |
assert self.parent is not None, str(self)
assert new is not None
if not isinstance(new, list):
new = [new]
l_children = []
found = False
for ch in self.parent.children:
if ch is self:
assert not found, (self.parent.children... | def replace(self, new) | Replace this node with a new one in the parent. | 2.692118 | 2.574036 | 1.045874 |
node = self
while not isinstance(node, Leaf):
if not node.children:
return
node = node.children[0]
return node.lineno | def get_lineno(self) | Return the line number which generated the invocant node. | 4.306315 | 3.609999 | 1.192885 |
if self.parent:
for i, node in enumerate(self.parent.children):
if node is self:
self.parent.changed()
del self.parent.children[i]
self.parent = None
return i | def remove(self) | Remove the node from the tree. Returns the position of the node in its
parent's children before it was removed. | 3.596591 | 2.673591 | 1.345229 |
if self.parent is None:
return None
# Can't use index(); we need to test by identity
for i, child in enumerate(self.parent.children):
if child is self:
try:
return self.parent.children[i+1]
except IndexError:
... | def next_sibling(self) | The node immediately following the invocant in their parent's children
list. If the invocant does not have a next sibling, it is None | 3.418734 | 3.359616 | 1.017597 |
if self.parent is None:
return None
# Can't use index(); we need to test by identity
for i, child in enumerate(self.parent.children):
if child is self:
if i == 0:
return None
return self.parent.children[i-1] | def prev_sibling(self) | The node immediately preceding the invocant in their parent's children
list. If the invocant does not have a previous sibling, it is None. | 3.375362 | 3.131448 | 1.077892 |
return (self.type, self.children) == (other.type, other.children) | def _eq(self, other) | Compare two nodes for equality. | 5.294288 | 3.650843 | 1.450155 |
return Node(self.type, [ch.clone() for ch in self.children],
fixers_applied=self.fixers_applied) | def clone(self) | Return a cloned (deep) copy of self. | 7.792542 | 7.329696 | 1.063147 |
for child in self.children:
for node in child.post_order():
yield node
yield self | def post_order(self) | Return a post-order iterator for the tree. | 3.314894 | 2.760414 | 1.200868 |
yield self
for child in self.children:
for node in child.pre_order():
yield node | def pre_order(self) | Return a pre-order iterator for the tree. | 3.199984 | 2.620341 | 1.221209 |
child.parent = self
self.children[i].parent = None
self.children[i] = child
self.changed() | def set_child(self, i, child) | Equivalent to 'node.children[i] = child'. This method also sets the
child's parent attribute appropriately. | 3.477352 | 3.766244 | 0.923294 |
child.parent = self
self.children.insert(i, child)
self.changed() | def insert_child(self, i, child) | Equivalent to 'node.children.insert(i, child)'. This method also sets
the child's parent attribute appropriately. | 3.848569 | 3.676749 | 1.046731 |
child.parent = self
self.children.append(child)
self.changed() | def append_child(self, child) | Equivalent to 'node.children.append(child)'. This method also sets the
child's parent attribute appropriately. | 4.236848 | 4.272339 | 0.991693 |
return (self.type, self.value) == (other.type, other.value) | def _eq(self, other) | Compare two nodes for equality. | 4.144339 | 3.163084 | 1.310221 |
return Leaf(self.type, self.value,
(self.prefix, (self.lineno, self.column)),
fixers_applied=self.fixers_applied) | def clone(self) | Return a cloned (deep) copy of self. | 9.40661 | 9.059196 | 1.038349 |
if self.type is not None and node.type != self.type:
return False
if self.content is not None:
r = None
if results is not None:
r = {}
if not self._submatch(node, r):
return False
if r:
r... | def match(self, node, results=None) | Does this pattern exactly match a node?
Returns True if it matches, False if not.
If results is not None, it must be a dict which will be
updated with the nodes matching named subpatterns.
Default implementation for non-wildcard patterns. | 2.782059 | 2.607231 | 1.067055 |
if len(nodes) != 1:
return False
return self.match(nodes[0], results) | def match_seq(self, nodes, results=None) | Does this pattern exactly match a sequence of nodes?
Default implementation for non-wildcard patterns. | 3.862507 | 3.255917 | 1.186304 |
r = {}
if nodes and self.match(nodes[0], r):
yield 1, r | def generate_matches(self, nodes) | Generator yielding all matches for this pattern.
Default implementation for non-wildcard patterns. | 14.079097 | 11.445328 | 1.230117 |
if not isinstance(node, Leaf):
return False
return BasePattern.match(self, node, results) | def match(self, node, results=None) | Override match() to insist on a leaf node. | 6.119067 | 4.552828 | 1.344014 |
if self.wildcards:
for c, r in generate_matches(self.content, node.children):
if c == len(node.children):
if results is not None:
results.update(r)
return True
return False
if len(self.conten... | def _submatch(self, node, results=None) | Match the pattern's content to the node's children.
This assumes the node type matches and self.content is not None.
Returns True if it matches, False if not.
If results is not None, it must be a dict which will be
updated with the nodes matching named subpatterns.
When retur... | 3.221105 | 2.951274 | 1.091428 |
subpattern = None
if (self.content is not None and
len(self.content) == 1 and len(self.content[0]) == 1):
subpattern = self.content[0][0]
if self.min == 1 and self.max == 1:
if self.content is None:
return NodePattern(name=self.name)
... | def optimize(self) | Optimize certain stacked wildcard patterns. | 3.091281 | 2.783264 | 1.110667 |
for c, r in self.generate_matches(nodes):
if c == len(nodes):
if results is not None:
results.update(r)
if self.name:
results[self.name] = list(nodes)
return True
return False | def match_seq(self, nodes, results=None) | Does this pattern exactly match a sequence of nodes? | 4.356943 | 3.813936 | 1.142375 |
if self.content is None:
# Shortcut for special case (see __init__.__doc__)
for count in xrange(self.min, 1 + min(len(nodes), self.max)):
r = {}
if self.name:
r[self.name] = nodes[:count]
yield count, r
... | def generate_matches(self, nodes) | Generator yielding matches for a sequence of nodes.
Args:
nodes: sequence of nodes
Yields:
(count, results) tuples where:
count: the match comprises nodes[:count];
results: dict containing named submatches. | 4.43893 | 4.182638 | 1.061275 |
nodelen = len(nodes)
if 0 >= self.min:
yield 0, {}
results = []
# generate matches that use just one alt from self.content
for alt in self.content:
for c, r in generate_matches(alt, nodes):
yield c, r
results.appen... | def _iterative_matches(self, nodes) | Helper to iteratively yield the matches. | 3.818799 | 3.720777 | 1.026344 |
count = 0
r = {}
done = False
max = len(nodes)
while not done and count < max:
done = True
for leaf in self.content:
if leaf[0].match(nodes[count], r):
count += 1
done = False
... | def _bare_name_matches(self, nodes) | Special optimized matcher for bare_name. | 4.199137 | 4.139251 | 1.014468 |
assert self.content is not None
if count >= self.min:
yield 0, {}
if count < self.max:
for alt in self.content:
for c0, r0 in generate_matches(alt, nodes):
for c1, r1 in self._recursive_matches(nodes[c0:], count+1):
... | def _recursive_matches(self, nodes, count) | Helper to recursively yield the matches. | 3.684361 | 3.516469 | 1.047745 |
r = Reload(mod)
r.apply()
found_change = r.found_change
r = None
pydevd_dont_trace.clear_trace_filter_cache()
return found_change | def xreload(mod) | Reload a module in place, updating classes, methods and functions.
mod: a module object
Returns a boolean indicating whether a change was done. | 8.79747 | 9.777802 | 0.899739 |
try:
notify_info2('Updating: ', oldobj)
if oldobj is newobj:
# Probably something imported
return
if type(oldobj) is not type(newobj):
# Cop-out: if the type changed, give up
notify_error('Type of: %s c... | def _update(self, namespace, name, oldobj, newobj, is_class_namespace=False) | Update oldobj, if possible in place, with newobj.
If oldobj is immutable, this simply returns newobj.
Args:
oldobj: the object to be updated
newobj: the object used as the source for the update | 3.224009 | 3.30199 | 0.976384 |
oldfunc.__doc__ = newfunc.__doc__
oldfunc.__dict__.update(newfunc.__dict__)
try:
newfunc.__code__
attr_name = '__code__'
except AttributeError:
newfunc.func_code
attr_name = 'func_code'
old_code = getattr(oldfunc, attr_na... | def _update_function(self, oldfunc, newfunc) | Update a function object. | 2.64125 | 2.564175 | 1.030059 |
# XXX What if im_func is not a function?
if hasattr(oldmeth, 'im_func') and hasattr(newmeth, 'im_func'):
self._update(None, None, oldmeth.im_func, newmeth.im_func)
elif hasattr(oldmeth, '__func__') and hasattr(newmeth, '__func__'):
self._update(None, None, oldmet... | def _update_method(self, oldmeth, newmeth) | Update a method object. | 2.448504 | 2.409205 | 1.016312 |
olddict = oldclass.__dict__
newdict = newclass.__dict__
oldnames = set(olddict)
newnames = set(newdict)
for name in newnames - oldnames:
setattr(oldclass, name, newdict[name])
notify_info0('Added:', name, 'to', oldclass)
self.found_c... | def _update_class(self, oldclass, newclass) | Update a class object. | 3.519673 | 3.501433 | 1.005209 |
# While we can't modify the classmethod object itself (it has no
# mutable attributes), we *can* extract the underlying function
# (by calling __get__(), which returns a method object) and update
# it in-place. We don't have the class available to pass to
# __get__() bu... | def _update_classmethod(self, oldcm, newcm) | Update a classmethod update. | 10.055888 | 9.555309 | 1.052388 |
# While we can't modify the staticmethod object itself (it has no
# mutable attributes), we *can* extract the underlying function
# (by calling __get__(), which returns it) and update it in-place.
# We don't have the class available to pass to __get__() but any
# object ... | def _update_staticmethod(self, oldsm, newsm) | Update a staticmethod update. | 10.213532 | 9.87987 | 1.033772 |
try:
if '__pypy__' in sys.builtin_module_names:
import __pypy__ # @UnresolvedImport
save_locals = __pypy__.locals_to_fast
except:
pass
else:
if '__pypy__' in sys.builtin_module_names:
def save_locals_pypy_impl(frame):
save_loc... | def make_save_locals_impl() | Factory for the 'save_locals_impl' method. This may seem like a complicated pattern but it is essential that the method is created at
module load time. Inner imports after module load time would cause an occasional debugger deadlock due to the importer lock and debugger
lock being taken in different order in d... | 2.354268 | 2.407656 | 0.977826 |
if not isinstance(target, list):
target = [target]
if not isinstance(source, list):
source.prefix = u" "
source = [source]
return Node(syms.atom,
target + [Leaf(token.EQUAL, u"=", prefix=u" ")] + source) | def Assign(target, source) | Build an assignment statement | 5.475719 | 4.834962 | 1.132526 |
node = Node(syms.trailer, [lparen.clone(), rparen.clone()])
if args:
node.insert_child(1, Node(syms.arglist, args))
return node | def ArgList(args, lparen=LParen(), rparen=RParen()) | A parenthesised argument list, used by Call() | 4.088973 | 4.218548 | 0.969285 |
node = Node(syms.power, [func_name, ArgList(args)])
if prefix is not None:
node.prefix = prefix
return node | def Call(func_name, args=None, prefix=None) | A function call | 5.038843 | 4.999358 | 1.007898 |
return Node(syms.trailer, [Leaf(token.LBRACE, u"["),
index_node,
Leaf(token.RBRACE, u"]")]) | def Subscript(index_node) | A numeric or string subscript | 5.238555 | 5.725035 | 0.915026 |
xp.prefix = u""
fp.prefix = u" "
it.prefix = u" "
for_leaf = Leaf(token.NAME, u"for")
for_leaf.prefix = u" "
in_leaf = Leaf(token.NAME, u"in")
in_leaf.prefix = u" "
inner_args = [for_leaf, fp, in_leaf, it]
if test:
test.prefix = u" "
if_leaf = Leaf(token.NAME, u"... | def ListComp(xp, fp, it, test=None) | A list comprehension of the form [xp for fp in it if test].
If test is None, the "if test" part is omitted. | 2.803458 | 2.770657 | 1.011839 |
# XXX: May not handle dotted imports properly (eg, package_name='foo.bar')
#assert package_name == '.' or '.' not in package_name, "FromImport has "\
# "not been tested with dotted package names -- use at your own "\
# "peril!"
for leaf in name_leafs:
# Pull the leaves out ... | def FromImport(package_name, name_leafs) | Return an import statement in the form:
from package import name_leafs | 6.193923 | 6.06219 | 1.02173 |
if isinstance(node, Node) and node.children == [LParen(), RParen()]:
return True
return (isinstance(node, Node)
and len(node.children) == 3
and isinstance(node.children[0], Leaf)
and isinstance(node.children[1], Node)
and isinstance(node.children[2], ... | def is_tuple(node) | Does the node represent a tuple literal? | 2.328756 | 2.193276 | 1.06177 |
return (isinstance(node, Node)
and len(node.children) > 1
and isinstance(node.children[0], Leaf)
and isinstance(node.children[-1], Leaf)
and node.children[0].value == u"["
and node.children[-1].value == u"]") | def is_list(node) | Does the node represent a list literal? | 2.334637 | 2.113782 | 1.104483 |
next = getattr(obj, attr)
while next:
yield next
next = getattr(next, attr) | def attr_chain(obj, attr) | Follow an attribute chain.
If you have a chain of objects where a.foo -> b, b.foo-> c, etc,
use this to iterate over all objects in the chain. Iteration is
terminated by getattr(x, attr) is None.
Args:
obj: the starting object
attr: the name of the chaining attribute
Yields:
... | 3.056906 | 4.4274 | 0.690452 |
global p0, p1, p2, pats_built
if not pats_built:
p0 = patcomp.compile_pattern(p0)
p1 = patcomp.compile_pattern(p1)
p2 = patcomp.compile_pattern(p2)
pats_built = True
patterns = [p0, p1, p2]
for pattern, parent in zip(patterns, attr_chain(node, "parent")):
res... | def in_special_context(node) | Returns true if node is in an environment where all that is required
of it is being iterable (ie, it doesn't matter if it returns a list
or an iterator).
See test_map_nochange in test_fixers.py for some examples and tests. | 3.793123 | 3.831302 | 0.990035 |
prev = node.prev_sibling
if prev is not None and prev.type == token.DOT:
# Attribute lookup.
return False
parent = node.parent
if parent.type in (syms.funcdef, syms.classdef):
return False
if parent.type == syms.expr_stmt and parent.children[0] is node:
# Assignm... | def is_probably_builtin(node) | Check that something isn't an attribute or function name etc. | 3.100067 | 2.865401 | 1.081896 |
while node is not None:
if node.type == syms.suite and len(node.children) > 2:
indent = node.children[1]
if indent.type == token.INDENT:
return indent.value
node = node.parent
return u"" | def find_indentation(node) | Find the indentation of *node*. | 2.982497 | 3.095054 | 0.963633 |
# Scamper up to the top level namespace
while node.type != syms.file_input:
node = node.parent
if not node:
raise ValueError("root found before file_input node was found.")
return node | def find_root(node) | Find the top level namespace. | 9.546392 | 7.813827 | 1.221731 |
binding = find_binding(name, find_root(node), package)
return bool(binding) | def does_tree_import(package, name, node) | Returns true if name is imported from package at the
top level of the tree which node belongs to.
To cover the case of an import like 'import foo', use
None for the package and 'foo' for the name. | 10.221798 | 12.181527 | 0.839123 |
def is_import_stmt(node):
return (node.type == syms.simple_stmt and node.children and
is_import(node.children[0]))
root = find_root(node)
if does_tree_import(package, name, root):
return
# figure out where to insert the new import. First try to find
# the fir... | def touch_import(package, name, node) | Works like `does_tree_import` but adds an import statement
if it was not imported. | 3.030685 | 2.963986 | 1.022503 |
for child in node.children:
ret = None
if child.type == syms.for_stmt:
if _find(name, child.children[1]):
return child
n = find_binding(name, make_suite(child.children[-1]), package)
if n: ret = n
elif child.type in (syms.if_stmt, syms... | def find_binding(name, node, package=None) | Returns the node which binds variable name, otherwise None.
If optional argument package is supplied, only imports will
be returned.
See test cases for examples. | 2.289969 | 2.346644 | 0.975849 |
if node.type == syms.import_name and not package:
imp = node.children[1]
if imp.type == syms.dotted_as_names:
for child in imp.children:
if child.type == syms.dotted_as_name:
if child.children[2].value == name:
return node... | def _is_import_binding(node, name, package=None) | Will reuturn node if node will import name, or node
will import * from package. None is returned otherwise.
See test cases for examples. | 2.644448 | 2.605026 | 1.015133 |
if InteractiveConsoleCache.thread_id == thread_id and InteractiveConsoleCache.frame_id == frame_id:
return InteractiveConsoleCache.interactive_console_instance
InteractiveConsoleCache.interactive_console_instance = DebugConsole()
InteractiveConsoleCache.thread_id = thread_id
InteractiveCon... | def get_interactive_console(thread_id, frame_id, frame, console_message) | returns the global interactive console.
interactive console should have been initialized by this time
:rtype: DebugConsole | 2.865875 | 2.820008 | 1.016265 |
console_message = ConsoleMessage()
interpreter = get_interactive_console(thread_id, frame_id, frame, console_message)
more, output_messages, error_messages = interpreter.push(line, frame, buffer_output)
console_message.update_more(more)
for message in output_messages:
console_message.... | def execute_console_command(frame, thread_id, frame_id, line, buffer_output=True) | fetch an interactive console instance from the cache and
push the received command to the console.
create and return an instance of console_message | 3.220143 | 2.983677 | 1.079253 |
for m in message.split("\n"):
if m.strip():
self.console_messages.append((message_type, m)) | def add_console_message(self, message_type, message) | add messages in the console_messages list | 3.652692 | 3.072845 | 1.1887 |
makeValid = make_valid_xml_value
xml = '<xml><more>%s</more>' % (self.more)
for message_type, message in self.console_messages:
xml += '<%s message="%s"></%s>' % (message_type, makeValid(message), message_type)
xml += '</xml>'
return xml | def to_xml(self) | Create an XML for console message_list, error and more (true/false)
<xml>
<message_list>console message_list</message_list>
<error>console error</error>
<more>true/false</more>
</xml> | 5.78155 | 4.706793 | 1.228342 |
self.__buffer_output = buffer_output
more = False
if buffer_output:
original_stdout = sys.stdout
original_stderr = sys.stderr
try:
try:
self.frame = frame
if buffer_output:
out = sys.stdout =... | def push(self, line, frame, buffer_output=True) | Change built-in stdout and stderr methods by the
new custom StdMessage.
execute the InteractiveConsole.push.
Change the stdout and stderr back be the original built-ins
:param buffer_output: if False won't redirect the output.
Return boolean (True if more input is required else... | 3.041019 | 2.98272 | 1.019546 |
try:
Exec(code, self.frame.f_globals, self.frame.f_locals)
pydevd_save_locals.save_locals(self.frame)
except SystemExit:
raise
except:
# In case sys.excepthook called, use original excepthook #PyDev-877: Debug console freezes with Python 3... | def runcode(self, code) | Execute a code object.
When an exception occurs, self.showtraceback() is called to
display a traceback. All exceptions are caught except
SystemExit, which is reraised.
A note about KeyboardInterrupt: this exception may occur
elsewhere in this code, and may not always be caught... | 5.514434 | 5.630963 | 0.979306 |
'Instance a new structure from a Python dictionary.'
fsa = dict(fsa)
s = cls()
for key in cls._integer_members:
setattr(s, key, fsa.get(key))
ra = fsa.get('RegisterArea', None)
if ra is not None:
for index in compat.xrange(0, SIZE_OF_80387_REGISTER... | def from_dict(cls, fsa) | Instance a new structure from a Python dictionary. | 6.085057 | 5.121358 | 1.188172 |
'Convert a structure into a Python dictionary.'
fsa = dict()
for key in self._integer_members:
fsa[key] = getattr(self, key)
ra = [ self.RegisterArea[index] for index in compat.xrange(0, SIZE_OF_80387_REGISTERS) ]
ra = tuple(ra)
fsa['RegisterArea'] = ra
... | def to_dict(self) | Convert a structure into a Python dictionary. | 8.529422 | 7.730556 | 1.103339 |
'Instance a new structure from a Python dictionary.'
ctx = Context(ctx)
s = cls()
ContextFlags = ctx['ContextFlags']
setattr(s, 'ContextFlags', ContextFlags)
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for key in s._ctx_debug:
... | def from_dict(cls, ctx) | Instance a new structure from a Python dictionary. | 2.596631 | 2.419223 | 1.073333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.