repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixer_util.py | is_list | def is_list(node):
"""Does the node represent a list literal?"""
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"]") | python | def is_list(node):
"""Does the node represent a list literal?"""
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",
")",
":",
"return",
"(",
"isinstance",
"(",
"node",
",",
"Node",
")",
"and",
"len",
"(",
"node",
".",
"children",
")",
">",
"1",
"and",
"isinstance",
"(",
"node",
".",
"children",
"[",
"0",
"]",
",",
"Leaf",
")",
"a... | Does the node represent a list literal? | [
"Does",
"the",
"node",
"represent",
"a",
"list",
"literal?"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L149-L156 | train | 209,800 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixer_util.py | attr_chain | 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:
Each successive object in the chain.
"""
next = getattr(obj, attr)
while next:
yield next
next = getattr(next, attr) | python | 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:
Each successive object in the chain.
"""
next = getattr(obj, attr)
while next:
yield next
next = getattr(next, attr) | [
"def",
"attr_chain",
"(",
"obj",
",",
"attr",
")",
":",
"next",
"=",
"getattr",
"(",
"obj",
",",
"attr",
")",
"while",
"next",
":",
"yield",
"next",
"next",
"=",
"getattr",
"(",
"next",
",",
"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:
Each successive object in the chain. | [
"Follow",
"an",
"attribute",
"chain",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L170-L187 | train | 209,801 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixer_util.py | is_probably_builtin | def is_probably_builtin(node):
"""
Check that something isn't an attribute or function name etc.
"""
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:
# Assignment.
return False
if parent.type == syms.parameters or \
(parent.type == syms.typedargslist and (
(prev is not None and prev.type == token.COMMA) or
parent.children[0] is node
)):
# The name of an argument.
return False
return True | python | def is_probably_builtin(node):
"""
Check that something isn't an attribute or function name etc.
"""
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:
# Assignment.
return False
if parent.type == syms.parameters or \
(parent.type == syms.typedargslist and (
(prev is not None and prev.type == token.COMMA) or
parent.children[0] is node
)):
# The name of an argument.
return False
return True | [
"def",
"is_probably_builtin",
"(",
"node",
")",
":",
"prev",
"=",
"node",
".",
"prev_sibling",
"if",
"prev",
"is",
"not",
"None",
"and",
"prev",
".",
"type",
"==",
"token",
".",
"DOT",
":",
"# Attribute lookup.",
"return",
"False",
"parent",
"=",
"node",
... | Check that something isn't an attribute or function name etc. | [
"Check",
"that",
"something",
"isn",
"t",
"an",
"attribute",
"or",
"function",
"name",
"etc",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L227-L248 | train | 209,802 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixer_util.py | find_root | def find_root(node):
"""Find the top level namespace."""
# 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 | python | def find_root(node):
"""Find the top level namespace."""
# 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",
")",
":",
"# Scamper up to the top level namespace",
"while",
"node",
".",
"type",
"!=",
"syms",
".",
"file_input",
":",
"node",
"=",
"node",
".",
"parent",
"if",
"not",
"node",
":",
"raise",
"ValueError",
"(",
"\"root found be... | Find the top level namespace. | [
"Find",
"the",
"top",
"level",
"namespace",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L273-L280 | train | 209,803 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixer_util.py | does_tree_import | 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. """
binding = find_binding(name, find_root(node), package)
return bool(binding) | python | 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. """
binding = find_binding(name, find_root(node), package)
return bool(binding) | [
"def",
"does_tree_import",
"(",
"package",
",",
"name",
",",
"node",
")",
":",
"binding",
"=",
"find_binding",
"(",
"name",
",",
"find_root",
"(",
"node",
")",
",",
"package",
")",
"return",
"bool",
"(",
"binding",
")"
] | 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. | [
"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",
"... | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L282-L288 | train | 209,804 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixer_util.py | touch_import | def touch_import(package, name, node):
""" Works like `does_tree_import` but adds an import statement
if it was not imported. """
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 first import and then skip to the last one.
insert_pos = offset = 0
for idx, node in enumerate(root.children):
if not is_import_stmt(node):
continue
for offset, node2 in enumerate(root.children[idx:]):
if not is_import_stmt(node2):
break
insert_pos = idx + offset
break
# if there are no imports where we can insert, find the docstring.
# if that also fails, we stick to the beginning of the file
if insert_pos == 0:
for idx, node in enumerate(root.children):
if (node.type == syms.simple_stmt and node.children and
node.children[0].type == token.STRING):
insert_pos = idx + 1
break
if package is None:
import_ = Node(syms.import_name, [
Leaf(token.NAME, u"import"),
Leaf(token.NAME, name, prefix=u" ")
])
else:
import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")])
children = [import_, Newline()]
root.insert_child(insert_pos, Node(syms.simple_stmt, children)) | python | def touch_import(package, name, node):
""" Works like `does_tree_import` but adds an import statement
if it was not imported. """
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 first import and then skip to the last one.
insert_pos = offset = 0
for idx, node in enumerate(root.children):
if not is_import_stmt(node):
continue
for offset, node2 in enumerate(root.children[idx:]):
if not is_import_stmt(node2):
break
insert_pos = idx + offset
break
# if there are no imports where we can insert, find the docstring.
# if that also fails, we stick to the beginning of the file
if insert_pos == 0:
for idx, node in enumerate(root.children):
if (node.type == syms.simple_stmt and node.children and
node.children[0].type == token.STRING):
insert_pos = idx + 1
break
if package is None:
import_ = Node(syms.import_name, [
Leaf(token.NAME, u"import"),
Leaf(token.NAME, name, prefix=u" ")
])
else:
import_ = FromImport(package, [Leaf(token.NAME, name, prefix=u" ")])
children = [import_, Newline()]
root.insert_child(insert_pos, Node(syms.simple_stmt, children)) | [
"def",
"touch_import",
"(",
"package",
",",
"name",
",",
"node",
")",
":",
"def",
"is_import_stmt",
"(",
"node",
")",
":",
"return",
"(",
"node",
".",
"type",
"==",
"syms",
".",
"simple_stmt",
"and",
"node",
".",
"children",
"and",
"is_import",
"(",
"n... | Works like `does_tree_import` but adds an import statement
if it was not imported. | [
"Works",
"like",
"does_tree_import",
"but",
"adds",
"an",
"import",
"statement",
"if",
"it",
"was",
"not",
"imported",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L294-L336 | train | 209,805 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixer_util.py | find_binding | 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."""
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.while_stmt):
n = find_binding(name, make_suite(child.children[-1]), package)
if n: ret = n
elif child.type == syms.try_stmt:
n = find_binding(name, make_suite(child.children[2]), package)
if n:
ret = n
else:
for i, kid in enumerate(child.children[3:]):
if kid.type == token.COLON and kid.value == ":":
# i+3 is the colon, i+4 is the suite
n = find_binding(name, make_suite(child.children[i+4]), package)
if n: ret = n
elif child.type in _def_syms and child.children[1].value == name:
ret = child
elif _is_import_binding(child, name, package):
ret = child
elif child.type == syms.simple_stmt:
ret = find_binding(name, child, package)
elif child.type == syms.expr_stmt:
if _find(name, child.children[0]):
ret = child
if ret:
if not package:
return ret
if is_import(ret):
return ret
return None | python | 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."""
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.while_stmt):
n = find_binding(name, make_suite(child.children[-1]), package)
if n: ret = n
elif child.type == syms.try_stmt:
n = find_binding(name, make_suite(child.children[2]), package)
if n:
ret = n
else:
for i, kid in enumerate(child.children[3:]):
if kid.type == token.COLON and kid.value == ":":
# i+3 is the colon, i+4 is the suite
n = find_binding(name, make_suite(child.children[i+4]), package)
if n: ret = n
elif child.type in _def_syms and child.children[1].value == name:
ret = child
elif _is_import_binding(child, name, package):
ret = child
elif child.type == syms.simple_stmt:
ret = find_binding(name, child, package)
elif child.type == syms.expr_stmt:
if _find(name, child.children[0]):
ret = child
if ret:
if not package:
return ret
if is_import(ret):
return ret
return None | [
"def",
"find_binding",
"(",
"name",
",",
"node",
",",
"package",
"=",
"None",
")",
":",
"for",
"child",
"in",
"node",
".",
"children",
":",
"ret",
"=",
"None",
"if",
"child",
".",
"type",
"==",
"syms",
".",
"for_stmt",
":",
"if",
"_find",
"(",
"nam... | 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. | [
"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",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixer_util.py#L340-L380 | train | 209,806 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_console.py | execute_console_command | 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
"""
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.add_console_message(CONSOLE_OUTPUT, message)
for message in error_messages:
console_message.add_console_message(CONSOLE_ERROR, message)
return console_message | python | 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
"""
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.add_console_message(CONSOLE_OUTPUT, message)
for message in error_messages:
console_message.add_console_message(CONSOLE_ERROR, message)
return console_message | [
"def",
"execute_console_command",
"(",
"frame",
",",
"thread_id",
",",
"frame_id",
",",
"line",
",",
"buffer_output",
"=",
"True",
")",
":",
"console_message",
"=",
"ConsoleMessage",
"(",
")",
"interpreter",
"=",
"get_interactive_console",
"(",
"thread_id",
",",
... | fetch an interactive console instance from the cache and
push the received command to the console.
create and return an instance of console_message | [
"fetch",
"an",
"interactive",
"console",
"instance",
"from",
"the",
"cache",
"and",
"push",
"the",
"received",
"command",
"to",
"the",
"console",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_console.py#L213-L231 | train | 209,807 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_console.py | ConsoleMessage.add_console_message | def add_console_message(self, message_type, message):
"""add messages in the console_messages list
"""
for m in message.split("\n"):
if m.strip():
self.console_messages.append((message_type, m)) | python | def add_console_message(self, message_type, message):
"""add messages in the console_messages list
"""
for m in message.split("\n"):
if m.strip():
self.console_messages.append((message_type, m)) | [
"def",
"add_console_message",
"(",
"self",
",",
"message_type",
",",
"message",
")",
":",
"for",
"m",
"in",
"message",
".",
"split",
"(",
"\"\\n\"",
")",
":",
"if",
"m",
".",
"strip",
"(",
")",
":",
"self",
".",
"console_messages",
".",
"append",
"(",
... | add messages in the console_messages list | [
"add",
"messages",
"in",
"the",
"console_messages",
"list"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_console.py#L31-L36 | train | 209,808 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_console.py | DebugConsole.push | 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 False),
output_messages and input_messages
"""
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 = IOBuf()
err = sys.stderr = IOBuf()
more = self.add_exec(line)
except Exception:
exc = get_exception_traceback_str()
if buffer_output:
err.buflist.append("Internal Error: %s" % (exc,))
else:
sys.stderr.write("Internal Error: %s\n" % (exc,))
finally:
#Remove frame references.
self.frame = None
frame = None
if buffer_output:
sys.stdout = original_stdout
sys.stderr = original_stderr
if buffer_output:
return more, out.buflist, err.buflist
else:
return more, [], [] | python | 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 False),
output_messages and input_messages
"""
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 = IOBuf()
err = sys.stderr = IOBuf()
more = self.add_exec(line)
except Exception:
exc = get_exception_traceback_str()
if buffer_output:
err.buflist.append("Internal Error: %s" % (exc,))
else:
sys.stderr.write("Internal Error: %s\n" % (exc,))
finally:
#Remove frame references.
self.frame = None
frame = None
if buffer_output:
sys.stdout = original_stdout
sys.stderr = original_stderr
if buffer_output:
return more, out.buflist, err.buflist
else:
return more, [], [] | [
"def",
"push",
"(",
"self",
",",
"line",
",",
"frame",
",",
"buffer_output",
"=",
"True",
")",
":",
"self",
".",
"__buffer_output",
"=",
"buffer_output",
"more",
"=",
"False",
"if",
"buffer_output",
":",
"original_stdout",
"=",
"sys",
".",
"stdout",
"origi... | 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 False),
output_messages and input_messages | [
"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... | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_console.py#L94-L134 | train | 209,809 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/win32/context_i386.py | CONTEXT.to_dict | def to_dict(self):
'Convert a structure into a Python native type.'
ctx = Context()
ContextFlags = self.ContextFlags
ctx['ContextFlags'] = ContextFlags
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for key in self._ctx_debug:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT:
ctx['FloatSave'] = self.FloatSave.to_dict()
if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
for key in self._ctx_segs:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
for key in self._ctx_int:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
for key in self._ctx_ctrl:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS:
er = [ self.ExtendedRegisters[index] for index in compat.xrange(0, MAXIMUM_SUPPORTED_EXTENSION) ]
er = tuple(er)
ctx['ExtendedRegisters'] = er
return ctx | python | def to_dict(self):
'Convert a structure into a Python native type.'
ctx = Context()
ContextFlags = self.ContextFlags
ctx['ContextFlags'] = ContextFlags
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for key in self._ctx_debug:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_FLOATING_POINT) == CONTEXT_FLOATING_POINT:
ctx['FloatSave'] = self.FloatSave.to_dict()
if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
for key in self._ctx_segs:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
for key in self._ctx_int:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
for key in self._ctx_ctrl:
ctx[key] = getattr(self, key)
if (ContextFlags & CONTEXT_EXTENDED_REGISTERS) == CONTEXT_EXTENDED_REGISTERS:
er = [ self.ExtendedRegisters[index] for index in compat.xrange(0, MAXIMUM_SUPPORTED_EXTENSION) ]
er = tuple(er)
ctx['ExtendedRegisters'] = er
return ctx | [
"def",
"to_dict",
"(",
"self",
")",
":",
"ctx",
"=",
"Context",
"(",
")",
"ContextFlags",
"=",
"self",
".",
"ContextFlags",
"ctx",
"[",
"'ContextFlags'",
"]",
"=",
"ContextFlags",
"if",
"(",
"ContextFlags",
"&",
"CONTEXT_DEBUG_REGISTERS",
")",
"==",
"CONTEXT... | Convert a structure into a Python native type. | [
"Convert",
"a",
"structure",
"into",
"a",
"Python",
"native",
"type",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/win32/context_i386.py#L271-L294 | train | 209,810 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/pgen2/tokenize.py | _get_normal_name | def _get_normal_name(orig_enc):
"""Imitates get_normal_name in tokenizer.c."""
# Only care about the first 12 characters.
enc = orig_enc[:12].lower().replace("_", "-")
if enc == "utf-8" or enc.startswith("utf-8-"):
return "utf-8"
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
return "iso-8859-1"
return orig_enc | python | def _get_normal_name(orig_enc):
"""Imitates get_normal_name in tokenizer.c."""
# Only care about the first 12 characters.
enc = orig_enc[:12].lower().replace("_", "-")
if enc == "utf-8" or enc.startswith("utf-8-"):
return "utf-8"
if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \
enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")):
return "iso-8859-1"
return orig_enc | [
"def",
"_get_normal_name",
"(",
"orig_enc",
")",
":",
"# Only care about the first 12 characters.",
"enc",
"=",
"orig_enc",
"[",
":",
"12",
"]",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"\"_\"",
",",
"\"-\"",
")",
"if",
"enc",
"==",
"\"utf-8\"",
"or",
... | Imitates get_normal_name in tokenizer.c. | [
"Imitates",
"get_normal_name",
"in",
"tokenizer",
".",
"c",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pgen2/tokenize.py#L241-L250 | train | 209,811 |
fabioz/PyDev.Debugger | third_party/isort_container/isort/hooks.py | get_lines | def get_lines(command):
"""
Run a command and return lines of output
:param str command: the command to run
:returns: list of whitespace-stripped lines output by command
"""
stdout = get_output(command)
return [line.strip().decode('utf-8') for line in stdout.splitlines()] | python | def get_lines(command):
"""
Run a command and return lines of output
:param str command: the command to run
:returns: list of whitespace-stripped lines output by command
"""
stdout = get_output(command)
return [line.strip().decode('utf-8') for line in stdout.splitlines()] | [
"def",
"get_lines",
"(",
"command",
")",
":",
"stdout",
"=",
"get_output",
"(",
"command",
")",
"return",
"[",
"line",
".",
"strip",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"line",
"in",
"stdout",
".",
"splitlines",
"(",
")",
"]"
] | Run a command and return lines of output
:param str command: the command to run
:returns: list of whitespace-stripped lines output by command | [
"Run",
"a",
"command",
"and",
"return",
"lines",
"of",
"output"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/isort_container/isort/hooks.py#L40-L48 | train | 209,812 |
fabioz/PyDev.Debugger | third_party/isort_container/isort/hooks.py | git_hook | def git_hook(strict=False):
"""
Git pre-commit hook to check staged files for isort errors
:param bool strict - if True, return number of errors on exit,
causing the hook to fail. If False, return zero so it will
just act as a warning.
:return number of errors if in strict mode, 0 otherwise.
"""
# Get list of files modified and staged
diff_cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD"
files_modified = get_lines(diff_cmd)
errors = 0
for filename in files_modified:
if filename.endswith('.py'):
# Get the staged contents of the file
staged_cmd = "git show :%s" % filename
staged_contents = get_output(staged_cmd)
sort = SortImports(
file_path=filename,
file_contents=staged_contents.decode(),
check=True
)
if sort.incorrectly_sorted:
errors += 1
return errors if strict else 0 | python | def git_hook(strict=False):
"""
Git pre-commit hook to check staged files for isort errors
:param bool strict - if True, return number of errors on exit,
causing the hook to fail. If False, return zero so it will
just act as a warning.
:return number of errors if in strict mode, 0 otherwise.
"""
# Get list of files modified and staged
diff_cmd = "git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD"
files_modified = get_lines(diff_cmd)
errors = 0
for filename in files_modified:
if filename.endswith('.py'):
# Get the staged contents of the file
staged_cmd = "git show :%s" % filename
staged_contents = get_output(staged_cmd)
sort = SortImports(
file_path=filename,
file_contents=staged_contents.decode(),
check=True
)
if sort.incorrectly_sorted:
errors += 1
return errors if strict else 0 | [
"def",
"git_hook",
"(",
"strict",
"=",
"False",
")",
":",
"# Get list of files modified and staged",
"diff_cmd",
"=",
"\"git diff-index --cached --name-only --diff-filter=ACMRTUXB HEAD\"",
"files_modified",
"=",
"get_lines",
"(",
"diff_cmd",
")",
"errors",
"=",
"0",
"for",
... | Git pre-commit hook to check staged files for isort errors
:param bool strict - if True, return number of errors on exit,
causing the hook to fail. If False, return zero so it will
just act as a warning.
:return number of errors if in strict mode, 0 otherwise. | [
"Git",
"pre",
"-",
"commit",
"hook",
"to",
"check",
"staged",
"files",
"for",
"isort",
"errors"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/isort_container/isort/hooks.py#L51-L82 | train | 209,813 |
fabioz/PyDev.Debugger | _pydev_imps/_pydev_BaseHTTPServer.py | BaseHTTPRequestHandler.send_header | def send_header(self, keyword, value):
"""Send a MIME header."""
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s: %s\r\n" % (keyword, value))
if keyword.lower() == 'connection':
if value.lower() == 'close':
self.close_connection = 1
elif value.lower() == 'keep-alive':
self.close_connection = 0 | python | def send_header(self, keyword, value):
"""Send a MIME header."""
if self.request_version != 'HTTP/0.9':
self.wfile.write("%s: %s\r\n" % (keyword, value))
if keyword.lower() == 'connection':
if value.lower() == 'close':
self.close_connection = 1
elif value.lower() == 'keep-alive':
self.close_connection = 0 | [
"def",
"send_header",
"(",
"self",
",",
"keyword",
",",
"value",
")",
":",
"if",
"self",
".",
"request_version",
"!=",
"'HTTP/0.9'",
":",
"self",
".",
"wfile",
".",
"write",
"(",
"\"%s: %s\\r\\n\"",
"%",
"(",
"keyword",
",",
"value",
")",
")",
"if",
"k... | Send a MIME header. | [
"Send",
"a",
"MIME",
"header",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_BaseHTTPServer.py#L399-L408 | train | 209,814 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/main.py | diff_texts | def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
lineterm="") | python | def diff_texts(a, b, filename):
"""Return a unified diff of two strings."""
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
lineterm="") | [
"def",
"diff_texts",
"(",
"a",
",",
"b",
",",
"filename",
")",
":",
"a",
"=",
"a",
".",
"splitlines",
"(",
")",
"b",
"=",
"b",
".",
"splitlines",
"(",
")",
"return",
"difflib",
".",
"unified_diff",
"(",
"a",
",",
"b",
",",
"filename",
",",
"filen... | Return a unified diff of two strings. | [
"Return",
"a",
"unified",
"diff",
"of",
"two",
"strings",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/main.py#L17-L23 | train | 209,815 |
fabioz/PyDev.Debugger | pydev_ipython/inputhookqt5.py | create_inputhook_qt5 | def create_inputhook_qt5(mgr, app=None):
"""Create an input hook for running the Qt5 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Returns
-------
A pair consisting of a Qt Application (either the one given or the
one found or created) and a inputhook.
Notes
-----
We use a custom input hook instead of PyQt5's default one, as it
interacts better with the readline packages (issue #481).
The inputhook function works in tandem with a 'pre_prompt_hook'
which automatically restores the hook as an inputhook in case the
latter has been temporarily disabled after having intercepted a
KeyboardInterrupt.
"""
if app is None:
app = QtCore.QCoreApplication.instance()
if app is None:
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([" "])
# Re-use previously created inputhook if any
ip = InteractiveShell.instance()
if hasattr(ip, '_inputhook_qt5'):
return app, ip._inputhook_qt5
# Otherwise create the inputhook_qt5/preprompthook_qt5 pair of
# hooks (they both share the got_kbdint flag)
def inputhook_qt5():
"""PyOS_InputHook python hook for Qt5.
Process pending Qt events and if there's no pending keyboard
input, spend a short slice of time (50ms) running the Qt event
loop.
As a Python ctypes callback can't raise an exception, we catch
the KeyboardInterrupt and temporarily deactivate the hook,
which will let a *second* CTRL+C be processed normally and go
back to a clean prompt line.
"""
try:
allow_CTRL_C()
app = QtCore.QCoreApplication.instance()
if not app: # shouldn't happen, but safer if it happens anyway...
return 0
app.processEvents(QtCore.QEventLoop.AllEvents, 300)
if not stdin_ready():
# Generally a program would run QCoreApplication::exec()
# from main() to enter and process the Qt event loop until
# quit() or exit() is called and the program terminates.
#
# For our input hook integration, we need to repeatedly
# enter and process the Qt event loop for only a short
# amount of time (say 50ms) to ensure that Python stays
# responsive to other user inputs.
#
# A naive approach would be to repeatedly call
# QCoreApplication::exec(), using a timer to quit after a
# short amount of time. Unfortunately, QCoreApplication
# emits an aboutToQuit signal before stopping, which has
# the undesirable effect of closing all modal windows.
#
# To work around this problem, we instead create a
# QEventLoop and call QEventLoop::exec(). Other than
# setting some state variables which do not seem to be
# used anywhere, the only thing QCoreApplication adds is
# the aboutToQuit signal which is precisely what we are
# trying to avoid.
timer = QtCore.QTimer()
event_loop = QtCore.QEventLoop()
timer.timeout.connect(event_loop.quit)
while not stdin_ready():
timer.start(50)
event_loop.exec_()
timer.stop()
except KeyboardInterrupt:
global got_kbdint, sigint_timer
ignore_CTRL_C()
got_kbdint = True
mgr.clear_inputhook()
# This generates a second SIGINT so the user doesn't have to
# press CTRL+C twice to get a clean prompt.
#
# Since we can't catch the resulting KeyboardInterrupt here
# (because this is a ctypes callback), we use a timer to
# generate the SIGINT after we leave this callback.
#
# Unfortunately this doesn't work on Windows (SIGINT kills
# Python and CTRL_C_EVENT doesn't work).
if(os.name == 'posix'):
pid = os.getpid()
if(not sigint_timer):
sigint_timer = threading.Timer(.01, os.kill,
args=[pid, signal.SIGINT] )
sigint_timer.start()
else:
print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
except: # NO exceptions are allowed to escape from a ctypes callback
ignore_CTRL_C()
from traceback import print_exc
print_exc()
print("Got exception from inputhook_qt5, unregistering.")
mgr.clear_inputhook()
finally:
allow_CTRL_C()
return 0
def preprompthook_qt5(ishell):
"""'pre_prompt_hook' used to restore the Qt5 input hook
(in case the latter was temporarily deactivated after a
CTRL+C)
"""
global got_kbdint, sigint_timer
if(sigint_timer):
sigint_timer.cancel()
sigint_timer = None
if got_kbdint:
mgr.set_inputhook(inputhook_qt5)
got_kbdint = False
ip._inputhook_qt5 = inputhook_qt5
ip.set_hook('pre_prompt_hook', preprompthook_qt5)
return app, inputhook_qt5 | python | def create_inputhook_qt5(mgr, app=None):
"""Create an input hook for running the Qt5 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Returns
-------
A pair consisting of a Qt Application (either the one given or the
one found or created) and a inputhook.
Notes
-----
We use a custom input hook instead of PyQt5's default one, as it
interacts better with the readline packages (issue #481).
The inputhook function works in tandem with a 'pre_prompt_hook'
which automatically restores the hook as an inputhook in case the
latter has been temporarily disabled after having intercepted a
KeyboardInterrupt.
"""
if app is None:
app = QtCore.QCoreApplication.instance()
if app is None:
from PyQt5 import QtWidgets
app = QtWidgets.QApplication([" "])
# Re-use previously created inputhook if any
ip = InteractiveShell.instance()
if hasattr(ip, '_inputhook_qt5'):
return app, ip._inputhook_qt5
# Otherwise create the inputhook_qt5/preprompthook_qt5 pair of
# hooks (they both share the got_kbdint flag)
def inputhook_qt5():
"""PyOS_InputHook python hook for Qt5.
Process pending Qt events and if there's no pending keyboard
input, spend a short slice of time (50ms) running the Qt event
loop.
As a Python ctypes callback can't raise an exception, we catch
the KeyboardInterrupt and temporarily deactivate the hook,
which will let a *second* CTRL+C be processed normally and go
back to a clean prompt line.
"""
try:
allow_CTRL_C()
app = QtCore.QCoreApplication.instance()
if not app: # shouldn't happen, but safer if it happens anyway...
return 0
app.processEvents(QtCore.QEventLoop.AllEvents, 300)
if not stdin_ready():
# Generally a program would run QCoreApplication::exec()
# from main() to enter and process the Qt event loop until
# quit() or exit() is called and the program terminates.
#
# For our input hook integration, we need to repeatedly
# enter and process the Qt event loop for only a short
# amount of time (say 50ms) to ensure that Python stays
# responsive to other user inputs.
#
# A naive approach would be to repeatedly call
# QCoreApplication::exec(), using a timer to quit after a
# short amount of time. Unfortunately, QCoreApplication
# emits an aboutToQuit signal before stopping, which has
# the undesirable effect of closing all modal windows.
#
# To work around this problem, we instead create a
# QEventLoop and call QEventLoop::exec(). Other than
# setting some state variables which do not seem to be
# used anywhere, the only thing QCoreApplication adds is
# the aboutToQuit signal which is precisely what we are
# trying to avoid.
timer = QtCore.QTimer()
event_loop = QtCore.QEventLoop()
timer.timeout.connect(event_loop.quit)
while not stdin_ready():
timer.start(50)
event_loop.exec_()
timer.stop()
except KeyboardInterrupt:
global got_kbdint, sigint_timer
ignore_CTRL_C()
got_kbdint = True
mgr.clear_inputhook()
# This generates a second SIGINT so the user doesn't have to
# press CTRL+C twice to get a clean prompt.
#
# Since we can't catch the resulting KeyboardInterrupt here
# (because this is a ctypes callback), we use a timer to
# generate the SIGINT after we leave this callback.
#
# Unfortunately this doesn't work on Windows (SIGINT kills
# Python and CTRL_C_EVENT doesn't work).
if(os.name == 'posix'):
pid = os.getpid()
if(not sigint_timer):
sigint_timer = threading.Timer(.01, os.kill,
args=[pid, signal.SIGINT] )
sigint_timer.start()
else:
print("\nKeyboardInterrupt - Ctrl-C again for new prompt")
except: # NO exceptions are allowed to escape from a ctypes callback
ignore_CTRL_C()
from traceback import print_exc
print_exc()
print("Got exception from inputhook_qt5, unregistering.")
mgr.clear_inputhook()
finally:
allow_CTRL_C()
return 0
def preprompthook_qt5(ishell):
"""'pre_prompt_hook' used to restore the Qt5 input hook
(in case the latter was temporarily deactivated after a
CTRL+C)
"""
global got_kbdint, sigint_timer
if(sigint_timer):
sigint_timer.cancel()
sigint_timer = None
if got_kbdint:
mgr.set_inputhook(inputhook_qt5)
got_kbdint = False
ip._inputhook_qt5 = inputhook_qt5
ip.set_hook('pre_prompt_hook', preprompthook_qt5)
return app, inputhook_qt5 | [
"def",
"create_inputhook_qt5",
"(",
"mgr",
",",
"app",
"=",
"None",
")",
":",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"QtCore",
".",
"QCoreApplication",
".",
"instance",
"(",
")",
"if",
"app",
"is",
"None",
":",
"from",
"PyQt5",
"import",
"QtWidget... | Create an input hook for running the Qt5 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, and create a new one if none is found.
Returns
-------
A pair consisting of a Qt Application (either the one given or the
one found or created) and a inputhook.
Notes
-----
We use a custom input hook instead of PyQt5's default one, as it
interacts better with the readline packages (issue #481).
The inputhook function works in tandem with a 'pre_prompt_hook'
which automatically restores the hook as an inputhook in case the
latter has been temporarily disabled after having intercepted a
KeyboardInterrupt. | [
"Create",
"an",
"input",
"hook",
"for",
"running",
"the",
"Qt5",
"application",
"event",
"loop",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/inputhookqt5.py#L54-L197 | train | 209,816 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/win32/context_amd64.py | CONTEXT.from_dict | def from_dict(cls, ctx):
'Instance a new structure from a Python native type.'
ctx = Context(ctx)
s = cls()
ContextFlags = ctx['ContextFlags']
s.ContextFlags = ContextFlags
for key in cls._others:
if key != 'VectorRegister':
setattr(s, key, ctx[key])
else:
w = ctx[key]
v = (M128A * len(w))()
i = 0
for x in w:
y = M128A()
y.High = x >> 64
y.Low = x - (x >> 64)
v[i] = y
i += 1
setattr(s, key, v)
if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
for key in cls._control:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
for key in cls._integer:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
for key in cls._segments:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for key in cls._debug:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_MMX_REGISTERS) == CONTEXT_MMX_REGISTERS:
xmm = s.FltSave.xmm
for key in cls._mmx:
y = M128A()
y.High = x >> 64
y.Low = x - (x >> 64)
setattr(xmm, key, y)
return s | python | def from_dict(cls, ctx):
'Instance a new structure from a Python native type.'
ctx = Context(ctx)
s = cls()
ContextFlags = ctx['ContextFlags']
s.ContextFlags = ContextFlags
for key in cls._others:
if key != 'VectorRegister':
setattr(s, key, ctx[key])
else:
w = ctx[key]
v = (M128A * len(w))()
i = 0
for x in w:
y = M128A()
y.High = x >> 64
y.Low = x - (x >> 64)
v[i] = y
i += 1
setattr(s, key, v)
if (ContextFlags & CONTEXT_CONTROL) == CONTEXT_CONTROL:
for key in cls._control:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_INTEGER) == CONTEXT_INTEGER:
for key in cls._integer:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_SEGMENTS) == CONTEXT_SEGMENTS:
for key in cls._segments:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_DEBUG_REGISTERS) == CONTEXT_DEBUG_REGISTERS:
for key in cls._debug:
setattr(s, key, ctx[key])
if (ContextFlags & CONTEXT_MMX_REGISTERS) == CONTEXT_MMX_REGISTERS:
xmm = s.FltSave.xmm
for key in cls._mmx:
y = M128A()
y.High = x >> 64
y.Low = x - (x >> 64)
setattr(xmm, key, y)
return s | [
"def",
"from_dict",
"(",
"cls",
",",
"ctx",
")",
":",
"ctx",
"=",
"Context",
"(",
"ctx",
")",
"s",
"=",
"cls",
"(",
")",
"ContextFlags",
"=",
"ctx",
"[",
"'ContextFlags'",
"]",
"s",
".",
"ContextFlags",
"=",
"ContextFlags",
"for",
"key",
"in",
"cls",... | Instance a new structure from a Python native type. | [
"Instance",
"a",
"new",
"structure",
"from",
"a",
"Python",
"native",
"type",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/win32/context_amd64.py#L426-L465 | train | 209,817 |
fabioz/PyDev.Debugger | pydevconsole.py | do_exit | def do_exit(*args):
'''
We have to override the exit because calling sys.exit will only actually exit the main thread,
and as we're in a Xml-rpc server, that won't work.
'''
try:
import java.lang.System
java.lang.System.exit(1)
except ImportError:
if len(args) == 1:
os._exit(args[0])
else:
os._exit(0) | python | def do_exit(*args):
'''
We have to override the exit because calling sys.exit will only actually exit the main thread,
and as we're in a Xml-rpc server, that won't work.
'''
try:
import java.lang.System
java.lang.System.exit(1)
except ImportError:
if len(args) == 1:
os._exit(args[0])
else:
os._exit(0) | [
"def",
"do_exit",
"(",
"*",
"args",
")",
":",
"try",
":",
"import",
"java",
".",
"lang",
".",
"System",
"java",
".",
"lang",
".",
"System",
".",
"exit",
"(",
"1",
")",
"except",
"ImportError",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
... | We have to override the exit because calling sys.exit will only actually exit the main thread,
and as we're in a Xml-rpc server, that won't work. | [
"We",
"have",
"to",
"override",
"the",
"exit",
"because",
"calling",
"sys",
".",
"exit",
"will",
"only",
"actually",
"exit",
"the",
"main",
"thread",
"and",
"as",
"we",
"re",
"in",
"a",
"Xml",
"-",
"rpc",
"server",
"that",
"won",
"t",
"work",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevconsole.py#L342-L356 | train | 209,818 |
fabioz/PyDev.Debugger | pydevconsole.py | console_exec | def console_exec(thread_id, frame_id, expression, dbg):
"""returns 'False' in case expression is partially correct
"""
frame = dbg.find_frame(thread_id, frame_id)
is_multiline = expression.count('@LINE@') > 1
expression = str(expression.replace('@LINE@', '\n'))
# Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329
# (Names not resolved in generator expression in method)
# See message: http://mail.python.org/pipermail/python-list/2009-January/526522.html
updated_globals = {}
updated_globals.update(frame.f_globals)
updated_globals.update(frame.f_locals) # locals later because it has precedence over the actual globals
if IPYTHON:
need_more = exec_code(CodeFragment(expression), updated_globals, frame.f_locals, dbg)
if not need_more:
pydevd_save_locals.save_locals(frame)
return need_more
interpreter = ConsoleWriter()
if not is_multiline:
try:
code = compile_command(expression)
except (OverflowError, SyntaxError, ValueError):
# Case 1
interpreter.showsyntaxerror()
return False
if code is None:
# Case 2
return True
else:
code = expression
# Case 3
try:
Exec(code, updated_globals, frame.f_locals)
except SystemExit:
raise
except:
interpreter.showtraceback()
else:
pydevd_save_locals.save_locals(frame)
return False | python | def console_exec(thread_id, frame_id, expression, dbg):
"""returns 'False' in case expression is partially correct
"""
frame = dbg.find_frame(thread_id, frame_id)
is_multiline = expression.count('@LINE@') > 1
expression = str(expression.replace('@LINE@', '\n'))
# Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329
# (Names not resolved in generator expression in method)
# See message: http://mail.python.org/pipermail/python-list/2009-January/526522.html
updated_globals = {}
updated_globals.update(frame.f_globals)
updated_globals.update(frame.f_locals) # locals later because it has precedence over the actual globals
if IPYTHON:
need_more = exec_code(CodeFragment(expression), updated_globals, frame.f_locals, dbg)
if not need_more:
pydevd_save_locals.save_locals(frame)
return need_more
interpreter = ConsoleWriter()
if not is_multiline:
try:
code = compile_command(expression)
except (OverflowError, SyntaxError, ValueError):
# Case 1
interpreter.showsyntaxerror()
return False
if code is None:
# Case 2
return True
else:
code = expression
# Case 3
try:
Exec(code, updated_globals, frame.f_locals)
except SystemExit:
raise
except:
interpreter.showtraceback()
else:
pydevd_save_locals.save_locals(frame)
return False | [
"def",
"console_exec",
"(",
"thread_id",
",",
"frame_id",
",",
"expression",
",",
"dbg",
")",
":",
"frame",
"=",
"dbg",
".",
"find_frame",
"(",
"thread_id",
",",
"frame_id",
")",
"is_multiline",
"=",
"expression",
".",
"count",
"(",
"'@LINE@'",
")",
">",
... | returns 'False' in case expression is partially correct | [
"returns",
"False",
"in",
"case",
"expression",
"is",
"partially",
"correct"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevconsole.py#L546-L593 | train | 209,819 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/util.py | CustomAddressIterator | def CustomAddressIterator(memory_map, condition):
"""
Generator function that iterates through a memory map, filtering memory
region blocks by any given condition.
@type memory_map: list( L{win32.MemoryBasicInformation} )
@param memory_map: List of memory region information objects.
Returned by L{Process.get_memory_map}.
@type condition: function
@param condition: Callback function that returns C{True} if the memory
block should be returned, or C{False} if it should be filtered.
@rtype: generator of L{win32.MemoryBasicInformation}
@return: Generator object to iterate memory blocks.
"""
for mbi in memory_map:
if condition(mbi):
address = mbi.BaseAddress
max_addr = address + mbi.RegionSize
while address < max_addr:
yield address
address = address + 1 | python | def CustomAddressIterator(memory_map, condition):
"""
Generator function that iterates through a memory map, filtering memory
region blocks by any given condition.
@type memory_map: list( L{win32.MemoryBasicInformation} )
@param memory_map: List of memory region information objects.
Returned by L{Process.get_memory_map}.
@type condition: function
@param condition: Callback function that returns C{True} if the memory
block should be returned, or C{False} if it should be filtered.
@rtype: generator of L{win32.MemoryBasicInformation}
@return: Generator object to iterate memory blocks.
"""
for mbi in memory_map:
if condition(mbi):
address = mbi.BaseAddress
max_addr = address + mbi.RegionSize
while address < max_addr:
yield address
address = address + 1 | [
"def",
"CustomAddressIterator",
"(",
"memory_map",
",",
"condition",
")",
":",
"for",
"mbi",
"in",
"memory_map",
":",
"if",
"condition",
"(",
"mbi",
")",
":",
"address",
"=",
"mbi",
".",
"BaseAddress",
"max_addr",
"=",
"address",
"+",
"mbi",
".",
"RegionSi... | Generator function that iterates through a memory map, filtering memory
region blocks by any given condition.
@type memory_map: list( L{win32.MemoryBasicInformation} )
@param memory_map: List of memory region information objects.
Returned by L{Process.get_memory_map}.
@type condition: function
@param condition: Callback function that returns C{True} if the memory
block should be returned, or C{False} if it should be filtered.
@rtype: generator of L{win32.MemoryBasicInformation}
@return: Generator object to iterate memory blocks. | [
"Generator",
"function",
"that",
"iterates",
"through",
"a",
"memory",
"map",
"filtering",
"memory",
"region",
"blocks",
"by",
"any",
"given",
"condition",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/util.py#L468-L490 | train | 209,820 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/util.py | MemoryAddresses.pageSize | def pageSize(cls):
"""
Try to get the pageSize value on runtime.
"""
try:
try:
pageSize = win32.GetSystemInfo().dwPageSize
except WindowsError:
pageSize = 0x1000
except NameError:
pageSize = 0x1000
cls.pageSize = pageSize # now this function won't be called again
return pageSize | python | def pageSize(cls):
"""
Try to get the pageSize value on runtime.
"""
try:
try:
pageSize = win32.GetSystemInfo().dwPageSize
except WindowsError:
pageSize = 0x1000
except NameError:
pageSize = 0x1000
cls.pageSize = pageSize # now this function won't be called again
return pageSize | [
"def",
"pageSize",
"(",
"cls",
")",
":",
"try",
":",
"try",
":",
"pageSize",
"=",
"win32",
".",
"GetSystemInfo",
"(",
")",
".",
"dwPageSize",
"except",
"WindowsError",
":",
"pageSize",
"=",
"0x1000",
"except",
"NameError",
":",
"pageSize",
"=",
"0x1000",
... | Try to get the pageSize value on runtime. | [
"Try",
"to",
"get",
"the",
"pageSize",
"value",
"on",
"runtime",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/util.py#L351-L363 | train | 209,821 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/util.py | MemoryAddresses.get_buffer_size_in_pages | def get_buffer_size_in_pages(cls, address, size):
"""
Get the number of pages in use by the given buffer.
@type address: int
@param address: Aligned memory address.
@type size: int
@param size: Buffer size.
@rtype: int
@return: Buffer size in number of pages.
"""
if size < 0:
size = -size
address = address - size
begin, end = cls.align_address_range(address, address + size)
# XXX FIXME
# I think this rounding fails at least for address 0xFFFFFFFF size 1
return int(float(end - begin) / float(cls.pageSize)) | python | def get_buffer_size_in_pages(cls, address, size):
"""
Get the number of pages in use by the given buffer.
@type address: int
@param address: Aligned memory address.
@type size: int
@param size: Buffer size.
@rtype: int
@return: Buffer size in number of pages.
"""
if size < 0:
size = -size
address = address - size
begin, end = cls.align_address_range(address, address + size)
# XXX FIXME
# I think this rounding fails at least for address 0xFFFFFFFF size 1
return int(float(end - begin) / float(cls.pageSize)) | [
"def",
"get_buffer_size_in_pages",
"(",
"cls",
",",
"address",
",",
"size",
")",
":",
"if",
"size",
"<",
"0",
":",
"size",
"=",
"-",
"size",
"address",
"=",
"address",
"-",
"size",
"begin",
",",
"end",
"=",
"cls",
".",
"align_address_range",
"(",
"addr... | Get the number of pages in use by the given buffer.
@type address: int
@param address: Aligned memory address.
@type size: int
@param size: Buffer size.
@rtype: int
@return: Buffer size in number of pages. | [
"Get",
"the",
"number",
"of",
"pages",
"in",
"use",
"by",
"the",
"given",
"buffer",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/util.py#L420-L439 | train | 209,822 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/util.py | MemoryAddresses.do_ranges_intersect | def do_ranges_intersect(begin, end, old_begin, old_end):
"""
Determine if the two given memory address ranges intersect.
@type begin: int
@param begin: Start address of the first range.
@type end: int
@param end: End address of the first range.
@type old_begin: int
@param old_begin: Start address of the second range.
@type old_end: int
@param old_end: End address of the second range.
@rtype: bool
@return: C{True} if the two ranges intersect, C{False} otherwise.
"""
return (old_begin <= begin < old_end) or \
(old_begin < end <= old_end) or \
(begin <= old_begin < end) or \
(begin < old_end <= end) | python | def do_ranges_intersect(begin, end, old_begin, old_end):
"""
Determine if the two given memory address ranges intersect.
@type begin: int
@param begin: Start address of the first range.
@type end: int
@param end: End address of the first range.
@type old_begin: int
@param old_begin: Start address of the second range.
@type old_end: int
@param old_end: End address of the second range.
@rtype: bool
@return: C{True} if the two ranges intersect, C{False} otherwise.
"""
return (old_begin <= begin < old_end) or \
(old_begin < end <= old_end) or \
(begin <= old_begin < end) or \
(begin < old_end <= end) | [
"def",
"do_ranges_intersect",
"(",
"begin",
",",
"end",
",",
"old_begin",
",",
"old_end",
")",
":",
"return",
"(",
"old_begin",
"<=",
"begin",
"<",
"old_end",
")",
"or",
"(",
"old_begin",
"<",
"end",
"<=",
"old_end",
")",
"or",
"(",
"begin",
"<=",
"old... | Determine if the two given memory address ranges intersect.
@type begin: int
@param begin: Start address of the first range.
@type end: int
@param end: End address of the first range.
@type old_begin: int
@param old_begin: Start address of the second range.
@type old_end: int
@param old_end: End address of the second range.
@rtype: bool
@return: C{True} if the two ranges intersect, C{False} otherwise. | [
"Determine",
"if",
"the",
"two",
"given",
"memory",
"address",
"ranges",
"intersect",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/util.py#L442-L464 | train | 209,823 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/util.py | DebugRegister.clear_bp | def clear_bp(cls, ctx, register):
"""
Clears a hardware breakpoint.
@see: find_slot, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register) for hardware breakpoint.
"""
ctx['Dr7'] &= cls.clearMask[register]
ctx['Dr%d' % register] = 0 | python | def clear_bp(cls, ctx, register):
"""
Clears a hardware breakpoint.
@see: find_slot, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register) for hardware breakpoint.
"""
ctx['Dr7'] &= cls.clearMask[register]
ctx['Dr%d' % register] = 0 | [
"def",
"clear_bp",
"(",
"cls",
",",
"ctx",
",",
"register",
")",
":",
"ctx",
"[",
"'Dr7'",
"]",
"&=",
"cls",
".",
"clearMask",
"[",
"register",
"]",
"ctx",
"[",
"'Dr%d'",
"%",
"register",
"]",
"=",
"0"
] | Clears a hardware breakpoint.
@see: find_slot, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register) for hardware breakpoint. | [
"Clears",
"a",
"hardware",
"breakpoint",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/util.py#L971-L984 | train | 209,824 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/util.py | DebugRegister.set_bp | def set_bp(cls, ctx, register, address, trigger, watch):
"""
Sets a hardware breakpoint.
@see: clear_bp, find_slot
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register).
@type address: int
@param address: Memory address.
@type trigger: int
@param trigger: Trigger flag. See L{HardwareBreakpoint.validTriggers}.
@type watch: int
@param watch: Watch flag. See L{HardwareBreakpoint.validWatchSizes}.
"""
Dr7 = ctx['Dr7']
Dr7 |= cls.enableMask[register]
orMask, andMask = cls.triggerMask[register][trigger]
Dr7 &= andMask
Dr7 |= orMask
orMask, andMask = cls.watchMask[register][watch]
Dr7 &= andMask
Dr7 |= orMask
ctx['Dr7'] = Dr7
ctx['Dr%d' % register] = address | python | def set_bp(cls, ctx, register, address, trigger, watch):
"""
Sets a hardware breakpoint.
@see: clear_bp, find_slot
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register).
@type address: int
@param address: Memory address.
@type trigger: int
@param trigger: Trigger flag. See L{HardwareBreakpoint.validTriggers}.
@type watch: int
@param watch: Watch flag. See L{HardwareBreakpoint.validWatchSizes}.
"""
Dr7 = ctx['Dr7']
Dr7 |= cls.enableMask[register]
orMask, andMask = cls.triggerMask[register][trigger]
Dr7 &= andMask
Dr7 |= orMask
orMask, andMask = cls.watchMask[register][watch]
Dr7 &= andMask
Dr7 |= orMask
ctx['Dr7'] = Dr7
ctx['Dr%d' % register] = address | [
"def",
"set_bp",
"(",
"cls",
",",
"ctx",
",",
"register",
",",
"address",
",",
"trigger",
",",
"watch",
")",
":",
"Dr7",
"=",
"ctx",
"[",
"'Dr7'",
"]",
"Dr7",
"|=",
"cls",
".",
"enableMask",
"[",
"register",
"]",
"orMask",
",",
"andMask",
"=",
"cls... | Sets a hardware breakpoint.
@see: clear_bp, find_slot
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@type register: int
@param register: Slot (debug register).
@type address: int
@param address: Memory address.
@type trigger: int
@param trigger: Trigger flag. See L{HardwareBreakpoint.validTriggers}.
@type watch: int
@param watch: Watch flag. See L{HardwareBreakpoint.validWatchSizes}. | [
"Sets",
"a",
"hardware",
"breakpoint",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/util.py#L987-L1017 | train | 209,825 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/util.py | DebugRegister.find_slot | def find_slot(cls, ctx):
"""
Finds an empty slot to set a hardware breakpoint.
@see: clear_bp, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@rtype: int
@return: Slot (debug register) for hardware breakpoint.
"""
Dr7 = ctx['Dr7']
slot = 0
for m in cls.enableMask:
if (Dr7 & m) == 0:
return slot
slot += 1
return None | python | def find_slot(cls, ctx):
"""
Finds an empty slot to set a hardware breakpoint.
@see: clear_bp, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@rtype: int
@return: Slot (debug register) for hardware breakpoint.
"""
Dr7 = ctx['Dr7']
slot = 0
for m in cls.enableMask:
if (Dr7 & m) == 0:
return slot
slot += 1
return None | [
"def",
"find_slot",
"(",
"cls",
",",
"ctx",
")",
":",
"Dr7",
"=",
"ctx",
"[",
"'Dr7'",
"]",
"slot",
"=",
"0",
"for",
"m",
"in",
"cls",
".",
"enableMask",
":",
"if",
"(",
"Dr7",
"&",
"m",
")",
"==",
"0",
":",
"return",
"slot",
"slot",
"+=",
"1... | Finds an empty slot to set a hardware breakpoint.
@see: clear_bp, set_bp
@type ctx: dict( str S{->} int )
@param ctx: Thread context dictionary.
@rtype: int
@return: Slot (debug register) for hardware breakpoint. | [
"Finds",
"an",
"empty",
"slot",
"to",
"set",
"a",
"hardware",
"breakpoint",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/util.py#L1020-L1038 | train | 209,826 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/pgen2/conv.py | Converter.run | def run(self, graminit_h, graminit_c):
"""Load the grammar tables from the text files written by pgen."""
self.parse_graminit_h(graminit_h)
self.parse_graminit_c(graminit_c)
self.finish_off() | python | def run(self, graminit_h, graminit_c):
"""Load the grammar tables from the text files written by pgen."""
self.parse_graminit_h(graminit_h)
self.parse_graminit_c(graminit_c)
self.finish_off() | [
"def",
"run",
"(",
"self",
",",
"graminit_h",
",",
"graminit_c",
")",
":",
"self",
".",
"parse_graminit_h",
"(",
"graminit_h",
")",
"self",
".",
"parse_graminit_c",
"(",
"graminit_c",
")",
"self",
".",
"finish_off",
"(",
")"
] | Load the grammar tables from the text files written by pgen. | [
"Load",
"the",
"grammar",
"tables",
"from",
"the",
"text",
"files",
"written",
"by",
"pgen",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/pgen2/conv.py#L47-L51 | train | 209,827 |
fabioz/PyDev.Debugger | pycompletionserver.py | complete_from_dir | def complete_from_dir(directory):
'''
This is necessary so that we get the imports from the same directory where the file
we are completing is located.
'''
global currDirModule
if currDirModule is not None:
if len(sys.path) > 0 and sys.path[0] == currDirModule:
del sys.path[0]
currDirModule = directory
sys.path.insert(0, directory) | python | def complete_from_dir(directory):
'''
This is necessary so that we get the imports from the same directory where the file
we are completing is located.
'''
global currDirModule
if currDirModule is not None:
if len(sys.path) > 0 and sys.path[0] == currDirModule:
del sys.path[0]
currDirModule = directory
sys.path.insert(0, directory) | [
"def",
"complete_from_dir",
"(",
"directory",
")",
":",
"global",
"currDirModule",
"if",
"currDirModule",
"is",
"not",
"None",
":",
"if",
"len",
"(",
"sys",
".",
"path",
")",
">",
"0",
"and",
"sys",
".",
"path",
"[",
"0",
"]",
"==",
"currDirModule",
":... | This is necessary so that we get the imports from the same directory where the file
we are completing is located. | [
"This",
"is",
"necessary",
"so",
"that",
"we",
"get",
"the",
"imports",
"from",
"the",
"same",
"directory",
"where",
"the",
"file",
"we",
"are",
"completing",
"is",
"located",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pycompletionserver.py#L101-L112 | train | 209,828 |
fabioz/PyDev.Debugger | _pydev_imps/_pydev_SocketServer.py | BaseServer.handle_request | def handle_request(self):
"""Handle one request, possibly blocking.
Respects self.timeout.
"""
# Support people who used socket.settimeout() to escape
# handle_request before self.timeout was available.
timeout = self.socket.gettimeout()
if timeout is None:
timeout = self.timeout
elif self.timeout is not None:
timeout = min(timeout, self.timeout)
fd_sets = select.select([self], [], [], timeout)
if not fd_sets[0]:
self.handle_timeout()
return
self._handle_request_noblock() | python | def handle_request(self):
"""Handle one request, possibly blocking.
Respects self.timeout.
"""
# Support people who used socket.settimeout() to escape
# handle_request before self.timeout was available.
timeout = self.socket.gettimeout()
if timeout is None:
timeout = self.timeout
elif self.timeout is not None:
timeout = min(timeout, self.timeout)
fd_sets = select.select([self], [], [], timeout)
if not fd_sets[0]:
self.handle_timeout()
return
self._handle_request_noblock() | [
"def",
"handle_request",
"(",
"self",
")",
":",
"# Support people who used socket.settimeout() to escape",
"# handle_request before self.timeout was available.",
"timeout",
"=",
"self",
".",
"socket",
".",
"gettimeout",
"(",
")",
"if",
"timeout",
"is",
"None",
":",
"timeo... | Handle one request, possibly blocking.
Respects self.timeout. | [
"Handle",
"one",
"request",
"possibly",
"blocking",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_SocketServer.py#L253-L269 | train | 209,829 |
fabioz/PyDev.Debugger | _pydev_imps/_pydev_SocketServer.py | BaseServer.handle_error | def handle_error(self, request, client_address):
"""Handle an error gracefully. May be overridden.
The default is to print a traceback and continue.
"""
print '-'*40
print 'Exception happened during processing of request from',
print client_address
import traceback
traceback.print_exc() # XXX But this goes to stderr!
print '-'*40 | python | def handle_error(self, request, client_address):
"""Handle an error gracefully. May be overridden.
The default is to print a traceback and continue.
"""
print '-'*40
print 'Exception happened during processing of request from',
print client_address
import traceback
traceback.print_exc() # XXX But this goes to stderr!
print '-'*40 | [
"def",
"handle_error",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"print",
"'-'",
"*",
"40",
"print",
"'Exception happened during processing of request from'",
",",
"print",
"client_address",
"import",
"traceback",
"traceback",
".",
"print_exc",
"("... | Handle an error gracefully. May be overridden.
The default is to print a traceback and continue. | [
"Handle",
"an",
"error",
"gracefully",
".",
"May",
"be",
"overridden",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_SocketServer.py#L333-L344 | train | 209,830 |
fabioz/PyDev.Debugger | _pydev_imps/_pydev_SocketServer.py | ForkingMixIn.collect_children | def collect_children(self):
"""Internal routine to wait for children that have exited."""
if self.active_children is None: return
while len(self.active_children) >= self.max_children:
# XXX: This will wait for any child process, not just ones
# spawned by this library. This could confuse other
# libraries that expect to be able to wait for their own
# children.
try:
pid, status = os.waitpid(0, 0)
except os.error:
pid = None
if pid not in self.active_children: continue
self.active_children.remove(pid)
# XXX: This loop runs more system calls than it ought
# to. There should be a way to put the active_children into a
# process group and then use os.waitpid(-pgid) to wait for any
# of that set, but I couldn't find a way to allocate pgids
# that couldn't collide.
for child in self.active_children:
try:
pid, status = os.waitpid(child, os.WNOHANG) # @UndefinedVariable
except os.error:
pid = None
if not pid: continue
try:
self.active_children.remove(pid)
except ValueError, e:
raise ValueError('%s. x=%d and list=%r' % (e.message, pid,
self.active_children)) | python | def collect_children(self):
"""Internal routine to wait for children that have exited."""
if self.active_children is None: return
while len(self.active_children) >= self.max_children:
# XXX: This will wait for any child process, not just ones
# spawned by this library. This could confuse other
# libraries that expect to be able to wait for their own
# children.
try:
pid, status = os.waitpid(0, 0)
except os.error:
pid = None
if pid not in self.active_children: continue
self.active_children.remove(pid)
# XXX: This loop runs more system calls than it ought
# to. There should be a way to put the active_children into a
# process group and then use os.waitpid(-pgid) to wait for any
# of that set, but I couldn't find a way to allocate pgids
# that couldn't collide.
for child in self.active_children:
try:
pid, status = os.waitpid(child, os.WNOHANG) # @UndefinedVariable
except os.error:
pid = None
if not pid: continue
try:
self.active_children.remove(pid)
except ValueError, e:
raise ValueError('%s. x=%d and list=%r' % (e.message, pid,
self.active_children)) | [
"def",
"collect_children",
"(",
"self",
")",
":",
"if",
"self",
".",
"active_children",
"is",
"None",
":",
"return",
"while",
"len",
"(",
"self",
".",
"active_children",
")",
">=",
"self",
".",
"max_children",
":",
"# XXX: This will wait for any child process, not... | Internal routine to wait for children that have exited. | [
"Internal",
"routine",
"to",
"wait",
"for",
"children",
"that",
"have",
"exited",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_SocketServer.py#L503-L533 | train | 209,831 |
fabioz/PyDev.Debugger | _pydev_imps/_pydev_SocketServer.py | ForkingMixIn.process_request | def process_request(self, request, client_address):
"""Fork a new subprocess to process the request."""
self.collect_children()
pid = os.fork() # @UndefinedVariable
if pid:
# Parent process
if self.active_children is None:
self.active_children = []
self.active_children.append(pid)
self.close_request(request) #close handle in parent process
return
else:
# Child process.
# This must never return, hence os._exit()!
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
os._exit(0)
except:
try:
self.handle_error(request, client_address)
self.shutdown_request(request)
finally:
os._exit(1) | python | def process_request(self, request, client_address):
"""Fork a new subprocess to process the request."""
self.collect_children()
pid = os.fork() # @UndefinedVariable
if pid:
# Parent process
if self.active_children is None:
self.active_children = []
self.active_children.append(pid)
self.close_request(request) #close handle in parent process
return
else:
# Child process.
# This must never return, hence os._exit()!
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
os._exit(0)
except:
try:
self.handle_error(request, client_address)
self.shutdown_request(request)
finally:
os._exit(1) | [
"def",
"process_request",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"self",
".",
"collect_children",
"(",
")",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"# @UndefinedVariable",
"if",
"pid",
":",
"# Parent process",
"if",
"self",
".",
"ac... | Fork a new subprocess to process the request. | [
"Fork",
"a",
"new",
"subprocess",
"to",
"process",
"the",
"request",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_SocketServer.py#L542-L565 | train | 209,832 |
fabioz/PyDev.Debugger | _pydev_imps/_pydev_SocketServer.py | ThreadingMixIn.process_request_thread | def process_request_thread(self, request, client_address):
"""Same as in BaseServer but as a thread.
In addition, exception handling is done here.
"""
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
except:
self.handle_error(request, client_address)
self.shutdown_request(request) | python | def process_request_thread(self, request, client_address):
"""Same as in BaseServer but as a thread.
In addition, exception handling is done here.
"""
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
except:
self.handle_error(request, client_address)
self.shutdown_request(request) | [
"def",
"process_request_thread",
"(",
"self",
",",
"request",
",",
"client_address",
")",
":",
"try",
":",
"self",
".",
"finish_request",
"(",
"request",
",",
"client_address",
")",
"self",
".",
"shutdown_request",
"(",
"request",
")",
"except",
":",
"self",
... | Same as in BaseServer but as a thread.
In addition, exception handling is done here. | [
"Same",
"as",
"in",
"BaseServer",
"but",
"as",
"a",
"thread",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_SocketServer.py#L575-L586 | train | 209,833 |
fabioz/PyDev.Debugger | pydev_ipython/qt_for_kernel.py | get_options | def get_options():
"""Return a list of acceptable QT APIs, in decreasing order of
preference
"""
#already imported Qt somewhere. Use that
loaded = loaded_api()
if loaded is not None:
return [loaded]
mpl = sys.modules.get('matplotlib', None)
if mpl is not None and not check_version(mpl.__version__, '1.0.2'):
#1.0.1 only supports PyQt4 v1
return [QT_API_PYQT_DEFAULT]
if os.environ.get('QT_API', None) is None:
#no ETS variable. Ask mpl, then use either
return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE, QT_API_PYQT5]
#ETS variable present. Will fallback to external.qt
return None | python | def get_options():
"""Return a list of acceptable QT APIs, in decreasing order of
preference
"""
#already imported Qt somewhere. Use that
loaded = loaded_api()
if loaded is not None:
return [loaded]
mpl = sys.modules.get('matplotlib', None)
if mpl is not None and not check_version(mpl.__version__, '1.0.2'):
#1.0.1 only supports PyQt4 v1
return [QT_API_PYQT_DEFAULT]
if os.environ.get('QT_API', None) is None:
#no ETS variable. Ask mpl, then use either
return matplotlib_options(mpl) or [QT_API_PYQT_DEFAULT, QT_API_PYSIDE, QT_API_PYQT5]
#ETS variable present. Will fallback to external.qt
return None | [
"def",
"get_options",
"(",
")",
":",
"#already imported Qt somewhere. Use that",
"loaded",
"=",
"loaded_api",
"(",
")",
"if",
"loaded",
"is",
"not",
"None",
":",
"return",
"[",
"loaded",
"]",
"mpl",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"'matplotlib'"... | Return a list of acceptable QT APIs, in decreasing order of
preference | [
"Return",
"a",
"list",
"of",
"acceptable",
"QT",
"APIs",
"in",
"decreasing",
"order",
"of",
"preference"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydev_ipython/qt_for_kernel.py#L91-L111 | train | 209,834 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | tabs_or_spaces | def tabs_or_spaces(physical_line, indent_char):
r"""Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively. When
invoking the Python command line interpreter with the -t option, it issues
warnings about code that illegally mixes tabs and spaces. When using -tt
these warnings become errors. These options are highly recommended!
Okay: if a == 0:\n a = 1\n b = 1
E101: if a == 0:\n a = 1\n\tb = 1
"""
indent = INDENT_REGEX.match(physical_line).group(1)
for offset, char in enumerate(indent):
if char != indent_char:
return offset, "E101 indentation contains mixed spaces and tabs" | python | def tabs_or_spaces(physical_line, indent_char):
r"""Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively. When
invoking the Python command line interpreter with the -t option, it issues
warnings about code that illegally mixes tabs and spaces. When using -tt
these warnings become errors. These options are highly recommended!
Okay: if a == 0:\n a = 1\n b = 1
E101: if a == 0:\n a = 1\n\tb = 1
"""
indent = INDENT_REGEX.match(physical_line).group(1)
for offset, char in enumerate(indent):
if char != indent_char:
return offset, "E101 indentation contains mixed spaces and tabs" | [
"def",
"tabs_or_spaces",
"(",
"physical_line",
",",
"indent_char",
")",
":",
"indent",
"=",
"INDENT_REGEX",
".",
"match",
"(",
"physical_line",
")",
".",
"group",
"(",
"1",
")",
"for",
"offset",
",",
"char",
"in",
"enumerate",
"(",
"indent",
")",
":",
"i... | r"""Never mix tabs and spaces.
The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a mixture
of tabs and spaces should be converted to using spaces exclusively. When
invoking the Python command line interpreter with the -t option, it issues
warnings about code that illegally mixes tabs and spaces. When using -tt
these warnings become errors. These options are highly recommended!
Okay: if a == 0:\n a = 1\n b = 1
E101: if a == 0:\n a = 1\n\tb = 1 | [
"r",
"Never",
"mix",
"tabs",
"and",
"spaces",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L149-L165 | train | 209,835 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | tabs_obsolete | def tabs_obsolete(physical_line):
r"""For new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn
"""
indent = INDENT_REGEX.match(physical_line).group(1)
if '\t' in indent:
return indent.index('\t'), "W191 indentation contains tabs" | python | def tabs_obsolete(physical_line):
r"""For new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn
"""
indent = INDENT_REGEX.match(physical_line).group(1)
if '\t' in indent:
return indent.index('\t'), "W191 indentation contains tabs" | [
"def",
"tabs_obsolete",
"(",
"physical_line",
")",
":",
"indent",
"=",
"INDENT_REGEX",
".",
"match",
"(",
"physical_line",
")",
".",
"group",
"(",
"1",
")",
"if",
"'\\t'",
"in",
"indent",
":",
"return",
"indent",
".",
"index",
"(",
"'\\t'",
")",
",",
"... | r"""For new projects, spaces-only are strongly recommended over tabs.
Okay: if True:\n return
W191: if True:\n\treturn | [
"r",
"For",
"new",
"projects",
"spaces",
"-",
"only",
"are",
"strongly",
"recommended",
"over",
"tabs",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L168-L176 | train | 209,836 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | trailing_whitespace | def trailing_whitespace(physical_line):
r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank, for easier
filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
"""
physical_line = physical_line.rstrip('\n') # chr(10), newline
physical_line = physical_line.rstrip('\r') # chr(13), carriage return
physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L
stripped = physical_line.rstrip(' \t\v')
if physical_line != stripped:
if stripped:
return len(stripped), "W291 trailing whitespace"
else:
return 0, "W293 blank line contains whitespace" | python | def trailing_whitespace(physical_line):
r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank, for easier
filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12
"""
physical_line = physical_line.rstrip('\n') # chr(10), newline
physical_line = physical_line.rstrip('\r') # chr(13), carriage return
physical_line = physical_line.rstrip('\x0c') # chr(12), form feed, ^L
stripped = physical_line.rstrip(' \t\v')
if physical_line != stripped:
if stripped:
return len(stripped), "W291 trailing whitespace"
else:
return 0, "W293 blank line contains whitespace" | [
"def",
"trailing_whitespace",
"(",
"physical_line",
")",
":",
"physical_line",
"=",
"physical_line",
".",
"rstrip",
"(",
"'\\n'",
")",
"# chr(10), newline",
"physical_line",
"=",
"physical_line",
".",
"rstrip",
"(",
"'\\r'",
")",
"# chr(13), carriage return",
"physica... | r"""Trailing whitespace is superfluous.
The warning returned varies on whether the line itself is blank, for easier
filtering for those who want to indent their blank lines.
Okay: spam(1)\n#
W291: spam(1) \n#
W293: class Foo(object):\n \n bang = 12 | [
"r",
"Trailing",
"whitespace",
"is",
"superfluous",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L179-L197 | train | 209,837 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | trailing_blank_lines | def trailing_blank_lines(physical_line, lines, line_number, total_lines):
r"""Trailing blank lines are superfluous.
Okay: spam(1)
W391: spam(1)\n
However the last line should end with a new line (warning W292).
"""
if line_number == total_lines:
stripped_last_line = physical_line.rstrip()
if not stripped_last_line:
return 0, "W391 blank line at end of file"
if stripped_last_line == physical_line:
return len(physical_line), "W292 no newline at end of file" | python | def trailing_blank_lines(physical_line, lines, line_number, total_lines):
r"""Trailing blank lines are superfluous.
Okay: spam(1)
W391: spam(1)\n
However the last line should end with a new line (warning W292).
"""
if line_number == total_lines:
stripped_last_line = physical_line.rstrip()
if not stripped_last_line:
return 0, "W391 blank line at end of file"
if stripped_last_line == physical_line:
return len(physical_line), "W292 no newline at end of file" | [
"def",
"trailing_blank_lines",
"(",
"physical_line",
",",
"lines",
",",
"line_number",
",",
"total_lines",
")",
":",
"if",
"line_number",
"==",
"total_lines",
":",
"stripped_last_line",
"=",
"physical_line",
".",
"rstrip",
"(",
")",
"if",
"not",
"stripped_last_lin... | r"""Trailing blank lines are superfluous.
Okay: spam(1)
W391: spam(1)\n
However the last line should end with a new line (warning W292). | [
"r",
"Trailing",
"blank",
"lines",
"are",
"superfluous",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L200-L213 | train | 209,838 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | maximum_line_length | def maximum_line_length(physical_line, max_line_length, multiline, noqa):
r"""Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character
lines; plus, limiting windows to 80 characters makes it possible to have
several windows side-by-side. The default wrapping on such devices looks
ugly. Therefore, please limit all lines to a maximum of 79 characters.
For flowing long blocks of text (docstrings or comments), limiting the
length to 72 characters is recommended.
Reports error E501.
"""
line = physical_line.rstrip()
length = len(line)
if length > max_line_length and not noqa:
# Special case for long URLs in multi-line docstrings or comments,
# but still report the error when the 72 first chars are whitespaces.
chunks = line.split()
if ((len(chunks) == 1 and multiline) or
(len(chunks) == 2 and chunks[0] == '#')) and \
len(line) - len(chunks[-1]) < max_line_length - 7:
return
if hasattr(line, 'decode'): # Python 2
# The line could contain multi-byte characters
try:
length = len(line.decode('utf-8'))
except UnicodeError:
pass
if length > max_line_length:
return (max_line_length, "E501 line too long "
"(%d > %d characters)" % (length, max_line_length)) | python | def maximum_line_length(physical_line, max_line_length, multiline, noqa):
r"""Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character
lines; plus, limiting windows to 80 characters makes it possible to have
several windows side-by-side. The default wrapping on such devices looks
ugly. Therefore, please limit all lines to a maximum of 79 characters.
For flowing long blocks of text (docstrings or comments), limiting the
length to 72 characters is recommended.
Reports error E501.
"""
line = physical_line.rstrip()
length = len(line)
if length > max_line_length and not noqa:
# Special case for long URLs in multi-line docstrings or comments,
# but still report the error when the 72 first chars are whitespaces.
chunks = line.split()
if ((len(chunks) == 1 and multiline) or
(len(chunks) == 2 and chunks[0] == '#')) and \
len(line) - len(chunks[-1]) < max_line_length - 7:
return
if hasattr(line, 'decode'): # Python 2
# The line could contain multi-byte characters
try:
length = len(line.decode('utf-8'))
except UnicodeError:
pass
if length > max_line_length:
return (max_line_length, "E501 line too long "
"(%d > %d characters)" % (length, max_line_length)) | [
"def",
"maximum_line_length",
"(",
"physical_line",
",",
"max_line_length",
",",
"multiline",
",",
"noqa",
")",
":",
"line",
"=",
"physical_line",
".",
"rstrip",
"(",
")",
"length",
"=",
"len",
"(",
"line",
")",
"if",
"length",
">",
"max_line_length",
"and",... | r"""Limit all lines to a maximum of 79 characters.
There are still many devices around that are limited to 80 character
lines; plus, limiting windows to 80 characters makes it possible to have
several windows side-by-side. The default wrapping on such devices looks
ugly. Therefore, please limit all lines to a maximum of 79 characters.
For flowing long blocks of text (docstrings or comments), limiting the
length to 72 characters is recommended.
Reports error E501. | [
"r",
"Limit",
"all",
"lines",
"to",
"a",
"maximum",
"of",
"79",
"characters",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L216-L246 | train | 209,839 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | blank_lines | def blank_lines(logical_line, blank_lines, indent_level, line_number,
blank_before, previous_logical,
previous_unindented_logical_line, previous_indent_level,
lines):
r"""Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related
functions. Blank lines may be omitted between a bunch of related
one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Okay: def a():\n pass\n\n\ndef b():\n pass
Okay: def a():\n pass\n\n\nasync def b():\n pass
Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass
Okay: default = 1\nfoo = 1
Okay: classify = 1\nfoo = 1
E301: class Foo:\n b = 0\n def bar():\n pass
E302: def a():\n pass\n\ndef b(n):\n pass
E302: def a():\n pass\n\nasync def b(n):\n pass
E303: def a():\n pass\n\n\n\ndef b(n):\n pass
E303: def a():\n\n\n\n pass
E304: @decorator\n\ndef a():\n pass
E305: def a():\n pass\na()
E306: def a():\n def b():\n pass\n def c():\n pass
"""
if line_number < 3 and not previous_logical:
return # Don't expect blank lines before the first line
if previous_logical.startswith('@'):
if blank_lines:
yield 0, "E304 blank lines found after function decorator"
elif blank_lines > 2 or (indent_level and blank_lines == 2):
yield 0, "E303 too many blank lines (%d)" % blank_lines
elif STARTSWITH_TOP_LEVEL_REGEX.match(logical_line):
if indent_level:
if not (blank_before or previous_indent_level < indent_level or
DOCSTRING_REGEX.match(previous_logical)):
ancestor_level = indent_level
nested = False
# Search backwards for a def ancestor or tree root (top level).
for line in lines[line_number - 2::-1]:
if line.strip() and expand_indent(line) < ancestor_level:
ancestor_level = expand_indent(line)
nested = line.lstrip().startswith('def ')
if nested or ancestor_level == 0:
break
if nested:
yield 0, "E306 expected 1 blank line before a " \
"nested definition, found 0"
else:
yield 0, "E301 expected 1 blank line, found 0"
elif blank_before != 2:
yield 0, "E302 expected 2 blank lines, found %d" % blank_before
elif (logical_line and not indent_level and blank_before != 2 and
previous_unindented_logical_line.startswith(('def ', 'class '))):
yield 0, "E305 expected 2 blank lines after " \
"class or function definition, found %d" % blank_before | python | def blank_lines(logical_line, blank_lines, indent_level, line_number,
blank_before, previous_logical,
previous_unindented_logical_line, previous_indent_level,
lines):
r"""Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related
functions. Blank lines may be omitted between a bunch of related
one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Okay: def a():\n pass\n\n\ndef b():\n pass
Okay: def a():\n pass\n\n\nasync def b():\n pass
Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass
Okay: default = 1\nfoo = 1
Okay: classify = 1\nfoo = 1
E301: class Foo:\n b = 0\n def bar():\n pass
E302: def a():\n pass\n\ndef b(n):\n pass
E302: def a():\n pass\n\nasync def b(n):\n pass
E303: def a():\n pass\n\n\n\ndef b(n):\n pass
E303: def a():\n\n\n\n pass
E304: @decorator\n\ndef a():\n pass
E305: def a():\n pass\na()
E306: def a():\n def b():\n pass\n def c():\n pass
"""
if line_number < 3 and not previous_logical:
return # Don't expect blank lines before the first line
if previous_logical.startswith('@'):
if blank_lines:
yield 0, "E304 blank lines found after function decorator"
elif blank_lines > 2 or (indent_level and blank_lines == 2):
yield 0, "E303 too many blank lines (%d)" % blank_lines
elif STARTSWITH_TOP_LEVEL_REGEX.match(logical_line):
if indent_level:
if not (blank_before or previous_indent_level < indent_level or
DOCSTRING_REGEX.match(previous_logical)):
ancestor_level = indent_level
nested = False
# Search backwards for a def ancestor or tree root (top level).
for line in lines[line_number - 2::-1]:
if line.strip() and expand_indent(line) < ancestor_level:
ancestor_level = expand_indent(line)
nested = line.lstrip().startswith('def ')
if nested or ancestor_level == 0:
break
if nested:
yield 0, "E306 expected 1 blank line before a " \
"nested definition, found 0"
else:
yield 0, "E301 expected 1 blank line, found 0"
elif blank_before != 2:
yield 0, "E302 expected 2 blank lines, found %d" % blank_before
elif (logical_line and not indent_level and blank_before != 2 and
previous_unindented_logical_line.startswith(('def ', 'class '))):
yield 0, "E305 expected 2 blank lines after " \
"class or function definition, found %d" % blank_before | [
"def",
"blank_lines",
"(",
"logical_line",
",",
"blank_lines",
",",
"indent_level",
",",
"line_number",
",",
"blank_before",
",",
"previous_logical",
",",
"previous_unindented_logical_line",
",",
"previous_indent_level",
",",
"lines",
")",
":",
"if",
"line_number",
"<... | r"""Separate top-level function and class definitions with two blank lines.
Method definitions inside a class are separated by a single blank line.
Extra blank lines may be used (sparingly) to separate groups of related
functions. Blank lines may be omitted between a bunch of related
one-liners (e.g. a set of dummy implementations).
Use blank lines in functions, sparingly, to indicate logical sections.
Okay: def a():\n pass\n\n\ndef b():\n pass
Okay: def a():\n pass\n\n\nasync def b():\n pass
Okay: def a():\n pass\n\n\n# Foo\n# Bar\n\ndef b():\n pass
Okay: default = 1\nfoo = 1
Okay: classify = 1\nfoo = 1
E301: class Foo:\n b = 0\n def bar():\n pass
E302: def a():\n pass\n\ndef b(n):\n pass
E302: def a():\n pass\n\nasync def b(n):\n pass
E303: def a():\n pass\n\n\n\ndef b(n):\n pass
E303: def a():\n\n\n\n pass
E304: @decorator\n\ndef a():\n pass
E305: def a():\n pass\na()
E306: def a():\n def b():\n pass\n def c():\n pass | [
"r",
"Separate",
"top",
"-",
"level",
"function",
"and",
"class",
"definitions",
"with",
"two",
"blank",
"lines",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L254-L313 | train | 209,840 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | whitespace_around_keywords | def whitespace_around_keywords(logical_line):
r"""Avoid extraneous whitespace around keywords.
Okay: True and False
E271: True and False
E272: True and False
E273: True and\tFalse
E274: True\tand False
"""
for match in KEYWORD_REGEX.finditer(logical_line):
before, after = match.groups()
if '\t' in before:
yield match.start(1), "E274 tab before keyword"
elif len(before) > 1:
yield match.start(1), "E272 multiple spaces before keyword"
if '\t' in after:
yield match.start(2), "E273 tab after keyword"
elif len(after) > 1:
yield match.start(2), "E271 multiple spaces after keyword" | python | def whitespace_around_keywords(logical_line):
r"""Avoid extraneous whitespace around keywords.
Okay: True and False
E271: True and False
E272: True and False
E273: True and\tFalse
E274: True\tand False
"""
for match in KEYWORD_REGEX.finditer(logical_line):
before, after = match.groups()
if '\t' in before:
yield match.start(1), "E274 tab before keyword"
elif len(before) > 1:
yield match.start(1), "E272 multiple spaces before keyword"
if '\t' in after:
yield match.start(2), "E273 tab after keyword"
elif len(after) > 1:
yield match.start(2), "E271 multiple spaces after keyword" | [
"def",
"whitespace_around_keywords",
"(",
"logical_line",
")",
":",
"for",
"match",
"in",
"KEYWORD_REGEX",
".",
"finditer",
"(",
"logical_line",
")",
":",
"before",
",",
"after",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"'\\t'",
"in",
"before",
":",
"y... | r"""Avoid extraneous whitespace around keywords.
Okay: True and False
E271: True and False
E272: True and False
E273: True and\tFalse
E274: True\tand False | [
"r",
"Avoid",
"extraneous",
"whitespace",
"around",
"keywords",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L348-L368 | train | 209,841 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | missing_whitespace | def missing_whitespace(logical_line):
r"""Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
Okay: (3,)
Okay: a[1:4]
Okay: a[:4]
Okay: a[1:]
Okay: a[1:4:2]
E231: ['a','b']
E231: foo(bar,baz)
E231: [{'a':'b'}]
"""
line = logical_line
for index in range(len(line) - 1):
char = line[index]
if char in ',;:' and line[index + 1] not in WHITESPACE:
before = line[:index]
if char == ':' and before.count('[') > before.count(']') and \
before.rfind('{') < before.rfind('['):
continue # Slice syntax, no space required
if char == ',' and line[index + 1] == ')':
continue # Allow tuple with only one element: (3,)
yield index, "E231 missing whitespace after '%s'" % char | python | def missing_whitespace(logical_line):
r"""Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
Okay: (3,)
Okay: a[1:4]
Okay: a[:4]
Okay: a[1:]
Okay: a[1:4:2]
E231: ['a','b']
E231: foo(bar,baz)
E231: [{'a':'b'}]
"""
line = logical_line
for index in range(len(line) - 1):
char = line[index]
if char in ',;:' and line[index + 1] not in WHITESPACE:
before = line[:index]
if char == ':' and before.count('[') > before.count(']') and \
before.rfind('{') < before.rfind('['):
continue # Slice syntax, no space required
if char == ',' and line[index + 1] == ')':
continue # Allow tuple with only one element: (3,)
yield index, "E231 missing whitespace after '%s'" % char | [
"def",
"missing_whitespace",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"line",
")",
"-",
"1",
")",
":",
"char",
"=",
"line",
"[",
"index",
"]",
"if",
"char",
"in",
"',;:'",
"and",
"lin... | r"""Each comma, semicolon or colon should be followed by whitespace.
Okay: [a, b]
Okay: (3,)
Okay: a[1:4]
Okay: a[:4]
Okay: a[1:]
Okay: a[1:4:2]
E231: ['a','b']
E231: foo(bar,baz)
E231: [{'a':'b'}] | [
"r",
"Each",
"comma",
"semicolon",
"or",
"colon",
"should",
"be",
"followed",
"by",
"whitespace",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L388-L411 | train | 209,842 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | indentation | def indentation(logical_line, previous_logical, indent_char,
indent_level, previous_indent_level):
r"""Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue to
use 8-space tabs.
Okay: a = 1
Okay: if a == 0:\n a = 1
E111: a = 1
E114: # a = 1
Okay: for item in items:\n pass
E112: for item in items:\npass
E115: for item in items:\n# Hi\n pass
Okay: a = 1\nb = 2
E113: a = 1\n b = 2
E116: a = 1\n # b = 2
"""
c = 0 if logical_line else 3
tmpl = "E11%d %s" if logical_line else "E11%d %s (comment)"
if indent_level % 4:
yield 0, tmpl % (1 + c, "indentation is not a multiple of four")
indent_expect = previous_logical.endswith(':')
if indent_expect and indent_level <= previous_indent_level:
yield 0, tmpl % (2 + c, "expected an indented block")
elif not indent_expect and indent_level > previous_indent_level:
yield 0, tmpl % (3 + c, "unexpected indentation") | python | def indentation(logical_line, previous_logical, indent_char,
indent_level, previous_indent_level):
r"""Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue to
use 8-space tabs.
Okay: a = 1
Okay: if a == 0:\n a = 1
E111: a = 1
E114: # a = 1
Okay: for item in items:\n pass
E112: for item in items:\npass
E115: for item in items:\n# Hi\n pass
Okay: a = 1\nb = 2
E113: a = 1\n b = 2
E116: a = 1\n # b = 2
"""
c = 0 if logical_line else 3
tmpl = "E11%d %s" if logical_line else "E11%d %s (comment)"
if indent_level % 4:
yield 0, tmpl % (1 + c, "indentation is not a multiple of four")
indent_expect = previous_logical.endswith(':')
if indent_expect and indent_level <= previous_indent_level:
yield 0, tmpl % (2 + c, "expected an indented block")
elif not indent_expect and indent_level > previous_indent_level:
yield 0, tmpl % (3 + c, "unexpected indentation") | [
"def",
"indentation",
"(",
"logical_line",
",",
"previous_logical",
",",
"indent_char",
",",
"indent_level",
",",
"previous_indent_level",
")",
":",
"c",
"=",
"0",
"if",
"logical_line",
"else",
"3",
"tmpl",
"=",
"\"E11%d %s\"",
"if",
"logical_line",
"else",
"\"E... | r"""Use 4 spaces per indentation level.
For really old code that you don't want to mess up, you can continue to
use 8-space tabs.
Okay: a = 1
Okay: if a == 0:\n a = 1
E111: a = 1
E114: # a = 1
Okay: for item in items:\n pass
E112: for item in items:\npass
E115: for item in items:\n# Hi\n pass
Okay: a = 1\nb = 2
E113: a = 1\n b = 2
E116: a = 1\n # b = 2 | [
"r",
"Use",
"4",
"spaces",
"per",
"indentation",
"level",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L414-L442 | train | 209,843 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | whitespace_around_operator | def whitespace_around_operator(logical_line):
r"""Avoid extraneous whitespace around an operator.
Okay: a = 12 + 3
E221: a = 4 + 5
E222: a = 4 + 5
E223: a = 4\t+ 5
E224: a = 4 +\t5
"""
for match in OPERATOR_REGEX.finditer(logical_line):
before, after = match.groups()
if '\t' in before:
yield match.start(1), "E223 tab before operator"
elif len(before) > 1:
yield match.start(1), "E221 multiple spaces before operator"
if '\t' in after:
yield match.start(2), "E224 tab after operator"
elif len(after) > 1:
yield match.start(2), "E222 multiple spaces after operator" | python | def whitespace_around_operator(logical_line):
r"""Avoid extraneous whitespace around an operator.
Okay: a = 12 + 3
E221: a = 4 + 5
E222: a = 4 + 5
E223: a = 4\t+ 5
E224: a = 4 +\t5
"""
for match in OPERATOR_REGEX.finditer(logical_line):
before, after = match.groups()
if '\t' in before:
yield match.start(1), "E223 tab before operator"
elif len(before) > 1:
yield match.start(1), "E221 multiple spaces before operator"
if '\t' in after:
yield match.start(2), "E224 tab after operator"
elif len(after) > 1:
yield match.start(2), "E222 multiple spaces after operator" | [
"def",
"whitespace_around_operator",
"(",
"logical_line",
")",
":",
"for",
"match",
"in",
"OPERATOR_REGEX",
".",
"finditer",
"(",
"logical_line",
")",
":",
"before",
",",
"after",
"=",
"match",
".",
"groups",
"(",
")",
"if",
"'\\t'",
"in",
"before",
":",
"... | r"""Avoid extraneous whitespace around an operator.
Okay: a = 12 + 3
E221: a = 4 + 5
E222: a = 4 + 5
E223: a = 4\t+ 5
E224: a = 4 +\t5 | [
"r",
"Avoid",
"extraneous",
"whitespace",
"around",
"an",
"operator",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L676-L696 | train | 209,844 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | missing_whitespace_around_operator | def missing_whitespace_around_operator(logical_line, tokens):
r"""Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
either side: assignment (=), augmented assignment (+=, -= etc.),
comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
Booleans (and, or, not).
- If operators with different priorities are used, consider adding
whitespace around the operators with the lowest priorities.
Okay: i = i + 1
Okay: submitted += 1
Okay: x = x * 2 - 1
Okay: hypot2 = x * x + y * y
Okay: c = (a + b) * (a - b)
Okay: foo(bar, key='word', *args, **kwargs)
Okay: alpha[:-i]
E225: i=i+1
E225: submitted +=1
E225: x = x /2 - 1
E225: z = x **y
E226: c = (a+b) * (a-b)
E226: hypot2 = x*x + y*y
E227: c = a|b
E228: msg = fmt%(errno, errmsg)
"""
parens = 0
need_space = False
prev_type = tokenize.OP
prev_text = prev_end = None
for token_type, text, start, end, line in tokens:
if token_type in SKIP_COMMENTS:
continue
if text in ('(', 'lambda'):
parens += 1
elif text == ')':
parens -= 1
if need_space:
if start != prev_end:
# Found a (probably) needed space
if need_space is not True and not need_space[1]:
yield (need_space[0],
"E225 missing whitespace around operator")
need_space = False
elif text == '>' and prev_text in ('<', '-'):
# Tolerate the "<>" operator, even if running Python 3
# Deal with Python 3's annotated return value "->"
pass
else:
if need_space is True or need_space[1]:
# A needed trailing space was not found
yield prev_end, "E225 missing whitespace around operator"
elif prev_text != '**':
code, optype = 'E226', 'arithmetic'
if prev_text == '%':
code, optype = 'E228', 'modulo'
elif prev_text not in ARITHMETIC_OP:
code, optype = 'E227', 'bitwise or shift'
yield (need_space[0], "%s missing whitespace "
"around %s operator" % (code, optype))
need_space = False
elif token_type == tokenize.OP and prev_end is not None:
if text == '=' and parens:
# Allow keyword args or defaults: foo(bar=None).
pass
elif text in WS_NEEDED_OPERATORS:
need_space = True
elif text in UNARY_OPERATORS:
# Check if the operator is being used as a binary operator
# Allow unary operators: -123, -x, +1.
# Allow argument unpacking: foo(*args, **kwargs).
if (prev_text in '}])' if prev_type == tokenize.OP
else prev_text not in KEYWORDS):
need_space = None
elif text in WS_OPTIONAL_OPERATORS:
need_space = None
if need_space is None:
# Surrounding space is optional, but ensure that
# trailing space matches opening space
need_space = (prev_end, start != prev_end)
elif need_space and start == prev_end:
# A needed opening space was not found
yield prev_end, "E225 missing whitespace around operator"
need_space = False
prev_type = token_type
prev_text = text
prev_end = end | python | def missing_whitespace_around_operator(logical_line, tokens):
r"""Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
either side: assignment (=), augmented assignment (+=, -= etc.),
comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
Booleans (and, or, not).
- If operators with different priorities are used, consider adding
whitespace around the operators with the lowest priorities.
Okay: i = i + 1
Okay: submitted += 1
Okay: x = x * 2 - 1
Okay: hypot2 = x * x + y * y
Okay: c = (a + b) * (a - b)
Okay: foo(bar, key='word', *args, **kwargs)
Okay: alpha[:-i]
E225: i=i+1
E225: submitted +=1
E225: x = x /2 - 1
E225: z = x **y
E226: c = (a+b) * (a-b)
E226: hypot2 = x*x + y*y
E227: c = a|b
E228: msg = fmt%(errno, errmsg)
"""
parens = 0
need_space = False
prev_type = tokenize.OP
prev_text = prev_end = None
for token_type, text, start, end, line in tokens:
if token_type in SKIP_COMMENTS:
continue
if text in ('(', 'lambda'):
parens += 1
elif text == ')':
parens -= 1
if need_space:
if start != prev_end:
# Found a (probably) needed space
if need_space is not True and not need_space[1]:
yield (need_space[0],
"E225 missing whitespace around operator")
need_space = False
elif text == '>' and prev_text in ('<', '-'):
# Tolerate the "<>" operator, even if running Python 3
# Deal with Python 3's annotated return value "->"
pass
else:
if need_space is True or need_space[1]:
# A needed trailing space was not found
yield prev_end, "E225 missing whitespace around operator"
elif prev_text != '**':
code, optype = 'E226', 'arithmetic'
if prev_text == '%':
code, optype = 'E228', 'modulo'
elif prev_text not in ARITHMETIC_OP:
code, optype = 'E227', 'bitwise or shift'
yield (need_space[0], "%s missing whitespace "
"around %s operator" % (code, optype))
need_space = False
elif token_type == tokenize.OP and prev_end is not None:
if text == '=' and parens:
# Allow keyword args or defaults: foo(bar=None).
pass
elif text in WS_NEEDED_OPERATORS:
need_space = True
elif text in UNARY_OPERATORS:
# Check if the operator is being used as a binary operator
# Allow unary operators: -123, -x, +1.
# Allow argument unpacking: foo(*args, **kwargs).
if (prev_text in '}])' if prev_type == tokenize.OP
else prev_text not in KEYWORDS):
need_space = None
elif text in WS_OPTIONAL_OPERATORS:
need_space = None
if need_space is None:
# Surrounding space is optional, but ensure that
# trailing space matches opening space
need_space = (prev_end, start != prev_end)
elif need_space and start == prev_end:
# A needed opening space was not found
yield prev_end, "E225 missing whitespace around operator"
need_space = False
prev_type = token_type
prev_text = text
prev_end = end | [
"def",
"missing_whitespace_around_operator",
"(",
"logical_line",
",",
"tokens",
")",
":",
"parens",
"=",
"0",
"need_space",
"=",
"False",
"prev_type",
"=",
"tokenize",
".",
"OP",
"prev_text",
"=",
"prev_end",
"=",
"None",
"for",
"token_type",
",",
"text",
","... | r"""Surround operators with a single space on either side.
- Always surround these binary operators with a single space on
either side: assignment (=), augmented assignment (+=, -= etc.),
comparisons (==, <, >, !=, <=, >=, in, not in, is, is not),
Booleans (and, or, not).
- If operators with different priorities are used, consider adding
whitespace around the operators with the lowest priorities.
Okay: i = i + 1
Okay: submitted += 1
Okay: x = x * 2 - 1
Okay: hypot2 = x * x + y * y
Okay: c = (a + b) * (a - b)
Okay: foo(bar, key='word', *args, **kwargs)
Okay: alpha[:-i]
E225: i=i+1
E225: submitted +=1
E225: x = x /2 - 1
E225: z = x **y
E226: c = (a+b) * (a-b)
E226: hypot2 = x*x + y*y
E227: c = a|b
E228: msg = fmt%(errno, errmsg) | [
"r",
"Surround",
"operators",
"with",
"a",
"single",
"space",
"on",
"either",
"side",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L699-L788 | train | 209,845 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | whitespace_around_comma | def whitespace_around_comma(logical_line):
r"""Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2)
E241: a = (1, 2)
E242: a = (1,\t2)
"""
line = logical_line
for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line):
found = m.start() + 1
if '\t' in m.group():
yield found, "E242 tab after '%s'" % m.group()[0]
else:
yield found, "E241 multiple spaces after '%s'" % m.group()[0] | python | def whitespace_around_comma(logical_line):
r"""Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2)
E241: a = (1, 2)
E242: a = (1,\t2)
"""
line = logical_line
for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line):
found = m.start() + 1
if '\t' in m.group():
yield found, "E242 tab after '%s'" % m.group()[0]
else:
yield found, "E241 multiple spaces after '%s'" % m.group()[0] | [
"def",
"whitespace_around_comma",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"for",
"m",
"in",
"WHITESPACE_AFTER_COMMA_REGEX",
".",
"finditer",
"(",
"line",
")",
":",
"found",
"=",
"m",
".",
"start",
"(",
")",
"+",
"1",
"if",
"'\\t'",
"in"... | r"""Avoid extraneous whitespace after a comma or a colon.
Note: these checks are disabled by default
Okay: a = (1, 2)
E241: a = (1, 2)
E242: a = (1,\t2) | [
"r",
"Avoid",
"extraneous",
"whitespace",
"after",
"a",
"comma",
"or",
"a",
"colon",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L791-L806 | train | 209,846 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | whitespace_around_named_parameter_equals | def whitespace_around_named_parameter_equals(logical_line, tokens):
r"""Don't use spaces around the '=' sign in function arguments.
Don't use spaces around the '=' sign when used to indicate a
keyword argument or a default parameter value.
Okay: def complex(real, imag=0.0):
Okay: return magic(r=real, i=imag)
Okay: boolean(a == b)
Okay: boolean(a != b)
Okay: boolean(a <= b)
Okay: boolean(a >= b)
Okay: def foo(arg: int = 42):
Okay: async def foo(arg: int = 42):
E251: def complex(real, imag = 0.0):
E251: return magic(r = real, i = imag)
"""
parens = 0
no_space = False
prev_end = None
annotated_func_arg = False
in_def = bool(STARTSWITH_DEF_REGEX.match(logical_line))
message = "E251 unexpected spaces around keyword / parameter equals"
for token_type, text, start, end, line in tokens:
if token_type == tokenize.NL:
continue
if no_space:
no_space = False
if start != prev_end:
yield (prev_end, message)
if token_type == tokenize.OP:
if text in '([':
parens += 1
elif text in ')]':
parens -= 1
elif in_def and text == ':' and parens == 1:
annotated_func_arg = True
elif parens and text == ',' and parens == 1:
annotated_func_arg = False
elif parens and text == '=' and not annotated_func_arg:
no_space = True
if start != prev_end:
yield (prev_end, message)
if not parens:
annotated_func_arg = False
prev_end = end | python | def whitespace_around_named_parameter_equals(logical_line, tokens):
r"""Don't use spaces around the '=' sign in function arguments.
Don't use spaces around the '=' sign when used to indicate a
keyword argument or a default parameter value.
Okay: def complex(real, imag=0.0):
Okay: return magic(r=real, i=imag)
Okay: boolean(a == b)
Okay: boolean(a != b)
Okay: boolean(a <= b)
Okay: boolean(a >= b)
Okay: def foo(arg: int = 42):
Okay: async def foo(arg: int = 42):
E251: def complex(real, imag = 0.0):
E251: return magic(r = real, i = imag)
"""
parens = 0
no_space = False
prev_end = None
annotated_func_arg = False
in_def = bool(STARTSWITH_DEF_REGEX.match(logical_line))
message = "E251 unexpected spaces around keyword / parameter equals"
for token_type, text, start, end, line in tokens:
if token_type == tokenize.NL:
continue
if no_space:
no_space = False
if start != prev_end:
yield (prev_end, message)
if token_type == tokenize.OP:
if text in '([':
parens += 1
elif text in ')]':
parens -= 1
elif in_def and text == ':' and parens == 1:
annotated_func_arg = True
elif parens and text == ',' and parens == 1:
annotated_func_arg = False
elif parens and text == '=' and not annotated_func_arg:
no_space = True
if start != prev_end:
yield (prev_end, message)
if not parens:
annotated_func_arg = False
prev_end = end | [
"def",
"whitespace_around_named_parameter_equals",
"(",
"logical_line",
",",
"tokens",
")",
":",
"parens",
"=",
"0",
"no_space",
"=",
"False",
"prev_end",
"=",
"None",
"annotated_func_arg",
"=",
"False",
"in_def",
"=",
"bool",
"(",
"STARTSWITH_DEF_REGEX",
".",
"ma... | r"""Don't use spaces around the '=' sign in function arguments.
Don't use spaces around the '=' sign when used to indicate a
keyword argument or a default parameter value.
Okay: def complex(real, imag=0.0):
Okay: return magic(r=real, i=imag)
Okay: boolean(a == b)
Okay: boolean(a != b)
Okay: boolean(a <= b)
Okay: boolean(a >= b)
Okay: def foo(arg: int = 42):
Okay: async def foo(arg: int = 42):
E251: def complex(real, imag = 0.0):
E251: return magic(r = real, i = imag) | [
"r",
"Don",
"t",
"use",
"spaces",
"around",
"the",
"=",
"sign",
"in",
"function",
"arguments",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L809-L856 | train | 209,847 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | whitespace_before_comment | def whitespace_before_comment(logical_line, tokens):
r"""Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement. Inline
comments should be separated by at least two spaces from the statement.
They should start with a # and a single space.
Each line of a block comment starts with a # and a single space
(unless it is indented text inside the comment).
Okay: x = x + 1 # Increment x
Okay: x = x + 1 # Increment x
Okay: # Block comment
E261: x = x + 1 # Increment x
E262: x = x + 1 #Increment x
E262: x = x + 1 # Increment x
E265: #Block comment
E266: ### Block comment
"""
prev_end = (0, 0)
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
inline_comment = line[:start[1]].strip()
if inline_comment:
if prev_end[0] == start[0] and start[1] < prev_end[1] + 2:
yield (prev_end,
"E261 at least two spaces before inline comment")
symbol, sp, comment = text.partition(' ')
bad_prefix = symbol not in '#:' and (symbol.lstrip('#')[:1] or '#')
if inline_comment:
if bad_prefix or comment[:1] in WHITESPACE:
yield start, "E262 inline comment should start with '# '"
elif bad_prefix and (bad_prefix != '!' or start[0] > 1):
if bad_prefix != '#':
yield start, "E265 block comment should start with '# '"
elif comment:
yield start, "E266 too many leading '#' for block comment"
elif token_type != tokenize.NL:
prev_end = end | python | def whitespace_before_comment(logical_line, tokens):
r"""Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement. Inline
comments should be separated by at least two spaces from the statement.
They should start with a # and a single space.
Each line of a block comment starts with a # and a single space
(unless it is indented text inside the comment).
Okay: x = x + 1 # Increment x
Okay: x = x + 1 # Increment x
Okay: # Block comment
E261: x = x + 1 # Increment x
E262: x = x + 1 #Increment x
E262: x = x + 1 # Increment x
E265: #Block comment
E266: ### Block comment
"""
prev_end = (0, 0)
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
inline_comment = line[:start[1]].strip()
if inline_comment:
if prev_end[0] == start[0] and start[1] < prev_end[1] + 2:
yield (prev_end,
"E261 at least two spaces before inline comment")
symbol, sp, comment = text.partition(' ')
bad_prefix = symbol not in '#:' and (symbol.lstrip('#')[:1] or '#')
if inline_comment:
if bad_prefix or comment[:1] in WHITESPACE:
yield start, "E262 inline comment should start with '# '"
elif bad_prefix and (bad_prefix != '!' or start[0] > 1):
if bad_prefix != '#':
yield start, "E265 block comment should start with '# '"
elif comment:
yield start, "E266 too many leading '#' for block comment"
elif token_type != tokenize.NL:
prev_end = end | [
"def",
"whitespace_before_comment",
"(",
"logical_line",
",",
"tokens",
")",
":",
"prev_end",
"=",
"(",
"0",
",",
"0",
")",
"for",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"line",
"in",
"tokens",
":",
"if",
"token_type",
"==",
"tokenize"... | r"""Separate inline comments by at least two spaces.
An inline comment is a comment on the same line as a statement. Inline
comments should be separated by at least two spaces from the statement.
They should start with a # and a single space.
Each line of a block comment starts with a # and a single space
(unless it is indented text inside the comment).
Okay: x = x + 1 # Increment x
Okay: x = x + 1 # Increment x
Okay: # Block comment
E261: x = x + 1 # Increment x
E262: x = x + 1 #Increment x
E262: x = x + 1 # Increment x
E265: #Block comment
E266: ### Block comment | [
"r",
"Separate",
"inline",
"comments",
"by",
"at",
"least",
"two",
"spaces",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L859-L897 | train | 209,848 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | imports_on_separate_lines | def imports_on_separate_lines(logical_line):
r"""Place imports on separate lines.
Okay: import os\nimport sys
E401: import sys, os
Okay: from subprocess import Popen, PIPE
Okay: from myclas import MyClass
Okay: from foo.bar.yourclass import YourClass
Okay: import myclass
Okay: import foo.bar.yourclass
"""
line = logical_line
if line.startswith('import '):
found = line.find(',')
if -1 < found and ';' not in line[:found]:
yield found, "E401 multiple imports on one line" | python | def imports_on_separate_lines(logical_line):
r"""Place imports on separate lines.
Okay: import os\nimport sys
E401: import sys, os
Okay: from subprocess import Popen, PIPE
Okay: from myclas import MyClass
Okay: from foo.bar.yourclass import YourClass
Okay: import myclass
Okay: import foo.bar.yourclass
"""
line = logical_line
if line.startswith('import '):
found = line.find(',')
if -1 < found and ';' not in line[:found]:
yield found, "E401 multiple imports on one line" | [
"def",
"imports_on_separate_lines",
"(",
"logical_line",
")",
":",
"line",
"=",
"logical_line",
"if",
"line",
".",
"startswith",
"(",
"'import '",
")",
":",
"found",
"=",
"line",
".",
"find",
"(",
"','",
")",
"if",
"-",
"1",
"<",
"found",
"and",
"';'",
... | r"""Place imports on separate lines.
Okay: import os\nimport sys
E401: import sys, os
Okay: from subprocess import Popen, PIPE
Okay: from myclas import MyClass
Okay: from foo.bar.yourclass import YourClass
Okay: import myclass
Okay: import foo.bar.yourclass | [
"r",
"Place",
"imports",
"on",
"separate",
"lines",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L900-L916 | train | 209,849 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | module_imports_on_top_of_file | def module_imports_on_top_of_file(
logical_line, indent_level, checker_state, noqa):
r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module comments
and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is a comment\nimport os
Okay: '''this is a module docstring'''\nimport os
Okay: r'''this is a module docstring'''\nimport os
Okay:
try:\n\timport x\nexcept ImportError:\n\tpass\nelse:\n\tpass\nimport y
Okay:
try:\n\timport x\nexcept ImportError:\n\tpass\nfinally:\n\tpass\nimport y
E402: a=1\nimport os
E402: 'One string'\n"Two string"\nimport os
E402: a=1\nfrom sys import x
Okay: if x:\n import os
"""
def is_string_literal(line):
if line[0] in 'uUbB':
line = line[1:]
if line and line[0] in 'rR':
line = line[1:]
return line and (line[0] == '"' or line[0] == "'")
allowed_try_keywords = ('try', 'except', 'else', 'finally')
if indent_level: # Allow imports in conditional statements or functions
return
if not logical_line: # Allow empty lines or comments
return
if noqa:
return
line = logical_line
if line.startswith('import ') or line.startswith('from '):
if checker_state.get('seen_non_imports', False):
yield 0, "E402 module level import not at top of file"
elif re.match(DUNDER_REGEX, line):
return
elif any(line.startswith(kw) for kw in allowed_try_keywords):
# Allow try, except, else, finally keywords intermixed with imports in
# order to support conditional importing
return
elif is_string_literal(line):
# The first literal is a docstring, allow it. Otherwise, report error.
if checker_state.get('seen_docstring', False):
checker_state['seen_non_imports'] = True
else:
checker_state['seen_docstring'] = True
else:
checker_state['seen_non_imports'] = True | python | def module_imports_on_top_of_file(
logical_line, indent_level, checker_state, noqa):
r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module comments
and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is a comment\nimport os
Okay: '''this is a module docstring'''\nimport os
Okay: r'''this is a module docstring'''\nimport os
Okay:
try:\n\timport x\nexcept ImportError:\n\tpass\nelse:\n\tpass\nimport y
Okay:
try:\n\timport x\nexcept ImportError:\n\tpass\nfinally:\n\tpass\nimport y
E402: a=1\nimport os
E402: 'One string'\n"Two string"\nimport os
E402: a=1\nfrom sys import x
Okay: if x:\n import os
"""
def is_string_literal(line):
if line[0] in 'uUbB':
line = line[1:]
if line and line[0] in 'rR':
line = line[1:]
return line and (line[0] == '"' or line[0] == "'")
allowed_try_keywords = ('try', 'except', 'else', 'finally')
if indent_level: # Allow imports in conditional statements or functions
return
if not logical_line: # Allow empty lines or comments
return
if noqa:
return
line = logical_line
if line.startswith('import ') or line.startswith('from '):
if checker_state.get('seen_non_imports', False):
yield 0, "E402 module level import not at top of file"
elif re.match(DUNDER_REGEX, line):
return
elif any(line.startswith(kw) for kw in allowed_try_keywords):
# Allow try, except, else, finally keywords intermixed with imports in
# order to support conditional importing
return
elif is_string_literal(line):
# The first literal is a docstring, allow it. Otherwise, report error.
if checker_state.get('seen_docstring', False):
checker_state['seen_non_imports'] = True
else:
checker_state['seen_docstring'] = True
else:
checker_state['seen_non_imports'] = True | [
"def",
"module_imports_on_top_of_file",
"(",
"logical_line",
",",
"indent_level",
",",
"checker_state",
",",
"noqa",
")",
":",
"def",
"is_string_literal",
"(",
"line",
")",
":",
"if",
"line",
"[",
"0",
"]",
"in",
"'uUbB'",
":",
"line",
"=",
"line",
"[",
"1... | r"""Place imports at the top of the file.
Always put imports at the top of the file, just after any module comments
and docstrings, and before module globals and constants.
Okay: import os
Okay: # this is a comment\nimport os
Okay: '''this is a module docstring'''\nimport os
Okay: r'''this is a module docstring'''\nimport os
Okay:
try:\n\timport x\nexcept ImportError:\n\tpass\nelse:\n\tpass\nimport y
Okay:
try:\n\timport x\nexcept ImportError:\n\tpass\nfinally:\n\tpass\nimport y
E402: a=1\nimport os
E402: 'One string'\n"Two string"\nimport os
E402: a=1\nfrom sys import x
Okay: if x:\n import os | [
"r",
"Place",
"imports",
"at",
"the",
"top",
"of",
"the",
"file",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L919-L972 | train | 209,850 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | explicit_line_join | def explicit_line_join(logical_line, tokens):
r"""Avoid explicit line join between brackets.
The preferred way of wrapping long lines is by using Python's implied line
continuation inside parentheses, brackets and braces. Long lines can be
broken over multiple lines by wrapping expressions in parentheses. These
should be used in preference to using a backslash for line continuation.
E502: aaa = [123, \\n 123]
E502: aaa = ("bbb " \\n "ccc")
Okay: aaa = [123,\n 123]
Okay: aaa = ("bbb "\n "ccc")
Okay: aaa = "bbb " \\n "ccc"
Okay: aaa = 123 # \\
"""
prev_start = prev_end = parens = 0
comment = False
backslash = None
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
comment = True
if start[0] != prev_start and parens and backslash and not comment:
yield backslash, "E502 the backslash is redundant between brackets"
if end[0] != prev_end:
if line.rstrip('\r\n').endswith('\\'):
backslash = (end[0], len(line.splitlines()[-1]) - 1)
else:
backslash = None
prev_start = prev_end = end[0]
else:
prev_start = start[0]
if token_type == tokenize.OP:
if text in '([{':
parens += 1
elif text in ')]}':
parens -= 1 | python | def explicit_line_join(logical_line, tokens):
r"""Avoid explicit line join between brackets.
The preferred way of wrapping long lines is by using Python's implied line
continuation inside parentheses, brackets and braces. Long lines can be
broken over multiple lines by wrapping expressions in parentheses. These
should be used in preference to using a backslash for line continuation.
E502: aaa = [123, \\n 123]
E502: aaa = ("bbb " \\n "ccc")
Okay: aaa = [123,\n 123]
Okay: aaa = ("bbb "\n "ccc")
Okay: aaa = "bbb " \\n "ccc"
Okay: aaa = 123 # \\
"""
prev_start = prev_end = parens = 0
comment = False
backslash = None
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
comment = True
if start[0] != prev_start and parens and backslash and not comment:
yield backslash, "E502 the backslash is redundant between brackets"
if end[0] != prev_end:
if line.rstrip('\r\n').endswith('\\'):
backslash = (end[0], len(line.splitlines()[-1]) - 1)
else:
backslash = None
prev_start = prev_end = end[0]
else:
prev_start = start[0]
if token_type == tokenize.OP:
if text in '([{':
parens += 1
elif text in ')]}':
parens -= 1 | [
"def",
"explicit_line_join",
"(",
"logical_line",
",",
"tokens",
")",
":",
"prev_start",
"=",
"prev_end",
"=",
"parens",
"=",
"0",
"comment",
"=",
"False",
"backslash",
"=",
"None",
"for",
"token_type",
",",
"text",
",",
"start",
",",
"end",
",",
"line",
... | r"""Avoid explicit line join between brackets.
The preferred way of wrapping long lines is by using Python's implied line
continuation inside parentheses, brackets and braces. Long lines can be
broken over multiple lines by wrapping expressions in parentheses. These
should be used in preference to using a backslash for line continuation.
E502: aaa = [123, \\n 123]
E502: aaa = ("bbb " \\n "ccc")
Okay: aaa = [123,\n 123]
Okay: aaa = ("bbb "\n "ccc")
Okay: aaa = "bbb " \\n "ccc"
Okay: aaa = 123 # \\ | [
"r",
"Avoid",
"explicit",
"line",
"join",
"between",
"brackets",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1035-L1071 | train | 209,851 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | break_around_binary_operator | def break_around_binary_operator(logical_line, tokens):
r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
Okay: (width == 0 +\n height == 0)
Okay: foo(\n -x)
Okay: foo(x\n [])
Okay: x = '''\n''' + ''
Okay: foo(x,\n -y)
Okay: foo(x, # comment\n -y)
Okay: var = (1 &\n ~2)
Okay: var = (1 /\n -2)
Okay: var = (1 +\n -1 +\n -2)
"""
def is_binary_operator(token_type, text):
# The % character is strictly speaking a binary operator, but the
# common usage seems to be to put it next to the format parameters,
# after a line break.
return ((token_type == tokenize.OP or text in ['and', 'or']) and
text not in "()[]{},:.;@=%~")
line_break = False
unary_context = True
# Previous non-newline token types and text
previous_token_type = None
previous_text = None
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
continue
if ('\n' in text or '\r' in text) and token_type != tokenize.STRING:
line_break = True
else:
if (is_binary_operator(token_type, text) and line_break and
not unary_context and
not is_binary_operator(previous_token_type,
previous_text)):
yield start, "W503 line break before binary operator"
unary_context = text in '([{,;'
line_break = False
previous_token_type = token_type
previous_text = text | python | def break_around_binary_operator(logical_line, tokens):
r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
Okay: (width == 0 +\n height == 0)
Okay: foo(\n -x)
Okay: foo(x\n [])
Okay: x = '''\n''' + ''
Okay: foo(x,\n -y)
Okay: foo(x, # comment\n -y)
Okay: var = (1 &\n ~2)
Okay: var = (1 /\n -2)
Okay: var = (1 +\n -1 +\n -2)
"""
def is_binary_operator(token_type, text):
# The % character is strictly speaking a binary operator, but the
# common usage seems to be to put it next to the format parameters,
# after a line break.
return ((token_type == tokenize.OP or text in ['and', 'or']) and
text not in "()[]{},:.;@=%~")
line_break = False
unary_context = True
# Previous non-newline token types and text
previous_token_type = None
previous_text = None
for token_type, text, start, end, line in tokens:
if token_type == tokenize.COMMENT:
continue
if ('\n' in text or '\r' in text) and token_type != tokenize.STRING:
line_break = True
else:
if (is_binary_operator(token_type, text) and line_break and
not unary_context and
not is_binary_operator(previous_token_type,
previous_text)):
yield start, "W503 line break before binary operator"
unary_context = text in '([{,;'
line_break = False
previous_token_type = token_type
previous_text = text | [
"def",
"break_around_binary_operator",
"(",
"logical_line",
",",
"tokens",
")",
":",
"def",
"is_binary_operator",
"(",
"token_type",
",",
"text",
")",
":",
"# The % character is strictly speaking a binary operator, but the",
"# common usage seems to be to put it next to the format ... | r"""
Avoid breaks before binary operators.
The preferred place to break around a binary operator is after the
operator, not before it.
W503: (width == 0\n + height == 0)
W503: (width == 0\n and height == 0)
Okay: (width == 0 +\n height == 0)
Okay: foo(\n -x)
Okay: foo(x\n [])
Okay: x = '''\n''' + ''
Okay: foo(x,\n -y)
Okay: foo(x, # comment\n -y)
Okay: var = (1 &\n ~2)
Okay: var = (1 /\n -2)
Okay: var = (1 +\n -1 +\n -2) | [
"r",
"Avoid",
"breaks",
"before",
"binary",
"operators",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1074-L1120 | train | 209,852 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | comparison_to_singleton | def comparison_to_singleton(logical_line, noqa):
r"""Comparison to singletons should use "is" or "is not".
Comparisons to singletons like None should always be done
with "is" or "is not", never the equality operators.
Okay: if arg is not None:
E711: if arg != None:
E711: if None == arg:
E712: if arg == True:
E712: if False == arg:
Also, beware of writing if x when you really mean if x is not None --
e.g. when testing whether a variable or argument that defaults to None was
set to some other value. The other value might have a type (such as a
container) that could be false in a boolean context!
"""
match = not noqa and COMPARE_SINGLETON_REGEX.search(logical_line)
if match:
singleton = match.group(1) or match.group(3)
same = (match.group(2) == '==')
msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton)
if singleton in ('None',):
code = 'E711'
else:
code = 'E712'
nonzero = ((singleton == 'True' and same) or
(singleton == 'False' and not same))
msg += " or 'if %scond:'" % ('' if nonzero else 'not ')
yield match.start(2), ("%s comparison to %s should be %s" %
(code, singleton, msg)) | python | def comparison_to_singleton(logical_line, noqa):
r"""Comparison to singletons should use "is" or "is not".
Comparisons to singletons like None should always be done
with "is" or "is not", never the equality operators.
Okay: if arg is not None:
E711: if arg != None:
E711: if None == arg:
E712: if arg == True:
E712: if False == arg:
Also, beware of writing if x when you really mean if x is not None --
e.g. when testing whether a variable or argument that defaults to None was
set to some other value. The other value might have a type (such as a
container) that could be false in a boolean context!
"""
match = not noqa and COMPARE_SINGLETON_REGEX.search(logical_line)
if match:
singleton = match.group(1) or match.group(3)
same = (match.group(2) == '==')
msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton)
if singleton in ('None',):
code = 'E711'
else:
code = 'E712'
nonzero = ((singleton == 'True' and same) or
(singleton == 'False' and not same))
msg += " or 'if %scond:'" % ('' if nonzero else 'not ')
yield match.start(2), ("%s comparison to %s should be %s" %
(code, singleton, msg)) | [
"def",
"comparison_to_singleton",
"(",
"logical_line",
",",
"noqa",
")",
":",
"match",
"=",
"not",
"noqa",
"and",
"COMPARE_SINGLETON_REGEX",
".",
"search",
"(",
"logical_line",
")",
"if",
"match",
":",
"singleton",
"=",
"match",
".",
"group",
"(",
"1",
")",
... | r"""Comparison to singletons should use "is" or "is not".
Comparisons to singletons like None should always be done
with "is" or "is not", never the equality operators.
Okay: if arg is not None:
E711: if arg != None:
E711: if None == arg:
E712: if arg == True:
E712: if False == arg:
Also, beware of writing if x when you really mean if x is not None --
e.g. when testing whether a variable or argument that defaults to None was
set to some other value. The other value might have a type (such as a
container) that could be false in a boolean context! | [
"r",
"Comparison",
"to",
"singletons",
"should",
"use",
"is",
"or",
"is",
"not",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1123-L1154 | train | 209,853 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | comparison_negative | def comparison_negative(logical_line):
r"""Negative comparison should be done using "not in" and "is not".
Okay: if x not in y:\n pass
Okay: assert (X in Y or X is Z)
Okay: if not (X in Y):\n pass
Okay: zz = x is not y
E713: Z = not X in Y
E713: if not X.B in Y:\n pass
E714: if not X is Y:\n pass
E714: Z = not X.B is Y
"""
match = COMPARE_NEGATIVE_REGEX.search(logical_line)
if match:
pos = match.start(1)
if match.group(2) == 'in':
yield pos, "E713 test for membership should be 'not in'"
else:
yield pos, "E714 test for object identity should be 'is not'" | python | def comparison_negative(logical_line):
r"""Negative comparison should be done using "not in" and "is not".
Okay: if x not in y:\n pass
Okay: assert (X in Y or X is Z)
Okay: if not (X in Y):\n pass
Okay: zz = x is not y
E713: Z = not X in Y
E713: if not X.B in Y:\n pass
E714: if not X is Y:\n pass
E714: Z = not X.B is Y
"""
match = COMPARE_NEGATIVE_REGEX.search(logical_line)
if match:
pos = match.start(1)
if match.group(2) == 'in':
yield pos, "E713 test for membership should be 'not in'"
else:
yield pos, "E714 test for object identity should be 'is not'" | [
"def",
"comparison_negative",
"(",
"logical_line",
")",
":",
"match",
"=",
"COMPARE_NEGATIVE_REGEX",
".",
"search",
"(",
"logical_line",
")",
"if",
"match",
":",
"pos",
"=",
"match",
".",
"start",
"(",
"1",
")",
"if",
"match",
".",
"group",
"(",
"2",
")"... | r"""Negative comparison should be done using "not in" and "is not".
Okay: if x not in y:\n pass
Okay: assert (X in Y or X is Z)
Okay: if not (X in Y):\n pass
Okay: zz = x is not y
E713: Z = not X in Y
E713: if not X.B in Y:\n pass
E714: if not X is Y:\n pass
E714: Z = not X.B is Y | [
"r",
"Negative",
"comparison",
"should",
"be",
"done",
"using",
"not",
"in",
"and",
"is",
"not",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1157-L1175 | train | 209,854 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | bare_except | def bare_except(logical_line, noqa):
r"""When catching exceptions, mention specific exceptions whenever possible.
Okay: except Exception:
Okay: except BaseException:
E722: except:
"""
if noqa:
return
regex = re.compile(r"except\s*:")
match = regex.match(logical_line)
if match:
yield match.start(), "E722 do not use bare except'" | python | def bare_except(logical_line, noqa):
r"""When catching exceptions, mention specific exceptions whenever possible.
Okay: except Exception:
Okay: except BaseException:
E722: except:
"""
if noqa:
return
regex = re.compile(r"except\s*:")
match = regex.match(logical_line)
if match:
yield match.start(), "E722 do not use bare except'" | [
"def",
"bare_except",
"(",
"logical_line",
",",
"noqa",
")",
":",
"if",
"noqa",
":",
"return",
"regex",
"=",
"re",
".",
"compile",
"(",
"r\"except\\s*:\"",
")",
"match",
"=",
"regex",
".",
"match",
"(",
"logical_line",
")",
"if",
"match",
":",
"yield",
... | r"""When catching exceptions, mention specific exceptions whenever possible.
Okay: except Exception:
Okay: except BaseException:
E722: except: | [
"r",
"When",
"catching",
"exceptions",
"mention",
"specific",
"exceptions",
"whenever",
"possible",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1201-L1214 | train | 209,855 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | ambiguous_identifier | def ambiguous_identifier(logical_line, tokens):
r"""Never use the characters 'l', 'O', or 'I' as variable names.
In some fonts, these characters are indistinguishable from the numerals
one and zero. When tempted to use 'l', use 'L' instead.
Okay: L = 0
Okay: o = 123
Okay: i = 42
E741: l = 0
E741: O = 123
E741: I = 42
Variables can be bound in several other contexts, including class and
function definitions, 'global' and 'nonlocal' statements, exception
handlers, and 'with' statements.
Okay: except AttributeError as o:
Okay: with lock as L:
E741: except AttributeError as O:
E741: with lock as l:
E741: global I
E741: nonlocal l
E742: class I(object):
E743: def l(x):
"""
idents_to_avoid = ('l', 'O', 'I')
prev_type, prev_text, prev_start, prev_end, __ = tokens[0]
for token_type, text, start, end, line in tokens[1:]:
ident = pos = None
# identifiers on the lhs of an assignment operator
if token_type == tokenize.OP and '=' in text:
if prev_text in idents_to_avoid:
ident = prev_text
pos = prev_start
# identifiers bound to a value with 'as', 'global', or 'nonlocal'
if prev_text in ('as', 'global', 'nonlocal'):
if text in idents_to_avoid:
ident = text
pos = start
if prev_text == 'class':
if text in idents_to_avoid:
yield start, "E742 ambiguous class definition '%s'" % text
if prev_text == 'def':
if text in idents_to_avoid:
yield start, "E743 ambiguous function definition '%s'" % text
if ident:
yield pos, "E741 ambiguous variable name '%s'" % ident
prev_text = text
prev_start = start | python | def ambiguous_identifier(logical_line, tokens):
r"""Never use the characters 'l', 'O', or 'I' as variable names.
In some fonts, these characters are indistinguishable from the numerals
one and zero. When tempted to use 'l', use 'L' instead.
Okay: L = 0
Okay: o = 123
Okay: i = 42
E741: l = 0
E741: O = 123
E741: I = 42
Variables can be bound in several other contexts, including class and
function definitions, 'global' and 'nonlocal' statements, exception
handlers, and 'with' statements.
Okay: except AttributeError as o:
Okay: with lock as L:
E741: except AttributeError as O:
E741: with lock as l:
E741: global I
E741: nonlocal l
E742: class I(object):
E743: def l(x):
"""
idents_to_avoid = ('l', 'O', 'I')
prev_type, prev_text, prev_start, prev_end, __ = tokens[0]
for token_type, text, start, end, line in tokens[1:]:
ident = pos = None
# identifiers on the lhs of an assignment operator
if token_type == tokenize.OP and '=' in text:
if prev_text in idents_to_avoid:
ident = prev_text
pos = prev_start
# identifiers bound to a value with 'as', 'global', or 'nonlocal'
if prev_text in ('as', 'global', 'nonlocal'):
if text in idents_to_avoid:
ident = text
pos = start
if prev_text == 'class':
if text in idents_to_avoid:
yield start, "E742 ambiguous class definition '%s'" % text
if prev_text == 'def':
if text in idents_to_avoid:
yield start, "E743 ambiguous function definition '%s'" % text
if ident:
yield pos, "E741 ambiguous variable name '%s'" % ident
prev_text = text
prev_start = start | [
"def",
"ambiguous_identifier",
"(",
"logical_line",
",",
"tokens",
")",
":",
"idents_to_avoid",
"=",
"(",
"'l'",
",",
"'O'",
",",
"'I'",
")",
"prev_type",
",",
"prev_text",
",",
"prev_start",
",",
"prev_end",
",",
"__",
"=",
"tokens",
"[",
"0",
"]",
"for... | r"""Never use the characters 'l', 'O', or 'I' as variable names.
In some fonts, these characters are indistinguishable from the numerals
one and zero. When tempted to use 'l', use 'L' instead.
Okay: L = 0
Okay: o = 123
Okay: i = 42
E741: l = 0
E741: O = 123
E741: I = 42
Variables can be bound in several other contexts, including class and
function definitions, 'global' and 'nonlocal' statements, exception
handlers, and 'with' statements.
Okay: except AttributeError as o:
Okay: with lock as L:
E741: except AttributeError as O:
E741: with lock as l:
E741: global I
E741: nonlocal l
E742: class I(object):
E743: def l(x): | [
"r",
"Never",
"use",
"the",
"characters",
"l",
"O",
"or",
"I",
"as",
"variable",
"names",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1217-L1266 | train | 209,856 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | expand_indent | def expand_indent(line):
r"""Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\t')
8
>>> expand_indent(' \t')
8
>>> expand_indent(' \t')
16
"""
if '\t' not in line:
return len(line) - len(line.lstrip())
result = 0
for char in line:
if char == '\t':
result = result // 8 * 8 + 8
elif char == ' ':
result += 1
else:
break
return result | python | def expand_indent(line):
r"""Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\t')
8
>>> expand_indent(' \t')
8
>>> expand_indent(' \t')
16
"""
if '\t' not in line:
return len(line) - len(line.lstrip())
result = 0
for char in line:
if char == '\t':
result = result // 8 * 8 + 8
elif char == ' ':
result += 1
else:
break
return result | [
"def",
"expand_indent",
"(",
"line",
")",
":",
"if",
"'\\t'",
"not",
"in",
"line",
":",
"return",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
")",
")",
"result",
"=",
"0",
"for",
"char",
"in",
"line",
":",
"if",
"char",
... | r"""Return the amount of indentation.
Tabs are expanded to the next multiple of 8.
>>> expand_indent(' ')
4
>>> expand_indent('\t')
8
>>> expand_indent(' \t')
8
>>> expand_indent(' \t')
16 | [
"r",
"Return",
"the",
"amount",
"of",
"indentation",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1350-L1374 | train | 209,857 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | parse_udiff | def parse_udiff(diff, patterns=None, parent='.'):
"""Return a dictionary of matching lines."""
# For each file of the diff, the entry key is the filename,
# and the value is a set of row numbers to consider.
rv = {}
path = nrows = None
for line in diff.splitlines():
if nrows:
if line[:1] != '-':
nrows -= 1
continue
if line[:3] == '@@ ':
hunk_match = HUNK_REGEX.match(line)
(row, nrows) = [int(g or '1') for g in hunk_match.groups()]
rv[path].update(range(row, row + nrows))
elif line[:3] == '+++':
path = line[4:].split('\t', 1)[0]
if path[:2] == 'b/':
path = path[2:]
rv[path] = set()
return dict([(os.path.join(parent, path), rows)
for (path, rows) in rv.items()
if rows and filename_match(path, patterns)]) | python | def parse_udiff(diff, patterns=None, parent='.'):
"""Return a dictionary of matching lines."""
# For each file of the diff, the entry key is the filename,
# and the value is a set of row numbers to consider.
rv = {}
path = nrows = None
for line in diff.splitlines():
if nrows:
if line[:1] != '-':
nrows -= 1
continue
if line[:3] == '@@ ':
hunk_match = HUNK_REGEX.match(line)
(row, nrows) = [int(g or '1') for g in hunk_match.groups()]
rv[path].update(range(row, row + nrows))
elif line[:3] == '+++':
path = line[4:].split('\t', 1)[0]
if path[:2] == 'b/':
path = path[2:]
rv[path] = set()
return dict([(os.path.join(parent, path), rows)
for (path, rows) in rv.items()
if rows and filename_match(path, patterns)]) | [
"def",
"parse_udiff",
"(",
"diff",
",",
"patterns",
"=",
"None",
",",
"parent",
"=",
"'.'",
")",
":",
"# For each file of the diff, the entry key is the filename,",
"# and the value is a set of row numbers to consider.",
"rv",
"=",
"{",
"}",
"path",
"=",
"nrows",
"=",
... | Return a dictionary of matching lines. | [
"Return",
"a",
"dictionary",
"of",
"matching",
"lines",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1397-L1419 | train | 209,858 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | normalize_paths | def normalize_paths(value, parent=os.curdir):
"""Parse a comma-separated list of paths.
Return a list of absolute paths.
"""
if not value:
return []
if isinstance(value, list):
return value
paths = []
for path in value.split(','):
path = path.strip()
if '/' in path:
path = os.path.abspath(os.path.join(parent, path))
paths.append(path.rstrip('/'))
return paths | python | def normalize_paths(value, parent=os.curdir):
"""Parse a comma-separated list of paths.
Return a list of absolute paths.
"""
if not value:
return []
if isinstance(value, list):
return value
paths = []
for path in value.split(','):
path = path.strip()
if '/' in path:
path = os.path.abspath(os.path.join(parent, path))
paths.append(path.rstrip('/'))
return paths | [
"def",
"normalize_paths",
"(",
"value",
",",
"parent",
"=",
"os",
".",
"curdir",
")",
":",
"if",
"not",
"value",
":",
"return",
"[",
"]",
"if",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"return",
"value",
"paths",
"=",
"[",
"]",
"for",
"pa... | Parse a comma-separated list of paths.
Return a list of absolute paths. | [
"Parse",
"a",
"comma",
"-",
"separated",
"list",
"of",
"paths",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1422-L1437 | train | 209,859 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | filename_match | def filename_match(filename, patterns, default=True):
"""Check if patterns contains a pattern that matches filename.
If patterns is unspecified, this always returns True.
"""
if not patterns:
return default
return any(fnmatch(filename, pattern) for pattern in patterns) | python | def filename_match(filename, patterns, default=True):
"""Check if patterns contains a pattern that matches filename.
If patterns is unspecified, this always returns True.
"""
if not patterns:
return default
return any(fnmatch(filename, pattern) for pattern in patterns) | [
"def",
"filename_match",
"(",
"filename",
",",
"patterns",
",",
"default",
"=",
"True",
")",
":",
"if",
"not",
"patterns",
":",
"return",
"default",
"return",
"any",
"(",
"fnmatch",
"(",
"filename",
",",
"pattern",
")",
"for",
"pattern",
"in",
"patterns",
... | Check if patterns contains a pattern that matches filename.
If patterns is unspecified, this always returns True. | [
"Check",
"if",
"patterns",
"contains",
"a",
"pattern",
"that",
"matches",
"filename",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1440-L1447 | train | 209,860 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | register_check | def register_check(check, codes=None):
"""Register a new check object."""
def _add_check(check, kind, codes, args):
if check in _checks[kind]:
_checks[kind][check][0].extend(codes or [])
else:
_checks[kind][check] = (codes or [''], args)
if inspect.isfunction(check):
args = _get_parameters(check)
if args and args[0] in ('physical_line', 'logical_line'):
if codes is None:
codes = ERRORCODE_REGEX.findall(check.__doc__ or '')
_add_check(check, args[0], codes, args)
elif inspect.isclass(check):
if _get_parameters(check.__init__)[:2] == ['self', 'tree']:
_add_check(check, 'tree', codes, None) | python | def register_check(check, codes=None):
"""Register a new check object."""
def _add_check(check, kind, codes, args):
if check in _checks[kind]:
_checks[kind][check][0].extend(codes or [])
else:
_checks[kind][check] = (codes or [''], args)
if inspect.isfunction(check):
args = _get_parameters(check)
if args and args[0] in ('physical_line', 'logical_line'):
if codes is None:
codes = ERRORCODE_REGEX.findall(check.__doc__ or '')
_add_check(check, args[0], codes, args)
elif inspect.isclass(check):
if _get_parameters(check.__init__)[:2] == ['self', 'tree']:
_add_check(check, 'tree', codes, None) | [
"def",
"register_check",
"(",
"check",
",",
"codes",
"=",
"None",
")",
":",
"def",
"_add_check",
"(",
"check",
",",
"kind",
",",
"codes",
",",
"args",
")",
":",
"if",
"check",
"in",
"_checks",
"[",
"kind",
"]",
":",
"_checks",
"[",
"kind",
"]",
"["... | Register a new check object. | [
"Register",
"a",
"new",
"check",
"object",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1485-L1500 | train | 209,861 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | init_checks_registry | def init_checks_registry():
"""Register all globally visible functions.
The first argument name is either 'physical_line' or 'logical_line'.
"""
mod = inspect.getmodule(register_check)
for (name, function) in inspect.getmembers(mod, inspect.isfunction):
register_check(function) | python | def init_checks_registry():
"""Register all globally visible functions.
The first argument name is either 'physical_line' or 'logical_line'.
"""
mod = inspect.getmodule(register_check)
for (name, function) in inspect.getmembers(mod, inspect.isfunction):
register_check(function) | [
"def",
"init_checks_registry",
"(",
")",
":",
"mod",
"=",
"inspect",
".",
"getmodule",
"(",
"register_check",
")",
"for",
"(",
"name",
",",
"function",
")",
"in",
"inspect",
".",
"getmembers",
"(",
"mod",
",",
"inspect",
".",
"isfunction",
")",
":",
"reg... | Register all globally visible functions.
The first argument name is either 'physical_line' or 'logical_line'. | [
"Register",
"all",
"globally",
"visible",
"functions",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1503-L1510 | train | 209,862 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | read_config | def read_config(options, args, arglist, parser):
"""Read and parse configurations.
If a config file is specified on the command line with the "--config"
option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any local
configurations in the current directory or above will be merged together
(in that order) using the read method of ConfigParser.
"""
config = RawConfigParser()
cli_conf = options.config
local_dir = os.curdir
if USER_CONFIG and os.path.isfile(USER_CONFIG):
if options.verbose:
print('user configuration: %s' % USER_CONFIG)
config.read(USER_CONFIG)
parent = tail = args and os.path.abspath(os.path.commonprefix(args))
while tail:
if config.read(os.path.join(parent, fn) for fn in PROJECT_CONFIG):
local_dir = parent
if options.verbose:
print('local configuration: in %s' % parent)
break
(parent, tail) = os.path.split(parent)
if cli_conf and os.path.isfile(cli_conf):
if options.verbose:
print('cli configuration: %s' % cli_conf)
config.read(cli_conf)
pycodestyle_section = None
if config.has_section(parser.prog):
pycodestyle_section = parser.prog
elif config.has_section('pep8'):
pycodestyle_section = 'pep8' # Deprecated
warnings.warn('[pep8] section is deprecated. Use [pycodestyle].')
if pycodestyle_section:
option_list = dict([(o.dest, o.type or o.action)
for o in parser.option_list])
# First, read the default values
(new_options, __) = parser.parse_args([])
# Second, parse the configuration
for opt in config.options(pycodestyle_section):
if opt.replace('_', '-') not in parser.config_options:
print(" unknown option '%s' ignored" % opt)
continue
if options.verbose > 1:
print(" %s = %s" % (opt,
config.get(pycodestyle_section, opt)))
normalized_opt = opt.replace('-', '_')
opt_type = option_list[normalized_opt]
if opt_type in ('int', 'count'):
value = config.getint(pycodestyle_section, opt)
elif opt_type in ('store_true', 'store_false'):
value = config.getboolean(pycodestyle_section, opt)
else:
value = config.get(pycodestyle_section, opt)
if normalized_opt == 'exclude':
value = normalize_paths(value, local_dir)
setattr(new_options, normalized_opt, value)
# Third, overwrite with the command-line options
(options, __) = parser.parse_args(arglist, values=new_options)
options.doctest = options.testsuite = False
return options | python | def read_config(options, args, arglist, parser):
"""Read and parse configurations.
If a config file is specified on the command line with the "--config"
option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any local
configurations in the current directory or above will be merged together
(in that order) using the read method of ConfigParser.
"""
config = RawConfigParser()
cli_conf = options.config
local_dir = os.curdir
if USER_CONFIG and os.path.isfile(USER_CONFIG):
if options.verbose:
print('user configuration: %s' % USER_CONFIG)
config.read(USER_CONFIG)
parent = tail = args and os.path.abspath(os.path.commonprefix(args))
while tail:
if config.read(os.path.join(parent, fn) for fn in PROJECT_CONFIG):
local_dir = parent
if options.verbose:
print('local configuration: in %s' % parent)
break
(parent, tail) = os.path.split(parent)
if cli_conf and os.path.isfile(cli_conf):
if options.verbose:
print('cli configuration: %s' % cli_conf)
config.read(cli_conf)
pycodestyle_section = None
if config.has_section(parser.prog):
pycodestyle_section = parser.prog
elif config.has_section('pep8'):
pycodestyle_section = 'pep8' # Deprecated
warnings.warn('[pep8] section is deprecated. Use [pycodestyle].')
if pycodestyle_section:
option_list = dict([(o.dest, o.type or o.action)
for o in parser.option_list])
# First, read the default values
(new_options, __) = parser.parse_args([])
# Second, parse the configuration
for opt in config.options(pycodestyle_section):
if opt.replace('_', '-') not in parser.config_options:
print(" unknown option '%s' ignored" % opt)
continue
if options.verbose > 1:
print(" %s = %s" % (opt,
config.get(pycodestyle_section, opt)))
normalized_opt = opt.replace('-', '_')
opt_type = option_list[normalized_opt]
if opt_type in ('int', 'count'):
value = config.getint(pycodestyle_section, opt)
elif opt_type in ('store_true', 'store_false'):
value = config.getboolean(pycodestyle_section, opt)
else:
value = config.get(pycodestyle_section, opt)
if normalized_opt == 'exclude':
value = normalize_paths(value, local_dir)
setattr(new_options, normalized_opt, value)
# Third, overwrite with the command-line options
(options, __) = parser.parse_args(arglist, values=new_options)
options.doctest = options.testsuite = False
return options | [
"def",
"read_config",
"(",
"options",
",",
"args",
",",
"arglist",
",",
"parser",
")",
":",
"config",
"=",
"RawConfigParser",
"(",
")",
"cli_conf",
"=",
"options",
".",
"config",
"local_dir",
"=",
"os",
".",
"curdir",
"if",
"USER_CONFIG",
"and",
"os",
".... | Read and parse configurations.
If a config file is specified on the command line with the "--config"
option, then only it is used for configuration.
Otherwise, the user configuration (~/.config/pycodestyle) and any local
configurations in the current directory or above will be merged together
(in that order) using the read method of ConfigParser. | [
"Read",
"and",
"parse",
"configurations",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L2148-L2220 | train | 209,863 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | _parse_multi_options | def _parse_multi_options(options, split_token=','):
r"""Split and strip and discard empties.
Turns the following:
A,
B,
into ["A", "B"]
"""
if options:
return [o.strip() for o in options.split(split_token) if o.strip()]
else:
return options | python | def _parse_multi_options(options, split_token=','):
r"""Split and strip and discard empties.
Turns the following:
A,
B,
into ["A", "B"]
"""
if options:
return [o.strip() for o in options.split(split_token) if o.strip()]
else:
return options | [
"def",
"_parse_multi_options",
"(",
"options",
",",
"split_token",
"=",
"','",
")",
":",
"if",
"options",
":",
"return",
"[",
"o",
".",
"strip",
"(",
")",
"for",
"o",
"in",
"options",
".",
"split",
"(",
"split_token",
")",
"if",
"o",
".",
"strip",
"(... | r"""Split and strip and discard empties.
Turns the following:
A,
B,
into ["A", "B"] | [
"r",
"Split",
"and",
"strip",
"and",
"discard",
"empties",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L2274-L2287 | train | 209,864 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | Checker.report_invalid_syntax | def report_invalid_syntax(self):
"""Check if the syntax is valid."""
(exc_type, exc) = sys.exc_info()[:2]
if len(exc.args) > 1:
offset = exc.args[1]
if len(offset) > 2:
offset = offset[1:3]
else:
offset = (1, 0)
self.report_error(offset[0], offset[1] or 0,
'E901 %s: %s' % (exc_type.__name__, exc.args[0]),
self.report_invalid_syntax) | python | def report_invalid_syntax(self):
"""Check if the syntax is valid."""
(exc_type, exc) = sys.exc_info()[:2]
if len(exc.args) > 1:
offset = exc.args[1]
if len(offset) > 2:
offset = offset[1:3]
else:
offset = (1, 0)
self.report_error(offset[0], offset[1] or 0,
'E901 %s: %s' % (exc_type.__name__, exc.args[0]),
self.report_invalid_syntax) | [
"def",
"report_invalid_syntax",
"(",
"self",
")",
":",
"(",
"exc_type",
",",
"exc",
")",
"=",
"sys",
".",
"exc_info",
"(",
")",
"[",
":",
"2",
"]",
"if",
"len",
"(",
"exc",
".",
"args",
")",
">",
"1",
":",
"offset",
"=",
"exc",
".",
"args",
"["... | Check if the syntax is valid. | [
"Check",
"if",
"the",
"syntax",
"is",
"valid",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1562-L1573 | train | 209,865 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | Checker.run_check | def run_check(self, check, argument_names):
"""Run a check plugin."""
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*arguments) | python | def run_check(self, check, argument_names):
"""Run a check plugin."""
arguments = []
for name in argument_names:
arguments.append(getattr(self, name))
return check(*arguments) | [
"def",
"run_check",
"(",
"self",
",",
"check",
",",
"argument_names",
")",
":",
"arguments",
"=",
"[",
"]",
"for",
"name",
"in",
"argument_names",
":",
"arguments",
".",
"append",
"(",
"getattr",
"(",
"self",
",",
"name",
")",
")",
"return",
"check",
"... | Run a check plugin. | [
"Run",
"a",
"check",
"plugin",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1585-L1590 | train | 209,866 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | Checker.init_checker_state | def init_checker_state(self, name, argument_names):
"""Prepare custom state for the specific checker plugin."""
if 'checker_state' in argument_names:
self.checker_state = self._checker_states.setdefault(name, {}) | python | def init_checker_state(self, name, argument_names):
"""Prepare custom state for the specific checker plugin."""
if 'checker_state' in argument_names:
self.checker_state = self._checker_states.setdefault(name, {}) | [
"def",
"init_checker_state",
"(",
"self",
",",
"name",
",",
"argument_names",
")",
":",
"if",
"'checker_state'",
"in",
"argument_names",
":",
"self",
".",
"checker_state",
"=",
"self",
".",
"_checker_states",
".",
"setdefault",
"(",
"name",
",",
"{",
"}",
")... | Prepare custom state for the specific checker plugin. | [
"Prepare",
"custom",
"state",
"for",
"the",
"specific",
"checker",
"plugin",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1592-L1595 | train | 209,867 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | Checker.check_ast | def check_ast(self):
"""Build the file's AST and run all AST checks."""
try:
tree = compile(''.join(self.lines), '', 'exec', PyCF_ONLY_AST)
except (ValueError, SyntaxError, TypeError):
return self.report_invalid_syntax()
for name, cls, __ in self._ast_checks:
checker = cls(tree, self.filename)
for lineno, offset, text, check in checker.run():
if not self.lines or not noqa(self.lines[lineno - 1]):
self.report_error(lineno, offset, text, check) | python | def check_ast(self):
"""Build the file's AST and run all AST checks."""
try:
tree = compile(''.join(self.lines), '', 'exec', PyCF_ONLY_AST)
except (ValueError, SyntaxError, TypeError):
return self.report_invalid_syntax()
for name, cls, __ in self._ast_checks:
checker = cls(tree, self.filename)
for lineno, offset, text, check in checker.run():
if not self.lines or not noqa(self.lines[lineno - 1]):
self.report_error(lineno, offset, text, check) | [
"def",
"check_ast",
"(",
"self",
")",
":",
"try",
":",
"tree",
"=",
"compile",
"(",
"''",
".",
"join",
"(",
"self",
".",
"lines",
")",
",",
"''",
",",
"'exec'",
",",
"PyCF_ONLY_AST",
")",
"except",
"(",
"ValueError",
",",
"SyntaxError",
",",
"TypeErr... | Build the file's AST and run all AST checks. | [
"Build",
"the",
"file",
"s",
"AST",
"and",
"run",
"all",
"AST",
"checks",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1676-L1686 | train | 209,868 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | Checker.generate_tokens | def generate_tokens(self):
"""Tokenize the file, run physical line checks and yield tokens."""
if self._io_error:
self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
tokengen = tokenize.generate_tokens(self.readline)
try:
for token in tokengen:
if token[2][0] > self.total_lines:
return
self.noqa = token[4] and noqa(token[4])
self.maybe_check_physical(token)
yield token
except (SyntaxError, tokenize.TokenError):
self.report_invalid_syntax() | python | def generate_tokens(self):
"""Tokenize the file, run physical line checks and yield tokens."""
if self._io_error:
self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
tokengen = tokenize.generate_tokens(self.readline)
try:
for token in tokengen:
if token[2][0] > self.total_lines:
return
self.noqa = token[4] and noqa(token[4])
self.maybe_check_physical(token)
yield token
except (SyntaxError, tokenize.TokenError):
self.report_invalid_syntax() | [
"def",
"generate_tokens",
"(",
"self",
")",
":",
"if",
"self",
".",
"_io_error",
":",
"self",
".",
"report_error",
"(",
"1",
",",
"0",
",",
"'E902 %s'",
"%",
"self",
".",
"_io_error",
",",
"readlines",
")",
"tokengen",
"=",
"tokenize",
".",
"generate_tok... | Tokenize the file, run physical line checks and yield tokens. | [
"Tokenize",
"the",
"file",
"run",
"physical",
"line",
"checks",
"and",
"yield",
"tokens",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1688-L1701 | train | 209,869 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | BaseReport.get_count | def get_count(self, prefix=''):
"""Return the total count of errors and warnings."""
return sum([self.counters[key]
for key in self.messages if key.startswith(prefix)]) | python | def get_count(self, prefix=''):
"""Return the total count of errors and warnings."""
return sum([self.counters[key]
for key in self.messages if key.startswith(prefix)]) | [
"def",
"get_count",
"(",
"self",
",",
"prefix",
"=",
"''",
")",
":",
"return",
"sum",
"(",
"[",
"self",
".",
"counters",
"[",
"key",
"]",
"for",
"key",
"in",
"self",
".",
"messages",
"if",
"key",
".",
"startswith",
"(",
"prefix",
")",
"]",
")"
] | Return the total count of errors and warnings. | [
"Return",
"the",
"total",
"count",
"of",
"errors",
"and",
"warnings",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1846-L1849 | train | 209,870 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | StandardReport.get_file_results | def get_file_results(self):
"""Print the result and return the overall count for this file."""
self._deferred_print.sort()
for line_number, offset, code, text, doc in self._deferred_print:
print(self._fmt % {
'path': self.filename,
'row': self.line_offset + line_number, 'col': offset + 1,
'code': code, 'text': text,
})
if self._show_source:
if line_number > len(self.lines):
line = ''
else:
line = self.lines[line_number - 1]
print(line.rstrip())
print(re.sub(r'\S', ' ', line[:offset]) + '^')
if self._show_pep8 and doc:
print(' ' + doc.strip())
# stdout is block buffered when not stdout.isatty().
# line can be broken where buffer boundary since other processes
# write to same file.
# flush() after print() to avoid buffer boundary.
# Typical buffer size is 8192. line written safely when
# len(line) < 8192.
sys.stdout.flush()
return self.file_errors | python | def get_file_results(self):
"""Print the result and return the overall count for this file."""
self._deferred_print.sort()
for line_number, offset, code, text, doc in self._deferred_print:
print(self._fmt % {
'path': self.filename,
'row': self.line_offset + line_number, 'col': offset + 1,
'code': code, 'text': text,
})
if self._show_source:
if line_number > len(self.lines):
line = ''
else:
line = self.lines[line_number - 1]
print(line.rstrip())
print(re.sub(r'\S', ' ', line[:offset]) + '^')
if self._show_pep8 and doc:
print(' ' + doc.strip())
# stdout is block buffered when not stdout.isatty().
# line can be broken where buffer boundary since other processes
# write to same file.
# flush() after print() to avoid buffer boundary.
# Typical buffer size is 8192. line written safely when
# len(line) < 8192.
sys.stdout.flush()
return self.file_errors | [
"def",
"get_file_results",
"(",
"self",
")",
":",
"self",
".",
"_deferred_print",
".",
"sort",
"(",
")",
"for",
"line_number",
",",
"offset",
",",
"code",
",",
"text",
",",
"doc",
"in",
"self",
".",
"_deferred_print",
":",
"print",
"(",
"self",
".",
"_... | Print the result and return the overall count for this file. | [
"Print",
"the",
"result",
"and",
"return",
"the",
"overall",
"count",
"for",
"this",
"file",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1909-L1935 | train | 209,871 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | StyleGuide.init_report | def init_report(self, reporter=None):
"""Initialize the report instance."""
self.options.report = (reporter or self.options.reporter)(self.options)
return self.options.report | python | def init_report(self, reporter=None):
"""Initialize the report instance."""
self.options.report = (reporter or self.options.reporter)(self.options)
return self.options.report | [
"def",
"init_report",
"(",
"self",
",",
"reporter",
"=",
"None",
")",
":",
"self",
".",
"options",
".",
"report",
"=",
"(",
"reporter",
"or",
"self",
".",
"options",
".",
"reporter",
")",
"(",
"self",
".",
"options",
")",
"return",
"self",
".",
"opti... | Initialize the report instance. | [
"Initialize",
"the",
"report",
"instance",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1991-L1994 | train | 209,872 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | StyleGuide.check_files | def check_files(self, paths=None):
"""Run all checks on the paths."""
if paths is None:
paths = self.paths
report = self.options.report
runner = self.runner
report.start()
try:
for path in paths:
if os.path.isdir(path):
self.input_dir(path)
elif not self.excluded(path):
runner(path)
except KeyboardInterrupt:
print('... stopped')
report.stop()
return report | python | def check_files(self, paths=None):
"""Run all checks on the paths."""
if paths is None:
paths = self.paths
report = self.options.report
runner = self.runner
report.start()
try:
for path in paths:
if os.path.isdir(path):
self.input_dir(path)
elif not self.excluded(path):
runner(path)
except KeyboardInterrupt:
print('... stopped')
report.stop()
return report | [
"def",
"check_files",
"(",
"self",
",",
"paths",
"=",
"None",
")",
":",
"if",
"paths",
"is",
"None",
":",
"paths",
"=",
"self",
".",
"paths",
"report",
"=",
"self",
".",
"options",
".",
"report",
"runner",
"=",
"self",
".",
"runner",
"report",
".",
... | Run all checks on the paths. | [
"Run",
"all",
"checks",
"on",
"the",
"paths",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L1996-L2012 | train | 209,873 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | StyleGuide.input_dir | def input_dir(self, dirname):
"""Check all files in this directory and all subdirectories."""
dirname = dirname.rstrip('/')
if self.excluded(dirname):
return 0
counters = self.options.report.counters
verbose = self.options.verbose
filepatterns = self.options.filename
runner = self.runner
for root, dirs, files in os.walk(dirname):
if verbose:
print('directory ' + root)
counters['directories'] += 1
for subdir in sorted(dirs):
if self.excluded(subdir, root):
dirs.remove(subdir)
for filename in sorted(files):
# contain a pattern that matches?
if ((filename_match(filename, filepatterns) and
not self.excluded(filename, root))):
runner(os.path.join(root, filename)) | python | def input_dir(self, dirname):
"""Check all files in this directory and all subdirectories."""
dirname = dirname.rstrip('/')
if self.excluded(dirname):
return 0
counters = self.options.report.counters
verbose = self.options.verbose
filepatterns = self.options.filename
runner = self.runner
for root, dirs, files in os.walk(dirname):
if verbose:
print('directory ' + root)
counters['directories'] += 1
for subdir in sorted(dirs):
if self.excluded(subdir, root):
dirs.remove(subdir)
for filename in sorted(files):
# contain a pattern that matches?
if ((filename_match(filename, filepatterns) and
not self.excluded(filename, root))):
runner(os.path.join(root, filename)) | [
"def",
"input_dir",
"(",
"self",
",",
"dirname",
")",
":",
"dirname",
"=",
"dirname",
".",
"rstrip",
"(",
"'/'",
")",
"if",
"self",
".",
"excluded",
"(",
"dirname",
")",
":",
"return",
"0",
"counters",
"=",
"self",
".",
"options",
".",
"report",
".",... | Check all files in this directory and all subdirectories. | [
"Check",
"all",
"files",
"in",
"this",
"directory",
"and",
"all",
"subdirectories",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L2022-L2042 | train | 209,874 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | StyleGuide.ignore_code | def ignore_code(self, code):
"""Check if the error code should be ignored.
If 'options.select' contains a prefix of the error code,
return False. Else, if 'options.ignore' contains a prefix of
the error code, return True.
"""
if len(code) < 4 and any(s.startswith(code)
for s in self.options.select):
return False
return (code.startswith(self.options.ignore) and
not code.startswith(self.options.select)) | python | def ignore_code(self, code):
"""Check if the error code should be ignored.
If 'options.select' contains a prefix of the error code,
return False. Else, if 'options.ignore' contains a prefix of
the error code, return True.
"""
if len(code) < 4 and any(s.startswith(code)
for s in self.options.select):
return False
return (code.startswith(self.options.ignore) and
not code.startswith(self.options.select)) | [
"def",
"ignore_code",
"(",
"self",
",",
"code",
")",
":",
"if",
"len",
"(",
"code",
")",
"<",
"4",
"and",
"any",
"(",
"s",
".",
"startswith",
"(",
"code",
")",
"for",
"s",
"in",
"self",
".",
"options",
".",
"select",
")",
":",
"return",
"False",
... | Check if the error code should be ignored.
If 'options.select' contains a prefix of the error code,
return False. Else, if 'options.ignore' contains a prefix of
the error code, return True. | [
"Check",
"if",
"the",
"error",
"code",
"should",
"be",
"ignored",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L2059-L2070 | train | 209,875 |
fabioz/PyDev.Debugger | third_party/pep8/pycodestyle.py | StyleGuide.get_checks | def get_checks(self, argument_name):
"""Get all the checks for this category.
Find all globally visible functions where the first argument name
starts with argument_name and which contain selected tests.
"""
checks = []
for check, attrs in _checks[argument_name].items():
(codes, args) = attrs
if any(not (code and self.ignore_code(code)) for code in codes):
checks.append((check.__name__, check, args))
return sorted(checks) | python | def get_checks(self, argument_name):
"""Get all the checks for this category.
Find all globally visible functions where the first argument name
starts with argument_name and which contain selected tests.
"""
checks = []
for check, attrs in _checks[argument_name].items():
(codes, args) = attrs
if any(not (code and self.ignore_code(code)) for code in codes):
checks.append((check.__name__, check, args))
return sorted(checks) | [
"def",
"get_checks",
"(",
"self",
",",
"argument_name",
")",
":",
"checks",
"=",
"[",
"]",
"for",
"check",
",",
"attrs",
"in",
"_checks",
"[",
"argument_name",
"]",
".",
"items",
"(",
")",
":",
"(",
"codes",
",",
"args",
")",
"=",
"attrs",
"if",
"a... | Get all the checks for this category.
Find all globally visible functions where the first argument name
starts with argument_name and which contain selected tests. | [
"Get",
"all",
"the",
"checks",
"for",
"this",
"category",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/pycodestyle.py#L2072-L2083 | train | 209,876 |
fabioz/PyDev.Debugger | _pydev_imps/_pydev_xmlrpclib.py | loads | def loads(data, use_datetime=0):
"""data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
If the XML-RPC packet represents a fault condition, this function
raises a Fault exception.
"""
p, u = getparser(use_datetime=use_datetime)
p.feed(data)
p.close()
return u.close(), u.getmethodname() | python | def loads(data, use_datetime=0):
"""data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
If the XML-RPC packet represents a fault condition, this function
raises a Fault exception.
"""
p, u = getparser(use_datetime=use_datetime)
p.feed(data)
p.close()
return u.close(), u.getmethodname() | [
"def",
"loads",
"(",
"data",
",",
"use_datetime",
"=",
"0",
")",
":",
"p",
",",
"u",
"=",
"getparser",
"(",
"use_datetime",
"=",
"use_datetime",
")",
"p",
".",
"feed",
"(",
"data",
")",
"p",
".",
"close",
"(",
")",
"return",
"u",
".",
"close",
"(... | data -> unmarshalled data, method name
Convert an XML-RPC packet to unmarshalled data plus a method
name (None if not present).
If the XML-RPC packet represents a fault condition, this function
raises a Fault exception. | [
"data",
"-",
">",
"unmarshalled",
"data",
"method",
"name"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydev_imps/_pydev_xmlrpclib.py#L1125-L1137 | train | 209,877 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixes/fix_urllib.py | FixUrllib.transform_import | def transform_import(self, node, results):
"""Transform for the basic import case. Replaces the old
import name with a comma separated list of its
replacements.
"""
import_mod = results.get("module")
pref = import_mod.prefix
names = []
# create a Node list of the replacement modules
for name in MAPPING[import_mod.value][:-1]:
names.extend([Name(name[0], prefix=pref), Comma()])
names.append(Name(MAPPING[import_mod.value][-1][0], prefix=pref))
import_mod.replace(names) | python | def transform_import(self, node, results):
"""Transform for the basic import case. Replaces the old
import name with a comma separated list of its
replacements.
"""
import_mod = results.get("module")
pref = import_mod.prefix
names = []
# create a Node list of the replacement modules
for name in MAPPING[import_mod.value][:-1]:
names.extend([Name(name[0], prefix=pref), Comma()])
names.append(Name(MAPPING[import_mod.value][-1][0], prefix=pref))
import_mod.replace(names) | [
"def",
"transform_import",
"(",
"self",
",",
"node",
",",
"results",
")",
":",
"import_mod",
"=",
"results",
".",
"get",
"(",
"\"module\"",
")",
"pref",
"=",
"import_mod",
".",
"prefix",
"names",
"=",
"[",
"]",
"# create a Node list of the replacement modules",
... | Transform for the basic import case. Replaces the old
import name with a comma separated list of its
replacements. | [
"Transform",
"for",
"the",
"basic",
"import",
"case",
".",
"Replaces",
"the",
"old",
"import",
"name",
"with",
"a",
"comma",
"separated",
"list",
"of",
"its",
"replacements",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixes/fix_urllib.py#L77-L91 | train | 209,878 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixes/fix_urllib.py | FixUrllib.transform_member | def transform_member(self, node, results):
"""Transform for imports of specific module elements. Replaces
the module to be imported from with the appropriate new
module.
"""
mod_member = results.get("mod_member")
pref = mod_member.prefix
member = results.get("member")
# Simple case with only a single member being imported
if member:
# this may be a list of length one, or just a node
if isinstance(member, list):
member = member[0]
new_name = None
for change in MAPPING[mod_member.value]:
if member.value in change[1]:
new_name = change[0]
break
if new_name:
mod_member.replace(Name(new_name, prefix=pref))
else:
self.cannot_convert(node, "This is an invalid module element")
# Multiple members being imported
else:
# a dictionary for replacements, order matters
modules = []
mod_dict = {}
members = results["members"]
for member in members:
# we only care about the actual members
if member.type == syms.import_as_name:
as_name = member.children[2].value
member_name = member.children[0].value
else:
member_name = member.value
as_name = None
if member_name != u",":
for change in MAPPING[mod_member.value]:
if member_name in change[1]:
if change[0] not in mod_dict:
modules.append(change[0])
mod_dict.setdefault(change[0], []).append(member)
new_nodes = []
indentation = find_indentation(node)
first = True
def handle_name(name, prefix):
if name.type == syms.import_as_name:
kids = [Name(name.children[0].value, prefix=prefix),
name.children[1].clone(),
name.children[2].clone()]
return [Node(syms.import_as_name, kids)]
return [Name(name.value, prefix=prefix)]
for module in modules:
elts = mod_dict[module]
names = []
for elt in elts[:-1]:
names.extend(handle_name(elt, pref))
names.append(Comma())
names.extend(handle_name(elts[-1], pref))
new = FromImport(module, names)
if not first or node.parent.prefix.endswith(indentation):
new.prefix = indentation
new_nodes.append(new)
first = False
if new_nodes:
nodes = []
for new_node in new_nodes[:-1]:
nodes.extend([new_node, Newline()])
nodes.append(new_nodes[-1])
node.replace(nodes)
else:
self.cannot_convert(node, "All module elements are invalid") | python | def transform_member(self, node, results):
"""Transform for imports of specific module elements. Replaces
the module to be imported from with the appropriate new
module.
"""
mod_member = results.get("mod_member")
pref = mod_member.prefix
member = results.get("member")
# Simple case with only a single member being imported
if member:
# this may be a list of length one, or just a node
if isinstance(member, list):
member = member[0]
new_name = None
for change in MAPPING[mod_member.value]:
if member.value in change[1]:
new_name = change[0]
break
if new_name:
mod_member.replace(Name(new_name, prefix=pref))
else:
self.cannot_convert(node, "This is an invalid module element")
# Multiple members being imported
else:
# a dictionary for replacements, order matters
modules = []
mod_dict = {}
members = results["members"]
for member in members:
# we only care about the actual members
if member.type == syms.import_as_name:
as_name = member.children[2].value
member_name = member.children[0].value
else:
member_name = member.value
as_name = None
if member_name != u",":
for change in MAPPING[mod_member.value]:
if member_name in change[1]:
if change[0] not in mod_dict:
modules.append(change[0])
mod_dict.setdefault(change[0], []).append(member)
new_nodes = []
indentation = find_indentation(node)
first = True
def handle_name(name, prefix):
if name.type == syms.import_as_name:
kids = [Name(name.children[0].value, prefix=prefix),
name.children[1].clone(),
name.children[2].clone()]
return [Node(syms.import_as_name, kids)]
return [Name(name.value, prefix=prefix)]
for module in modules:
elts = mod_dict[module]
names = []
for elt in elts[:-1]:
names.extend(handle_name(elt, pref))
names.append(Comma())
names.extend(handle_name(elts[-1], pref))
new = FromImport(module, names)
if not first or node.parent.prefix.endswith(indentation):
new.prefix = indentation
new_nodes.append(new)
first = False
if new_nodes:
nodes = []
for new_node in new_nodes[:-1]:
nodes.extend([new_node, Newline()])
nodes.append(new_nodes[-1])
node.replace(nodes)
else:
self.cannot_convert(node, "All module elements are invalid") | [
"def",
"transform_member",
"(",
"self",
",",
"node",
",",
"results",
")",
":",
"mod_member",
"=",
"results",
".",
"get",
"(",
"\"mod_member\"",
")",
"pref",
"=",
"mod_member",
".",
"prefix",
"member",
"=",
"results",
".",
"get",
"(",
"\"member\"",
")",
"... | Transform for imports of specific module elements. Replaces
the module to be imported from with the appropriate new
module. | [
"Transform",
"for",
"imports",
"of",
"specific",
"module",
"elements",
".",
"Replaces",
"the",
"module",
"to",
"be",
"imported",
"from",
"with",
"the",
"appropriate",
"new",
"module",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixes/fix_urllib.py#L93-L167 | train | 209,879 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/fixes/fix_urllib.py | FixUrllib.transform_dot | def transform_dot(self, node, results):
"""Transform for calls to module members in code."""
module_dot = results.get("bare_with_attr")
member = results.get("member")
new_name = None
if isinstance(member, list):
member = member[0]
for change in MAPPING[module_dot.value]:
if member.value in change[1]:
new_name = change[0]
break
if new_name:
module_dot.replace(Name(new_name,
prefix=module_dot.prefix))
else:
self.cannot_convert(node, "This is an invalid module element") | python | def transform_dot(self, node, results):
"""Transform for calls to module members in code."""
module_dot = results.get("bare_with_attr")
member = results.get("member")
new_name = None
if isinstance(member, list):
member = member[0]
for change in MAPPING[module_dot.value]:
if member.value in change[1]:
new_name = change[0]
break
if new_name:
module_dot.replace(Name(new_name,
prefix=module_dot.prefix))
else:
self.cannot_convert(node, "This is an invalid module element") | [
"def",
"transform_dot",
"(",
"self",
",",
"node",
",",
"results",
")",
":",
"module_dot",
"=",
"results",
".",
"get",
"(",
"\"bare_with_attr\"",
")",
"member",
"=",
"results",
".",
"get",
"(",
"\"member\"",
")",
"new_name",
"=",
"None",
"if",
"isinstance",... | Transform for calls to module members in code. | [
"Transform",
"for",
"calls",
"to",
"module",
"members",
"in",
"code",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/fixes/fix_urllib.py#L169-L184 | train | 209,880 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_constants.py | call_only_once | def call_only_once(func):
'''
To be used as a decorator
@call_only_once
def func():
print 'Calling func only this time'
Actually, in PyDev it must be called as:
func = call_only_once(func) to support older versions of Python.
'''
def new_func(*args, **kwargs):
if not new_func._called:
new_func._called = True
return func(*args, **kwargs)
new_func._called = False
return new_func | python | def call_only_once(func):
'''
To be used as a decorator
@call_only_once
def func():
print 'Calling func only this time'
Actually, in PyDev it must be called as:
func = call_only_once(func) to support older versions of Python.
'''
def new_func(*args, **kwargs):
if not new_func._called:
new_func._called = True
return func(*args, **kwargs)
new_func._called = False
return new_func | [
"def",
"call_only_once",
"(",
"func",
")",
":",
"def",
"new_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"new_func",
".",
"_called",
":",
"new_func",
".",
"_called",
"=",
"True",
"return",
"func",
"(",
"*",
"args",
",",
... | To be used as a decorator
@call_only_once
def func():
print 'Calling func only this time'
Actually, in PyDev it must be called as:
func = call_only_once(func) to support older versions of Python. | [
"To",
"be",
"used",
"as",
"a",
"decorator"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_constants.py#L457-L476 | train | 209,881 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | get_all_fix_names | def get_all_fix_names(fixer_pkg, remove_prefix=True):
"""Return a sorted list of all available fix names in the given package."""
pkg = __import__(fixer_pkg, [], [], ["*"])
fixer_dir = os.path.dirname(pkg.__file__)
fix_names = []
for name in sorted(os.listdir(fixer_dir)):
if name.startswith("fix_") and name.endswith(".py"):
if remove_prefix:
name = name[4:]
fix_names.append(name[:-3])
return fix_names | python | def get_all_fix_names(fixer_pkg, remove_prefix=True):
"""Return a sorted list of all available fix names in the given package."""
pkg = __import__(fixer_pkg, [], [], ["*"])
fixer_dir = os.path.dirname(pkg.__file__)
fix_names = []
for name in sorted(os.listdir(fixer_dir)):
if name.startswith("fix_") and name.endswith(".py"):
if remove_prefix:
name = name[4:]
fix_names.append(name[:-3])
return fix_names | [
"def",
"get_all_fix_names",
"(",
"fixer_pkg",
",",
"remove_prefix",
"=",
"True",
")",
":",
"pkg",
"=",
"__import__",
"(",
"fixer_pkg",
",",
"[",
"]",
",",
"[",
"]",
",",
"[",
"\"*\"",
"]",
")",
"fixer_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"("... | Return a sorted list of all available fix names in the given package. | [
"Return",
"a",
"sorted",
"list",
"of",
"all",
"available",
"fix",
"names",
"in",
"the",
"given",
"package",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L33-L43 | train | 209,882 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | _get_head_types | def _get_head_types(pat):
""" Accepts a pytree Pattern Node and returns a set
of the pattern types which will match first. """
if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
# NodePatters must either have no type and no content
# or a type and content -- so they don't get any farther
# Always return leafs
if pat.type is None:
raise _EveryNode
return set([pat.type])
if isinstance(pat, pytree.NegatedPattern):
if pat.content:
return _get_head_types(pat.content)
raise _EveryNode # Negated Patterns don't have a type
if isinstance(pat, pytree.WildcardPattern):
# Recurse on each node in content
r = set()
for p in pat.content:
for x in p:
r.update(_get_head_types(x))
return r
raise Exception("Oh no! I don't understand pattern %s" %(pat)) | python | def _get_head_types(pat):
""" Accepts a pytree Pattern Node and returns a set
of the pattern types which will match first. """
if isinstance(pat, (pytree.NodePattern, pytree.LeafPattern)):
# NodePatters must either have no type and no content
# or a type and content -- so they don't get any farther
# Always return leafs
if pat.type is None:
raise _EveryNode
return set([pat.type])
if isinstance(pat, pytree.NegatedPattern):
if pat.content:
return _get_head_types(pat.content)
raise _EveryNode # Negated Patterns don't have a type
if isinstance(pat, pytree.WildcardPattern):
# Recurse on each node in content
r = set()
for p in pat.content:
for x in p:
r.update(_get_head_types(x))
return r
raise Exception("Oh no! I don't understand pattern %s" %(pat)) | [
"def",
"_get_head_types",
"(",
"pat",
")",
":",
"if",
"isinstance",
"(",
"pat",
",",
"(",
"pytree",
".",
"NodePattern",
",",
"pytree",
".",
"LeafPattern",
")",
")",
":",
"# NodePatters must either have no type and no content",
"# or a type and content -- so they don't... | Accepts a pytree Pattern Node and returns a set
of the pattern types which will match first. | [
"Accepts",
"a",
"pytree",
"Pattern",
"Node",
"and",
"returns",
"a",
"set",
"of",
"the",
"pattern",
"types",
"which",
"will",
"match",
"first",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L50-L75 | train | 209,883 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.get_fixers | def get_fixers(self):
"""Inspects the options to load the requested patterns and handlers.
Returns:
(pre_order, post_order), where pre_order is the list of fixers that
want a pre-order AST traversal, and post_order is the list that want
post-order traversal.
"""
pre_order_fixers = []
post_order_fixers = []
for fix_mod_path in self.fixers:
mod = __import__(fix_mod_path, {}, {}, ["*"])
fix_name = fix_mod_path.rsplit(".", 1)[-1]
if fix_name.startswith(self.FILE_PREFIX):
fix_name = fix_name[len(self.FILE_PREFIX):]
parts = fix_name.split("_")
class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
try:
fix_class = getattr(mod, class_name)
except AttributeError:
raise FixerError("Can't find %s.%s" % (fix_name, class_name))
fixer = fix_class(self.options, self.fixer_log)
if fixer.explicit and self.explicit is not True and \
fix_mod_path not in self.explicit:
self.log_message("Skipping implicit fixer: %s", fix_name)
continue
self.log_debug("Adding transformation: %s", fix_name)
if fixer.order == "pre":
pre_order_fixers.append(fixer)
elif fixer.order == "post":
post_order_fixers.append(fixer)
else:
raise FixerError("Illegal fixer order: %r" % fixer.order)
key_func = operator.attrgetter("run_order")
pre_order_fixers.sort(key=key_func)
post_order_fixers.sort(key=key_func)
return (pre_order_fixers, post_order_fixers) | python | def get_fixers(self):
"""Inspects the options to load the requested patterns and handlers.
Returns:
(pre_order, post_order), where pre_order is the list of fixers that
want a pre-order AST traversal, and post_order is the list that want
post-order traversal.
"""
pre_order_fixers = []
post_order_fixers = []
for fix_mod_path in self.fixers:
mod = __import__(fix_mod_path, {}, {}, ["*"])
fix_name = fix_mod_path.rsplit(".", 1)[-1]
if fix_name.startswith(self.FILE_PREFIX):
fix_name = fix_name[len(self.FILE_PREFIX):]
parts = fix_name.split("_")
class_name = self.CLASS_PREFIX + "".join([p.title() for p in parts])
try:
fix_class = getattr(mod, class_name)
except AttributeError:
raise FixerError("Can't find %s.%s" % (fix_name, class_name))
fixer = fix_class(self.options, self.fixer_log)
if fixer.explicit and self.explicit is not True and \
fix_mod_path not in self.explicit:
self.log_message("Skipping implicit fixer: %s", fix_name)
continue
self.log_debug("Adding transformation: %s", fix_name)
if fixer.order == "pre":
pre_order_fixers.append(fixer)
elif fixer.order == "post":
post_order_fixers.append(fixer)
else:
raise FixerError("Illegal fixer order: %r" % fixer.order)
key_func = operator.attrgetter("run_order")
pre_order_fixers.sort(key=key_func)
post_order_fixers.sort(key=key_func)
return (pre_order_fixers, post_order_fixers) | [
"def",
"get_fixers",
"(",
"self",
")",
":",
"pre_order_fixers",
"=",
"[",
"]",
"post_order_fixers",
"=",
"[",
"]",
"for",
"fix_mod_path",
"in",
"self",
".",
"fixers",
":",
"mod",
"=",
"__import__",
"(",
"fix_mod_path",
",",
"{",
"}",
",",
"{",
"}",
","... | Inspects the options to load the requested patterns and handlers.
Returns:
(pre_order, post_order), where pre_order is the list of fixers that
want a pre-order AST traversal, and post_order is the list that want
post-order traversal. | [
"Inspects",
"the",
"options",
"to",
"load",
"the",
"requested",
"patterns",
"and",
"handlers",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L234-L272 | train | 209,884 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.log_message | def log_message(self, msg, *args):
"""Hook to log a message."""
if args:
msg = msg % args
self.logger.info(msg) | python | def log_message(self, msg, *args):
"""Hook to log a message."""
if args:
msg = msg % args
self.logger.info(msg) | [
"def",
"log_message",
"(",
"self",
",",
"msg",
",",
"*",
"args",
")",
":",
"if",
"args",
":",
"msg",
"=",
"msg",
"%",
"args",
"self",
".",
"logger",
".",
"info",
"(",
"msg",
")"
] | Hook to log a message. | [
"Hook",
"to",
"log",
"a",
"message",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L278-L282 | train | 209,885 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.refactor | def refactor(self, items, write=False, doctests_only=False):
"""Refactor a list of files and directories."""
for dir_or_file in items:
if os.path.isdir(dir_or_file):
self.refactor_dir(dir_or_file, write, doctests_only)
else:
self.refactor_file(dir_or_file, write, doctests_only) | python | def refactor(self, items, write=False, doctests_only=False):
"""Refactor a list of files and directories."""
for dir_or_file in items:
if os.path.isdir(dir_or_file):
self.refactor_dir(dir_or_file, write, doctests_only)
else:
self.refactor_file(dir_or_file, write, doctests_only) | [
"def",
"refactor",
"(",
"self",
",",
"items",
",",
"write",
"=",
"False",
",",
"doctests_only",
"=",
"False",
")",
":",
"for",
"dir_or_file",
"in",
"items",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dir_or_file",
")",
":",
"self",
".",
"refac... | Refactor a list of files and directories. | [
"Refactor",
"a",
"list",
"of",
"files",
"and",
"directories",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L294-L301 | train | 209,886 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.refactor_dir | def refactor_dir(self, dir_name, write=False, doctests_only=False):
"""Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with '.' are skipped.
"""
py_ext = os.extsep + "py"
for dirpath, dirnames, filenames in os.walk(dir_name):
self.log_debug("Descending into %s", dirpath)
dirnames.sort()
filenames.sort()
for name in filenames:
if (not name.startswith(".") and
os.path.splitext(name)[1] == py_ext):
fullname = os.path.join(dirpath, name)
self.refactor_file(fullname, write, doctests_only)
# Modify dirnames in-place to remove subdirs with leading dots
dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")] | python | def refactor_dir(self, dir_name, write=False, doctests_only=False):
"""Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with '.' are skipped.
"""
py_ext = os.extsep + "py"
for dirpath, dirnames, filenames in os.walk(dir_name):
self.log_debug("Descending into %s", dirpath)
dirnames.sort()
filenames.sort()
for name in filenames:
if (not name.startswith(".") and
os.path.splitext(name)[1] == py_ext):
fullname = os.path.join(dirpath, name)
self.refactor_file(fullname, write, doctests_only)
# Modify dirnames in-place to remove subdirs with leading dots
dirnames[:] = [dn for dn in dirnames if not dn.startswith(".")] | [
"def",
"refactor_dir",
"(",
"self",
",",
"dir_name",
",",
"write",
"=",
"False",
",",
"doctests_only",
"=",
"False",
")",
":",
"py_ext",
"=",
"os",
".",
"extsep",
"+",
"\"py\"",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"wal... | Descends down a directory and refactor every Python file found.
Python files are assumed to have a .py extension.
Files and subdirectories starting with '.' are skipped. | [
"Descends",
"down",
"a",
"directory",
"and",
"refactor",
"every",
"Python",
"file",
"found",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L303-L321 | train | 209,887 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool._read_python_source | def _read_python_source(self, filename):
"""
Do our best to decode a Python source file correctly.
"""
try:
f = open(filename, "rb")
except IOError as err:
self.log_error("Can't open %s: %s", filename, err)
return None, None
try:
encoding = tokenize.detect_encoding(f.readline)[0]
finally:
f.close()
with _open_with_encoding(filename, "r", encoding=encoding) as f:
return _from_system_newlines(f.read()), encoding | python | def _read_python_source(self, filename):
"""
Do our best to decode a Python source file correctly.
"""
try:
f = open(filename, "rb")
except IOError as err:
self.log_error("Can't open %s: %s", filename, err)
return None, None
try:
encoding = tokenize.detect_encoding(f.readline)[0]
finally:
f.close()
with _open_with_encoding(filename, "r", encoding=encoding) as f:
return _from_system_newlines(f.read()), encoding | [
"def",
"_read_python_source",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"f",
"=",
"open",
"(",
"filename",
",",
"\"rb\"",
")",
"except",
"IOError",
"as",
"err",
":",
"self",
".",
"log_error",
"(",
"\"Can't open %s: %s\"",
",",
"filename",
",",
... | Do our best to decode a Python source file correctly. | [
"Do",
"our",
"best",
"to",
"decode",
"a",
"Python",
"source",
"file",
"correctly",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L323-L337 | train | 209,888 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.refactor_file | def refactor_file(self, filename, write=False, doctests_only=False):
"""Refactors a file."""
input, encoding = self._read_python_source(filename)
if input is None:
# Reading the file failed.
return
input += u"\n" # Silence certain parse errors
if doctests_only:
self.log_debug("Refactoring doctests in %s", filename)
output = self.refactor_docstring(input, filename)
if self.write_unchanged_files or output != input:
self.processed_file(output, filename, input, write, encoding)
else:
self.log_debug("No doctest changes in %s", filename)
else:
tree = self.refactor_string(input, filename)
if self.write_unchanged_files or (tree and tree.was_changed):
# The [:-1] is to take off the \n we added earlier
self.processed_file(unicode(tree)[:-1], filename,
write=write, encoding=encoding)
else:
self.log_debug("No changes in %s", filename) | python | def refactor_file(self, filename, write=False, doctests_only=False):
"""Refactors a file."""
input, encoding = self._read_python_source(filename)
if input is None:
# Reading the file failed.
return
input += u"\n" # Silence certain parse errors
if doctests_only:
self.log_debug("Refactoring doctests in %s", filename)
output = self.refactor_docstring(input, filename)
if self.write_unchanged_files or output != input:
self.processed_file(output, filename, input, write, encoding)
else:
self.log_debug("No doctest changes in %s", filename)
else:
tree = self.refactor_string(input, filename)
if self.write_unchanged_files or (tree and tree.was_changed):
# The [:-1] is to take off the \n we added earlier
self.processed_file(unicode(tree)[:-1], filename,
write=write, encoding=encoding)
else:
self.log_debug("No changes in %s", filename) | [
"def",
"refactor_file",
"(",
"self",
",",
"filename",
",",
"write",
"=",
"False",
",",
"doctests_only",
"=",
"False",
")",
":",
"input",
",",
"encoding",
"=",
"self",
".",
"_read_python_source",
"(",
"filename",
")",
"if",
"input",
"is",
"None",
":",
"# ... | Refactors a file. | [
"Refactors",
"a",
"file",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L339-L360 | train | 209,889 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.refactor_string | def refactor_string(self, data, name):
"""Refactor a given input string.
Args:
data: a string holding the code to be refactored.
name: a human-readable name for use in error/log messages.
Returns:
An AST corresponding to the refactored input stream; None if
there were errors during the parse.
"""
features = _detect_future_features(data)
if "print_function" in features:
self.driver.grammar = pygram.python_grammar_no_print_statement
try:
tree = self.driver.parse_string(data)
except Exception as err:
self.log_error("Can't parse %s: %s: %s",
name, err.__class__.__name__, err)
return
finally:
self.driver.grammar = self.grammar
tree.future_features = features
self.log_debug("Refactoring %s", name)
self.refactor_tree(tree, name)
return tree | python | def refactor_string(self, data, name):
"""Refactor a given input string.
Args:
data: a string holding the code to be refactored.
name: a human-readable name for use in error/log messages.
Returns:
An AST corresponding to the refactored input stream; None if
there were errors during the parse.
"""
features = _detect_future_features(data)
if "print_function" in features:
self.driver.grammar = pygram.python_grammar_no_print_statement
try:
tree = self.driver.parse_string(data)
except Exception as err:
self.log_error("Can't parse %s: %s: %s",
name, err.__class__.__name__, err)
return
finally:
self.driver.grammar = self.grammar
tree.future_features = features
self.log_debug("Refactoring %s", name)
self.refactor_tree(tree, name)
return tree | [
"def",
"refactor_string",
"(",
"self",
",",
"data",
",",
"name",
")",
":",
"features",
"=",
"_detect_future_features",
"(",
"data",
")",
"if",
"\"print_function\"",
"in",
"features",
":",
"self",
".",
"driver",
".",
"grammar",
"=",
"pygram",
".",
"python_gra... | Refactor a given input string.
Args:
data: a string holding the code to be refactored.
name: a human-readable name for use in error/log messages.
Returns:
An AST corresponding to the refactored input stream; None if
there were errors during the parse. | [
"Refactor",
"a",
"given",
"input",
"string",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L362-L387 | train | 209,890 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.traverse_by | def traverse_by(self, fixers, traversal):
"""Traverse an AST, applying a set of fixers to each node.
This is a helper method for refactor_tree().
Args:
fixers: a list of fixer instances.
traversal: a generator that yields AST nodes.
Returns:
None
"""
if not fixers:
return
for node in traversal:
for fixer in fixers[node.type]:
results = fixer.match(node)
if results:
new = fixer.transform(node, results)
if new is not None:
node.replace(new)
node = new | python | def traverse_by(self, fixers, traversal):
"""Traverse an AST, applying a set of fixers to each node.
This is a helper method for refactor_tree().
Args:
fixers: a list of fixer instances.
traversal: a generator that yields AST nodes.
Returns:
None
"""
if not fixers:
return
for node in traversal:
for fixer in fixers[node.type]:
results = fixer.match(node)
if results:
new = fixer.transform(node, results)
if new is not None:
node.replace(new)
node = new | [
"def",
"traverse_by",
"(",
"self",
",",
"fixers",
",",
"traversal",
")",
":",
"if",
"not",
"fixers",
":",
"return",
"for",
"node",
"in",
"traversal",
":",
"for",
"fixer",
"in",
"fixers",
"[",
"node",
".",
"type",
"]",
":",
"results",
"=",
"fixer",
".... | Traverse an AST, applying a set of fixers to each node.
This is a helper method for refactor_tree().
Args:
fixers: a list of fixer instances.
traversal: a generator that yields AST nodes.
Returns:
None | [
"Traverse",
"an",
"AST",
"applying",
"a",
"set",
"of",
"fixers",
"to",
"each",
"node",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L484-L505 | train | 209,891 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.processed_file | def processed_file(self, new_text, filename, old_text=None, write=False,
encoding=None):
"""
Called when a file has been refactored and there may be changes.
"""
self.files.append(filename)
if old_text is None:
old_text = self._read_python_source(filename)[0]
if old_text is None:
return
equal = old_text == new_text
self.print_output(old_text, new_text, filename, equal)
if equal:
self.log_debug("No changes to %s", filename)
if not self.write_unchanged_files:
return
if write:
self.write_file(new_text, filename, old_text, encoding)
else:
self.log_debug("Not writing changes to %s", filename) | python | def processed_file(self, new_text, filename, old_text=None, write=False,
encoding=None):
"""
Called when a file has been refactored and there may be changes.
"""
self.files.append(filename)
if old_text is None:
old_text = self._read_python_source(filename)[0]
if old_text is None:
return
equal = old_text == new_text
self.print_output(old_text, new_text, filename, equal)
if equal:
self.log_debug("No changes to %s", filename)
if not self.write_unchanged_files:
return
if write:
self.write_file(new_text, filename, old_text, encoding)
else:
self.log_debug("Not writing changes to %s", filename) | [
"def",
"processed_file",
"(",
"self",
",",
"new_text",
",",
"filename",
",",
"old_text",
"=",
"None",
",",
"write",
"=",
"False",
",",
"encoding",
"=",
"None",
")",
":",
"self",
".",
"files",
".",
"append",
"(",
"filename",
")",
"if",
"old_text",
"is",... | Called when a file has been refactored and there may be changes. | [
"Called",
"when",
"a",
"file",
"has",
"been",
"refactored",
"and",
"there",
"may",
"be",
"changes",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L507-L526 | train | 209,892 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.write_file | def write_file(self, new_text, filename, old_text, encoding=None):
"""Writes a string to a file.
It first shows a unified diff between the old text and the new text, and
then rewrites the file; the latter is only done if the write option is
set.
"""
try:
f = _open_with_encoding(filename, "w", encoding=encoding)
except os.error as err:
self.log_error("Can't create %s: %s", filename, err)
return
try:
f.write(_to_system_newlines(new_text))
except os.error as err:
self.log_error("Can't write %s: %s", filename, err)
finally:
f.close()
self.log_debug("Wrote changes to %s", filename)
self.wrote = True | python | def write_file(self, new_text, filename, old_text, encoding=None):
"""Writes a string to a file.
It first shows a unified diff between the old text and the new text, and
then rewrites the file; the latter is only done if the write option is
set.
"""
try:
f = _open_with_encoding(filename, "w", encoding=encoding)
except os.error as err:
self.log_error("Can't create %s: %s", filename, err)
return
try:
f.write(_to_system_newlines(new_text))
except os.error as err:
self.log_error("Can't write %s: %s", filename, err)
finally:
f.close()
self.log_debug("Wrote changes to %s", filename)
self.wrote = True | [
"def",
"write_file",
"(",
"self",
",",
"new_text",
",",
"filename",
",",
"old_text",
",",
"encoding",
"=",
"None",
")",
":",
"try",
":",
"f",
"=",
"_open_with_encoding",
"(",
"filename",
",",
"\"w\"",
",",
"encoding",
"=",
"encoding",
")",
"except",
"os"... | Writes a string to a file.
It first shows a unified diff between the old text and the new text, and
then rewrites the file; the latter is only done if the write option is
set. | [
"Writes",
"a",
"string",
"to",
"a",
"file",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L528-L547 | train | 209,893 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.refactor_docstring | def refactor_docstring(self, input, filename):
"""Refactors a docstring, looking for doctests.
This returns a modified version of the input string. It looks
for doctests, which start with a ">>>" prompt, and may be
continued with "..." prompts, as long as the "..." is indented
the same as the ">>>".
(Unfortunately we can't use the doctest module's parser,
since, like most parsers, it is not geared towards preserving
the original source.)
"""
result = []
block = None
block_lineno = None
indent = None
lineno = 0
for line in input.splitlines(True):
lineno += 1
if line.lstrip().startswith(self.PS1):
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
block_lineno = lineno
block = [line]
i = line.find(self.PS1)
indent = line[:i]
elif (indent is not None and
(line.startswith(indent + self.PS2) or
line == indent + self.PS2.rstrip() + u"\n")):
block.append(line)
else:
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
block = None
indent = None
result.append(line)
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
return u"".join(result) | python | def refactor_docstring(self, input, filename):
"""Refactors a docstring, looking for doctests.
This returns a modified version of the input string. It looks
for doctests, which start with a ">>>" prompt, and may be
continued with "..." prompts, as long as the "..." is indented
the same as the ">>>".
(Unfortunately we can't use the doctest module's parser,
since, like most parsers, it is not geared towards preserving
the original source.)
"""
result = []
block = None
block_lineno = None
indent = None
lineno = 0
for line in input.splitlines(True):
lineno += 1
if line.lstrip().startswith(self.PS1):
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
block_lineno = lineno
block = [line]
i = line.find(self.PS1)
indent = line[:i]
elif (indent is not None and
(line.startswith(indent + self.PS2) or
line == indent + self.PS2.rstrip() + u"\n")):
block.append(line)
else:
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
block = None
indent = None
result.append(line)
if block is not None:
result.extend(self.refactor_doctest(block, block_lineno,
indent, filename))
return u"".join(result) | [
"def",
"refactor_docstring",
"(",
"self",
",",
"input",
",",
"filename",
")",
":",
"result",
"=",
"[",
"]",
"block",
"=",
"None",
"block_lineno",
"=",
"None",
"indent",
"=",
"None",
"lineno",
"=",
"0",
"for",
"line",
"in",
"input",
".",
"splitlines",
"... | Refactors a docstring, looking for doctests.
This returns a modified version of the input string. It looks
for doctests, which start with a ">>>" prompt, and may be
continued with "..." prompts, as long as the "..." is indented
the same as the ">>>".
(Unfortunately we can't use the doctest module's parser,
since, like most parsers, it is not geared towards preserving
the original source.) | [
"Refactors",
"a",
"docstring",
"looking",
"for",
"doctests",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L552-L593 | train | 209,894 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.parse_block | def parse_block(self, block, lineno, indent):
"""Parses a block into a tree.
This is necessary to get correct line number / offset information
in the parser diagnostics and embedded into the parse tree.
"""
tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
tree.future_features = frozenset()
return tree | python | def parse_block(self, block, lineno, indent):
"""Parses a block into a tree.
This is necessary to get correct line number / offset information
in the parser diagnostics and embedded into the parse tree.
"""
tree = self.driver.parse_tokens(self.wrap_toks(block, lineno, indent))
tree.future_features = frozenset()
return tree | [
"def",
"parse_block",
"(",
"self",
",",
"block",
",",
"lineno",
",",
"indent",
")",
":",
"tree",
"=",
"self",
".",
"driver",
".",
"parse_tokens",
"(",
"self",
".",
"wrap_toks",
"(",
"block",
",",
"lineno",
",",
"indent",
")",
")",
"tree",
".",
"futur... | Parses a block into a tree.
This is necessary to get correct line number / offset information
in the parser diagnostics and embedded into the parse tree. | [
"Parses",
"a",
"block",
"into",
"a",
"tree",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L647-L655 | train | 209,895 |
fabioz/PyDev.Debugger | third_party/pep8/lib2to3/lib2to3/refactor.py | RefactoringTool.gen_lines | def gen_lines(self, block, indent):
"""Generates lines as expected by tokenize from a list of lines.
This strips the first len(indent + self.PS1) characters off each line.
"""
prefix1 = indent + self.PS1
prefix2 = indent + self.PS2
prefix = prefix1
for line in block:
if line.startswith(prefix):
yield line[len(prefix):]
elif line == prefix.rstrip() + u"\n":
yield u"\n"
else:
raise AssertionError("line=%r, prefix=%r" % (line, prefix))
prefix = prefix2
while True:
yield "" | python | def gen_lines(self, block, indent):
"""Generates lines as expected by tokenize from a list of lines.
This strips the first len(indent + self.PS1) characters off each line.
"""
prefix1 = indent + self.PS1
prefix2 = indent + self.PS2
prefix = prefix1
for line in block:
if line.startswith(prefix):
yield line[len(prefix):]
elif line == prefix.rstrip() + u"\n":
yield u"\n"
else:
raise AssertionError("line=%r, prefix=%r" % (line, prefix))
prefix = prefix2
while True:
yield "" | [
"def",
"gen_lines",
"(",
"self",
",",
"block",
",",
"indent",
")",
":",
"prefix1",
"=",
"indent",
"+",
"self",
".",
"PS1",
"prefix2",
"=",
"indent",
"+",
"self",
".",
"PS2",
"prefix",
"=",
"prefix1",
"for",
"line",
"in",
"block",
":",
"if",
"line",
... | Generates lines as expected by tokenize from a list of lines.
This strips the first len(indent + self.PS1) characters off each line. | [
"Generates",
"lines",
"as",
"expected",
"by",
"tokenize",
"from",
"a",
"list",
"of",
"lines",
"."
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/third_party/pep8/lib2to3/lib2to3/refactor.py#L671-L688 | train | 209,896 |
fabioz/PyDev.Debugger | _pydevd_bundle/pydevd_xml.py | var_to_xml | def var_to_xml(val, name, trim_if_too_big=True, additional_in_xml='', evaluate_full_value=True):
""" single variable or dictionary to xml representation """
type_name, type_qualifier, is_exception_on_eval, resolver, value = get_variable_details(
val, evaluate_full_value)
try:
name = quote(name, '/>_= ') # TODO: Fix PY-5834 without using quote
except:
pass
xml = '<var name="%s" type="%s" ' % (make_valid_xml_value(name), make_valid_xml_value(type_name))
if type_qualifier:
xml_qualifier = 'qualifier="%s"' % make_valid_xml_value(type_qualifier)
else:
xml_qualifier = ''
if value:
# cannot be too big... communication may not handle it.
if len(value) > MAXIMUM_VARIABLE_REPRESENTATION_SIZE and trim_if_too_big:
value = value[0:MAXIMUM_VARIABLE_REPRESENTATION_SIZE]
value += '...'
xml_value = ' value="%s"' % (make_valid_xml_value(quote(value, '/>_= ')))
else:
xml_value = ''
if is_exception_on_eval:
xml_container = ' isErrorOnEval="True"'
else:
if resolver is not None:
xml_container = ' isContainer="True"'
else:
xml_container = ''
return ''.join((xml, xml_qualifier, xml_value, xml_container, additional_in_xml, ' />\n')) | python | def var_to_xml(val, name, trim_if_too_big=True, additional_in_xml='', evaluate_full_value=True):
""" single variable or dictionary to xml representation """
type_name, type_qualifier, is_exception_on_eval, resolver, value = get_variable_details(
val, evaluate_full_value)
try:
name = quote(name, '/>_= ') # TODO: Fix PY-5834 without using quote
except:
pass
xml = '<var name="%s" type="%s" ' % (make_valid_xml_value(name), make_valid_xml_value(type_name))
if type_qualifier:
xml_qualifier = 'qualifier="%s"' % make_valid_xml_value(type_qualifier)
else:
xml_qualifier = ''
if value:
# cannot be too big... communication may not handle it.
if len(value) > MAXIMUM_VARIABLE_REPRESENTATION_SIZE and trim_if_too_big:
value = value[0:MAXIMUM_VARIABLE_REPRESENTATION_SIZE]
value += '...'
xml_value = ' value="%s"' % (make_valid_xml_value(quote(value, '/>_= ')))
else:
xml_value = ''
if is_exception_on_eval:
xml_container = ' isErrorOnEval="True"'
else:
if resolver is not None:
xml_container = ' isContainer="True"'
else:
xml_container = ''
return ''.join((xml, xml_qualifier, xml_value, xml_container, additional_in_xml, ' />\n')) | [
"def",
"var_to_xml",
"(",
"val",
",",
"name",
",",
"trim_if_too_big",
"=",
"True",
",",
"additional_in_xml",
"=",
"''",
",",
"evaluate_full_value",
"=",
"True",
")",
":",
"type_name",
",",
"type_qualifier",
",",
"is_exception_on_eval",
",",
"resolver",
",",
"v... | single variable or dictionary to xml representation | [
"single",
"variable",
"or",
"dictionary",
"to",
"xml",
"representation"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/_pydevd_bundle/pydevd_xml.py#L343-L379 | train | 209,897 |
fabioz/PyDev.Debugger | pydevd_attach_to_process/winappdbg/plugins/do_exploitable.py | do | def do(self, arg):
".exploitable - Determine the approximate exploitability rating"
from winappdbg import Crash
event = self.debug.lastEvent
crash = Crash(event)
crash.fetch_extra_data(event)
status, rule, description = crash.isExploitable()
print "-" * 79
print "Exploitability: %s" % status
print "Matched rule: %s" % rule
print "Description: %s" % description
print "-" * 79 | python | def do(self, arg):
".exploitable - Determine the approximate exploitability rating"
from winappdbg import Crash
event = self.debug.lastEvent
crash = Crash(event)
crash.fetch_extra_data(event)
status, rule, description = crash.isExploitable()
print "-" * 79
print "Exploitability: %s" % status
print "Matched rule: %s" % rule
print "Description: %s" % description
print "-" * 79 | [
"def",
"do",
"(",
"self",
",",
"arg",
")",
":",
"from",
"winappdbg",
"import",
"Crash",
"event",
"=",
"self",
".",
"debug",
".",
"lastEvent",
"crash",
"=",
"Crash",
"(",
"event",
")",
"crash",
".",
"fetch_extra_data",
"(",
"event",
")",
"status",
",",
... | .exploitable - Determine the approximate exploitability rating | [
".",
"exploitable",
"-",
"Determine",
"the",
"approximate",
"exploitability",
"rating"
] | ed9c4307662a5593b8a7f1f3389ecd0e79b8c503 | https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/plugins/do_exploitable.py#L35-L50 | train | 209,898 |
timClicks/slate | src/slate/classes.py | PDF._cleanup | def _cleanup(self):
"""
Frees lots of non-textual information, such as the fonts
and images and the objects that were needed to parse the
PDF.
"""
self.device = None
self.doc = None
self.parser = None
self.resmgr = None
self.interpreter = None | python | def _cleanup(self):
"""
Frees lots of non-textual information, such as the fonts
and images and the objects that were needed to parse the
PDF.
"""
self.device = None
self.doc = None
self.parser = None
self.resmgr = None
self.interpreter = None | [
"def",
"_cleanup",
"(",
"self",
")",
":",
"self",
".",
"device",
"=",
"None",
"self",
".",
"doc",
"=",
"None",
"self",
".",
"parser",
"=",
"None",
"self",
".",
"resmgr",
"=",
"None",
"self",
".",
"interpreter",
"=",
"None"
] | Frees lots of non-textual information, such as the fonts
and images and the objects that were needed to parse the
PDF. | [
"Frees",
"lots",
"of",
"non",
"-",
"textual",
"information",
"such",
"as",
"the",
"fonts",
"and",
"images",
"and",
"the",
"objects",
"that",
"were",
"needed",
"to",
"parse",
"the",
"PDF",
"."
] | e796bbb09ea5ab473aa33ce2984bf9fc2bebb64b | https://github.com/timClicks/slate/blob/e796bbb09ea5ab473aa33ce2984bf9fc2bebb64b/src/slate/classes.py#L80-L90 | train | 209,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.