partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | ConsoleWidget._set_tab_width | Sets the width (in terms of space characters) for tab characters. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width | def _set_tab_width(self, tab_width):
""" Sets the width (in terms of space characters) for tab characters.
"""
font_metrics = QtGui.QFontMetrics(self.font)
self._control.setTabStopWidth(tab_width * font_metrics.width(' '))
self._tab_width = tab_width | [
"Sets",
"the",
"width",
"(",
"in",
"terms",
"of",
"space",
"characters",
")",
"for",
"tab",
"characters",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L770-L776 | [
"def",
"_set_tab_width",
"(",
"self",
",",
"tab_width",
")",
":",
"font_metrics",
"=",
"QtGui",
".",
"QFontMetrics",
"(",
"self",
".",
"font",
")",
"self",
".",
"_control",
".",
"setTabStopWidth",
"(",
"tab_width",
"*",
"font_metrics",
".",
"width",
"(",
"' '",
")",
")",
"self",
".",
"_tab_width",
"=",
"tab_width"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._append_custom | A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _append_custom(self, insert, input, before_prompt=False):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the content.
cursor = self._control.textCursor()
if before_prompt and (self._reading or not self._executing):
cursor.setPosition(self._append_before_prompt_pos)
else:
cursor.movePosition(QtGui.QTextCursor.End)
start_pos = cursor.position()
# Perform the insertion.
result = insert(cursor, input)
# Adjust the prompt position if we have inserted before it. This is safe
# because buffer truncation is disabled when not executing.
if before_prompt and not self._executing:
diff = cursor.position() - start_pos
self._append_before_prompt_pos += diff
self._prompt_pos += diff
return result | def _append_custom(self, insert, input, before_prompt=False):
""" A low-level method for appending content to the end of the buffer.
If 'before_prompt' is enabled, the content will be inserted before the
current prompt, if there is one.
"""
# Determine where to insert the content.
cursor = self._control.textCursor()
if before_prompt and (self._reading or not self._executing):
cursor.setPosition(self._append_before_prompt_pos)
else:
cursor.movePosition(QtGui.QTextCursor.End)
start_pos = cursor.position()
# Perform the insertion.
result = insert(cursor, input)
# Adjust the prompt position if we have inserted before it. This is safe
# because buffer truncation is disabled when not executing.
if before_prompt and not self._executing:
diff = cursor.position() - start_pos
self._append_before_prompt_pos += diff
self._prompt_pos += diff
return result | [
"A",
"low",
"-",
"level",
"method",
"for",
"appending",
"content",
"to",
"the",
"end",
"of",
"the",
"buffer",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L835-L859 | [
"def",
"_append_custom",
"(",
"self",
",",
"insert",
",",
"input",
",",
"before_prompt",
"=",
"False",
")",
":",
"# Determine where to insert the content.",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"if",
"before_prompt",
"and",
"(",
"self",
".",
"_reading",
"or",
"not",
"self",
".",
"_executing",
")",
":",
"cursor",
".",
"setPosition",
"(",
"self",
".",
"_append_before_prompt_pos",
")",
"else",
":",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")",
"start_pos",
"=",
"cursor",
".",
"position",
"(",
")",
"# Perform the insertion.",
"result",
"=",
"insert",
"(",
"cursor",
",",
"input",
")",
"# Adjust the prompt position if we have inserted before it. This is safe",
"# because buffer truncation is disabled when not executing.",
"if",
"before_prompt",
"and",
"not",
"self",
".",
"_executing",
":",
"diff",
"=",
"cursor",
".",
"position",
"(",
")",
"-",
"start_pos",
"self",
".",
"_append_before_prompt_pos",
"+=",
"diff",
"self",
".",
"_prompt_pos",
"+=",
"diff",
"return",
"result"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._append_html | Appends HTML at the end of the console buffer. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt) | def _append_html(self, html, before_prompt=False):
""" Appends HTML at the end of the console buffer.
"""
self._append_custom(self._insert_html, html, before_prompt) | [
"Appends",
"HTML",
"at",
"the",
"end",
"of",
"the",
"console",
"buffer",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L861-L864 | [
"def",
"_append_html",
"(",
"self",
",",
"html",
",",
"before_prompt",
"=",
"False",
")",
":",
"self",
".",
"_append_custom",
"(",
"self",
".",
"_insert_html",
",",
"html",
",",
"before_prompt",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._append_html_fetching_plain_text | Appends HTML, then returns the plain text version of it. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt) | def _append_html_fetching_plain_text(self, html, before_prompt=False):
""" Appends HTML, then returns the plain text version of it.
"""
return self._append_custom(self._insert_html_fetching_plain_text,
html, before_prompt) | [
"Appends",
"HTML",
"then",
"returns",
"the",
"plain",
"text",
"version",
"of",
"it",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L866-L870 | [
"def",
"_append_html_fetching_plain_text",
"(",
"self",
",",
"html",
",",
"before_prompt",
"=",
"False",
")",
":",
"return",
"self",
".",
"_append_custom",
"(",
"self",
".",
"_insert_html_fetching_plain_text",
",",
"html",
",",
"before_prompt",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._append_plain_text | Appends plain text, processing ANSI codes if enabled. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt) | def _append_plain_text(self, text, before_prompt=False):
""" Appends plain text, processing ANSI codes if enabled.
"""
self._append_custom(self._insert_plain_text, text, before_prompt) | [
"Appends",
"plain",
"text",
"processing",
"ANSI",
"codes",
"if",
"enabled",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L872-L875 | [
"def",
"_append_plain_text",
"(",
"self",
",",
"text",
",",
"before_prompt",
"=",
"False",
")",
":",
"self",
".",
"_append_custom",
"(",
"self",
".",
"_insert_plain_text",
",",
"text",
",",
"before_prompt",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._clear_temporary_buffer | Clears the "temporary text" buffer, i.e. all the text following
the prompt region. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if(self._temp_buffer_filled):
self._temp_buffer_filled = False
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True) | def _clear_temporary_buffer(self):
""" Clears the "temporary text" buffer, i.e. all the text following
the prompt region.
"""
# Select and remove all text below the input buffer.
cursor = self._get_prompt_cursor()
prompt = self._continuation_prompt.lstrip()
if(self._temp_buffer_filled):
self._temp_buffer_filled = False
while cursor.movePosition(QtGui.QTextCursor.NextBlock):
temp_cursor = QtGui.QTextCursor(cursor)
temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)
text = temp_cursor.selection().toPlainText().lstrip()
if not text.startswith(prompt):
break
else:
# We've reached the end of the input buffer and no text follows.
return
cursor.movePosition(QtGui.QTextCursor.Left) # Grab the newline.
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
# After doing this, we have no choice but to clear the undo/redo
# history. Otherwise, the text is not "temporary" at all, because it
# can be recalled with undo/redo. Unfortunately, Qt does not expose
# fine-grained control to the undo/redo system.
if self._control.isUndoRedoEnabled():
self._control.setUndoRedoEnabled(False)
self._control.setUndoRedoEnabled(True) | [
"Clears",
"the",
"temporary",
"text",
"buffer",
"i",
".",
"e",
".",
"all",
"the",
"text",
"following",
"the",
"prompt",
"region",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L882-L911 | [
"def",
"_clear_temporary_buffer",
"(",
"self",
")",
":",
"# Select and remove all text below the input buffer.",
"cursor",
"=",
"self",
".",
"_get_prompt_cursor",
"(",
")",
"prompt",
"=",
"self",
".",
"_continuation_prompt",
".",
"lstrip",
"(",
")",
"if",
"(",
"self",
".",
"_temp_buffer_filled",
")",
":",
"self",
".",
"_temp_buffer_filled",
"=",
"False",
"while",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"NextBlock",
")",
":",
"temp_cursor",
"=",
"QtGui",
".",
"QTextCursor",
"(",
"cursor",
")",
"temp_cursor",
".",
"select",
"(",
"QtGui",
".",
"QTextCursor",
".",
"BlockUnderCursor",
")",
"text",
"=",
"temp_cursor",
".",
"selection",
"(",
")",
".",
"toPlainText",
"(",
")",
".",
"lstrip",
"(",
")",
"if",
"not",
"text",
".",
"startswith",
"(",
"prompt",
")",
":",
"break",
"else",
":",
"# We've reached the end of the input buffer and no text follows.",
"return",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Left",
")",
"# Grab the newline.",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"cursor",
".",
"removeSelectedText",
"(",
")",
"# After doing this, we have no choice but to clear the undo/redo",
"# history. Otherwise, the text is not \"temporary\" at all, because it",
"# can be recalled with undo/redo. Unfortunately, Qt does not expose",
"# fine-grained control to the undo/redo system.",
"if",
"self",
".",
"_control",
".",
"isUndoRedoEnabled",
"(",
")",
":",
"self",
".",
"_control",
".",
"setUndoRedoEnabled",
"(",
"False",
")",
"self",
".",
"_control",
".",
"setUndoRedoEnabled",
"(",
"True",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._complete_with_items | Performs completion with 'items' at the specified cursor location. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
self._completion_widget.show_items(cursor, items) | def _complete_with_items(self, cursor, items):
""" Performs completion with 'items' at the specified cursor location.
"""
self._cancel_completion()
if len(items) == 1:
cursor.setPosition(self._control.textCursor().position(),
QtGui.QTextCursor.KeepAnchor)
cursor.insertText(items[0])
elif len(items) > 1:
current_pos = self._control.textCursor().position()
prefix = commonprefix(items)
if prefix:
cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)
cursor.insertText(prefix)
current_pos = cursor.position()
cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))
self._completion_widget.show_items(cursor, items) | [
"Performs",
"completion",
"with",
"items",
"at",
"the",
"specified",
"cursor",
"location",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L913-L932 | [
"def",
"_complete_with_items",
"(",
"self",
",",
"cursor",
",",
"items",
")",
":",
"self",
".",
"_cancel_completion",
"(",
")",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"cursor",
".",
"setPosition",
"(",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
".",
"position",
"(",
")",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"cursor",
".",
"insertText",
"(",
"items",
"[",
"0",
"]",
")",
"elif",
"len",
"(",
"items",
")",
">",
"1",
":",
"current_pos",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
".",
"position",
"(",
")",
"prefix",
"=",
"commonprefix",
"(",
"items",
")",
"if",
"prefix",
":",
"cursor",
".",
"setPosition",
"(",
"current_pos",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"cursor",
".",
"insertText",
"(",
"prefix",
")",
"current_pos",
"=",
"cursor",
".",
"position",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Left",
",",
"n",
"=",
"len",
"(",
"prefix",
")",
")",
"self",
".",
"_completion_widget",
".",
"show_items",
"(",
"cursor",
",",
"items",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._fill_temporary_buffer | fill the area below the active editting zone with text | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._temp_buffer_filled = True | def _fill_temporary_buffer(self, cursor, text, html=False):
"""fill the area below the active editting zone with text"""
current_pos = self._control.textCursor().position()
cursor.beginEditBlock()
self._append_plain_text('\n')
self._page(text, html=html)
cursor.endEditBlock()
cursor.setPosition(current_pos)
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
self._temp_buffer_filled = True | [
"fill",
"the",
"area",
"below",
"the",
"active",
"editting",
"zone",
"with",
"text"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L935-L949 | [
"def",
"_fill_temporary_buffer",
"(",
"self",
",",
"cursor",
",",
"text",
",",
"html",
"=",
"False",
")",
":",
"current_pos",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
".",
"position",
"(",
")",
"cursor",
".",
"beginEditBlock",
"(",
")",
"self",
".",
"_append_plain_text",
"(",
"'\\n'",
")",
"self",
".",
"_page",
"(",
"text",
",",
"html",
"=",
"html",
")",
"cursor",
".",
"endEditBlock",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"current_pos",
")",
"self",
".",
"_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")",
"self",
".",
"_control",
".",
"setTextCursor",
"(",
"cursor",
")",
"self",
".",
"_temp_buffer_filled",
"=",
"True"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._context_menu_make | Creates a context menu for the given QPoint (in widget coordinates). | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
self.copy_action = menu.addAction('Copy', self.copy)
self.copy_action.setEnabled(self.can_copy())
self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
self.paste_action = menu.addAction('Paste', self.paste)
self.paste_action.setEnabled(self.can_paste())
self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
menu.addSeparator()
menu.addAction(self.select_all_action)
menu.addSeparator()
menu.addAction(self.export_action)
menu.addAction(self.print_action)
return menu | def _context_menu_make(self, pos):
""" Creates a context menu for the given QPoint (in widget coordinates).
"""
menu = QtGui.QMenu(self)
self.cut_action = menu.addAction('Cut', self.cut)
self.cut_action.setEnabled(self.can_cut())
self.cut_action.setShortcut(QtGui.QKeySequence.Cut)
self.copy_action = menu.addAction('Copy', self.copy)
self.copy_action.setEnabled(self.can_copy())
self.copy_action.setShortcut(QtGui.QKeySequence.Copy)
self.paste_action = menu.addAction('Paste', self.paste)
self.paste_action.setEnabled(self.can_paste())
self.paste_action.setShortcut(QtGui.QKeySequence.Paste)
menu.addSeparator()
menu.addAction(self.select_all_action)
menu.addSeparator()
menu.addAction(self.export_action)
menu.addAction(self.print_action)
return menu | [
"Creates",
"a",
"context",
"menu",
"for",
"the",
"given",
"QPoint",
"(",
"in",
"widget",
"coordinates",
")",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L952-L976 | [
"def",
"_context_menu_make",
"(",
"self",
",",
"pos",
")",
":",
"menu",
"=",
"QtGui",
".",
"QMenu",
"(",
"self",
")",
"self",
".",
"cut_action",
"=",
"menu",
".",
"addAction",
"(",
"'Cut'",
",",
"self",
".",
"cut",
")",
"self",
".",
"cut_action",
".",
"setEnabled",
"(",
"self",
".",
"can_cut",
"(",
")",
")",
"self",
".",
"cut_action",
".",
"setShortcut",
"(",
"QtGui",
".",
"QKeySequence",
".",
"Cut",
")",
"self",
".",
"copy_action",
"=",
"menu",
".",
"addAction",
"(",
"'Copy'",
",",
"self",
".",
"copy",
")",
"self",
".",
"copy_action",
".",
"setEnabled",
"(",
"self",
".",
"can_copy",
"(",
")",
")",
"self",
".",
"copy_action",
".",
"setShortcut",
"(",
"QtGui",
".",
"QKeySequence",
".",
"Copy",
")",
"self",
".",
"paste_action",
"=",
"menu",
".",
"addAction",
"(",
"'Paste'",
",",
"self",
".",
"paste",
")",
"self",
".",
"paste_action",
".",
"setEnabled",
"(",
"self",
".",
"can_paste",
"(",
")",
")",
"self",
".",
"paste_action",
".",
"setShortcut",
"(",
"QtGui",
".",
"QKeySequence",
".",
"Paste",
")",
"menu",
".",
"addSeparator",
"(",
")",
"menu",
".",
"addAction",
"(",
"self",
".",
"select_all_action",
")",
"menu",
".",
"addSeparator",
"(",
")",
"menu",
".",
"addAction",
"(",
"self",
".",
"export_action",
")",
"menu",
".",
"addAction",
"(",
"self",
".",
"print_action",
")",
"return",
"menu"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._control_key_down | Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters:
-----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters:
-----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier) | def _control_key_down(self, modifiers, include_command=False):
""" Given a KeyboardModifiers flags object, return whether the Control
key is down.
Parameters:
-----------
include_command : bool, optional (default True)
Whether to treat the Command key as a (mutually exclusive) synonym
for Control when in Mac OS.
"""
# Note that on Mac OS, ControlModifier corresponds to the Command key
# while MetaModifier corresponds to the Control key.
if sys.platform == 'darwin':
down = include_command and (modifiers & QtCore.Qt.ControlModifier)
return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)
else:
return bool(modifiers & QtCore.Qt.ControlModifier) | [
"Given",
"a",
"KeyboardModifiers",
"flags",
"object",
"return",
"whether",
"the",
"Control",
"key",
"is",
"down",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L978-L994 | [
"def",
"_control_key_down",
"(",
"self",
",",
"modifiers",
",",
"include_command",
"=",
"False",
")",
":",
"# Note that on Mac OS, ControlModifier corresponds to the Command key",
"# while MetaModifier corresponds to the Control key.",
"if",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"down",
"=",
"include_command",
"and",
"(",
"modifiers",
"&",
"QtCore",
".",
"Qt",
".",
"ControlModifier",
")",
"return",
"bool",
"(",
"down",
")",
"^",
"bool",
"(",
"modifiers",
"&",
"QtCore",
".",
"Qt",
".",
"MetaModifier",
")",
"else",
":",
"return",
"bool",
"(",
"modifiers",
"&",
"QtCore",
".",
"Qt",
".",
"ControlModifier",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._create_control | Creates and connects the underlying text widget. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.custom_control:
control = self.custom_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.setAcceptRichText(False)
# Install event filters. The filter on the viewport is needed for
# mouse events and drag events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the control.
control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control | def _create_control(self):
""" Creates and connects the underlying text widget.
"""
# Create the underlying control.
if self.custom_control:
control = self.custom_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.setAcceptRichText(False)
# Install event filters. The filter on the viewport is needed for
# mouse events and drag events.
control.installEventFilter(self)
control.viewport().installEventFilter(self)
# Connect signals.
control.customContextMenuRequested.connect(
self._custom_context_menu_requested)
control.copyAvailable.connect(self.copy_available)
control.redoAvailable.connect(self.redo_available)
control.undoAvailable.connect(self.undo_available)
# Hijack the document size change signal to prevent Qt from adjusting
# the viewport's scrollbar. We are relying on an implementation detail
# of Q(Plain)TextEdit here, which is potentially dangerous, but without
# this functionality we cannot create a nice terminal interface.
layout = control.document().documentLayout()
layout.documentSizeChanged.disconnect()
layout.documentSizeChanged.connect(self._adjust_scrollbars)
# Configure the control.
control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
control.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control | [
"Creates",
"and",
"connects",
"the",
"underlying",
"text",
"widget",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L996-L1034 | [
"def",
"_create_control",
"(",
"self",
")",
":",
"# Create the underlying control.",
"if",
"self",
".",
"custom_control",
":",
"control",
"=",
"self",
".",
"custom_control",
"(",
")",
"elif",
"self",
".",
"kind",
"==",
"'plain'",
":",
"control",
"=",
"QtGui",
".",
"QPlainTextEdit",
"(",
")",
"elif",
"self",
".",
"kind",
"==",
"'rich'",
":",
"control",
"=",
"QtGui",
".",
"QTextEdit",
"(",
")",
"control",
".",
"setAcceptRichText",
"(",
"False",
")",
"# Install event filters. The filter on the viewport is needed for",
"# mouse events and drag events.",
"control",
".",
"installEventFilter",
"(",
"self",
")",
"control",
".",
"viewport",
"(",
")",
".",
"installEventFilter",
"(",
"self",
")",
"# Connect signals.",
"control",
".",
"customContextMenuRequested",
".",
"connect",
"(",
"self",
".",
"_custom_context_menu_requested",
")",
"control",
".",
"copyAvailable",
".",
"connect",
"(",
"self",
".",
"copy_available",
")",
"control",
".",
"redoAvailable",
".",
"connect",
"(",
"self",
".",
"redo_available",
")",
"control",
".",
"undoAvailable",
".",
"connect",
"(",
"self",
".",
"undo_available",
")",
"# Hijack the document size change signal to prevent Qt from adjusting",
"# the viewport's scrollbar. We are relying on an implementation detail",
"# of Q(Plain)TextEdit here, which is potentially dangerous, but without",
"# this functionality we cannot create a nice terminal interface.",
"layout",
"=",
"control",
".",
"document",
"(",
")",
".",
"documentLayout",
"(",
")",
"layout",
".",
"documentSizeChanged",
".",
"disconnect",
"(",
")",
"layout",
".",
"documentSizeChanged",
".",
"connect",
"(",
"self",
".",
"_adjust_scrollbars",
")",
"# Configure the control.",
"control",
".",
"setAttribute",
"(",
"QtCore",
".",
"Qt",
".",
"WA_InputMethodEnabled",
",",
"True",
")",
"control",
".",
"setContextMenuPolicy",
"(",
"QtCore",
".",
"Qt",
".",
"CustomContextMenu",
")",
"control",
".",
"setReadOnly",
"(",
"True",
")",
"control",
".",
"setUndoRedoEnabled",
"(",
"False",
")",
"control",
".",
"setVerticalScrollBarPolicy",
"(",
"QtCore",
".",
"Qt",
".",
"ScrollBarAlwaysOn",
")",
"return",
"control"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._create_page_control | Creates and connects the underlying paging widget. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.installEventFilter(self)
viewport = control.viewport()
viewport.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control | def _create_page_control(self):
""" Creates and connects the underlying paging widget.
"""
if self.custom_page_control:
control = self.custom_page_control()
elif self.kind == 'plain':
control = QtGui.QPlainTextEdit()
elif self.kind == 'rich':
control = QtGui.QTextEdit()
control.installEventFilter(self)
viewport = control.viewport()
viewport.installEventFilter(self)
control.setReadOnly(True)
control.setUndoRedoEnabled(False)
control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
return control | [
"Creates",
"and",
"connects",
"the",
"underlying",
"paging",
"widget",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1036-L1051 | [
"def",
"_create_page_control",
"(",
"self",
")",
":",
"if",
"self",
".",
"custom_page_control",
":",
"control",
"=",
"self",
".",
"custom_page_control",
"(",
")",
"elif",
"self",
".",
"kind",
"==",
"'plain'",
":",
"control",
"=",
"QtGui",
".",
"QPlainTextEdit",
"(",
")",
"elif",
"self",
".",
"kind",
"==",
"'rich'",
":",
"control",
"=",
"QtGui",
".",
"QTextEdit",
"(",
")",
"control",
".",
"installEventFilter",
"(",
"self",
")",
"viewport",
"=",
"control",
".",
"viewport",
"(",
")",
"viewport",
".",
"installEventFilter",
"(",
"self",
")",
"control",
".",
"setReadOnly",
"(",
"True",
")",
"control",
".",
"setUndoRedoEnabled",
"(",
"False",
")",
"control",
".",
"setVerticalScrollBarPolicy",
"(",
"QtCore",
".",
"Qt",
".",
"ScrollBarAlwaysOn",
")",
"return",
"control"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._event_filter_console_keypress | Filter key events for the underlying text widget to create a
console-like interface. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special sequences ----------------------------------------------
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
#------ Special modifier logic -----------------------------------------
elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_completion()
if self._in_buffer(position):
# Special handling when a reading a line of raw input.
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.
elif not self._executing:
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
at_end = len(cursor.selectedText().strip()) == 0
single_line = (self._get_end_cursor().blockNumber() ==
self._get_prompt_cursor().blockNumber())
if (at_end or shift_down or single_line) and not ctrl_down:
self.execute(interactive = not shift_down)
else:
# Do this inside an edit block for clean undo/redo.
cursor.beginEditBlock()
cursor.setPosition(position)
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Ensure that the whole input buffer is visible.
# FIXME: This will not be usable if the input buffer is
# taller than the console widget.
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
#------ Control/Cmd modifier -------------------------------------------
elif ctrl_down:
if key == QtCore.Qt.Key_G:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_K:
if self._in_buffer(position):
cursor.clearSelection()
cursor.movePosition(QtGui.QTextCursor.EndOfLine,
QtGui.QTextCursor.KeepAnchor)
if not cursor.hasSelection():
# Line deletion (remove continuation prompt)
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_L:
self.prompt_to_top()
intercepted = True
elif key == QtCore.Qt.Key_O:
if self._page_control and self._page_control.isVisible():
self._page_control.setFocus()
intercepted = True
elif key == QtCore.Qt.Key_U:
if self._in_buffer(position):
cursor.clearSelection()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
offset = len(self._prompt)
else:
offset = len(self._continuation_prompt)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor, offset)
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._keep_cursor_in_buffer()
self._kill_ring.yank()
intercepted = True
elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
if key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
else: # key == QtCore.Qt.Key_Delete
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
if len(self.input_buffer) == 0:
self.exit_requested.emit(self)
else:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Delete,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._control, new_event)
intercepted = True
#------ Alt modifier ---------------------------------------------------
elif alt_down:
if key == QtCore.Qt.Key_B:
self._set_cursor(self._get_word_start_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_F:
self._set_cursor(self._get_word_end_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._kill_ring.rotate()
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Delete:
intercepted = True
elif key == QtCore.Qt.Key_Greater:
self._control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._control.setTextCursor(self._get_prompt_cursor())
intercepted = True
#------ No modifiers ---------------------------------------------------
else:
if shift_down:
anchormode = QtGui.QTextCursor.KeepAnchor
else:
anchormode = QtGui.QTextCursor.MoveAnchor
if key == QtCore.Qt.Key_Escape:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_Up:
if self._reading or not self._up_pressed(shift_down):
intercepted = True
else:
prompt_line = self._get_prompt_cursor().blockNumber()
intercepted = cursor.blockNumber() <= prompt_line
elif key == QtCore.Qt.Key_Down:
if self._reading or not self._down_pressed(shift_down):
intercepted = True
else:
end_line = self._get_end_cursor().blockNumber()
intercepted = cursor.blockNumber() == end_line
elif key == QtCore.Qt.Key_Tab:
if not self._reading:
if self._tab_pressed():
# real tab-key, insert four spaces
cursor.insertText(' '*4)
intercepted = True
elif key == QtCore.Qt.Key_Left:
# Move to the previous line
line, col = cursor.blockNumber(), cursor.columnNumber()
if line > self._get_prompt_cursor().blockNumber() and \
col == len(self._continuation_prompt):
self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
mode=anchormode)
self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
mode=anchormode)
intercepted = True
# Regular left movement
else:
intercepted = not self._in_buffer(position - 1)
elif key == QtCore.Qt.Key_Right:
original_block_number = cursor.blockNumber()
cursor.movePosition(QtGui.QTextCursor.Right,
mode=anchormode)
if cursor.blockNumber() != original_block_number:
cursor.movePosition(QtGui.QTextCursor.Right,
n=len(self._continuation_prompt),
mode=anchormode)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Home:
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
start_pos = self._prompt_pos
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
start_pos = cursor.position()
start_pos += len(self._continuation_prompt)
cursor.setPosition(position)
if shift_down and self._in_buffer(position):
cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
else:
cursor.setPosition(start_pos)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
# Line deletion (remove continuation prompt)
line, col = cursor.blockNumber(), cursor.columnNumber()
if not self._reading and \
col == len(self._continuation_prompt) and \
line > self._get_prompt_cursor().blockNumber():
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.deletePreviousChar()
cursor.endEditBlock()
intercepted = True
# Regular backwards deletion
else:
anchor = cursor.anchor()
if anchor == position:
intercepted = not self._in_buffer(position - 1)
else:
intercepted = not self._in_buffer(min(anchor, position))
elif key == QtCore.Qt.Key_Delete:
# Line deletion (remove continuation prompt)
if not self._reading and self._in_buffer(position) and \
cursor.atBlockEnd() and not cursor.hasSelection():
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
# Regular forwards deletion:
else:
anchor = cursor.anchor()
intercepted = (not self._in_buffer(anchor) or
not self._in_buffer(position))
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
# using the keyboard in any part of the buffer. Also, permit scrolling
# with Page Up/Down keys. Finally, if we're executing, don't move the
# cursor (if even this made sense, we can't guarantee that the prompt
# position is still valid due to text truncation).
if not (self._control_key_down(event.modifiers(), include_command=True)
or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
or (self._executing and not self._reading)):
self._keep_cursor_in_buffer()
return intercepted | def _event_filter_console_keypress(self, event):
""" Filter key events for the underlying text widget to create a
console-like interface.
"""
intercepted = False
cursor = self._control.textCursor()
position = cursor.position()
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
shift_down = event.modifiers() & QtCore.Qt.ShiftModifier
#------ Special sequences ----------------------------------------------
if event.matches(QtGui.QKeySequence.Copy):
self.copy()
intercepted = True
elif event.matches(QtGui.QKeySequence.Cut):
self.cut()
intercepted = True
elif event.matches(QtGui.QKeySequence.Paste):
self.paste()
intercepted = True
#------ Special modifier logic -----------------------------------------
elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):
intercepted = True
# Special handling when tab completing in text mode.
self._cancel_completion()
if self._in_buffer(position):
# Special handling when a reading a line of raw input.
if self._reading:
self._append_plain_text('\n')
self._reading = False
if self._reading_callback:
self._reading_callback()
# If the input buffer is a single line or there is only
# whitespace after the cursor, execute. Otherwise, split the
# line with a continuation prompt.
elif not self._executing:
cursor.movePosition(QtGui.QTextCursor.End,
QtGui.QTextCursor.KeepAnchor)
at_end = len(cursor.selectedText().strip()) == 0
single_line = (self._get_end_cursor().blockNumber() ==
self._get_prompt_cursor().blockNumber())
if (at_end or shift_down or single_line) and not ctrl_down:
self.execute(interactive = not shift_down)
else:
# Do this inside an edit block for clean undo/redo.
cursor.beginEditBlock()
cursor.setPosition(position)
cursor.insertText('\n')
self._insert_continuation_prompt(cursor)
cursor.endEditBlock()
# Ensure that the whole input buffer is visible.
# FIXME: This will not be usable if the input buffer is
# taller than the console widget.
self._control.moveCursor(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
#------ Control/Cmd modifier -------------------------------------------
elif ctrl_down:
if key == QtCore.Qt.Key_G:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_K:
if self._in_buffer(position):
cursor.clearSelection()
cursor.movePosition(QtGui.QTextCursor.EndOfLine,
QtGui.QTextCursor.KeepAnchor)
if not cursor.hasSelection():
# Line deletion (remove continuation prompt)
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_L:
self.prompt_to_top()
intercepted = True
elif key == QtCore.Qt.Key_O:
if self._page_control and self._page_control.isVisible():
self._page_control.setFocus()
intercepted = True
elif key == QtCore.Qt.Key_U:
if self._in_buffer(position):
cursor.clearSelection()
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
offset = len(self._prompt)
else:
offset = len(self._continuation_prompt)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor, offset)
self._kill_ring.kill_cursor(cursor)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._keep_cursor_in_buffer()
self._kill_ring.yank()
intercepted = True
elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):
if key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
else: # key == QtCore.Qt.Key_Delete
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
if len(self.input_buffer) == 0:
self.exit_requested.emit(self)
else:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_Delete,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._control, new_event)
intercepted = True
#------ Alt modifier ---------------------------------------------------
elif alt_down:
if key == QtCore.Qt.Key_B:
self._set_cursor(self._get_word_start_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_F:
self._set_cursor(self._get_word_end_cursor(position))
intercepted = True
elif key == QtCore.Qt.Key_Y:
self._kill_ring.rotate()
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
cursor = self._get_word_start_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_D:
cursor = self._get_word_end_cursor(position)
cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)
self._kill_ring.kill_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Delete:
intercepted = True
elif key == QtCore.Qt.Key_Greater:
self._control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._control.setTextCursor(self._get_prompt_cursor())
intercepted = True
#------ No modifiers ---------------------------------------------------
else:
if shift_down:
anchormode = QtGui.QTextCursor.KeepAnchor
else:
anchormode = QtGui.QTextCursor.MoveAnchor
if key == QtCore.Qt.Key_Escape:
self._keyboard_quit()
intercepted = True
elif key == QtCore.Qt.Key_Up:
if self._reading or not self._up_pressed(shift_down):
intercepted = True
else:
prompt_line = self._get_prompt_cursor().blockNumber()
intercepted = cursor.blockNumber() <= prompt_line
elif key == QtCore.Qt.Key_Down:
if self._reading or not self._down_pressed(shift_down):
intercepted = True
else:
end_line = self._get_end_cursor().blockNumber()
intercepted = cursor.blockNumber() == end_line
elif key == QtCore.Qt.Key_Tab:
if not self._reading:
if self._tab_pressed():
# real tab-key, insert four spaces
cursor.insertText(' '*4)
intercepted = True
elif key == QtCore.Qt.Key_Left:
# Move to the previous line
line, col = cursor.blockNumber(), cursor.columnNumber()
if line > self._get_prompt_cursor().blockNumber() and \
col == len(self._continuation_prompt):
self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,
mode=anchormode)
self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,
mode=anchormode)
intercepted = True
# Regular left movement
else:
intercepted = not self._in_buffer(position - 1)
elif key == QtCore.Qt.Key_Right:
original_block_number = cursor.blockNumber()
cursor.movePosition(QtGui.QTextCursor.Right,
mode=anchormode)
if cursor.blockNumber() != original_block_number:
cursor.movePosition(QtGui.QTextCursor.Right,
n=len(self._continuation_prompt),
mode=anchormode)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Home:
start_line = cursor.blockNumber()
if start_line == self._get_prompt_cursor().blockNumber():
start_pos = self._prompt_pos
else:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
start_pos = cursor.position()
start_pos += len(self._continuation_prompt)
cursor.setPosition(position)
if shift_down and self._in_buffer(position):
cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)
else:
cursor.setPosition(start_pos)
self._set_cursor(cursor)
intercepted = True
elif key == QtCore.Qt.Key_Backspace:
# Line deletion (remove continuation prompt)
line, col = cursor.blockNumber(), cursor.columnNumber()
if not self._reading and \
col == len(self._continuation_prompt) and \
line > self._get_prompt_cursor().blockNumber():
cursor.beginEditBlock()
cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.removeSelectedText()
cursor.deletePreviousChar()
cursor.endEditBlock()
intercepted = True
# Regular backwards deletion
else:
anchor = cursor.anchor()
if anchor == position:
intercepted = not self._in_buffer(position - 1)
else:
intercepted = not self._in_buffer(min(anchor, position))
elif key == QtCore.Qt.Key_Delete:
# Line deletion (remove continuation prompt)
if not self._reading and self._in_buffer(position) and \
cursor.atBlockEnd() and not cursor.hasSelection():
cursor.movePosition(QtGui.QTextCursor.NextBlock,
QtGui.QTextCursor.KeepAnchor)
cursor.movePosition(QtGui.QTextCursor.Right,
QtGui.QTextCursor.KeepAnchor,
len(self._continuation_prompt))
cursor.removeSelectedText()
intercepted = True
# Regular forwards deletion:
else:
anchor = cursor.anchor()
intercepted = (not self._in_buffer(anchor) or
not self._in_buffer(position))
# Don't move the cursor if Control/Cmd is pressed to allow copy-paste
# using the keyboard in any part of the buffer. Also, permit scrolling
# with Page Up/Down keys. Finally, if we're executing, don't move the
# cursor (if even this made sense, we can't guarantee that the prompt
# position is still valid due to text truncation).
if not (self._control_key_down(event.modifiers(), include_command=True)
or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)
or (self._executing and not self._reading)):
self._keep_cursor_in_buffer()
return intercepted | [
"Filter",
"key",
"events",
"for",
"the",
"underlying",
"text",
"widget",
"to",
"create",
"a",
"console",
"-",
"like",
"interface",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1053-L1359 | [
"def",
"_event_filter_console_keypress",
"(",
"self",
",",
"event",
")",
":",
"intercepted",
"=",
"False",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"position",
"=",
"cursor",
".",
"position",
"(",
")",
"key",
"=",
"event",
".",
"key",
"(",
")",
"ctrl_down",
"=",
"self",
".",
"_control_key_down",
"(",
"event",
".",
"modifiers",
"(",
")",
")",
"alt_down",
"=",
"event",
".",
"modifiers",
"(",
")",
"&",
"QtCore",
".",
"Qt",
".",
"AltModifier",
"shift_down",
"=",
"event",
".",
"modifiers",
"(",
")",
"&",
"QtCore",
".",
"Qt",
".",
"ShiftModifier",
"#------ Special sequences ----------------------------------------------",
"if",
"event",
".",
"matches",
"(",
"QtGui",
".",
"QKeySequence",
".",
"Copy",
")",
":",
"self",
".",
"copy",
"(",
")",
"intercepted",
"=",
"True",
"elif",
"event",
".",
"matches",
"(",
"QtGui",
".",
"QKeySequence",
".",
"Cut",
")",
":",
"self",
".",
"cut",
"(",
")",
"intercepted",
"=",
"True",
"elif",
"event",
".",
"matches",
"(",
"QtGui",
".",
"QKeySequence",
".",
"Paste",
")",
":",
"self",
".",
"paste",
"(",
")",
"intercepted",
"=",
"True",
"#------ Special modifier logic -----------------------------------------",
"elif",
"key",
"in",
"(",
"QtCore",
".",
"Qt",
".",
"Key_Return",
",",
"QtCore",
".",
"Qt",
".",
"Key_Enter",
")",
":",
"intercepted",
"=",
"True",
"# Special handling when tab completing in text mode.",
"self",
".",
"_cancel_completion",
"(",
")",
"if",
"self",
".",
"_in_buffer",
"(",
"position",
")",
":",
"# Special handling when a reading a line of raw input.",
"if",
"self",
".",
"_reading",
":",
"self",
".",
"_append_plain_text",
"(",
"'\\n'",
")",
"self",
".",
"_reading",
"=",
"False",
"if",
"self",
".",
"_reading_callback",
":",
"self",
".",
"_reading_callback",
"(",
")",
"# If the input buffer is a single line or there is only",
"# whitespace after the cursor, execute. Otherwise, split the",
"# line with a continuation prompt.",
"elif",
"not",
"self",
".",
"_executing",
":",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"at_end",
"=",
"len",
"(",
"cursor",
".",
"selectedText",
"(",
")",
".",
"strip",
"(",
")",
")",
"==",
"0",
"single_line",
"=",
"(",
"self",
".",
"_get_end_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
"==",
"self",
".",
"_get_prompt_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
")",
"if",
"(",
"at_end",
"or",
"shift_down",
"or",
"single_line",
")",
"and",
"not",
"ctrl_down",
":",
"self",
".",
"execute",
"(",
"interactive",
"=",
"not",
"shift_down",
")",
"else",
":",
"# Do this inside an edit block for clean undo/redo.",
"cursor",
".",
"beginEditBlock",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"position",
")",
"cursor",
".",
"insertText",
"(",
"'\\n'",
")",
"self",
".",
"_insert_continuation_prompt",
"(",
"cursor",
")",
"cursor",
".",
"endEditBlock",
"(",
")",
"# Ensure that the whole input buffer is visible.",
"# FIXME: This will not be usable if the input buffer is",
"# taller than the console widget.",
"self",
".",
"_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")",
"self",
".",
"_control",
".",
"setTextCursor",
"(",
"cursor",
")",
"#------ Control/Cmd modifier -------------------------------------------",
"elif",
"ctrl_down",
":",
"if",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_G",
":",
"self",
".",
"_keyboard_quit",
"(",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_K",
":",
"if",
"self",
".",
"_in_buffer",
"(",
"position",
")",
":",
"cursor",
".",
"clearSelection",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"EndOfLine",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"if",
"not",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"# Line deletion (remove continuation prompt)",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"NextBlock",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Right",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
",",
"len",
"(",
"self",
".",
"_continuation_prompt",
")",
")",
"self",
".",
"_kill_ring",
".",
"kill_cursor",
"(",
"cursor",
")",
"self",
".",
"_set_cursor",
"(",
"cursor",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_L",
":",
"self",
".",
"prompt_to_top",
"(",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_O",
":",
"if",
"self",
".",
"_page_control",
"and",
"self",
".",
"_page_control",
".",
"isVisible",
"(",
")",
":",
"self",
".",
"_page_control",
".",
"setFocus",
"(",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_U",
":",
"if",
"self",
".",
"_in_buffer",
"(",
"position",
")",
":",
"cursor",
".",
"clearSelection",
"(",
")",
"start_line",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
"if",
"start_line",
"==",
"self",
".",
"_get_prompt_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
":",
"offset",
"=",
"len",
"(",
"self",
".",
"_prompt",
")",
"else",
":",
"offset",
"=",
"len",
"(",
"self",
".",
"_continuation_prompt",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"StartOfBlock",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Right",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
",",
"offset",
")",
"self",
".",
"_kill_ring",
".",
"kill_cursor",
"(",
"cursor",
")",
"self",
".",
"_set_cursor",
"(",
"cursor",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Y",
":",
"self",
".",
"_keep_cursor_in_buffer",
"(",
")",
"self",
".",
"_kill_ring",
".",
"yank",
"(",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"in",
"(",
"QtCore",
".",
"Qt",
".",
"Key_Backspace",
",",
"QtCore",
".",
"Qt",
".",
"Key_Delete",
")",
":",
"if",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Backspace",
":",
"cursor",
"=",
"self",
".",
"_get_word_start_cursor",
"(",
"position",
")",
"else",
":",
"# key == QtCore.Qt.Key_Delete",
"cursor",
"=",
"self",
".",
"_get_word_end_cursor",
"(",
"position",
")",
"cursor",
".",
"setPosition",
"(",
"position",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"self",
".",
"_kill_ring",
".",
"kill_cursor",
"(",
"cursor",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_D",
":",
"if",
"len",
"(",
"self",
".",
"input_buffer",
")",
"==",
"0",
":",
"self",
".",
"exit_requested",
".",
"emit",
"(",
"self",
")",
"else",
":",
"new_event",
"=",
"QtGui",
".",
"QKeyEvent",
"(",
"QtCore",
".",
"QEvent",
".",
"KeyPress",
",",
"QtCore",
".",
"Qt",
".",
"Key_Delete",
",",
"QtCore",
".",
"Qt",
".",
"NoModifier",
")",
"QtGui",
".",
"qApp",
".",
"sendEvent",
"(",
"self",
".",
"_control",
",",
"new_event",
")",
"intercepted",
"=",
"True",
"#------ Alt modifier ---------------------------------------------------",
"elif",
"alt_down",
":",
"if",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_B",
":",
"self",
".",
"_set_cursor",
"(",
"self",
".",
"_get_word_start_cursor",
"(",
"position",
")",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_F",
":",
"self",
".",
"_set_cursor",
"(",
"self",
".",
"_get_word_end_cursor",
"(",
"position",
")",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Y",
":",
"self",
".",
"_kill_ring",
".",
"rotate",
"(",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Backspace",
":",
"cursor",
"=",
"self",
".",
"_get_word_start_cursor",
"(",
"position",
")",
"cursor",
".",
"setPosition",
"(",
"position",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"self",
".",
"_kill_ring",
".",
"kill_cursor",
"(",
"cursor",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_D",
":",
"cursor",
"=",
"self",
".",
"_get_word_end_cursor",
"(",
"position",
")",
"cursor",
".",
"setPosition",
"(",
"position",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"self",
".",
"_kill_ring",
".",
"kill_cursor",
"(",
"cursor",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Delete",
":",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Greater",
":",
"self",
".",
"_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Less",
":",
"self",
".",
"_control",
".",
"setTextCursor",
"(",
"self",
".",
"_get_prompt_cursor",
"(",
")",
")",
"intercepted",
"=",
"True",
"#------ No modifiers ---------------------------------------------------",
"else",
":",
"if",
"shift_down",
":",
"anchormode",
"=",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
"else",
":",
"anchormode",
"=",
"QtGui",
".",
"QTextCursor",
".",
"MoveAnchor",
"if",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Escape",
":",
"self",
".",
"_keyboard_quit",
"(",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Up",
":",
"if",
"self",
".",
"_reading",
"or",
"not",
"self",
".",
"_up_pressed",
"(",
"shift_down",
")",
":",
"intercepted",
"=",
"True",
"else",
":",
"prompt_line",
"=",
"self",
".",
"_get_prompt_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
"intercepted",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
"<=",
"prompt_line",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Down",
":",
"if",
"self",
".",
"_reading",
"or",
"not",
"self",
".",
"_down_pressed",
"(",
"shift_down",
")",
":",
"intercepted",
"=",
"True",
"else",
":",
"end_line",
"=",
"self",
".",
"_get_end_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
"intercepted",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
"==",
"end_line",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Tab",
":",
"if",
"not",
"self",
".",
"_reading",
":",
"if",
"self",
".",
"_tab_pressed",
"(",
")",
":",
"# real tab-key, insert four spaces",
"cursor",
".",
"insertText",
"(",
"' '",
"*",
"4",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Left",
":",
"# Move to the previous line",
"line",
",",
"col",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
",",
"cursor",
".",
"columnNumber",
"(",
")",
"if",
"line",
">",
"self",
".",
"_get_prompt_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
"and",
"col",
"==",
"len",
"(",
"self",
".",
"_continuation_prompt",
")",
":",
"self",
".",
"_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"PreviousBlock",
",",
"mode",
"=",
"anchormode",
")",
"self",
".",
"_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"EndOfBlock",
",",
"mode",
"=",
"anchormode",
")",
"intercepted",
"=",
"True",
"# Regular left movement",
"else",
":",
"intercepted",
"=",
"not",
"self",
".",
"_in_buffer",
"(",
"position",
"-",
"1",
")",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Right",
":",
"original_block_number",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Right",
",",
"mode",
"=",
"anchormode",
")",
"if",
"cursor",
".",
"blockNumber",
"(",
")",
"!=",
"original_block_number",
":",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Right",
",",
"n",
"=",
"len",
"(",
"self",
".",
"_continuation_prompt",
")",
",",
"mode",
"=",
"anchormode",
")",
"self",
".",
"_set_cursor",
"(",
"cursor",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Home",
":",
"start_line",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
"if",
"start_line",
"==",
"self",
".",
"_get_prompt_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
":",
"start_pos",
"=",
"self",
".",
"_prompt_pos",
"else",
":",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"StartOfBlock",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"start_pos",
"=",
"cursor",
".",
"position",
"(",
")",
"start_pos",
"+=",
"len",
"(",
"self",
".",
"_continuation_prompt",
")",
"cursor",
".",
"setPosition",
"(",
"position",
")",
"if",
"shift_down",
"and",
"self",
".",
"_in_buffer",
"(",
"position",
")",
":",
"cursor",
".",
"setPosition",
"(",
"start_pos",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"else",
":",
"cursor",
".",
"setPosition",
"(",
"start_pos",
")",
"self",
".",
"_set_cursor",
"(",
"cursor",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Backspace",
":",
"# Line deletion (remove continuation prompt)",
"line",
",",
"col",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
",",
"cursor",
".",
"columnNumber",
"(",
")",
"if",
"not",
"self",
".",
"_reading",
"and",
"col",
"==",
"len",
"(",
"self",
".",
"_continuation_prompt",
")",
"and",
"line",
">",
"self",
".",
"_get_prompt_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
":",
"cursor",
".",
"beginEditBlock",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"StartOfBlock",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"cursor",
".",
"removeSelectedText",
"(",
")",
"cursor",
".",
"deletePreviousChar",
"(",
")",
"cursor",
".",
"endEditBlock",
"(",
")",
"intercepted",
"=",
"True",
"# Regular backwards deletion",
"else",
":",
"anchor",
"=",
"cursor",
".",
"anchor",
"(",
")",
"if",
"anchor",
"==",
"position",
":",
"intercepted",
"=",
"not",
"self",
".",
"_in_buffer",
"(",
"position",
"-",
"1",
")",
"else",
":",
"intercepted",
"=",
"not",
"self",
".",
"_in_buffer",
"(",
"min",
"(",
"anchor",
",",
"position",
")",
")",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Delete",
":",
"# Line deletion (remove continuation prompt)",
"if",
"not",
"self",
".",
"_reading",
"and",
"self",
".",
"_in_buffer",
"(",
"position",
")",
"and",
"cursor",
".",
"atBlockEnd",
"(",
")",
"and",
"not",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"NextBlock",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Right",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
",",
"len",
"(",
"self",
".",
"_continuation_prompt",
")",
")",
"cursor",
".",
"removeSelectedText",
"(",
")",
"intercepted",
"=",
"True",
"# Regular forwards deletion:",
"else",
":",
"anchor",
"=",
"cursor",
".",
"anchor",
"(",
")",
"intercepted",
"=",
"(",
"not",
"self",
".",
"_in_buffer",
"(",
"anchor",
")",
"or",
"not",
"self",
".",
"_in_buffer",
"(",
"position",
")",
")",
"# Don't move the cursor if Control/Cmd is pressed to allow copy-paste",
"# using the keyboard in any part of the buffer. Also, permit scrolling",
"# with Page Up/Down keys. Finally, if we're executing, don't move the",
"# cursor (if even this made sense, we can't guarantee that the prompt",
"# position is still valid due to text truncation).",
"if",
"not",
"(",
"self",
".",
"_control_key_down",
"(",
"event",
".",
"modifiers",
"(",
")",
",",
"include_command",
"=",
"True",
")",
"or",
"key",
"in",
"(",
"QtCore",
".",
"Qt",
".",
"Key_PageUp",
",",
"QtCore",
".",
"Qt",
".",
"Key_PageDown",
")",
"or",
"(",
"self",
".",
"_executing",
"and",
"not",
"self",
".",
"_reading",
")",
")",
":",
"self",
".",
"_keep_cursor_in_buffer",
"(",
")",
"return",
"intercepted"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._event_filter_page_keypress | Filter key events for the paging widget to create console-like
interface. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctrl_down:
if key == QtCore.Qt.Key_O:
self._control.setFocus()
intercept = True
elif alt_down:
if key == QtCore.Qt.Key_Greater:
self._page_control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._page_control.moveCursor(QtGui.QTextCursor.Start)
intercepted = True
elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
if self._splitter:
self._page_control.hide()
self._control.setFocus()
else:
self.layout().setCurrentWidget(self._control)
return True
elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
QtCore.Qt.Key_Tab):
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageDown,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
elif key == QtCore.Qt.Key_Backspace:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageUp,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
return False | def _event_filter_page_keypress(self, event):
""" Filter key events for the paging widget to create console-like
interface.
"""
key = event.key()
ctrl_down = self._control_key_down(event.modifiers())
alt_down = event.modifiers() & QtCore.Qt.AltModifier
if ctrl_down:
if key == QtCore.Qt.Key_O:
self._control.setFocus()
intercept = True
elif alt_down:
if key == QtCore.Qt.Key_Greater:
self._page_control.moveCursor(QtGui.QTextCursor.End)
intercepted = True
elif key == QtCore.Qt.Key_Less:
self._page_control.moveCursor(QtGui.QTextCursor.Start)
intercepted = True
elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):
if self._splitter:
self._page_control.hide()
self._control.setFocus()
else:
self.layout().setCurrentWidget(self._control)
return True
elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,
QtCore.Qt.Key_Tab):
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageDown,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
elif key == QtCore.Qt.Key_Backspace:
new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,
QtCore.Qt.Key_PageUp,
QtCore.Qt.NoModifier)
QtGui.qApp.sendEvent(self._page_control, new_event)
return True
return False | [
"Filter",
"key",
"events",
"for",
"the",
"paging",
"widget",
"to",
"create",
"console",
"-",
"like",
"interface",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1361-L1406 | [
"def",
"_event_filter_page_keypress",
"(",
"self",
",",
"event",
")",
":",
"key",
"=",
"event",
".",
"key",
"(",
")",
"ctrl_down",
"=",
"self",
".",
"_control_key_down",
"(",
"event",
".",
"modifiers",
"(",
")",
")",
"alt_down",
"=",
"event",
".",
"modifiers",
"(",
")",
"&",
"QtCore",
".",
"Qt",
".",
"AltModifier",
"if",
"ctrl_down",
":",
"if",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_O",
":",
"self",
".",
"_control",
".",
"setFocus",
"(",
")",
"intercept",
"=",
"True",
"elif",
"alt_down",
":",
"if",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Greater",
":",
"self",
".",
"_page_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Less",
":",
"self",
".",
"_page_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Start",
")",
"intercepted",
"=",
"True",
"elif",
"key",
"in",
"(",
"QtCore",
".",
"Qt",
".",
"Key_Q",
",",
"QtCore",
".",
"Qt",
".",
"Key_Escape",
")",
":",
"if",
"self",
".",
"_splitter",
":",
"self",
".",
"_page_control",
".",
"hide",
"(",
")",
"self",
".",
"_control",
".",
"setFocus",
"(",
")",
"else",
":",
"self",
".",
"layout",
"(",
")",
".",
"setCurrentWidget",
"(",
"self",
".",
"_control",
")",
"return",
"True",
"elif",
"key",
"in",
"(",
"QtCore",
".",
"Qt",
".",
"Key_Enter",
",",
"QtCore",
".",
"Qt",
".",
"Key_Return",
",",
"QtCore",
".",
"Qt",
".",
"Key_Tab",
")",
":",
"new_event",
"=",
"QtGui",
".",
"QKeyEvent",
"(",
"QtCore",
".",
"QEvent",
".",
"KeyPress",
",",
"QtCore",
".",
"Qt",
".",
"Key_PageDown",
",",
"QtCore",
".",
"Qt",
".",
"NoModifier",
")",
"QtGui",
".",
"qApp",
".",
"sendEvent",
"(",
"self",
".",
"_page_control",
",",
"new_event",
")",
"return",
"True",
"elif",
"key",
"==",
"QtCore",
".",
"Qt",
".",
"Key_Backspace",
":",
"new_event",
"=",
"QtGui",
".",
"QKeyEvent",
"(",
"QtCore",
".",
"QEvent",
".",
"KeyPress",
",",
"QtCore",
".",
"Qt",
".",
"Key_PageUp",
",",
"QtCore",
".",
"Qt",
".",
"NoModifier",
")",
"QtGui",
".",
"qApp",
".",
"sendEvent",
"(",
"self",
".",
"_page_control",
",",
"new_event",
")",
"return",
"True",
"return",
"False"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._format_as_columns | Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _format_as_columns(self, items, separator=' '):
""" Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string.
"""
# Calculate the number of characters available.
width = self._control.viewport().width()
char_width = QtGui.QFontMetrics(self.font).width(' ')
displaywidth = max(10, (width / char_width) - 1)
return columnize(items, separator, displaywidth) | def _format_as_columns(self, items, separator=' '):
""" Transform a list of strings into a single string with columns.
Parameters
----------
items : sequence of strings
The strings to process.
separator : str, optional [default is two spaces]
The string that separates columns.
Returns
-------
The formatted string.
"""
# Calculate the number of characters available.
width = self._control.viewport().width()
char_width = QtGui.QFontMetrics(self.font).width(' ')
displaywidth = max(10, (width / char_width) - 1)
return columnize(items, separator, displaywidth) | [
"Transform",
"a",
"list",
"of",
"strings",
"into",
"a",
"single",
"string",
"with",
"columns",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1408-L1428 | [
"def",
"_format_as_columns",
"(",
"self",
",",
"items",
",",
"separator",
"=",
"' '",
")",
":",
"# Calculate the number of characters available.",
"width",
"=",
"self",
".",
"_control",
".",
"viewport",
"(",
")",
".",
"width",
"(",
")",
"char_width",
"=",
"QtGui",
".",
"QFontMetrics",
"(",
"self",
".",
"font",
")",
".",
"width",
"(",
"' '",
")",
"displaywidth",
"=",
"max",
"(",
"10",
",",
"(",
"width",
"/",
"char_width",
")",
"-",
"1",
")",
"return",
"columnize",
"(",
"items",
",",
"separator",
",",
"displaywidth",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_block_plain_text | Given a QTextBlock, return its unformatted text. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
return cursor.selection().toPlainText() | def _get_block_plain_text(self, block):
""" Given a QTextBlock, return its unformatted text.
"""
cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
cursor.movePosition(QtGui.QTextCursor.EndOfBlock,
QtGui.QTextCursor.KeepAnchor)
return cursor.selection().toPlainText() | [
"Given",
"a",
"QTextBlock",
"return",
"its",
"unformatted",
"text",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1430-L1437 | [
"def",
"_get_block_plain_text",
"(",
"self",
",",
"block",
")",
":",
"cursor",
"=",
"QtGui",
".",
"QTextCursor",
"(",
"block",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"StartOfBlock",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"EndOfBlock",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"return",
"cursor",
".",
"selection",
"(",
")",
".",
"toPlainText",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_end_cursor | Convenience method that returns a cursor for the last character. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_end_cursor(self):
""" Convenience method that returns a cursor for the last character.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor | def _get_end_cursor(self):
""" Convenience method that returns a cursor for the last character.
"""
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
return cursor | [
"Convenience",
"method",
"that",
"returns",
"a",
"cursor",
"for",
"the",
"last",
"character",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1444-L1449 | [
"def",
"_get_end_cursor",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")",
"return",
"cursor"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_input_buffer_cursor_column | Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_input_buffer_cursor_column(self):
""" Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
else:
cursor = self._control.textCursor()
return cursor.columnNumber() - len(prompt) | def _get_input_buffer_cursor_column(self):
""" Returns the column of the cursor in the input buffer, excluding the
contribution by the prompt, or -1 if there is no such column.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return -1
else:
cursor = self._control.textCursor()
return cursor.columnNumber() - len(prompt) | [
"Returns",
"the",
"column",
"of",
"the",
"cursor",
"in",
"the",
"input",
"buffer",
"excluding",
"the",
"contribution",
"by",
"the",
"prompt",
"or",
"-",
"1",
"if",
"there",
"is",
"no",
"such",
"column",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1451-L1460 | [
"def",
"_get_input_buffer_cursor_column",
"(",
"self",
")",
":",
"prompt",
"=",
"self",
".",
"_get_input_buffer_cursor_prompt",
"(",
")",
"if",
"prompt",
"is",
"None",
":",
"return",
"-",
"1",
"else",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"return",
"cursor",
".",
"columnNumber",
"(",
")",
"-",
"len",
"(",
"prompt",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_input_buffer_cursor_line | Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
cursor = self._control.textCursor()
text = self._get_block_plain_text(cursor.block())
return text[len(prompt):] | def _get_input_buffer_cursor_line(self):
""" Returns the text of the line of the input buffer that contains the
cursor, or None if there is no such line.
"""
prompt = self._get_input_buffer_cursor_prompt()
if prompt is None:
return None
else:
cursor = self._control.textCursor()
text = self._get_block_plain_text(cursor.block())
return text[len(prompt):] | [
"Returns",
"the",
"text",
"of",
"the",
"line",
"of",
"the",
"input",
"buffer",
"that",
"contains",
"the",
"cursor",
"or",
"None",
"if",
"there",
"is",
"no",
"such",
"line",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1462-L1472 | [
"def",
"_get_input_buffer_cursor_line",
"(",
"self",
")",
":",
"prompt",
"=",
"self",
".",
"_get_input_buffer_cursor_prompt",
"(",
")",
"if",
"prompt",
"is",
"None",
":",
"return",
"None",
"else",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"text",
"=",
"self",
".",
"_get_block_plain_text",
"(",
"cursor",
".",
"block",
"(",
")",
")",
"return",
"text",
"[",
"len",
"(",
"prompt",
")",
":",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_input_buffer_cursor_prompt | Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_input_buffer_cursor_prompt(self):
""" Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line.
"""
if self._executing:
return None
cursor = self._control.textCursor()
if cursor.position() >= self._prompt_pos:
if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
return self._prompt
else:
return self._continuation_prompt
else:
return None | def _get_input_buffer_cursor_prompt(self):
""" Returns the (plain text) prompt for line of the input buffer that
contains the cursor, or None if there is no such line.
"""
if self._executing:
return None
cursor = self._control.textCursor()
if cursor.position() >= self._prompt_pos:
if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():
return self._prompt
else:
return self._continuation_prompt
else:
return None | [
"Returns",
"the",
"(",
"plain",
"text",
")",
"prompt",
"for",
"line",
"of",
"the",
"input",
"buffer",
"that",
"contains",
"the",
"cursor",
"or",
"None",
"if",
"there",
"is",
"no",
"such",
"line",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1474-L1487 | [
"def",
"_get_input_buffer_cursor_prompt",
"(",
"self",
")",
":",
"if",
"self",
".",
"_executing",
":",
"return",
"None",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"if",
"cursor",
".",
"position",
"(",
")",
">=",
"self",
".",
"_prompt_pos",
":",
"if",
"cursor",
".",
"blockNumber",
"(",
")",
"==",
"self",
".",
"_get_prompt_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
":",
"return",
"self",
".",
"_prompt",
"else",
":",
"return",
"self",
".",
"_continuation_prompt",
"else",
":",
"return",
"None"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_prompt_cursor | Convenience method that returns a cursor for the prompt position. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor | def _get_prompt_cursor(self):
""" Convenience method that returns a cursor for the prompt position.
"""
cursor = self._control.textCursor()
cursor.setPosition(self._prompt_pos)
return cursor | [
"Convenience",
"method",
"that",
"returns",
"a",
"cursor",
"for",
"the",
"prompt",
"position",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1489-L1494 | [
"def",
"_get_prompt_cursor",
"(",
"self",
")",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"self",
".",
"_prompt_pos",
")",
"return",
"cursor"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_selection_cursor | Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_selection_cursor(self, start, end):
""" Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
return cursor | def _get_selection_cursor(self, start, end):
""" Convenience method that returns a cursor with text selected between
the positions 'start' and 'end'.
"""
cursor = self._control.textCursor()
cursor.setPosition(start)
cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)
return cursor | [
"Convenience",
"method",
"that",
"returns",
"a",
"cursor",
"with",
"text",
"selected",
"between",
"the",
"positions",
"start",
"and",
"end",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1496-L1503 | [
"def",
"_get_selection_cursor",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"start",
")",
"cursor",
".",
"setPosition",
"(",
"end",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"return",
"cursor"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_word_start_cursor | Find the start of the word to the left the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.) | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_word_start_cursor(self, position):
""" Find the start of the word to the left the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
position -= 1
while position >= self._prompt_pos and \
not is_letter_or_number(document.characterAt(position)):
position -= 1
while position >= self._prompt_pos and \
is_letter_or_number(document.characterAt(position)):
position -= 1
cursor = self._control.textCursor()
cursor.setPosition(position + 1)
return cursor | def _get_word_start_cursor(self, position):
""" Find the start of the word to the left the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
position -= 1
while position >= self._prompt_pos and \
not is_letter_or_number(document.characterAt(position)):
position -= 1
while position >= self._prompt_pos and \
is_letter_or_number(document.characterAt(position)):
position -= 1
cursor = self._control.textCursor()
cursor.setPosition(position + 1)
return cursor | [
"Find",
"the",
"start",
"of",
"the",
"word",
"to",
"the",
"left",
"the",
"given",
"position",
".",
"If",
"a",
"sequence",
"of",
"non",
"-",
"word",
"characters",
"precedes",
"the",
"first",
"word",
"skip",
"over",
"them",
".",
"(",
"This",
"emulates",
"the",
"behavior",
"of",
"bash",
"emacs",
"etc",
".",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1505-L1520 | [
"def",
"_get_word_start_cursor",
"(",
"self",
",",
"position",
")",
":",
"document",
"=",
"self",
".",
"_control",
".",
"document",
"(",
")",
"position",
"-=",
"1",
"while",
"position",
">=",
"self",
".",
"_prompt_pos",
"and",
"not",
"is_letter_or_number",
"(",
"document",
".",
"characterAt",
"(",
"position",
")",
")",
":",
"position",
"-=",
"1",
"while",
"position",
">=",
"self",
".",
"_prompt_pos",
"and",
"is_letter_or_number",
"(",
"document",
".",
"characterAt",
"(",
"position",
")",
")",
":",
"position",
"-=",
"1",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"position",
"+",
"1",
")",
"return",
"cursor"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._get_word_end_cursor | Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.) | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _get_word_end_cursor(self, position):
""" Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
end = self._get_end_cursor().position()
while position < end and \
not is_letter_or_number(document.characterAt(position)):
position += 1
while position < end and \
is_letter_or_number(document.characterAt(position)):
position += 1
cursor = self._control.textCursor()
cursor.setPosition(position)
return cursor | def _get_word_end_cursor(self, position):
""" Find the end of the word to the right the given position. If a
sequence of non-word characters precedes the first word, skip over
them. (This emulates the behavior of bash, emacs, etc.)
"""
document = self._control.document()
end = self._get_end_cursor().position()
while position < end and \
not is_letter_or_number(document.characterAt(position)):
position += 1
while position < end and \
is_letter_or_number(document.characterAt(position)):
position += 1
cursor = self._control.textCursor()
cursor.setPosition(position)
return cursor | [
"Find",
"the",
"end",
"of",
"the",
"word",
"to",
"the",
"right",
"the",
"given",
"position",
".",
"If",
"a",
"sequence",
"of",
"non",
"-",
"word",
"characters",
"precedes",
"the",
"first",
"word",
"skip",
"over",
"them",
".",
"(",
"This",
"emulates",
"the",
"behavior",
"of",
"bash",
"emacs",
"etc",
".",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1522-L1537 | [
"def",
"_get_word_end_cursor",
"(",
"self",
",",
"position",
")",
":",
"document",
"=",
"self",
".",
"_control",
".",
"document",
"(",
")",
"end",
"=",
"self",
".",
"_get_end_cursor",
"(",
")",
".",
"position",
"(",
")",
"while",
"position",
"<",
"end",
"and",
"not",
"is_letter_or_number",
"(",
"document",
".",
"characterAt",
"(",
"position",
")",
")",
":",
"position",
"+=",
"1",
"while",
"position",
"<",
"end",
"and",
"is_letter_or_number",
"(",
"document",
".",
"characterAt",
"(",
"position",
")",
")",
":",
"position",
"+=",
"1",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"position",
")",
"return",
"cursor"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._insert_continuation_prompt | Inserts new continuation prompt using the specified cursor. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html) | def _insert_continuation_prompt(self, cursor):
""" Inserts new continuation prompt using the specified cursor.
"""
if self._continuation_prompt_html is None:
self._insert_plain_text(cursor, self._continuation_prompt)
else:
self._continuation_prompt = self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html) | [
"Inserts",
"new",
"continuation",
"prompt",
"using",
"the",
"specified",
"cursor",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1539-L1546 | [
"def",
"_insert_continuation_prompt",
"(",
"self",
",",
"cursor",
")",
":",
"if",
"self",
".",
"_continuation_prompt_html",
"is",
"None",
":",
"self",
".",
"_insert_plain_text",
"(",
"cursor",
",",
"self",
".",
"_continuation_prompt",
")",
"else",
":",
"self",
".",
"_continuation_prompt",
"=",
"self",
".",
"_insert_html_fetching_plain_text",
"(",
"cursor",
",",
"self",
".",
"_continuation_prompt_html",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._insert_html | Inserts HTML using the specified cursor in such a way that future
formatting is unaffected. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _insert_html(self, cursor, html):
""" Inserts HTML using the specified cursor in such a way that future
formatting is unaffected.
"""
cursor.beginEditBlock()
cursor.insertHtml(html)
# After inserting HTML, the text document "remembers" it's in "html
# mode", which means that subsequent calls adding plain text will result
# in unwanted formatting, lost tab characters, etc. The following code
# hacks around this behavior, which I consider to be a bug in Qt, by
# (crudely) resetting the document's style state.
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() == ' ':
cursor.removeSelectedText()
else:
cursor.movePosition(QtGui.QTextCursor.Right)
cursor.insertText(' ', QtGui.QTextCharFormat())
cursor.endEditBlock() | def _insert_html(self, cursor, html):
""" Inserts HTML using the specified cursor in such a way that future
formatting is unaffected.
"""
cursor.beginEditBlock()
cursor.insertHtml(html)
# After inserting HTML, the text document "remembers" it's in "html
# mode", which means that subsequent calls adding plain text will result
# in unwanted formatting, lost tab characters, etc. The following code
# hacks around this behavior, which I consider to be a bug in Qt, by
# (crudely) resetting the document's style state.
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() == ' ':
cursor.removeSelectedText()
else:
cursor.movePosition(QtGui.QTextCursor.Right)
cursor.insertText(' ', QtGui.QTextCharFormat())
cursor.endEditBlock() | [
"Inserts",
"HTML",
"using",
"the",
"specified",
"cursor",
"in",
"such",
"a",
"way",
"that",
"future",
"formatting",
"is",
"unaffected",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1548-L1567 | [
"def",
"_insert_html",
"(",
"self",
",",
"cursor",
",",
"html",
")",
":",
"cursor",
".",
"beginEditBlock",
"(",
")",
"cursor",
".",
"insertHtml",
"(",
"html",
")",
"# After inserting HTML, the text document \"remembers\" it's in \"html",
"# mode\", which means that subsequent calls adding plain text will result",
"# in unwanted formatting, lost tab characters, etc. The following code",
"# hacks around this behavior, which I consider to be a bug in Qt, by",
"# (crudely) resetting the document's style state.",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Left",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"if",
"cursor",
".",
"selection",
"(",
")",
".",
"toPlainText",
"(",
")",
"==",
"' '",
":",
"cursor",
".",
"removeSelectedText",
"(",
")",
"else",
":",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Right",
")",
"cursor",
".",
"insertText",
"(",
"' '",
",",
"QtGui",
".",
"QTextCharFormat",
"(",
")",
")",
"cursor",
".",
"endEditBlock",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._insert_html_fetching_plain_text | Inserts HTML using the specified cursor, then returns its plain text
version. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _insert_html_fetching_plain_text(self, cursor, html):
""" Inserts HTML using the specified cursor, then returns its plain text
version.
"""
cursor.beginEditBlock()
cursor.removeSelectedText()
start = cursor.position()
self._insert_html(cursor, html)
end = cursor.position()
cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
text = cursor.selection().toPlainText()
cursor.setPosition(end)
cursor.endEditBlock()
return text | def _insert_html_fetching_plain_text(self, cursor, html):
""" Inserts HTML using the specified cursor, then returns its plain text
version.
"""
cursor.beginEditBlock()
cursor.removeSelectedText()
start = cursor.position()
self._insert_html(cursor, html)
end = cursor.position()
cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)
text = cursor.selection().toPlainText()
cursor.setPosition(end)
cursor.endEditBlock()
return text | [
"Inserts",
"HTML",
"using",
"the",
"specified",
"cursor",
"then",
"returns",
"its",
"plain",
"text",
"version",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1569-L1584 | [
"def",
"_insert_html_fetching_plain_text",
"(",
"self",
",",
"cursor",
",",
"html",
")",
":",
"cursor",
".",
"beginEditBlock",
"(",
")",
"cursor",
".",
"removeSelectedText",
"(",
")",
"start",
"=",
"cursor",
".",
"position",
"(",
")",
"self",
".",
"_insert_html",
"(",
"cursor",
",",
"html",
")",
"end",
"=",
"cursor",
".",
"position",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"start",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"text",
"=",
"cursor",
".",
"selection",
"(",
")",
".",
"toPlainText",
"(",
")",
"cursor",
".",
"setPosition",
"(",
"end",
")",
"cursor",
".",
"endEditBlock",
"(",
")",
"return",
"text"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._insert_plain_text | Inserts plain text using the specified cursor, processing ANSI codes
if enabled. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _insert_plain_text(self, cursor, text):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
cursor.beginEditBlock()
if self.ansi_codes:
for substring in self._ansi_processor.split_string(text):
for act in self._ansi_processor.actions:
# Unlike real terminal emulators, we don't distinguish
# between the screen and the scrollback buffer. A screen
# erase request clears everything.
if act.action == 'erase' and act.area == 'screen':
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
# Simulate a form feed by scrolling just past the last line.
elif act.action == 'scroll' and act.unit == 'page':
cursor.insertText('\n')
cursor.endEditBlock()
self._set_top_cursor(cursor)
cursor.joinPreviousEditBlock()
cursor.deletePreviousChar()
elif act.action == 'carriage-return':
cursor.movePosition(
cursor.StartOfLine, cursor.KeepAnchor)
elif act.action == 'beep':
QtGui.qApp.beep()
elif act.action == 'backspace':
if not cursor.atBlockStart():
cursor.movePosition(
cursor.PreviousCharacter, cursor.KeepAnchor)
elif act.action == 'newline':
cursor.movePosition(cursor.EndOfLine)
format = self._ansi_processor.get_format()
selection = cursor.selectedText()
if len(selection) == 0:
cursor.insertText(substring, format)
elif substring is not None:
# BS and CR are treated as a change in print
# position, rather than a backwards character
# deletion for output equivalence with (I)Python
# terminal.
if len(substring) >= len(selection):
cursor.insertText(substring, format)
else:
old_text = selection[len(substring):]
cursor.insertText(substring + old_text, format)
cursor.movePosition(cursor.PreviousCharacter,
cursor.KeepAnchor, len(old_text))
else:
cursor.insertText(text)
cursor.endEditBlock() | def _insert_plain_text(self, cursor, text):
""" Inserts plain text using the specified cursor, processing ANSI codes
if enabled.
"""
cursor.beginEditBlock()
if self.ansi_codes:
for substring in self._ansi_processor.split_string(text):
for act in self._ansi_processor.actions:
# Unlike real terminal emulators, we don't distinguish
# between the screen and the scrollback buffer. A screen
# erase request clears everything.
if act.action == 'erase' and act.area == 'screen':
cursor.select(QtGui.QTextCursor.Document)
cursor.removeSelectedText()
# Simulate a form feed by scrolling just past the last line.
elif act.action == 'scroll' and act.unit == 'page':
cursor.insertText('\n')
cursor.endEditBlock()
self._set_top_cursor(cursor)
cursor.joinPreviousEditBlock()
cursor.deletePreviousChar()
elif act.action == 'carriage-return':
cursor.movePosition(
cursor.StartOfLine, cursor.KeepAnchor)
elif act.action == 'beep':
QtGui.qApp.beep()
elif act.action == 'backspace':
if not cursor.atBlockStart():
cursor.movePosition(
cursor.PreviousCharacter, cursor.KeepAnchor)
elif act.action == 'newline':
cursor.movePosition(cursor.EndOfLine)
format = self._ansi_processor.get_format()
selection = cursor.selectedText()
if len(selection) == 0:
cursor.insertText(substring, format)
elif substring is not None:
# BS and CR are treated as a change in print
# position, rather than a backwards character
# deletion for output equivalence with (I)Python
# terminal.
if len(substring) >= len(selection):
cursor.insertText(substring, format)
else:
old_text = selection[len(substring):]
cursor.insertText(substring + old_text, format)
cursor.movePosition(cursor.PreviousCharacter,
cursor.KeepAnchor, len(old_text))
else:
cursor.insertText(text)
cursor.endEditBlock() | [
"Inserts",
"plain",
"text",
"using",
"the",
"specified",
"cursor",
"processing",
"ANSI",
"codes",
"if",
"enabled",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1586-L1644 | [
"def",
"_insert_plain_text",
"(",
"self",
",",
"cursor",
",",
"text",
")",
":",
"cursor",
".",
"beginEditBlock",
"(",
")",
"if",
"self",
".",
"ansi_codes",
":",
"for",
"substring",
"in",
"self",
".",
"_ansi_processor",
".",
"split_string",
"(",
"text",
")",
":",
"for",
"act",
"in",
"self",
".",
"_ansi_processor",
".",
"actions",
":",
"# Unlike real terminal emulators, we don't distinguish",
"# between the screen and the scrollback buffer. A screen",
"# erase request clears everything.",
"if",
"act",
".",
"action",
"==",
"'erase'",
"and",
"act",
".",
"area",
"==",
"'screen'",
":",
"cursor",
".",
"select",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Document",
")",
"cursor",
".",
"removeSelectedText",
"(",
")",
"# Simulate a form feed by scrolling just past the last line.",
"elif",
"act",
".",
"action",
"==",
"'scroll'",
"and",
"act",
".",
"unit",
"==",
"'page'",
":",
"cursor",
".",
"insertText",
"(",
"'\\n'",
")",
"cursor",
".",
"endEditBlock",
"(",
")",
"self",
".",
"_set_top_cursor",
"(",
"cursor",
")",
"cursor",
".",
"joinPreviousEditBlock",
"(",
")",
"cursor",
".",
"deletePreviousChar",
"(",
")",
"elif",
"act",
".",
"action",
"==",
"'carriage-return'",
":",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"StartOfLine",
",",
"cursor",
".",
"KeepAnchor",
")",
"elif",
"act",
".",
"action",
"==",
"'beep'",
":",
"QtGui",
".",
"qApp",
".",
"beep",
"(",
")",
"elif",
"act",
".",
"action",
"==",
"'backspace'",
":",
"if",
"not",
"cursor",
".",
"atBlockStart",
"(",
")",
":",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"PreviousCharacter",
",",
"cursor",
".",
"KeepAnchor",
")",
"elif",
"act",
".",
"action",
"==",
"'newline'",
":",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"EndOfLine",
")",
"format",
"=",
"self",
".",
"_ansi_processor",
".",
"get_format",
"(",
")",
"selection",
"=",
"cursor",
".",
"selectedText",
"(",
")",
"if",
"len",
"(",
"selection",
")",
"==",
"0",
":",
"cursor",
".",
"insertText",
"(",
"substring",
",",
"format",
")",
"elif",
"substring",
"is",
"not",
"None",
":",
"# BS and CR are treated as a change in print",
"# position, rather than a backwards character",
"# deletion for output equivalence with (I)Python",
"# terminal.",
"if",
"len",
"(",
"substring",
")",
">=",
"len",
"(",
"selection",
")",
":",
"cursor",
".",
"insertText",
"(",
"substring",
",",
"format",
")",
"else",
":",
"old_text",
"=",
"selection",
"[",
"len",
"(",
"substring",
")",
":",
"]",
"cursor",
".",
"insertText",
"(",
"substring",
"+",
"old_text",
",",
"format",
")",
"cursor",
".",
"movePosition",
"(",
"cursor",
".",
"PreviousCharacter",
",",
"cursor",
".",
"KeepAnchor",
",",
"len",
"(",
"old_text",
")",
")",
"else",
":",
"cursor",
".",
"insertText",
"(",
"text",
")",
"cursor",
".",
"endEditBlock",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._insert_plain_text_into_buffer | Inserts text into the input buffer using the specified cursor (which
must be in the input buffer), ensuring that continuation prompts are
inserted as necessary. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _insert_plain_text_into_buffer(self, cursor, text):
""" Inserts text into the input buffer using the specified cursor (which
must be in the input buffer), ensuring that continuation prompts are
inserted as necessary.
"""
lines = text.splitlines(True)
if lines:
cursor.beginEditBlock()
cursor.insertText(lines[0])
for line in lines[1:]:
if self._continuation_prompt_html is None:
cursor.insertText(self._continuation_prompt)
else:
self._continuation_prompt = \
self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
cursor.insertText(line)
cursor.endEditBlock() | def _insert_plain_text_into_buffer(self, cursor, text):
""" Inserts text into the input buffer using the specified cursor (which
must be in the input buffer), ensuring that continuation prompts are
inserted as necessary.
"""
lines = text.splitlines(True)
if lines:
cursor.beginEditBlock()
cursor.insertText(lines[0])
for line in lines[1:]:
if self._continuation_prompt_html is None:
cursor.insertText(self._continuation_prompt)
else:
self._continuation_prompt = \
self._insert_html_fetching_plain_text(
cursor, self._continuation_prompt_html)
cursor.insertText(line)
cursor.endEditBlock() | [
"Inserts",
"text",
"into",
"the",
"input",
"buffer",
"using",
"the",
"specified",
"cursor",
"(",
"which",
"must",
"be",
"in",
"the",
"input",
"buffer",
")",
"ensuring",
"that",
"continuation",
"prompts",
"are",
"inserted",
"as",
"necessary",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1646-L1663 | [
"def",
"_insert_plain_text_into_buffer",
"(",
"self",
",",
"cursor",
",",
"text",
")",
":",
"lines",
"=",
"text",
".",
"splitlines",
"(",
"True",
")",
"if",
"lines",
":",
"cursor",
".",
"beginEditBlock",
"(",
")",
"cursor",
".",
"insertText",
"(",
"lines",
"[",
"0",
"]",
")",
"for",
"line",
"in",
"lines",
"[",
"1",
":",
"]",
":",
"if",
"self",
".",
"_continuation_prompt_html",
"is",
"None",
":",
"cursor",
".",
"insertText",
"(",
"self",
".",
"_continuation_prompt",
")",
"else",
":",
"self",
".",
"_continuation_prompt",
"=",
"self",
".",
"_insert_html_fetching_plain_text",
"(",
"cursor",
",",
"self",
".",
"_continuation_prompt_html",
")",
"cursor",
".",
"insertText",
"(",
"line",
")",
"cursor",
".",
"endEditBlock",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._in_buffer | Returns whether the current cursor (or, if specified, a position) is
inside the editing region. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _in_buffer(self, position=None):
""" Returns whether the current cursor (or, if specified, a position) is
inside the editing region.
"""
cursor = self._control.textCursor()
if position is None:
position = cursor.position()
else:
cursor.setPosition(position)
line = cursor.blockNumber()
prompt_line = self._get_prompt_cursor().blockNumber()
if line == prompt_line:
return position >= self._prompt_pos
elif line > prompt_line:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
prompt_pos = cursor.position() + len(self._continuation_prompt)
return position >= prompt_pos
return False | def _in_buffer(self, position=None):
""" Returns whether the current cursor (or, if specified, a position) is
inside the editing region.
"""
cursor = self._control.textCursor()
if position is None:
position = cursor.position()
else:
cursor.setPosition(position)
line = cursor.blockNumber()
prompt_line = self._get_prompt_cursor().blockNumber()
if line == prompt_line:
return position >= self._prompt_pos
elif line > prompt_line:
cursor.movePosition(QtGui.QTextCursor.StartOfBlock)
prompt_pos = cursor.position() + len(self._continuation_prompt)
return position >= prompt_pos
return False | [
"Returns",
"whether",
"the",
"current",
"cursor",
"(",
"or",
"if",
"specified",
"a",
"position",
")",
"is",
"inside",
"the",
"editing",
"region",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1665-L1682 | [
"def",
"_in_buffer",
"(",
"self",
",",
"position",
"=",
"None",
")",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"if",
"position",
"is",
"None",
":",
"position",
"=",
"cursor",
".",
"position",
"(",
")",
"else",
":",
"cursor",
".",
"setPosition",
"(",
"position",
")",
"line",
"=",
"cursor",
".",
"blockNumber",
"(",
")",
"prompt_line",
"=",
"self",
".",
"_get_prompt_cursor",
"(",
")",
".",
"blockNumber",
"(",
")",
"if",
"line",
"==",
"prompt_line",
":",
"return",
"position",
">=",
"self",
".",
"_prompt_pos",
"elif",
"line",
">",
"prompt_line",
":",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"StartOfBlock",
")",
"prompt_pos",
"=",
"cursor",
".",
"position",
"(",
")",
"+",
"len",
"(",
"self",
".",
"_continuation_prompt",
")",
"return",
"position",
">=",
"prompt_pos",
"return",
"False"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._keep_cursor_in_buffer | Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
return moved | def _keep_cursor_in_buffer(self):
""" Ensures that the cursor is inside the editing region. Returns
whether the cursor was moved.
"""
moved = not self._in_buffer()
if moved:
cursor = self._control.textCursor()
cursor.movePosition(QtGui.QTextCursor.End)
self._control.setTextCursor(cursor)
return moved | [
"Ensures",
"that",
"the",
"cursor",
"is",
"inside",
"the",
"editing",
"region",
".",
"Returns",
"whether",
"the",
"cursor",
"was",
"moved",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1684-L1693 | [
"def",
"_keep_cursor_in_buffer",
"(",
"self",
")",
":",
"moved",
"=",
"not",
"self",
".",
"_in_buffer",
"(",
")",
"if",
"moved",
":",
"cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")",
"self",
".",
"_control",
".",
"setTextCursor",
"(",
"cursor",
")",
"return",
"moved"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._keyboard_quit | Cancels the current editing task ala Ctrl-G in Emacs. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _keyboard_quit(self):
""" Cancels the current editing task ala Ctrl-G in Emacs.
"""
if self._temp_buffer_filled :
self._cancel_completion()
self._clear_temporary_buffer()
else:
self.input_buffer = '' | def _keyboard_quit(self):
""" Cancels the current editing task ala Ctrl-G in Emacs.
"""
if self._temp_buffer_filled :
self._cancel_completion()
self._clear_temporary_buffer()
else:
self.input_buffer = '' | [
"Cancels",
"the",
"current",
"editing",
"task",
"ala",
"Ctrl",
"-",
"G",
"in",
"Emacs",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1695-L1702 | [
"def",
"_keyboard_quit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_temp_buffer_filled",
":",
"self",
".",
"_cancel_completion",
"(",
")",
"self",
".",
"_clear_temporary_buffer",
"(",
")",
"else",
":",
"self",
".",
"input_buffer",
"=",
"''"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._page | Displays text using the pager if it exceeds the height of the
viewport.
Parameters:
-----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _page(self, text, html=False):
""" Displays text using the pager if it exceeds the height of the
viewport.
Parameters:
-----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text.
"""
line_height = QtGui.QFontMetrics(self.font).height()
minlines = self._control.viewport().height() / line_height
if self.paging != 'none' and \
re.match("(?:[^\n]*\n){%i}" % minlines, text):
if self.paging == 'custom':
self.custom_page_requested.emit(text)
else:
self._page_control.clear()
cursor = self._page_control.textCursor()
if html:
self._insert_html(cursor, text)
else:
self._insert_plain_text(cursor, text)
self._page_control.moveCursor(QtGui.QTextCursor.Start)
self._page_control.viewport().resize(self._control.size())
if self._splitter:
self._page_control.show()
self._page_control.setFocus()
else:
self.layout().setCurrentWidget(self._page_control)
elif html:
self._append_html(text)
else:
self._append_plain_text(text) | def _page(self, text, html=False):
""" Displays text using the pager if it exceeds the height of the
viewport.
Parameters:
-----------
html : bool, optional (default False)
If set, the text will be interpreted as HTML instead of plain text.
"""
line_height = QtGui.QFontMetrics(self.font).height()
minlines = self._control.viewport().height() / line_height
if self.paging != 'none' and \
re.match("(?:[^\n]*\n){%i}" % minlines, text):
if self.paging == 'custom':
self.custom_page_requested.emit(text)
else:
self._page_control.clear()
cursor = self._page_control.textCursor()
if html:
self._insert_html(cursor, text)
else:
self._insert_plain_text(cursor, text)
self._page_control.moveCursor(QtGui.QTextCursor.Start)
self._page_control.viewport().resize(self._control.size())
if self._splitter:
self._page_control.show()
self._page_control.setFocus()
else:
self.layout().setCurrentWidget(self._page_control)
elif html:
self._append_html(text)
else:
self._append_plain_text(text) | [
"Displays",
"text",
"using",
"the",
"pager",
"if",
"it",
"exceeds",
"the",
"height",
"of",
"the",
"viewport",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1704-L1737 | [
"def",
"_page",
"(",
"self",
",",
"text",
",",
"html",
"=",
"False",
")",
":",
"line_height",
"=",
"QtGui",
".",
"QFontMetrics",
"(",
"self",
".",
"font",
")",
".",
"height",
"(",
")",
"minlines",
"=",
"self",
".",
"_control",
".",
"viewport",
"(",
")",
".",
"height",
"(",
")",
"/",
"line_height",
"if",
"self",
".",
"paging",
"!=",
"'none'",
"and",
"re",
".",
"match",
"(",
"\"(?:[^\\n]*\\n){%i}\"",
"%",
"minlines",
",",
"text",
")",
":",
"if",
"self",
".",
"paging",
"==",
"'custom'",
":",
"self",
".",
"custom_page_requested",
".",
"emit",
"(",
"text",
")",
"else",
":",
"self",
".",
"_page_control",
".",
"clear",
"(",
")",
"cursor",
"=",
"self",
".",
"_page_control",
".",
"textCursor",
"(",
")",
"if",
"html",
":",
"self",
".",
"_insert_html",
"(",
"cursor",
",",
"text",
")",
"else",
":",
"self",
".",
"_insert_plain_text",
"(",
"cursor",
",",
"text",
")",
"self",
".",
"_page_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Start",
")",
"self",
".",
"_page_control",
".",
"viewport",
"(",
")",
".",
"resize",
"(",
"self",
".",
"_control",
".",
"size",
"(",
")",
")",
"if",
"self",
".",
"_splitter",
":",
"self",
".",
"_page_control",
".",
"show",
"(",
")",
"self",
".",
"_page_control",
".",
"setFocus",
"(",
")",
"else",
":",
"self",
".",
"layout",
"(",
")",
".",
"setCurrentWidget",
"(",
"self",
".",
"_page_control",
")",
"elif",
"html",
":",
"self",
".",
"_append_html",
"(",
"text",
")",
"else",
":",
"self",
".",
"_append_plain_text",
"(",
"text",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._prompt_started | Called immediately after a new prompt is displayed. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _prompt_started(self):
""" Called immediately after a new prompt is displayed.
"""
# Temporarily disable the maximum block count to permit undo/redo and
# to ensure that the prompt position does not change due to truncation.
self._control.document().setMaximumBlockCount(0)
self._control.setUndoRedoEnabled(True)
# Work around bug in QPlainTextEdit: input method is not re-enabled
# when read-only is disabled.
self._control.setReadOnly(False)
self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
if not self._reading:
self._executing = False
self._prompt_started_hook()
# If the input buffer has changed while executing, load it.
if self._input_buffer_pending:
self.input_buffer = self._input_buffer_pending
self._input_buffer_pending = ''
self._control.moveCursor(QtGui.QTextCursor.End) | def _prompt_started(self):
""" Called immediately after a new prompt is displayed.
"""
# Temporarily disable the maximum block count to permit undo/redo and
# to ensure that the prompt position does not change due to truncation.
self._control.document().setMaximumBlockCount(0)
self._control.setUndoRedoEnabled(True)
# Work around bug in QPlainTextEdit: input method is not re-enabled
# when read-only is disabled.
self._control.setReadOnly(False)
self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)
if not self._reading:
self._executing = False
self._prompt_started_hook()
# If the input buffer has changed while executing, load it.
if self._input_buffer_pending:
self.input_buffer = self._input_buffer_pending
self._input_buffer_pending = ''
self._control.moveCursor(QtGui.QTextCursor.End) | [
"Called",
"immediately",
"after",
"a",
"new",
"prompt",
"is",
"displayed",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1746-L1768 | [
"def",
"_prompt_started",
"(",
"self",
")",
":",
"# Temporarily disable the maximum block count to permit undo/redo and",
"# to ensure that the prompt position does not change due to truncation.",
"self",
".",
"_control",
".",
"document",
"(",
")",
".",
"setMaximumBlockCount",
"(",
"0",
")",
"self",
".",
"_control",
".",
"setUndoRedoEnabled",
"(",
"True",
")",
"# Work around bug in QPlainTextEdit: input method is not re-enabled",
"# when read-only is disabled.",
"self",
".",
"_control",
".",
"setReadOnly",
"(",
"False",
")",
"self",
".",
"_control",
".",
"setAttribute",
"(",
"QtCore",
".",
"Qt",
".",
"WA_InputMethodEnabled",
",",
"True",
")",
"if",
"not",
"self",
".",
"_reading",
":",
"self",
".",
"_executing",
"=",
"False",
"self",
".",
"_prompt_started_hook",
"(",
")",
"# If the input buffer has changed while executing, load it.",
"if",
"self",
".",
"_input_buffer_pending",
":",
"self",
".",
"input_buffer",
"=",
"self",
".",
"_input_buffer_pending",
"self",
".",
"_input_buffer_pending",
"=",
"''",
"self",
".",
"_control",
".",
"moveCursor",
"(",
"QtGui",
".",
"QTextCursor",
".",
"End",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._readline | Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* and this method does not return until it has
been read.
Returns
-------
If a callback is specified, returns nothing. Otherwise, returns the
input string with the trailing newline stripped. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _readline(self, prompt='', callback=None):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* and this method does not return until it has
been read.
Returns
-------
If a callback is specified, returns nothing. Otherwise, returns the
input string with the trailing newline stripped.
"""
if self._reading:
raise RuntimeError('Cannot read a line. Widget is already reading.')
if not callback and not self.isVisible():
# If the user cannot see the widget, this function cannot return.
raise RuntimeError('Cannot synchronously read a line if the widget '
'is not visible!')
self._reading = True
self._show_prompt(prompt, newline=False)
if callback is None:
self._reading_callback = None
while self._reading:
QtCore.QCoreApplication.processEvents()
return self._get_input_buffer(force=True).rstrip('\n')
else:
self._reading_callback = lambda: \
callback(self._get_input_buffer(force=True).rstrip('\n')) | def _readline(self, prompt='', callback=None):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* and this method does not return until it has
been read.
Returns
-------
If a callback is specified, returns nothing. Otherwise, returns the
input string with the trailing newline stripped.
"""
if self._reading:
raise RuntimeError('Cannot read a line. Widget is already reading.')
if not callback and not self.isVisible():
# If the user cannot see the widget, this function cannot return.
raise RuntimeError('Cannot synchronously read a line if the widget '
'is not visible!')
self._reading = True
self._show_prompt(prompt, newline=False)
if callback is None:
self._reading_callback = None
while self._reading:
QtCore.QCoreApplication.processEvents()
return self._get_input_buffer(force=True).rstrip('\n')
else:
self._reading_callback = lambda: \
callback(self._get_input_buffer(force=True).rstrip('\n')) | [
"Reads",
"one",
"line",
"of",
"input",
"from",
"the",
"user",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1770-L1807 | [
"def",
"_readline",
"(",
"self",
",",
"prompt",
"=",
"''",
",",
"callback",
"=",
"None",
")",
":",
"if",
"self",
".",
"_reading",
":",
"raise",
"RuntimeError",
"(",
"'Cannot read a line. Widget is already reading.'",
")",
"if",
"not",
"callback",
"and",
"not",
"self",
".",
"isVisible",
"(",
")",
":",
"# If the user cannot see the widget, this function cannot return.",
"raise",
"RuntimeError",
"(",
"'Cannot synchronously read a line if the widget '",
"'is not visible!'",
")",
"self",
".",
"_reading",
"=",
"True",
"self",
".",
"_show_prompt",
"(",
"prompt",
",",
"newline",
"=",
"False",
")",
"if",
"callback",
"is",
"None",
":",
"self",
".",
"_reading_callback",
"=",
"None",
"while",
"self",
".",
"_reading",
":",
"QtCore",
".",
"QCoreApplication",
".",
"processEvents",
"(",
")",
"return",
"self",
".",
"_get_input_buffer",
"(",
"force",
"=",
"True",
")",
".",
"rstrip",
"(",
"'\\n'",
")",
"else",
":",
"self",
".",
"_reading_callback",
"=",
"lambda",
":",
"callback",
"(",
"self",
".",
"_get_input_buffer",
"(",
"force",
"=",
"True",
")",
".",
"rstrip",
"(",
"'\\n'",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._set_continuation_prompt | Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as formatted HTML. Otherwise,
the prompt will be treated as plain text, though ANSI color codes
will be handled. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _set_continuation_prompt(self, prompt, html=False):
""" Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as formatted HTML. Otherwise,
the prompt will be treated as plain text, though ANSI color codes
will be handled.
"""
if html:
self._continuation_prompt_html = prompt
else:
self._continuation_prompt = prompt
self._continuation_prompt_html = None | def _set_continuation_prompt(self, prompt, html=False):
""" Sets the continuation prompt.
Parameters
----------
prompt : str
The prompt to show when more input is needed.
html : bool, optional (default False)
If set, the prompt will be inserted as formatted HTML. Otherwise,
the prompt will be treated as plain text, though ANSI color codes
will be handled.
"""
if html:
self._continuation_prompt_html = prompt
else:
self._continuation_prompt = prompt
self._continuation_prompt_html = None | [
"Sets",
"the",
"continuation",
"prompt",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1809-L1826 | [
"def",
"_set_continuation_prompt",
"(",
"self",
",",
"prompt",
",",
"html",
"=",
"False",
")",
":",
"if",
"html",
":",
"self",
".",
"_continuation_prompt_html",
"=",
"prompt",
"else",
":",
"self",
".",
"_continuation_prompt",
"=",
"prompt",
"self",
".",
"_continuation_prompt_html",
"=",
"None"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._set_top_cursor | Scrolls the viewport so that the specified cursor is at the top. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _set_top_cursor(self, cursor):
""" Scrolls the viewport so that the specified cursor is at the top.
"""
scrollbar = self._control.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
original_cursor = self._control.textCursor()
self._control.setTextCursor(cursor)
self._control.ensureCursorVisible()
self._control.setTextCursor(original_cursor) | def _set_top_cursor(self, cursor):
""" Scrolls the viewport so that the specified cursor is at the top.
"""
scrollbar = self._control.verticalScrollBar()
scrollbar.setValue(scrollbar.maximum())
original_cursor = self._control.textCursor()
self._control.setTextCursor(cursor)
self._control.ensureCursorVisible()
self._control.setTextCursor(original_cursor) | [
"Scrolls",
"the",
"viewport",
"so",
"that",
"the",
"specified",
"cursor",
"is",
"at",
"the",
"top",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1833-L1841 | [
"def",
"_set_top_cursor",
"(",
"self",
",",
"cursor",
")",
":",
"scrollbar",
"=",
"self",
".",
"_control",
".",
"verticalScrollBar",
"(",
")",
"scrollbar",
".",
"setValue",
"(",
"scrollbar",
".",
"maximum",
"(",
")",
")",
"original_cursor",
"=",
"self",
".",
"_control",
".",
"textCursor",
"(",
")",
"self",
".",
"_control",
".",
"setTextCursor",
"(",
"cursor",
")",
"self",
".",
"_control",
".",
"ensureCursorVisible",
"(",
")",
"self",
".",
"_control",
".",
"setTextCursor",
"(",
"original_cursor",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._show_prompt | Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
Only relevant when a prompt is specified. If set, the prompt will
be inserted as formatted HTML. Otherwise, the prompt will be treated
as plain text, though ANSI color codes will be handled.
newline : bool, optional (default True)
If set, a new line will be written before showing the prompt if
there is not already a newline at the end of the buffer. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _show_prompt(self, prompt=None, html=False, newline=True):
""" Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
Only relevant when a prompt is specified. If set, the prompt will
be inserted as formatted HTML. Otherwise, the prompt will be treated
as plain text, though ANSI color codes will be handled.
newline : bool, optional (default True)
If set, a new line will be written before showing the prompt if
there is not already a newline at the end of the buffer.
"""
# Save the current end position to support _append*(before_prompt=True).
cursor = self._get_end_cursor()
self._append_before_prompt_pos = cursor.position()
# Insert a preliminary newline, if necessary.
if newline and cursor.position() > 0:
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() != '\n':
self._append_plain_text('\n')
# Write the prompt.
self._append_plain_text(self._prompt_sep)
if prompt is None:
if self._prompt_html is None:
self._append_plain_text(self._prompt)
else:
self._append_html(self._prompt_html)
else:
if html:
self._prompt = self._append_html_fetching_plain_text(prompt)
self._prompt_html = prompt
else:
self._append_plain_text(prompt)
self._prompt = prompt
self._prompt_html = None
self._prompt_pos = self._get_end_cursor().position()
self._prompt_started() | def _show_prompt(self, prompt=None, html=False, newline=True):
""" Writes a new prompt at the end of the buffer.
Parameters
----------
prompt : str, optional
The prompt to show. If not specified, the previous prompt is used.
html : bool, optional (default False)
Only relevant when a prompt is specified. If set, the prompt will
be inserted as formatted HTML. Otherwise, the prompt will be treated
as plain text, though ANSI color codes will be handled.
newline : bool, optional (default True)
If set, a new line will be written before showing the prompt if
there is not already a newline at the end of the buffer.
"""
# Save the current end position to support _append*(before_prompt=True).
cursor = self._get_end_cursor()
self._append_before_prompt_pos = cursor.position()
# Insert a preliminary newline, if necessary.
if newline and cursor.position() > 0:
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor)
if cursor.selection().toPlainText() != '\n':
self._append_plain_text('\n')
# Write the prompt.
self._append_plain_text(self._prompt_sep)
if prompt is None:
if self._prompt_html is None:
self._append_plain_text(self._prompt)
else:
self._append_html(self._prompt_html)
else:
if html:
self._prompt = self._append_html_fetching_plain_text(prompt)
self._prompt_html = prompt
else:
self._append_plain_text(prompt)
self._prompt = prompt
self._prompt_html = None
self._prompt_pos = self._get_end_cursor().position()
self._prompt_started() | [
"Writes",
"a",
"new",
"prompt",
"at",
"the",
"end",
"of",
"the",
"buffer",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1843-L1888 | [
"def",
"_show_prompt",
"(",
"self",
",",
"prompt",
"=",
"None",
",",
"html",
"=",
"False",
",",
"newline",
"=",
"True",
")",
":",
"# Save the current end position to support _append*(before_prompt=True).",
"cursor",
"=",
"self",
".",
"_get_end_cursor",
"(",
")",
"self",
".",
"_append_before_prompt_pos",
"=",
"cursor",
".",
"position",
"(",
")",
"# Insert a preliminary newline, if necessary.",
"if",
"newline",
"and",
"cursor",
".",
"position",
"(",
")",
">",
"0",
":",
"cursor",
".",
"movePosition",
"(",
"QtGui",
".",
"QTextCursor",
".",
"Left",
",",
"QtGui",
".",
"QTextCursor",
".",
"KeepAnchor",
")",
"if",
"cursor",
".",
"selection",
"(",
")",
".",
"toPlainText",
"(",
")",
"!=",
"'\\n'",
":",
"self",
".",
"_append_plain_text",
"(",
"'\\n'",
")",
"# Write the prompt.",
"self",
".",
"_append_plain_text",
"(",
"self",
".",
"_prompt_sep",
")",
"if",
"prompt",
"is",
"None",
":",
"if",
"self",
".",
"_prompt_html",
"is",
"None",
":",
"self",
".",
"_append_plain_text",
"(",
"self",
".",
"_prompt",
")",
"else",
":",
"self",
".",
"_append_html",
"(",
"self",
".",
"_prompt_html",
")",
"else",
":",
"if",
"html",
":",
"self",
".",
"_prompt",
"=",
"self",
".",
"_append_html_fetching_plain_text",
"(",
"prompt",
")",
"self",
".",
"_prompt_html",
"=",
"prompt",
"else",
":",
"self",
".",
"_append_plain_text",
"(",
"prompt",
")",
"self",
".",
"_prompt",
"=",
"prompt",
"self",
".",
"_prompt_html",
"=",
"None",
"self",
".",
"_prompt_pos",
"=",
"self",
".",
"_get_end_cursor",
"(",
")",
".",
"position",
"(",
")",
"self",
".",
"_prompt_started",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._adjust_scrollbars | Expands the vertical scrollbar beyond the range set by Qt. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _adjust_scrollbars(self):
""" Expands the vertical scrollbar beyond the range set by Qt.
"""
# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
# and qtextedit.cpp.
document = self._control.document()
scrollbar = self._control.verticalScrollBar()
viewport_height = self._control.viewport().height()
if isinstance(self._control, QtGui.QPlainTextEdit):
maximum = max(0, document.lineCount() - 1)
step = viewport_height / self._control.fontMetrics().lineSpacing()
else:
# QTextEdit does not do line-based layout and blocks will not in
# general have the same height. Therefore it does not make sense to
# attempt to scroll in line height increments.
maximum = document.size().height()
step = viewport_height
diff = maximum - scrollbar.maximum()
scrollbar.setRange(0, maximum)
scrollbar.setPageStep(step)
# Compensate for undesirable scrolling that occurs automatically due to
# maximumBlockCount() text truncation.
if diff < 0 and document.blockCount() == document.maximumBlockCount():
scrollbar.setValue(scrollbar.value() + diff) | def _adjust_scrollbars(self):
""" Expands the vertical scrollbar beyond the range set by Qt.
"""
# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp
# and qtextedit.cpp.
document = self._control.document()
scrollbar = self._control.verticalScrollBar()
viewport_height = self._control.viewport().height()
if isinstance(self._control, QtGui.QPlainTextEdit):
maximum = max(0, document.lineCount() - 1)
step = viewport_height / self._control.fontMetrics().lineSpacing()
else:
# QTextEdit does not do line-based layout and blocks will not in
# general have the same height. Therefore it does not make sense to
# attempt to scroll in line height increments.
maximum = document.size().height()
step = viewport_height
diff = maximum - scrollbar.maximum()
scrollbar.setRange(0, maximum)
scrollbar.setPageStep(step)
# Compensate for undesirable scrolling that occurs automatically due to
# maximumBlockCount() text truncation.
if diff < 0 and document.blockCount() == document.maximumBlockCount():
scrollbar.setValue(scrollbar.value() + diff) | [
"Expands",
"the",
"vertical",
"scrollbar",
"beyond",
"the",
"range",
"set",
"by",
"Qt",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1892-L1916 | [
"def",
"_adjust_scrollbars",
"(",
"self",
")",
":",
"# This code is adapted from _q_adjustScrollbars in qplaintextedit.cpp",
"# and qtextedit.cpp.",
"document",
"=",
"self",
".",
"_control",
".",
"document",
"(",
")",
"scrollbar",
"=",
"self",
".",
"_control",
".",
"verticalScrollBar",
"(",
")",
"viewport_height",
"=",
"self",
".",
"_control",
".",
"viewport",
"(",
")",
".",
"height",
"(",
")",
"if",
"isinstance",
"(",
"self",
".",
"_control",
",",
"QtGui",
".",
"QPlainTextEdit",
")",
":",
"maximum",
"=",
"max",
"(",
"0",
",",
"document",
".",
"lineCount",
"(",
")",
"-",
"1",
")",
"step",
"=",
"viewport_height",
"/",
"self",
".",
"_control",
".",
"fontMetrics",
"(",
")",
".",
"lineSpacing",
"(",
")",
"else",
":",
"# QTextEdit does not do line-based layout and blocks will not in",
"# general have the same height. Therefore it does not make sense to",
"# attempt to scroll in line height increments.",
"maximum",
"=",
"document",
".",
"size",
"(",
")",
".",
"height",
"(",
")",
"step",
"=",
"viewport_height",
"diff",
"=",
"maximum",
"-",
"scrollbar",
".",
"maximum",
"(",
")",
"scrollbar",
".",
"setRange",
"(",
"0",
",",
"maximum",
")",
"scrollbar",
".",
"setPageStep",
"(",
"step",
")",
"# Compensate for undesirable scrolling that occurs automatically due to",
"# maximumBlockCount() text truncation.",
"if",
"diff",
"<",
"0",
"and",
"document",
".",
"blockCount",
"(",
")",
"==",
"document",
".",
"maximumBlockCount",
"(",
")",
":",
"scrollbar",
".",
"setValue",
"(",
"scrollbar",
".",
"value",
"(",
")",
"+",
"diff",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ConsoleWidget._custom_context_menu_requested | Shows a context menu at the given QPoint (in widget coordinates). | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py | def _custom_context_menu_requested(self, pos):
""" Shows a context menu at the given QPoint (in widget coordinates).
"""
menu = self._context_menu_make(pos)
menu.exec_(self._control.mapToGlobal(pos)) | def _custom_context_menu_requested(self, pos):
""" Shows a context menu at the given QPoint (in widget coordinates).
"""
menu = self._context_menu_make(pos)
menu.exec_(self._control.mapToGlobal(pos)) | [
"Shows",
"a",
"context",
"menu",
"at",
"the",
"given",
"QPoint",
"(",
"in",
"widget",
"coordinates",
")",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/console_widget.py#L1918-L1922 | [
"def",
"_custom_context_menu_requested",
"(",
"self",
",",
"pos",
")",
":",
"menu",
"=",
"self",
".",
"_context_menu_make",
"(",
"pos",
")",
"menu",
".",
"exec_",
"(",
"self",
".",
"_control",
".",
"mapToGlobal",
"(",
"pos",
")",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | dist_in_usersite | Return True if given Distribution is installed in user site. | environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/util.py | def dist_in_usersite(dist):
"""
Return True if given Distribution is installed in user site.
"""
if user_site:
return normalize_path(dist_location(dist)).startswith(normalize_path(user_site))
else:
return False | def dist_in_usersite(dist):
"""
Return True if given Distribution is installed in user site.
"""
if user_site:
return normalize_path(dist_location(dist)).startswith(normalize_path(user_site))
else:
return False | [
"Return",
"True",
"if",
"given",
"Distribution",
"is",
"installed",
"in",
"user",
"site",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/util.py#L306-L313 | [
"def",
"dist_in_usersite",
"(",
"dist",
")",
":",
"if",
"user_site",
":",
"return",
"normalize_path",
"(",
"dist_location",
"(",
"dist",
")",
")",
".",
"startswith",
"(",
"normalize_path",
"(",
"user_site",
")",
")",
"else",
":",
"return",
"False"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | print_results | Print the informations from installed distributions found. | virtualEnvironment/lib/python2.7/site-packages/pip/commands/show.py | def print_results(distributions, list_all_files):
"""
Print the informations from installed distributions found.
"""
results_printed = False
for dist in distributions:
results_printed = True
logger.info("---")
logger.info("Name: %s" % dist['name'])
logger.info("Version: %s" % dist['version'])
logger.info("Location: %s" % dist['location'])
logger.info("Requires: %s" % ', '.join(dist['requires']))
if list_all_files:
logger.info("Files:")
if dist['files'] is not None:
for line in dist['files']:
logger.info(" %s" % line.strip())
else:
logger.info("Cannot locate installed-files.txt")
return results_printed | def print_results(distributions, list_all_files):
"""
Print the informations from installed distributions found.
"""
results_printed = False
for dist in distributions:
results_printed = True
logger.info("---")
logger.info("Name: %s" % dist['name'])
logger.info("Version: %s" % dist['version'])
logger.info("Location: %s" % dist['location'])
logger.info("Requires: %s" % ', '.join(dist['requires']))
if list_all_files:
logger.info("Files:")
if dist['files'] is not None:
for line in dist['files']:
logger.info(" %s" % line.strip())
else:
logger.info("Cannot locate installed-files.txt")
return results_printed | [
"Print",
"the",
"informations",
"from",
"installed",
"distributions",
"found",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/commands/show.py#L81-L100 | [
"def",
"print_results",
"(",
"distributions",
",",
"list_all_files",
")",
":",
"results_printed",
"=",
"False",
"for",
"dist",
"in",
"distributions",
":",
"results_printed",
"=",
"True",
"logger",
".",
"info",
"(",
"\"---\"",
")",
"logger",
".",
"info",
"(",
"\"Name: %s\"",
"%",
"dist",
"[",
"'name'",
"]",
")",
"logger",
".",
"info",
"(",
"\"Version: %s\"",
"%",
"dist",
"[",
"'version'",
"]",
")",
"logger",
".",
"info",
"(",
"\"Location: %s\"",
"%",
"dist",
"[",
"'location'",
"]",
")",
"logger",
".",
"info",
"(",
"\"Requires: %s\"",
"%",
"', '",
".",
"join",
"(",
"dist",
"[",
"'requires'",
"]",
")",
")",
"if",
"list_all_files",
":",
"logger",
".",
"info",
"(",
"\"Files:\"",
")",
"if",
"dist",
"[",
"'files'",
"]",
"is",
"not",
"None",
":",
"for",
"line",
"in",
"dist",
"[",
"'files'",
"]",
":",
"logger",
".",
"info",
"(",
"\" %s\"",
"%",
"line",
".",
"strip",
"(",
")",
")",
"else",
":",
"logger",
".",
"info",
"(",
"\"Cannot locate installed-files.txt\"",
")",
"return",
"results_printed"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | main | Entry point for pkginfo tool | virtualEnvironment/lib/python2.7/site-packages/pkginfo/commandline.py | def main(args=None):
"""Entry point for pkginfo tool
"""
options, paths = _parse_options(args)
format = getattr(options, 'output', 'simple')
formatter = _FORMATTERS[format](options)
for path in paths:
meta = get_metadata(path, options.metadata_version)
if meta is None:
continue
if options.download_url_prefix:
if meta.download_url is None:
filename = os.path.basename(path)
meta.download_url = '%s/%s' % (options.download_url_prefix,
filename)
formatter(meta)
formatter.finish() | def main(args=None):
"""Entry point for pkginfo tool
"""
options, paths = _parse_options(args)
format = getattr(options, 'output', 'simple')
formatter = _FORMATTERS[format](options)
for path in paths:
meta = get_metadata(path, options.metadata_version)
if meta is None:
continue
if options.download_url_prefix:
if meta.download_url is None:
filename = os.path.basename(path)
meta.download_url = '%s/%s' % (options.download_url_prefix,
filename)
formatter(meta)
formatter.finish() | [
"Entry",
"point",
"for",
"pkginfo",
"tool"
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pkginfo/commandline.py#L184-L204 | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"options",
",",
"paths",
"=",
"_parse_options",
"(",
"args",
")",
"format",
"=",
"getattr",
"(",
"options",
",",
"'output'",
",",
"'simple'",
")",
"formatter",
"=",
"_FORMATTERS",
"[",
"format",
"]",
"(",
"options",
")",
"for",
"path",
"in",
"paths",
":",
"meta",
"=",
"get_metadata",
"(",
"path",
",",
"options",
".",
"metadata_version",
")",
"if",
"meta",
"is",
"None",
":",
"continue",
"if",
"options",
".",
"download_url_prefix",
":",
"if",
"meta",
".",
"download_url",
"is",
"None",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"meta",
".",
"download_url",
"=",
"'%s/%s'",
"%",
"(",
"options",
".",
"download_url_prefix",
",",
"filename",
")",
"formatter",
"(",
"meta",
")",
"formatter",
".",
"finish",
"(",
")"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | CompletionLexer.get_context | Assuming the cursor is at the end of the specified string, get the
context (a list of names) for the symbol at cursor position. | environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_lexer.py | def get_context(self, string):
""" Assuming the cursor is at the end of the specified string, get the
context (a list of names) for the symbol at cursor position.
"""
context = []
reversed_tokens = list(self._lexer.get_tokens(string))
reversed_tokens.reverse()
# Pygments often tacks on a newline when none is specified in the input.
# Remove this newline.
if reversed_tokens and reversed_tokens[0][1].endswith('\n') and \
not string.endswith('\n'):
reversed_tokens.pop(0)
current_op = ''
for token, text in reversed_tokens:
if is_token_subtype(token, Token.Name):
# Handle a trailing separator, e.g 'foo.bar.'
if current_op in self._name_separators:
if not context:
context.insert(0, '')
# Handle non-separator operators and punction.
elif current_op:
break
context.insert(0, text)
current_op = ''
# Pygments doesn't understand that, e.g., '->' is a single operator
# in C++. This is why we have to build up an operator from
# potentially several tokens.
elif token is Token.Operator or token is Token.Punctuation:
current_op = text + current_op
# Break on anything that is not a Operator, Punctuation, or Name.
else:
break
return context | def get_context(self, string):
""" Assuming the cursor is at the end of the specified string, get the
context (a list of names) for the symbol at cursor position.
"""
context = []
reversed_tokens = list(self._lexer.get_tokens(string))
reversed_tokens.reverse()
# Pygments often tacks on a newline when none is specified in the input.
# Remove this newline.
if reversed_tokens and reversed_tokens[0][1].endswith('\n') and \
not string.endswith('\n'):
reversed_tokens.pop(0)
current_op = ''
for token, text in reversed_tokens:
if is_token_subtype(token, Token.Name):
# Handle a trailing separator, e.g 'foo.bar.'
if current_op in self._name_separators:
if not context:
context.insert(0, '')
# Handle non-separator operators and punction.
elif current_op:
break
context.insert(0, text)
current_op = ''
# Pygments doesn't understand that, e.g., '->' is a single operator
# in C++. This is why we have to build up an operator from
# potentially several tokens.
elif token is Token.Operator or token is Token.Punctuation:
current_op = text + current_op
# Break on anything that is not a Operator, Punctuation, or Name.
else:
break
return context | [
"Assuming",
"the",
"cursor",
"is",
"at",
"the",
"end",
"of",
"the",
"specified",
"string",
"get",
"the",
"context",
"(",
"a",
"list",
"of",
"names",
")",
"for",
"the",
"symbol",
"at",
"cursor",
"position",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_lexer.py#L20-L61 | [
"def",
"get_context",
"(",
"self",
",",
"string",
")",
":",
"context",
"=",
"[",
"]",
"reversed_tokens",
"=",
"list",
"(",
"self",
".",
"_lexer",
".",
"get_tokens",
"(",
"string",
")",
")",
"reversed_tokens",
".",
"reverse",
"(",
")",
"# Pygments often tacks on a newline when none is specified in the input.",
"# Remove this newline.",
"if",
"reversed_tokens",
"and",
"reversed_tokens",
"[",
"0",
"]",
"[",
"1",
"]",
".",
"endswith",
"(",
"'\\n'",
")",
"and",
"not",
"string",
".",
"endswith",
"(",
"'\\n'",
")",
":",
"reversed_tokens",
".",
"pop",
"(",
"0",
")",
"current_op",
"=",
"''",
"for",
"token",
",",
"text",
"in",
"reversed_tokens",
":",
"if",
"is_token_subtype",
"(",
"token",
",",
"Token",
".",
"Name",
")",
":",
"# Handle a trailing separator, e.g 'foo.bar.'",
"if",
"current_op",
"in",
"self",
".",
"_name_separators",
":",
"if",
"not",
"context",
":",
"context",
".",
"insert",
"(",
"0",
",",
"''",
")",
"# Handle non-separator operators and punction.",
"elif",
"current_op",
":",
"break",
"context",
".",
"insert",
"(",
"0",
",",
"text",
")",
"current_op",
"=",
"''",
"# Pygments doesn't understand that, e.g., '->' is a single operator",
"# in C++. This is why we have to build up an operator from",
"# potentially several tokens.",
"elif",
"token",
"is",
"Token",
".",
"Operator",
"or",
"token",
"is",
"Token",
".",
"Punctuation",
":",
"current_op",
"=",
"text",
"+",
"current_op",
"# Break on anything that is not a Operator, Punctuation, or Name.",
"else",
":",
"break",
"return",
"context"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ProfileDir.copy_config_file | Copy a default config file into the active profile directory.
Default configuration files are kept in :mod:`IPython.config.default`.
This function moves these from that location to the working profile
directory. | environment/lib/python2.7/site-packages/IPython/core/profiledir.py | def copy_config_file(self, config_file, path=None, overwrite=False):
"""Copy a default config file into the active profile directory.
Default configuration files are kept in :mod:`IPython.config.default`.
This function moves these from that location to the working profile
directory.
"""
dst = os.path.join(self.location, config_file)
if os.path.isfile(dst) and not overwrite:
return False
if path is None:
path = os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
src = os.path.join(path, config_file)
shutil.copy(src, dst)
return True | def copy_config_file(self, config_file, path=None, overwrite=False):
"""Copy a default config file into the active profile directory.
Default configuration files are kept in :mod:`IPython.config.default`.
This function moves these from that location to the working profile
directory.
"""
dst = os.path.join(self.location, config_file)
if os.path.isfile(dst) and not overwrite:
return False
if path is None:
path = os.path.join(get_ipython_package_dir(), u'config', u'profile', u'default')
src = os.path.join(path, config_file)
shutil.copy(src, dst)
return True | [
"Copy",
"a",
"default",
"config",
"file",
"into",
"the",
"active",
"profile",
"directory",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/profiledir.py#L138-L152 | [
"def",
"copy_config_file",
"(",
"self",
",",
"config_file",
",",
"path",
"=",
"None",
",",
"overwrite",
"=",
"False",
")",
":",
"dst",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"location",
",",
"config_file",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"dst",
")",
"and",
"not",
"overwrite",
":",
"return",
"False",
"if",
"path",
"is",
"None",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_ipython_package_dir",
"(",
")",
",",
"u'config'",
",",
"u'profile'",
",",
"u'default'",
")",
"src",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"config_file",
")",
"shutil",
".",
"copy",
"(",
"src",
",",
"dst",
")",
"return",
"True"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ProfileDir.create_profile_dir_by_name | Create a profile dir by profile name and path.
Parameters
----------
path : unicode
The path (directory) to put the profile directory in.
name : unicode
The name of the profile. The name of the profile directory will
be "profile_<profile>". | environment/lib/python2.7/site-packages/IPython/core/profiledir.py | def create_profile_dir_by_name(cls, path, name=u'default', config=None):
"""Create a profile dir by profile name and path.
Parameters
----------
path : unicode
The path (directory) to put the profile directory in.
name : unicode
The name of the profile. The name of the profile directory will
be "profile_<profile>".
"""
if not os.path.isdir(path):
raise ProfileDirError('Directory not found: %s' % path)
profile_dir = os.path.join(path, u'profile_' + name)
return cls(location=profile_dir, config=config) | def create_profile_dir_by_name(cls, path, name=u'default', config=None):
"""Create a profile dir by profile name and path.
Parameters
----------
path : unicode
The path (directory) to put the profile directory in.
name : unicode
The name of the profile. The name of the profile directory will
be "profile_<profile>".
"""
if not os.path.isdir(path):
raise ProfileDirError('Directory not found: %s' % path)
profile_dir = os.path.join(path, u'profile_' + name)
return cls(location=profile_dir, config=config) | [
"Create",
"a",
"profile",
"dir",
"by",
"profile",
"name",
"and",
"path",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/profiledir.py#L167-L181 | [
"def",
"create_profile_dir_by_name",
"(",
"cls",
",",
"path",
",",
"name",
"=",
"u'default'",
",",
"config",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"raise",
"ProfileDirError",
"(",
"'Directory not found: %s'",
"%",
"path",
")",
"profile_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"u'profile_'",
"+",
"name",
")",
"return",
"cls",
"(",
"location",
"=",
"profile_dir",
",",
"config",
"=",
"config",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ProfileDir.find_profile_dir_by_name | Find an existing profile dir by profile name, return its ProfileDir.
This searches through a sequence of paths for a profile dir. If it
is not found, a :class:`ProfileDirError` exception will be raised.
The search path algorithm is:
1. ``os.getcwdu()``
2. ``ipython_dir``
Parameters
----------
ipython_dir : unicode or str
The IPython directory to use.
name : unicode or str
The name of the profile. The name of the profile directory
will be "profile_<profile>". | environment/lib/python2.7/site-packages/IPython/core/profiledir.py | def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
"""Find an existing profile dir by profile name, return its ProfileDir.
This searches through a sequence of paths for a profile dir. If it
is not found, a :class:`ProfileDirError` exception will be raised.
The search path algorithm is:
1. ``os.getcwdu()``
2. ``ipython_dir``
Parameters
----------
ipython_dir : unicode or str
The IPython directory to use.
name : unicode or str
The name of the profile. The name of the profile directory
will be "profile_<profile>".
"""
dirname = u'profile_' + name
paths = [os.getcwdu(), ipython_dir]
for p in paths:
profile_dir = os.path.join(p, dirname)
if os.path.isdir(profile_dir):
return cls(location=profile_dir, config=config)
else:
raise ProfileDirError('Profile directory not found in paths: %s' % dirname) | def find_profile_dir_by_name(cls, ipython_dir, name=u'default', config=None):
"""Find an existing profile dir by profile name, return its ProfileDir.
This searches through a sequence of paths for a profile dir. If it
is not found, a :class:`ProfileDirError` exception will be raised.
The search path algorithm is:
1. ``os.getcwdu()``
2. ``ipython_dir``
Parameters
----------
ipython_dir : unicode or str
The IPython directory to use.
name : unicode or str
The name of the profile. The name of the profile directory
will be "profile_<profile>".
"""
dirname = u'profile_' + name
paths = [os.getcwdu(), ipython_dir]
for p in paths:
profile_dir = os.path.join(p, dirname)
if os.path.isdir(profile_dir):
return cls(location=profile_dir, config=config)
else:
raise ProfileDirError('Profile directory not found in paths: %s' % dirname) | [
"Find",
"an",
"existing",
"profile",
"dir",
"by",
"profile",
"name",
"return",
"its",
"ProfileDir",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/profiledir.py#L184-L209 | [
"def",
"find_profile_dir_by_name",
"(",
"cls",
",",
"ipython_dir",
",",
"name",
"=",
"u'default'",
",",
"config",
"=",
"None",
")",
":",
"dirname",
"=",
"u'profile_'",
"+",
"name",
"paths",
"=",
"[",
"os",
".",
"getcwdu",
"(",
")",
",",
"ipython_dir",
"]",
"for",
"p",
"in",
"paths",
":",
"profile_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"p",
",",
"dirname",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"profile_dir",
")",
":",
"return",
"cls",
"(",
"location",
"=",
"profile_dir",
",",
"config",
"=",
"config",
")",
"else",
":",
"raise",
"ProfileDirError",
"(",
"'Profile directory not found in paths: %s'",
"%",
"dirname",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ProfileDir.find_profile_dir | Find/create a profile dir and return its ProfileDir.
This will create the profile directory if it doesn't exist.
Parameters
----------
profile_dir : unicode or str
The path of the profile directory. This is expanded using
:func:`IPython.utils.genutils.expand_path`. | environment/lib/python2.7/site-packages/IPython/core/profiledir.py | def find_profile_dir(cls, profile_dir, config=None):
"""Find/create a profile dir and return its ProfileDir.
This will create the profile directory if it doesn't exist.
Parameters
----------
profile_dir : unicode or str
The path of the profile directory. This is expanded using
:func:`IPython.utils.genutils.expand_path`.
"""
profile_dir = expand_path(profile_dir)
if not os.path.isdir(profile_dir):
raise ProfileDirError('Profile directory not found: %s' % profile_dir)
return cls(location=profile_dir, config=config) | def find_profile_dir(cls, profile_dir, config=None):
"""Find/create a profile dir and return its ProfileDir.
This will create the profile directory if it doesn't exist.
Parameters
----------
profile_dir : unicode or str
The path of the profile directory. This is expanded using
:func:`IPython.utils.genutils.expand_path`.
"""
profile_dir = expand_path(profile_dir)
if not os.path.isdir(profile_dir):
raise ProfileDirError('Profile directory not found: %s' % profile_dir)
return cls(location=profile_dir, config=config) | [
"Find",
"/",
"create",
"a",
"profile",
"dir",
"and",
"return",
"its",
"ProfileDir",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/profiledir.py#L212-L226 | [
"def",
"find_profile_dir",
"(",
"cls",
",",
"profile_dir",
",",
"config",
"=",
"None",
")",
":",
"profile_dir",
"=",
"expand_path",
"(",
"profile_dir",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"profile_dir",
")",
":",
"raise",
"ProfileDirError",
"(",
"'Profile directory not found: %s'",
"%",
"profile_dir",
")",
"return",
"cls",
"(",
"location",
"=",
"profile_dir",
",",
"config",
"=",
"config",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | cmp_to_key | Convert a cmp= function into a key= function | environment/lib/python2.7/site-packages/nose/pyversion.py | def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class Key(object):
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
return Key | def cmp_to_key(mycmp):
'Convert a cmp= function into a key= function'
class Key(object):
def __init__(self, obj):
self.obj = obj
def __lt__(self, other):
return mycmp(self.obj, other.obj) < 0
def __gt__(self, other):
return mycmp(self.obj, other.obj) > 0
def __eq__(self, other):
return mycmp(self.obj, other.obj) == 0
return Key | [
"Convert",
"a",
"cmp",
"=",
"function",
"into",
"a",
"key",
"=",
"function"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/pyversion.py#L33-L44 | [
"def",
"cmp_to_key",
"(",
"mycmp",
")",
":",
"class",
"Key",
"(",
"object",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"obj",
")",
":",
"self",
".",
"obj",
"=",
"obj",
"def",
"__lt__",
"(",
"self",
",",
"other",
")",
":",
"return",
"mycmp",
"(",
"self",
".",
"obj",
",",
"other",
".",
"obj",
")",
"<",
"0",
"def",
"__gt__",
"(",
"self",
",",
"other",
")",
":",
"return",
"mycmp",
"(",
"self",
".",
"obj",
",",
"other",
".",
"obj",
")",
">",
"0",
"def",
"__eq__",
"(",
"self",
",",
"other",
")",
":",
"return",
"mycmp",
"(",
"self",
".",
"obj",
",",
"other",
".",
"obj",
")",
"==",
"0",
"return",
"Key"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | file_read | Read a file and close it. Returns the file source. | environment/lib/python2.7/site-packages/IPython/utils/io.py | def file_read(filename):
"""Read a file and close it. Returns the file source."""
fobj = open(filename,'r');
source = fobj.read();
fobj.close()
return source | def file_read(filename):
"""Read a file and close it. Returns the file source."""
fobj = open(filename,'r');
source = fobj.read();
fobj.close()
return source | [
"Read",
"a",
"file",
"and",
"close",
"it",
".",
"Returns",
"the",
"file",
"source",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L157-L162 | [
"def",
"file_read",
"(",
"filename",
")",
":",
"fobj",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"source",
"=",
"fobj",
".",
"read",
"(",
")",
"fobj",
".",
"close",
"(",
")",
"return",
"source"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | file_readlines | Read a file and close it. Returns the file source using readlines(). | environment/lib/python2.7/site-packages/IPython/utils/io.py | def file_readlines(filename):
"""Read a file and close it. Returns the file source using readlines()."""
fobj = open(filename,'r');
lines = fobj.readlines();
fobj.close()
return lines | def file_readlines(filename):
"""Read a file and close it. Returns the file source using readlines()."""
fobj = open(filename,'r');
lines = fobj.readlines();
fobj.close()
return lines | [
"Read",
"a",
"file",
"and",
"close",
"it",
".",
"Returns",
"the",
"file",
"source",
"using",
"readlines",
"()",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L165-L170 | [
"def",
"file_readlines",
"(",
"filename",
")",
":",
"fobj",
"=",
"open",
"(",
"filename",
",",
"'r'",
")",
"lines",
"=",
"fobj",
".",
"readlines",
"(",
")",
"fobj",
".",
"close",
"(",
")",
"return",
"lines"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | raw_input_multi | Take multiple lines of input.
A list with each line of input as a separate element is returned when a
termination string is entered (defaults to a single '.'). Input can also
terminate via EOF (^D in Unix, ^Z-RET in Windows).
Lines of input which end in \\ are joined into single entries (and a
secondary continuation prompt is issued as long as the user terminates
lines with \\). This allows entering very long strings which are still
meant to be treated as single entities. | environment/lib/python2.7/site-packages/IPython/utils/io.py | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
"""Take multiple lines of input.
A list with each line of input as a separate element is returned when a
termination string is entered (defaults to a single '.'). Input can also
terminate via EOF (^D in Unix, ^Z-RET in Windows).
Lines of input which end in \\ are joined into single entries (and a
secondary continuation prompt is issued as long as the user terminates
lines with \\). This allows entering very long strings which are still
meant to be treated as single entities.
"""
try:
if header:
header += '\n'
lines = [raw_input(header + ps1)]
except EOFError:
return []
terminate = [terminate_str]
try:
while lines[-1:] != terminate:
new_line = raw_input(ps1)
while new_line.endswith('\\'):
new_line = new_line[:-1] + raw_input(ps2)
lines.append(new_line)
return lines[:-1] # don't return the termination command
except EOFError:
print()
return lines | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'):
"""Take multiple lines of input.
A list with each line of input as a separate element is returned when a
termination string is entered (defaults to a single '.'). Input can also
terminate via EOF (^D in Unix, ^Z-RET in Windows).
Lines of input which end in \\ are joined into single entries (and a
secondary continuation prompt is issued as long as the user terminates
lines with \\). This allows entering very long strings which are still
meant to be treated as single entities.
"""
try:
if header:
header += '\n'
lines = [raw_input(header + ps1)]
except EOFError:
return []
terminate = [terminate_str]
try:
while lines[-1:] != terminate:
new_line = raw_input(ps1)
while new_line.endswith('\\'):
new_line = new_line[:-1] + raw_input(ps2)
lines.append(new_line)
return lines[:-1] # don't return the termination command
except EOFError:
print()
return lines | [
"Take",
"multiple",
"lines",
"of",
"input",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L173-L203 | [
"def",
"raw_input_multi",
"(",
"header",
"=",
"''",
",",
"ps1",
"=",
"'==> '",
",",
"ps2",
"=",
"'..> '",
",",
"terminate_str",
"=",
"'.'",
")",
":",
"try",
":",
"if",
"header",
":",
"header",
"+=",
"'\\n'",
"lines",
"=",
"[",
"raw_input",
"(",
"header",
"+",
"ps1",
")",
"]",
"except",
"EOFError",
":",
"return",
"[",
"]",
"terminate",
"=",
"[",
"terminate_str",
"]",
"try",
":",
"while",
"lines",
"[",
"-",
"1",
":",
"]",
"!=",
"terminate",
":",
"new_line",
"=",
"raw_input",
"(",
"ps1",
")",
"while",
"new_line",
".",
"endswith",
"(",
"'\\\\'",
")",
":",
"new_line",
"=",
"new_line",
"[",
":",
"-",
"1",
"]",
"+",
"raw_input",
"(",
"ps2",
")",
"lines",
".",
"append",
"(",
"new_line",
")",
"return",
"lines",
"[",
":",
"-",
"1",
"]",
"# don't return the termination command",
"except",
"EOFError",
":",
"print",
"(",
")",
"return",
"lines"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | raw_input_ext | Similar to raw_input(), but accepts extended lines if input ends with \\. | environment/lib/python2.7/site-packages/IPython/utils/io.py | def raw_input_ext(prompt='', ps2='... '):
"""Similar to raw_input(), but accepts extended lines if input ends with \\."""
line = raw_input(prompt)
while line.endswith('\\'):
line = line[:-1] + raw_input(ps2)
return line | def raw_input_ext(prompt='', ps2='... '):
"""Similar to raw_input(), but accepts extended lines if input ends with \\."""
line = raw_input(prompt)
while line.endswith('\\'):
line = line[:-1] + raw_input(ps2)
return line | [
"Similar",
"to",
"raw_input",
"()",
"but",
"accepts",
"extended",
"lines",
"if",
"input",
"ends",
"with",
"\\\\",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L206-L212 | [
"def",
"raw_input_ext",
"(",
"prompt",
"=",
"''",
",",
"ps2",
"=",
"'... '",
")",
":",
"line",
"=",
"raw_input",
"(",
"prompt",
")",
"while",
"line",
".",
"endswith",
"(",
"'\\\\'",
")",
":",
"line",
"=",
"line",
"[",
":",
"-",
"1",
"]",
"+",
"raw_input",
"(",
"ps2",
")",
"return",
"line"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | ask_yes_no | Asks a question and returns a boolean (y/n) answer.
If default is given (one of 'y','n'), it is used if the user input is
empty. Otherwise the question is repeated until an answer is given.
An EOF is treated as the default answer. If there is no default, an
exception is raised to prevent infinite loops.
Valid answers are: y/yes/n/no (match is not case sensitive). | environment/lib/python2.7/site-packages/IPython/utils/io.py | def ask_yes_no(prompt,default=None):
"""Asks a question and returns a boolean (y/n) answer.
If default is given (one of 'y','n'), it is used if the user input is
empty. Otherwise the question is repeated until an answer is given.
An EOF is treated as the default answer. If there is no default, an
exception is raised to prevent infinite loops.
Valid answers are: y/yes/n/no (match is not case sensitive)."""
answers = {'y':True,'n':False,'yes':True,'no':False}
ans = None
while ans not in answers.keys():
try:
ans = raw_input(prompt+' ').lower()
if not ans: # response was an empty string
ans = default
except KeyboardInterrupt:
pass
except EOFError:
if default in answers.keys():
ans = default
print()
else:
raise
return answers[ans] | def ask_yes_no(prompt,default=None):
"""Asks a question and returns a boolean (y/n) answer.
If default is given (one of 'y','n'), it is used if the user input is
empty. Otherwise the question is repeated until an answer is given.
An EOF is treated as the default answer. If there is no default, an
exception is raised to prevent infinite loops.
Valid answers are: y/yes/n/no (match is not case sensitive)."""
answers = {'y':True,'n':False,'yes':True,'no':False}
ans = None
while ans not in answers.keys():
try:
ans = raw_input(prompt+' ').lower()
if not ans: # response was an empty string
ans = default
except KeyboardInterrupt:
pass
except EOFError:
if default in answers.keys():
ans = default
print()
else:
raise
return answers[ans] | [
"Asks",
"a",
"question",
"and",
"returns",
"a",
"boolean",
"(",
"y",
"/",
"n",
")",
"answer",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L215-L242 | [
"def",
"ask_yes_no",
"(",
"prompt",
",",
"default",
"=",
"None",
")",
":",
"answers",
"=",
"{",
"'y'",
":",
"True",
",",
"'n'",
":",
"False",
",",
"'yes'",
":",
"True",
",",
"'no'",
":",
"False",
"}",
"ans",
"=",
"None",
"while",
"ans",
"not",
"in",
"answers",
".",
"keys",
"(",
")",
":",
"try",
":",
"ans",
"=",
"raw_input",
"(",
"prompt",
"+",
"' '",
")",
".",
"lower",
"(",
")",
"if",
"not",
"ans",
":",
"# response was an empty string",
"ans",
"=",
"default",
"except",
"KeyboardInterrupt",
":",
"pass",
"except",
"EOFError",
":",
"if",
"default",
"in",
"answers",
".",
"keys",
"(",
")",
":",
"ans",
"=",
"default",
"print",
"(",
")",
"else",
":",
"raise",
"return",
"answers",
"[",
"ans",
"]"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | temp_pyfile | Make a temporary python file, return filename and filehandle.
Parameters
----------
src : string or list of strings (no need for ending newlines if list)
Source code to be written to the file.
ext : optional, string
Extension for the generated file.
Returns
-------
(filename, open filehandle)
It is the caller's responsibility to close the open file and unlink it. | environment/lib/python2.7/site-packages/IPython/utils/io.py | def temp_pyfile(src, ext='.py'):
"""Make a temporary python file, return filename and filehandle.
Parameters
----------
src : string or list of strings (no need for ending newlines if list)
Source code to be written to the file.
ext : optional, string
Extension for the generated file.
Returns
-------
(filename, open filehandle)
It is the caller's responsibility to close the open file and unlink it.
"""
fname = tempfile.mkstemp(ext)[1]
f = open(fname,'w')
f.write(src)
f.flush()
return fname, f | def temp_pyfile(src, ext='.py'):
"""Make a temporary python file, return filename and filehandle.
Parameters
----------
src : string or list of strings (no need for ending newlines if list)
Source code to be written to the file.
ext : optional, string
Extension for the generated file.
Returns
-------
(filename, open filehandle)
It is the caller's responsibility to close the open file and unlink it.
"""
fname = tempfile.mkstemp(ext)[1]
f = open(fname,'w')
f.write(src)
f.flush()
return fname, f | [
"Make",
"a",
"temporary",
"python",
"file",
"return",
"filename",
"and",
"filehandle",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L283-L303 | [
"def",
"temp_pyfile",
"(",
"src",
",",
"ext",
"=",
"'.py'",
")",
":",
"fname",
"=",
"tempfile",
".",
"mkstemp",
"(",
"ext",
")",
"[",
"1",
"]",
"f",
"=",
"open",
"(",
"fname",
",",
"'w'",
")",
"f",
".",
"write",
"(",
"src",
")",
"f",
".",
"flush",
"(",
")",
"return",
"fname",
",",
"f"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | raw_print | Raw print to sys.__stdout__, otherwise identical interface to print(). | environment/lib/python2.7/site-packages/IPython/utils/io.py | def raw_print(*args, **kw):
"""Raw print to sys.__stdout__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
file=sys.__stdout__)
sys.__stdout__.flush() | def raw_print(*args, **kw):
"""Raw print to sys.__stdout__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
file=sys.__stdout__)
sys.__stdout__.flush() | [
"Raw",
"print",
"to",
"sys",
".",
"__stdout__",
"otherwise",
"identical",
"interface",
"to",
"print",
"()",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L306-L311 | [
"def",
"raw_print",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"print",
"(",
"*",
"args",
",",
"sep",
"=",
"kw",
".",
"get",
"(",
"'sep'",
",",
"' '",
")",
",",
"end",
"=",
"kw",
".",
"get",
"(",
"'end'",
",",
"'\\n'",
")",
",",
"file",
"=",
"sys",
".",
"__stdout__",
")",
"sys",
".",
"__stdout__",
".",
"flush",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | raw_print_err | Raw print to sys.__stderr__, otherwise identical interface to print(). | environment/lib/python2.7/site-packages/IPython/utils/io.py | def raw_print_err(*args, **kw):
"""Raw print to sys.__stderr__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
file=sys.__stderr__)
sys.__stderr__.flush() | def raw_print_err(*args, **kw):
"""Raw print to sys.__stderr__, otherwise identical interface to print()."""
print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'),
file=sys.__stderr__)
sys.__stderr__.flush() | [
"Raw",
"print",
"to",
"sys",
".",
"__stderr__",
"otherwise",
"identical",
"interface",
"to",
"print",
"()",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L314-L319 | [
"def",
"raw_print_err",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"print",
"(",
"*",
"args",
",",
"sep",
"=",
"kw",
".",
"get",
"(",
"'sep'",
",",
"' '",
")",
",",
"end",
"=",
"kw",
".",
"get",
"(",
"'end'",
",",
"'\\n'",
")",
",",
"file",
"=",
"sys",
".",
"__stderr__",
")",
"sys",
".",
"__stderr__",
".",
"flush",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Tee.close | Close the file and restore the channel. | environment/lib/python2.7/site-packages/IPython/utils/io.py | def close(self):
"""Close the file and restore the channel."""
self.flush()
setattr(sys, self.channel, self.ostream)
self.file.close()
self._closed = True | def close(self):
"""Close the file and restore the channel."""
self.flush()
setattr(sys, self.channel, self.ostream)
self.file.close()
self._closed = True | [
"Close",
"the",
"file",
"and",
"restore",
"the",
"channel",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L134-L139 | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"flush",
"(",
")",
"setattr",
"(",
"sys",
",",
"self",
".",
"channel",
",",
"self",
".",
"ostream",
")",
"self",
".",
"file",
".",
"close",
"(",
")",
"self",
".",
"_closed",
"=",
"True"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Tee.write | Write data to both channels. | environment/lib/python2.7/site-packages/IPython/utils/io.py | def write(self, data):
"""Write data to both channels."""
self.file.write(data)
self.ostream.write(data)
self.ostream.flush() | def write(self, data):
"""Write data to both channels."""
self.file.write(data)
self.ostream.write(data)
self.ostream.flush() | [
"Write",
"data",
"to",
"both",
"channels",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L141-L145 | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"file",
".",
"write",
"(",
"data",
")",
"self",
".",
"ostream",
".",
"write",
"(",
"data",
")",
"self",
".",
"ostream",
".",
"flush",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | CapturedIO.show | write my output to sys.stdout/err as appropriate | environment/lib/python2.7/site-packages/IPython/utils/io.py | def show(self):
"""write my output to sys.stdout/err as appropriate"""
sys.stdout.write(self.stdout)
sys.stderr.write(self.stderr)
sys.stdout.flush()
sys.stderr.flush() | def show(self):
"""write my output to sys.stdout/err as appropriate"""
sys.stdout.write(self.stdout)
sys.stderr.write(self.stderr)
sys.stdout.flush()
sys.stderr.flush() | [
"write",
"my",
"output",
"to",
"sys",
".",
"stdout",
"/",
"err",
"as",
"appropriate"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/io.py#L349-L354 | [
"def",
"show",
"(",
"self",
")",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"self",
".",
"stdout",
")",
"sys",
".",
"stderr",
".",
"write",
"(",
"self",
".",
"stderr",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HeartMonitor.add_new_heart_handler | add a new handler for new hearts | environment/lib/python2.7/site-packages/IPython/parallel/controller/heartmonitor.py | def add_new_heart_handler(self, handler):
"""add a new handler for new hearts"""
self.log.debug("heartbeat::new_heart_handler: %s", handler)
self._new_handlers.add(handler) | def add_new_heart_handler(self, handler):
"""add a new handler for new hearts"""
self.log.debug("heartbeat::new_heart_handler: %s", handler)
self._new_handlers.add(handler) | [
"add",
"a",
"new",
"handler",
"for",
"new",
"hearts"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/heartmonitor.py#L99-L102 | [
"def",
"add_new_heart_handler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"heartbeat::new_heart_handler: %s\"",
",",
"handler",
")",
"self",
".",
"_new_handlers",
".",
"add",
"(",
"handler",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HeartMonitor.add_heart_failure_handler | add a new handler for heart failure | environment/lib/python2.7/site-packages/IPython/parallel/controller/heartmonitor.py | def add_heart_failure_handler(self, handler):
"""add a new handler for heart failure"""
self.log.debug("heartbeat::new heart failure handler: %s", handler)
self._failure_handlers.add(handler) | def add_heart_failure_handler(self, handler):
"""add a new handler for heart failure"""
self.log.debug("heartbeat::new heart failure handler: %s", handler)
self._failure_handlers.add(handler) | [
"add",
"a",
"new",
"handler",
"for",
"heart",
"failure"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/heartmonitor.py#L104-L107 | [
"def",
"add_heart_failure_handler",
"(",
"self",
",",
"handler",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"heartbeat::new heart failure handler: %s\"",
",",
"handler",
")",
"self",
".",
"_failure_handlers",
".",
"add",
"(",
"handler",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | HeartMonitor.handle_pong | a heart just beat | environment/lib/python2.7/site-packages/IPython/parallel/controller/heartmonitor.py | def handle_pong(self, msg):
"a heart just beat"
current = str_to_bytes(str(self.lifetime))
last = str_to_bytes(str(self.last_ping))
if msg[1] == current:
delta = time.time()-self.tic
# self.log.debug("heartbeat::heart %r took %.2f ms to respond"%(msg[0], 1000*delta))
self.responses.add(msg[0])
elif msg[1] == last:
delta = time.time()-self.tic + (self.lifetime-self.last_ping)
self.log.warn("heartbeat::heart %r missed a beat, and took %.2f ms to respond", msg[0], 1000*delta)
self.responses.add(msg[0])
else:
self.log.warn("heartbeat::got bad heartbeat (possibly old?): %s (current=%.3f)", msg[1], self.lifetime) | def handle_pong(self, msg):
"a heart just beat"
current = str_to_bytes(str(self.lifetime))
last = str_to_bytes(str(self.last_ping))
if msg[1] == current:
delta = time.time()-self.tic
# self.log.debug("heartbeat::heart %r took %.2f ms to respond"%(msg[0], 1000*delta))
self.responses.add(msg[0])
elif msg[1] == last:
delta = time.time()-self.tic + (self.lifetime-self.last_ping)
self.log.warn("heartbeat::heart %r missed a beat, and took %.2f ms to respond", msg[0], 1000*delta)
self.responses.add(msg[0])
else:
self.log.warn("heartbeat::got bad heartbeat (possibly old?): %s (current=%.3f)", msg[1], self.lifetime) | [
"a",
"heart",
"just",
"beat"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/heartmonitor.py#L153-L166 | [
"def",
"handle_pong",
"(",
"self",
",",
"msg",
")",
":",
"current",
"=",
"str_to_bytes",
"(",
"str",
"(",
"self",
".",
"lifetime",
")",
")",
"last",
"=",
"str_to_bytes",
"(",
"str",
"(",
"self",
".",
"last_ping",
")",
")",
"if",
"msg",
"[",
"1",
"]",
"==",
"current",
":",
"delta",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"tic",
"# self.log.debug(\"heartbeat::heart %r took %.2f ms to respond\"%(msg[0], 1000*delta))",
"self",
".",
"responses",
".",
"add",
"(",
"msg",
"[",
"0",
"]",
")",
"elif",
"msg",
"[",
"1",
"]",
"==",
"last",
":",
"delta",
"=",
"time",
".",
"time",
"(",
")",
"-",
"self",
".",
"tic",
"+",
"(",
"self",
".",
"lifetime",
"-",
"self",
".",
"last_ping",
")",
"self",
".",
"log",
".",
"warn",
"(",
"\"heartbeat::heart %r missed a beat, and took %.2f ms to respond\"",
",",
"msg",
"[",
"0",
"]",
",",
"1000",
"*",
"delta",
")",
"self",
".",
"responses",
".",
"add",
"(",
"msg",
"[",
"0",
"]",
")",
"else",
":",
"self",
".",
"log",
".",
"warn",
"(",
"\"heartbeat::got bad heartbeat (possibly old?): %s (current=%.3f)\"",
",",
"msg",
"[",
"1",
"]",
",",
"self",
".",
"lifetime",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | catch | try:
retrun fcn(*args, **kwargs)
except:
print traceback
if 'spit' in kwargs.keys():
return kwargs['spit']
Parameters
----------
fcn : function
*args : unnamed parameters of fcn
**kwargs : named parameters of fcn
spit : returns the parameter named return in the exception
Returns
-------
The expected output of fcn or prints the exception traceback | turntable/utils.py | def catch(fcn, *args, **kwargs):
'''try:
retrun fcn(*args, **kwargs)
except:
print traceback
if 'spit' in kwargs.keys():
return kwargs['spit']
Parameters
----------
fcn : function
*args : unnamed parameters of fcn
**kwargs : named parameters of fcn
spit : returns the parameter named return in the exception
Returns
-------
The expected output of fcn or prints the exception traceback
'''
try:
# remove the special kwargs key "spit" and use it to return if it exists
spit = kwargs.pop('spit')
except:
spit = None
try:
results = fcn(*args, **kwargs)
if results:
return results
except:
print traceback.format_exc()
if spit:
return spit | def catch(fcn, *args, **kwargs):
'''try:
retrun fcn(*args, **kwargs)
except:
print traceback
if 'spit' in kwargs.keys():
return kwargs['spit']
Parameters
----------
fcn : function
*args : unnamed parameters of fcn
**kwargs : named parameters of fcn
spit : returns the parameter named return in the exception
Returns
-------
The expected output of fcn or prints the exception traceback
'''
try:
# remove the special kwargs key "spit" and use it to return if it exists
spit = kwargs.pop('spit')
except:
spit = None
try:
results = fcn(*args, **kwargs)
if results:
return results
except:
print traceback.format_exc()
if spit:
return spit | [
"try",
":",
"retrun",
"fcn",
"(",
"*",
"args",
"**",
"kwargs",
")",
"except",
":",
"print",
"traceback",
"if",
"spit",
"in",
"kwargs",
".",
"keys",
"()",
":",
"return",
"kwargs",
"[",
"spit",
"]"
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L21-L55 | [
"def",
"catch",
"(",
"fcn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"# remove the special kwargs key \"spit\" and use it to return if it exists",
"spit",
"=",
"kwargs",
".",
"pop",
"(",
"'spit'",
")",
"except",
":",
"spit",
"=",
"None",
"try",
":",
"results",
"=",
"fcn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"results",
":",
"return",
"results",
"except",
":",
"print",
"traceback",
".",
"format_exc",
"(",
")",
"if",
"spit",
":",
"return",
"spit"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | batch_list | Converts a list into a list of lists with equal batch_size.
Parameters
----------
sequence : list
list of items to be placed in batches
batch_size : int
length of each sub list
mod : int
remainder of list length devided by batch_size
mod = len(sequence) % batch_size
randomize = bool
should the initial sequence be randomized before being batched | turntable/utils.py | def batch_list(sequence, batch_size, mod = 0, randomize = False):
'''
Converts a list into a list of lists with equal batch_size.
Parameters
----------
sequence : list
list of items to be placed in batches
batch_size : int
length of each sub list
mod : int
remainder of list length devided by batch_size
mod = len(sequence) % batch_size
randomize = bool
should the initial sequence be randomized before being batched
'''
if randomize:
sequence = random.sample(sequence, len(sequence))
return [sequence[x:x + batch_size] for x in xrange(0, len(sequence)-mod, batch_size)] | def batch_list(sequence, batch_size, mod = 0, randomize = False):
'''
Converts a list into a list of lists with equal batch_size.
Parameters
----------
sequence : list
list of items to be placed in batches
batch_size : int
length of each sub list
mod : int
remainder of list length devided by batch_size
mod = len(sequence) % batch_size
randomize = bool
should the initial sequence be randomized before being batched
'''
if randomize:
sequence = random.sample(sequence, len(sequence))
return [sequence[x:x + batch_size] for x in xrange(0, len(sequence)-mod, batch_size)] | [
"Converts",
"a",
"list",
"into",
"a",
"list",
"of",
"lists",
"with",
"equal",
"batch_size",
"."
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L58-L79 | [
"def",
"batch_list",
"(",
"sequence",
",",
"batch_size",
",",
"mod",
"=",
"0",
",",
"randomize",
"=",
"False",
")",
":",
"if",
"randomize",
":",
"sequence",
"=",
"random",
".",
"sample",
"(",
"sequence",
",",
"len",
"(",
"sequence",
")",
")",
"return",
"[",
"sequence",
"[",
"x",
":",
"x",
"+",
"batch_size",
"]",
"for",
"x",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"sequence",
")",
"-",
"mod",
",",
"batch_size",
")",
"]"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | to_pickle | http://stackoverflow.com/questions/7900944/read-write-classes-to-files-in-an-efficent-way | turntable/utils.py | def to_pickle(obj, filename, clean_memory=False):
'''http://stackoverflow.com/questions/7900944/read-write-classes-to-files-in-an-efficent-way'''
path, filename = path_to_filename(filename)
create_dir(path)
with open(path + filename, "wb") as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
if clean_memory:
obj = None
# setting the global object to None requires a return assignment
return obj | def to_pickle(obj, filename, clean_memory=False):
'''http://stackoverflow.com/questions/7900944/read-write-classes-to-files-in-an-efficent-way'''
path, filename = path_to_filename(filename)
create_dir(path)
with open(path + filename, "wb") as output:
pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)
if clean_memory:
obj = None
# setting the global object to None requires a return assignment
return obj | [
"http",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"7900944",
"/",
"read",
"-",
"write",
"-",
"classes",
"-",
"to",
"-",
"files",
"-",
"in",
"-",
"an",
"-",
"efficent",
"-",
"way"
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L83-L96 | [
"def",
"to_pickle",
"(",
"obj",
",",
"filename",
",",
"clean_memory",
"=",
"False",
")",
":",
"path",
",",
"filename",
"=",
"path_to_filename",
"(",
"filename",
")",
"create_dir",
"(",
"path",
")",
"with",
"open",
"(",
"path",
"+",
"filename",
",",
"\"wb\"",
")",
"as",
"output",
":",
"pickle",
".",
"dump",
"(",
"obj",
",",
"output",
",",
"pickle",
".",
"HIGHEST_PROTOCOL",
")",
"if",
"clean_memory",
":",
"obj",
"=",
"None",
"# setting the global object to None requires a return assignment",
"return",
"obj"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | path_to_filename | Takes a path filename string and returns the split between the path and the filename
if filename is not given, filename = ''
if path is not given, path = './' | turntable/utils.py | def path_to_filename(pathfile):
'''
Takes a path filename string and returns the split between the path and the filename
if filename is not given, filename = ''
if path is not given, path = './'
'''
path = pathfile[:pathfile.rfind('/') + 1]
if path == '':
path = './'
filename = pathfile[pathfile.rfind('/') + 1:len(pathfile)]
if '.' not in filename:
path = pathfile
filename = ''
if (filename == '') and (path[len(path) - 1] != '/'):
path += '/'
return path, filename | def path_to_filename(pathfile):
'''
Takes a path filename string and returns the split between the path and the filename
if filename is not given, filename = ''
if path is not given, path = './'
'''
path = pathfile[:pathfile.rfind('/') + 1]
if path == '':
path = './'
filename = pathfile[pathfile.rfind('/') + 1:len(pathfile)]
if '.' not in filename:
path = pathfile
filename = ''
if (filename == '') and (path[len(path) - 1] != '/'):
path += '/'
return path, filename | [
"Takes",
"a",
"path",
"filename",
"string",
"and",
"returns",
"the",
"split",
"between",
"the",
"path",
"and",
"the",
"filename"
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L109-L130 | [
"def",
"path_to_filename",
"(",
"pathfile",
")",
":",
"path",
"=",
"pathfile",
"[",
":",
"pathfile",
".",
"rfind",
"(",
"'/'",
")",
"+",
"1",
"]",
"if",
"path",
"==",
"''",
":",
"path",
"=",
"'./'",
"filename",
"=",
"pathfile",
"[",
"pathfile",
".",
"rfind",
"(",
"'/'",
")",
"+",
"1",
":",
"len",
"(",
"pathfile",
")",
"]",
"if",
"'.'",
"not",
"in",
"filename",
":",
"path",
"=",
"pathfile",
"filename",
"=",
"''",
"if",
"(",
"filename",
"==",
"''",
")",
"and",
"(",
"path",
"[",
"len",
"(",
"path",
")",
"-",
"1",
"]",
"!=",
"'/'",
")",
":",
"path",
"+=",
"'/'",
"return",
"path",
",",
"filename"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | create_dir | Tries to create a new directory in the given path.
**create_dir** can also create subfolders according to the dictionnary given as second argument.
Parameters
----------
path : string
string giving the path of the location to create the directory, either absolute or relative.
dir_dict : dictionary, optional
Dictionary ordering the creation of subfolders. Keys must be strings, and values either None or path dictionaries.
the default is {}, which means that no subfolders will be created
Examples
--------
>>> path = './project'
>>> dir_dict = {'dir1':None, 'dir2':{'subdir21':None}}
>>> utils.create_dir(path, dir_dict)
will create:
* *project/dir1*
* *project/dir2/subdir21*
in your parent directory. | turntable/utils.py | def create_dir(path, dir_dict={}):
'''
Tries to create a new directory in the given path.
**create_dir** can also create subfolders according to the dictionnary given as second argument.
Parameters
----------
path : string
string giving the path of the location to create the directory, either absolute or relative.
dir_dict : dictionary, optional
Dictionary ordering the creation of subfolders. Keys must be strings, and values either None or path dictionaries.
the default is {}, which means that no subfolders will be created
Examples
--------
>>> path = './project'
>>> dir_dict = {'dir1':None, 'dir2':{'subdir21':None}}
>>> utils.create_dir(path, dir_dict)
will create:
* *project/dir1*
* *project/dir2/subdir21*
in your parent directory.
'''
folders = path.split('/')
folders = [i for i in folders if i != '']
rootPath = ''
if folders[0] == 'C:':
folders = folders[1:]
count = 0
for directory in folders:
count += 1
# required to handle the dot operators
if (directory[0] == '.') & (count == 1):
rootPath = directory
else:
rootPath = rootPath + '/' + directory
try:
os.makedirs(rootPath)
# If the file already exists (EEXIST), raise exception and do nothing
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
for key in dir_dict.keys():
rootPath = path + "/" + key
try:
os.makedirs(rootPath)
# If the file already exists (EEXIST), raise exception and do nothing
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
if dir_dict[key] is not None:
create_dir(rootPath, dir_dict[key]) | def create_dir(path, dir_dict={}):
'''
Tries to create a new directory in the given path.
**create_dir** can also create subfolders according to the dictionnary given as second argument.
Parameters
----------
path : string
string giving the path of the location to create the directory, either absolute or relative.
dir_dict : dictionary, optional
Dictionary ordering the creation of subfolders. Keys must be strings, and values either None or path dictionaries.
the default is {}, which means that no subfolders will be created
Examples
--------
>>> path = './project'
>>> dir_dict = {'dir1':None, 'dir2':{'subdir21':None}}
>>> utils.create_dir(path, dir_dict)
will create:
* *project/dir1*
* *project/dir2/subdir21*
in your parent directory.
'''
folders = path.split('/')
folders = [i for i in folders if i != '']
rootPath = ''
if folders[0] == 'C:':
folders = folders[1:]
count = 0
for directory in folders:
count += 1
# required to handle the dot operators
if (directory[0] == '.') & (count == 1):
rootPath = directory
else:
rootPath = rootPath + '/' + directory
try:
os.makedirs(rootPath)
# If the file already exists (EEXIST), raise exception and do nothing
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
for key in dir_dict.keys():
rootPath = path + "/" + key
try:
os.makedirs(rootPath)
# If the file already exists (EEXIST), raise exception and do nothing
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
if dir_dict[key] is not None:
create_dir(rootPath, dir_dict[key]) | [
"Tries",
"to",
"create",
"a",
"new",
"directory",
"in",
"the",
"given",
"path",
".",
"**",
"create_dir",
"**",
"can",
"also",
"create",
"subfolders",
"according",
"to",
"the",
"dictionnary",
"given",
"as",
"second",
"argument",
"."
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L142-L201 | [
"def",
"create_dir",
"(",
"path",
",",
"dir_dict",
"=",
"{",
"}",
")",
":",
"folders",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"folders",
"=",
"[",
"i",
"for",
"i",
"in",
"folders",
"if",
"i",
"!=",
"''",
"]",
"rootPath",
"=",
"''",
"if",
"folders",
"[",
"0",
"]",
"==",
"'C:'",
":",
"folders",
"=",
"folders",
"[",
"1",
":",
"]",
"count",
"=",
"0",
"for",
"directory",
"in",
"folders",
":",
"count",
"+=",
"1",
"# required to handle the dot operators",
"if",
"(",
"directory",
"[",
"0",
"]",
"==",
"'.'",
")",
"&",
"(",
"count",
"==",
"1",
")",
":",
"rootPath",
"=",
"directory",
"else",
":",
"rootPath",
"=",
"rootPath",
"+",
"'/'",
"+",
"directory",
"try",
":",
"os",
".",
"makedirs",
"(",
"rootPath",
")",
"# If the file already exists (EEXIST), raise exception and do nothing",
"except",
"OSError",
"as",
"exception",
":",
"if",
"exception",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"for",
"key",
"in",
"dir_dict",
".",
"keys",
"(",
")",
":",
"rootPath",
"=",
"path",
"+",
"\"/\"",
"+",
"key",
"try",
":",
"os",
".",
"makedirs",
"(",
"rootPath",
")",
"# If the file already exists (EEXIST), raise exception and do nothing",
"except",
"OSError",
"as",
"exception",
":",
"if",
"exception",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"if",
"dir_dict",
"[",
"key",
"]",
"is",
"not",
"None",
":",
"create_dir",
"(",
"rootPath",
",",
"dir_dict",
"[",
"key",
"]",
")"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | Walk | Generator for walking a directory tree.
Starts at specified root folder, returning files that match our pattern.
Optionally will also recurse through sub-folders.
Parameters
----------
root : string (default is *'.'*)
Path for the root folder to look in.
recurse : bool (default is *True*)
If *True*, will also look in the subfolders.
pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
The pattern to look for in the files' name.
Returns
-------
generator
**Walk** yields a generator from the matching files paths. | turntable/utils.py | def Walk(root='.', recurse=True, pattern='*'):
'''
Generator for walking a directory tree.
Starts at specified root folder, returning files that match our pattern.
Optionally will also recurse through sub-folders.
Parameters
----------
root : string (default is *'.'*)
Path for the root folder to look in.
recurse : bool (default is *True*)
If *True*, will also look in the subfolders.
pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
The pattern to look for in the files' name.
Returns
-------
generator
**Walk** yields a generator from the matching files paths.
'''
for path, subdirs, files in os.walk(root):
for name in files:
if fnmatch.fnmatch(name, pattern):
yield os.path.join(path, name)
if not recurse:
break | def Walk(root='.', recurse=True, pattern='*'):
'''
Generator for walking a directory tree.
Starts at specified root folder, returning files that match our pattern.
Optionally will also recurse through sub-folders.
Parameters
----------
root : string (default is *'.'*)
Path for the root folder to look in.
recurse : bool (default is *True*)
If *True*, will also look in the subfolders.
pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
The pattern to look for in the files' name.
Returns
-------
generator
**Walk** yields a generator from the matching files paths.
'''
for path, subdirs, files in os.walk(root):
for name in files:
if fnmatch.fnmatch(name, pattern):
yield os.path.join(path, name)
if not recurse:
break | [
"Generator",
"for",
"walking",
"a",
"directory",
"tree",
".",
"Starts",
"at",
"specified",
"root",
"folder",
"returning",
"files",
"that",
"match",
"our",
"pattern",
".",
"Optionally",
"will",
"also",
"recurse",
"through",
"sub",
"-",
"folders",
"."
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L203-L230 | [
"def",
"Walk",
"(",
"root",
"=",
"'.'",
",",
"recurse",
"=",
"True",
",",
"pattern",
"=",
"'*'",
")",
":",
"for",
"path",
",",
"subdirs",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
")",
":",
"for",
"name",
"in",
"files",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"name",
",",
"pattern",
")",
":",
"yield",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"name",
")",
"if",
"not",
"recurse",
":",
"break"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | scan_path | Runs a loop over the :doc:`Walk<relpy.utils.Walk>` Generator
to find all file paths in the root directory with the given
pattern. If recurse is *True*: matching paths are identified
for all sub directories.
Parameters
----------
root : string (default is *'.'*)
Path for the root folder to look in.
recurse : bool (default is *True*)
If *True*, will also look in the subfolders.
pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
The pattern to look for in the files' name.
Returns
-------
path_list : list
list of all the matching files paths. | turntable/utils.py | def scan_path(root='.', recurse=False, pattern='*'):
'''
Runs a loop over the :doc:`Walk<relpy.utils.Walk>` Generator
to find all file paths in the root directory with the given
pattern. If recurse is *True*: matching paths are identified
for all sub directories.
Parameters
----------
root : string (default is *'.'*)
Path for the root folder to look in.
recurse : bool (default is *True*)
If *True*, will also look in the subfolders.
pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
The pattern to look for in the files' name.
Returns
-------
path_list : list
list of all the matching files paths.
'''
path_list = []
for path in Walk(root=root, recurse=recurse, pattern=pattern):
path_list.append(path)
return path_list | def scan_path(root='.', recurse=False, pattern='*'):
'''
Runs a loop over the :doc:`Walk<relpy.utils.Walk>` Generator
to find all file paths in the root directory with the given
pattern. If recurse is *True*: matching paths are identified
for all sub directories.
Parameters
----------
root : string (default is *'.'*)
Path for the root folder to look in.
recurse : bool (default is *True*)
If *True*, will also look in the subfolders.
pattern : string (default is :emphasis:`'*'`, which means all the files are concerned)
The pattern to look for in the files' name.
Returns
-------
path_list : list
list of all the matching files paths.
'''
path_list = []
for path in Walk(root=root, recurse=recurse, pattern=pattern):
path_list.append(path)
return path_list | [
"Runs",
"a",
"loop",
"over",
"the",
":",
"doc",
":",
"Walk<relpy",
".",
"utils",
".",
"Walk",
">",
"Generator",
"to",
"find",
"all",
"file",
"paths",
"in",
"the",
"root",
"directory",
"with",
"the",
"given",
"pattern",
".",
"If",
"recurse",
"is",
"*",
"True",
"*",
":",
"matching",
"paths",
"are",
"identified",
"for",
"all",
"sub",
"directories",
"."
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L232-L258 | [
"def",
"scan_path",
"(",
"root",
"=",
"'.'",
",",
"recurse",
"=",
"False",
",",
"pattern",
"=",
"'*'",
")",
":",
"path_list",
"=",
"[",
"]",
"for",
"path",
"in",
"Walk",
"(",
"root",
"=",
"root",
",",
"recurse",
"=",
"recurse",
",",
"pattern",
"=",
"pattern",
")",
":",
"path_list",
".",
"append",
"(",
"path",
")",
"return",
"path_list"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | displayAll | Displays time if verbose is true and count is within the display amount | turntable/utils.py | def displayAll(elapsed, display_amt, est_end, nLoops, count, numPrints):
'''Displays time if verbose is true and count is within the display amount'''
if numPrints > nLoops:
display_amt = 1
else:
display_amt = round(nLoops / numPrints)
if count % display_amt == 0:
avg = elapsed / count
est_end = round(avg * nLoops)
(disp_elapsed,
disp_avg,
disp_est) = timeUnit(int(round(elapsed)),
int(round(avg)),
int(round(est_end)))
print "%s%%" % str(round(count / float(nLoops) * 100)), "@" + str(count),
totalTime = disp_est[0]
unit = disp_est[1]
if str(unit) == "secs":
remain = totalTime - round(elapsed)
remainUnit = "secs"
elif str(unit) == "mins":
remain = totalTime - round(elapsed) / 60
remainUnit = "mins"
elif str(unit) == "hr":
remain = totalTime - round(elapsed) / 3600
remainUnit = "hr"
print "ETA: %s %s" % (str(remain), remainUnit)
print
return | def displayAll(elapsed, display_amt, est_end, nLoops, count, numPrints):
'''Displays time if verbose is true and count is within the display amount'''
if numPrints > nLoops:
display_amt = 1
else:
display_amt = round(nLoops / numPrints)
if count % display_amt == 0:
avg = elapsed / count
est_end = round(avg * nLoops)
(disp_elapsed,
disp_avg,
disp_est) = timeUnit(int(round(elapsed)),
int(round(avg)),
int(round(est_end)))
print "%s%%" % str(round(count / float(nLoops) * 100)), "@" + str(count),
totalTime = disp_est[0]
unit = disp_est[1]
if str(unit) == "secs":
remain = totalTime - round(elapsed)
remainUnit = "secs"
elif str(unit) == "mins":
remain = totalTime - round(elapsed) / 60
remainUnit = "mins"
elif str(unit) == "hr":
remain = totalTime - round(elapsed) / 3600
remainUnit = "hr"
print "ETA: %s %s" % (str(remain), remainUnit)
print
return | [
"Displays",
"time",
"if",
"verbose",
"is",
"true",
"and",
"count",
"is",
"within",
"the",
"display",
"amount"
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L324-L361 | [
"def",
"displayAll",
"(",
"elapsed",
",",
"display_amt",
",",
"est_end",
",",
"nLoops",
",",
"count",
",",
"numPrints",
")",
":",
"if",
"numPrints",
">",
"nLoops",
":",
"display_amt",
"=",
"1",
"else",
":",
"display_amt",
"=",
"round",
"(",
"nLoops",
"/",
"numPrints",
")",
"if",
"count",
"%",
"display_amt",
"==",
"0",
":",
"avg",
"=",
"elapsed",
"/",
"count",
"est_end",
"=",
"round",
"(",
"avg",
"*",
"nLoops",
")",
"(",
"disp_elapsed",
",",
"disp_avg",
",",
"disp_est",
")",
"=",
"timeUnit",
"(",
"int",
"(",
"round",
"(",
"elapsed",
")",
")",
",",
"int",
"(",
"round",
"(",
"avg",
")",
")",
",",
"int",
"(",
"round",
"(",
"est_end",
")",
")",
")",
"print",
"\"%s%%\"",
"%",
"str",
"(",
"round",
"(",
"count",
"/",
"float",
"(",
"nLoops",
")",
"*",
"100",
")",
")",
",",
"\"@\"",
"+",
"str",
"(",
"count",
")",
",",
"totalTime",
"=",
"disp_est",
"[",
"0",
"]",
"unit",
"=",
"disp_est",
"[",
"1",
"]",
"if",
"str",
"(",
"unit",
")",
"==",
"\"secs\"",
":",
"remain",
"=",
"totalTime",
"-",
"round",
"(",
"elapsed",
")",
"remainUnit",
"=",
"\"secs\"",
"elif",
"str",
"(",
"unit",
")",
"==",
"\"mins\"",
":",
"remain",
"=",
"totalTime",
"-",
"round",
"(",
"elapsed",
")",
"/",
"60",
"remainUnit",
"=",
"\"mins\"",
"elif",
"str",
"(",
"unit",
")",
"==",
"\"hr\"",
":",
"remain",
"=",
"totalTime",
"-",
"round",
"(",
"elapsed",
")",
"/",
"3600",
"remainUnit",
"=",
"\"hr\"",
"print",
"\"ETA: %s %s\"",
"%",
"(",
"str",
"(",
"remain",
")",
",",
"remainUnit",
")",
"print",
"return"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | timeUnit | calculates unit of time to display | turntable/utils.py | def timeUnit(elapsed, avg, est_end):
'''calculates unit of time to display'''
minute = 60
hr = 3600
day = 86400
if elapsed <= 3 * minute:
unit_elapsed = (elapsed, "secs")
if elapsed > 3 * minute:
unit_elapsed = ((elapsed / 60), "mins")
if elapsed > 3 * hr:
unit_elapsed = ((elapsed / 3600), "hr")
if avg <= 3 * minute:
unit_avg = (avg, "secs")
if avg > 3 * minute:
unit_avg = ((avg / 60), "mins")
if avg > 3 * hr:
unit_avg = ((avg / 3600), "hr")
if est_end <= 3 * minute:
unit_estEnd = (est_end, "secs")
if est_end > 3 * minute:
unit_estEnd = ((est_end / 60), "mins")
if est_end > 3 * hr:
unit_estEnd = ((est_end / 3600), "hr")
return [unit_elapsed, unit_avg, unit_estEnd] | def timeUnit(elapsed, avg, est_end):
'''calculates unit of time to display'''
minute = 60
hr = 3600
day = 86400
if elapsed <= 3 * minute:
unit_elapsed = (elapsed, "secs")
if elapsed > 3 * minute:
unit_elapsed = ((elapsed / 60), "mins")
if elapsed > 3 * hr:
unit_elapsed = ((elapsed / 3600), "hr")
if avg <= 3 * minute:
unit_avg = (avg, "secs")
if avg > 3 * minute:
unit_avg = ((avg / 60), "mins")
if avg > 3 * hr:
unit_avg = ((avg / 3600), "hr")
if est_end <= 3 * minute:
unit_estEnd = (est_end, "secs")
if est_end > 3 * minute:
unit_estEnd = ((est_end / 60), "mins")
if est_end > 3 * hr:
unit_estEnd = ((est_end / 3600), "hr")
return [unit_elapsed, unit_avg, unit_estEnd] | [
"calculates",
"unit",
"of",
"time",
"to",
"display"
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L364-L391 | [
"def",
"timeUnit",
"(",
"elapsed",
",",
"avg",
",",
"est_end",
")",
":",
"minute",
"=",
"60",
"hr",
"=",
"3600",
"day",
"=",
"86400",
"if",
"elapsed",
"<=",
"3",
"*",
"minute",
":",
"unit_elapsed",
"=",
"(",
"elapsed",
",",
"\"secs\"",
")",
"if",
"elapsed",
">",
"3",
"*",
"minute",
":",
"unit_elapsed",
"=",
"(",
"(",
"elapsed",
"/",
"60",
")",
",",
"\"mins\"",
")",
"if",
"elapsed",
">",
"3",
"*",
"hr",
":",
"unit_elapsed",
"=",
"(",
"(",
"elapsed",
"/",
"3600",
")",
",",
"\"hr\"",
")",
"if",
"avg",
"<=",
"3",
"*",
"minute",
":",
"unit_avg",
"=",
"(",
"avg",
",",
"\"secs\"",
")",
"if",
"avg",
">",
"3",
"*",
"minute",
":",
"unit_avg",
"=",
"(",
"(",
"avg",
"/",
"60",
")",
",",
"\"mins\"",
")",
"if",
"avg",
">",
"3",
"*",
"hr",
":",
"unit_avg",
"=",
"(",
"(",
"avg",
"/",
"3600",
")",
",",
"\"hr\"",
")",
"if",
"est_end",
"<=",
"3",
"*",
"minute",
":",
"unit_estEnd",
"=",
"(",
"est_end",
",",
"\"secs\"",
")",
"if",
"est_end",
">",
"3",
"*",
"minute",
":",
"unit_estEnd",
"=",
"(",
"(",
"est_end",
"/",
"60",
")",
",",
"\"mins\"",
")",
"if",
"est_end",
">",
"3",
"*",
"hr",
":",
"unit_estEnd",
"=",
"(",
"(",
"est_end",
"/",
"3600",
")",
",",
"\"hr\"",
")",
"return",
"[",
"unit_elapsed",
",",
"unit_avg",
",",
"unit_estEnd",
"]"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | Timer.loop | Tracks the time in a loop. The estimated time to completion
can be calculated and if verbose is set to *True*, the object will print
estimated time to completion, and percent complete.
Actived in every loop to keep track | turntable/utils.py | def loop(self):
'''
Tracks the time in a loop. The estimated time to completion
can be calculated and if verbose is set to *True*, the object will print
estimated time to completion, and percent complete.
Actived in every loop to keep track'''
self.count += 1
self.tf = time.time()
self.elapsed = self.tf - self.ti
if self.verbose:
displayAll(self.elapsed, self.display_amt, self.est_end,
self.nLoops, self.count, self.numPrints) | def loop(self):
'''
Tracks the time in a loop. The estimated time to completion
can be calculated and if verbose is set to *True*, the object will print
estimated time to completion, and percent complete.
Actived in every loop to keep track'''
self.count += 1
self.tf = time.time()
self.elapsed = self.tf - self.ti
if self.verbose:
displayAll(self.elapsed, self.display_amt, self.est_end,
self.nLoops, self.count, self.numPrints) | [
"Tracks",
"the",
"time",
"in",
"a",
"loop",
".",
"The",
"estimated",
"time",
"to",
"completion",
"can",
"be",
"calculated",
"and",
"if",
"verbose",
"is",
"set",
"to",
"*",
"True",
"*",
"the",
"object",
"will",
"print",
"estimated",
"time",
"to",
"completion",
"and",
"percent",
"complete",
".",
"Actived",
"in",
"every",
"loop",
"to",
"keep",
"track"
] | jshiv/turntable | python | https://github.com/jshiv/turntable/blob/c095a93df14d672ba54db164a7ab7373444d1829/turntable/utils.py#L305-L318 | [
"def",
"loop",
"(",
"self",
")",
":",
"self",
".",
"count",
"+=",
"1",
"self",
".",
"tf",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"elapsed",
"=",
"self",
".",
"tf",
"-",
"self",
".",
"ti",
"if",
"self",
".",
"verbose",
":",
"displayAll",
"(",
"self",
".",
"elapsed",
",",
"self",
".",
"display_amt",
",",
"self",
".",
"est_end",
",",
"self",
".",
"nLoops",
",",
"self",
".",
"count",
",",
"self",
".",
"numPrints",
")"
] | c095a93df14d672ba54db164a7ab7373444d1829 |
test | add_path | Ensure that the path, or the root of the current package (if
path is in a package), is in sys.path. | environment/lib/python2.7/site-packages/nose/importer.py | def add_path(path, config=None):
"""Ensure that the path, or the root of the current package (if
path is in a package), is in sys.path.
"""
# FIXME add any src-looking dirs seen too... need to get config for that
log.debug('Add path %s' % path)
if not path:
return []
added = []
parent = os.path.dirname(path)
if (parent
and os.path.exists(os.path.join(path, '__init__.py'))):
added.extend(add_path(parent, config))
elif not path in sys.path:
log.debug("insert %s into sys.path", path)
sys.path.insert(0, path)
added.append(path)
if config and config.srcDirs:
for dirname in config.srcDirs:
dirpath = os.path.join(path, dirname)
if os.path.isdir(dirpath):
sys.path.insert(0, dirpath)
added.append(dirpath)
return added | def add_path(path, config=None):
"""Ensure that the path, or the root of the current package (if
path is in a package), is in sys.path.
"""
# FIXME add any src-looking dirs seen too... need to get config for that
log.debug('Add path %s' % path)
if not path:
return []
added = []
parent = os.path.dirname(path)
if (parent
and os.path.exists(os.path.join(path, '__init__.py'))):
added.extend(add_path(parent, config))
elif not path in sys.path:
log.debug("insert %s into sys.path", path)
sys.path.insert(0, path)
added.append(path)
if config and config.srcDirs:
for dirname in config.srcDirs:
dirpath = os.path.join(path, dirname)
if os.path.isdir(dirpath):
sys.path.insert(0, dirpath)
added.append(dirpath)
return added | [
"Ensure",
"that",
"the",
"path",
"or",
"the",
"root",
"of",
"the",
"current",
"package",
"(",
"if",
"path",
"is",
"in",
"a",
"package",
")",
"is",
"in",
"sys",
".",
"path",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/importer.py#L123-L148 | [
"def",
"add_path",
"(",
"path",
",",
"config",
"=",
"None",
")",
":",
"# FIXME add any src-looking dirs seen too... need to get config for that",
"log",
".",
"debug",
"(",
"'Add path %s'",
"%",
"path",
")",
"if",
"not",
"path",
":",
"return",
"[",
"]",
"added",
"=",
"[",
"]",
"parent",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"if",
"(",
"parent",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'__init__.py'",
")",
")",
")",
":",
"added",
".",
"extend",
"(",
"add_path",
"(",
"parent",
",",
"config",
")",
")",
"elif",
"not",
"path",
"in",
"sys",
".",
"path",
":",
"log",
".",
"debug",
"(",
"\"insert %s into sys.path\"",
",",
"path",
")",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"path",
")",
"added",
".",
"append",
"(",
"path",
")",
"if",
"config",
"and",
"config",
".",
"srcDirs",
":",
"for",
"dirname",
"in",
"config",
".",
"srcDirs",
":",
"dirpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"dirname",
")",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"dirpath",
")",
":",
"sys",
".",
"path",
".",
"insert",
"(",
"0",
",",
"dirpath",
")",
"added",
".",
"append",
"(",
"dirpath",
")",
"return",
"added"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Importer.importFromPath | Import a dotted-name package whose tail is at path. In other words,
given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then
bar from path/to/foo/bar, returning bar. | environment/lib/python2.7/site-packages/nose/importer.py | def importFromPath(self, path, fqname):
"""Import a dotted-name package whose tail is at path. In other words,
given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then
bar from path/to/foo/bar, returning bar.
"""
# find the base dir of the package
path_parts = os.path.normpath(os.path.abspath(path)).split(os.sep)
name_parts = fqname.split('.')
if path_parts[-1].startswith('__init__'):
path_parts.pop()
path_parts = path_parts[:-(len(name_parts))]
dir_path = os.sep.join(path_parts)
# then import fqname starting from that dir
return self.importFromDir(dir_path, fqname) | def importFromPath(self, path, fqname):
"""Import a dotted-name package whose tail is at path. In other words,
given foo.bar and path/to/foo/bar.py, import foo from path/to/foo then
bar from path/to/foo/bar, returning bar.
"""
# find the base dir of the package
path_parts = os.path.normpath(os.path.abspath(path)).split(os.sep)
name_parts = fqname.split('.')
if path_parts[-1].startswith('__init__'):
path_parts.pop()
path_parts = path_parts[:-(len(name_parts))]
dir_path = os.sep.join(path_parts)
# then import fqname starting from that dir
return self.importFromDir(dir_path, fqname) | [
"Import",
"a",
"dotted",
"-",
"name",
"package",
"whose",
"tail",
"is",
"at",
"path",
".",
"In",
"other",
"words",
"given",
"foo",
".",
"bar",
"and",
"path",
"/",
"to",
"/",
"foo",
"/",
"bar",
".",
"py",
"import",
"foo",
"from",
"path",
"/",
"to",
"/",
"foo",
"then",
"bar",
"from",
"path",
"/",
"to",
"/",
"foo",
"/",
"bar",
"returning",
"bar",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/importer.py#L26-L39 | [
"def",
"importFromPath",
"(",
"self",
",",
"path",
",",
"fqname",
")",
":",
"# find the base dir of the package",
"path_parts",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
")",
".",
"split",
"(",
"os",
".",
"sep",
")",
"name_parts",
"=",
"fqname",
".",
"split",
"(",
"'.'",
")",
"if",
"path_parts",
"[",
"-",
"1",
"]",
".",
"startswith",
"(",
"'__init__'",
")",
":",
"path_parts",
".",
"pop",
"(",
")",
"path_parts",
"=",
"path_parts",
"[",
":",
"-",
"(",
"len",
"(",
"name_parts",
")",
")",
"]",
"dir_path",
"=",
"os",
".",
"sep",
".",
"join",
"(",
"path_parts",
")",
"# then import fqname starting from that dir",
"return",
"self",
".",
"importFromDir",
"(",
"dir_path",
",",
"fqname",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | Importer.importFromDir | Import a module *only* from path, ignoring sys.path and
reloading if the version in sys.modules is not the one we want. | environment/lib/python2.7/site-packages/nose/importer.py | def importFromDir(self, dir, fqname):
"""Import a module *only* from path, ignoring sys.path and
reloading if the version in sys.modules is not the one we want.
"""
dir = os.path.normpath(os.path.abspath(dir))
log.debug("Import %s from %s", fqname, dir)
# FIXME reimplement local per-dir cache?
# special case for __main__
if fqname == '__main__':
return sys.modules[fqname]
if self.config.addPaths:
add_path(dir, self.config)
path = [dir]
parts = fqname.split('.')
part_fqname = ''
mod = parent = fh = None
for part in parts:
if part_fqname == '':
part_fqname = part
else:
part_fqname = "%s.%s" % (part_fqname, part)
try:
acquire_lock()
log.debug("find module part %s (%s) in %s",
part, part_fqname, path)
fh, filename, desc = find_module(part, path)
old = sys.modules.get(part_fqname)
if old is not None:
# test modules frequently have name overlap; make sure
# we get a fresh copy of anything we are trying to load
# from a new path
log.debug("sys.modules has %s as %s", part_fqname, old)
if (self.sameModule(old, filename)
or (self.config.firstPackageWins and
getattr(old, '__path__', None))):
mod = old
else:
del sys.modules[part_fqname]
mod = load_module(part_fqname, fh, filename, desc)
else:
mod = load_module(part_fqname, fh, filename, desc)
finally:
if fh:
fh.close()
release_lock()
if parent:
setattr(parent, part, mod)
if hasattr(mod, '__path__'):
path = mod.__path__
parent = mod
return mod | def importFromDir(self, dir, fqname):
"""Import a module *only* from path, ignoring sys.path and
reloading if the version in sys.modules is not the one we want.
"""
dir = os.path.normpath(os.path.abspath(dir))
log.debug("Import %s from %s", fqname, dir)
# FIXME reimplement local per-dir cache?
# special case for __main__
if fqname == '__main__':
return sys.modules[fqname]
if self.config.addPaths:
add_path(dir, self.config)
path = [dir]
parts = fqname.split('.')
part_fqname = ''
mod = parent = fh = None
for part in parts:
if part_fqname == '':
part_fqname = part
else:
part_fqname = "%s.%s" % (part_fqname, part)
try:
acquire_lock()
log.debug("find module part %s (%s) in %s",
part, part_fqname, path)
fh, filename, desc = find_module(part, path)
old = sys.modules.get(part_fqname)
if old is not None:
# test modules frequently have name overlap; make sure
# we get a fresh copy of anything we are trying to load
# from a new path
log.debug("sys.modules has %s as %s", part_fqname, old)
if (self.sameModule(old, filename)
or (self.config.firstPackageWins and
getattr(old, '__path__', None))):
mod = old
else:
del sys.modules[part_fqname]
mod = load_module(part_fqname, fh, filename, desc)
else:
mod = load_module(part_fqname, fh, filename, desc)
finally:
if fh:
fh.close()
release_lock()
if parent:
setattr(parent, part, mod)
if hasattr(mod, '__path__'):
path = mod.__path__
parent = mod
return mod | [
"Import",
"a",
"module",
"*",
"only",
"*",
"from",
"path",
"ignoring",
"sys",
".",
"path",
"and",
"reloading",
"if",
"the",
"version",
"in",
"sys",
".",
"modules",
"is",
"not",
"the",
"one",
"we",
"want",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/importer.py#L41-L96 | [
"def",
"importFromDir",
"(",
"self",
",",
"dir",
",",
"fqname",
")",
":",
"dir",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"dir",
")",
")",
"log",
".",
"debug",
"(",
"\"Import %s from %s\"",
",",
"fqname",
",",
"dir",
")",
"# FIXME reimplement local per-dir cache?",
"# special case for __main__",
"if",
"fqname",
"==",
"'__main__'",
":",
"return",
"sys",
".",
"modules",
"[",
"fqname",
"]",
"if",
"self",
".",
"config",
".",
"addPaths",
":",
"add_path",
"(",
"dir",
",",
"self",
".",
"config",
")",
"path",
"=",
"[",
"dir",
"]",
"parts",
"=",
"fqname",
".",
"split",
"(",
"'.'",
")",
"part_fqname",
"=",
"''",
"mod",
"=",
"parent",
"=",
"fh",
"=",
"None",
"for",
"part",
"in",
"parts",
":",
"if",
"part_fqname",
"==",
"''",
":",
"part_fqname",
"=",
"part",
"else",
":",
"part_fqname",
"=",
"\"%s.%s\"",
"%",
"(",
"part_fqname",
",",
"part",
")",
"try",
":",
"acquire_lock",
"(",
")",
"log",
".",
"debug",
"(",
"\"find module part %s (%s) in %s\"",
",",
"part",
",",
"part_fqname",
",",
"path",
")",
"fh",
",",
"filename",
",",
"desc",
"=",
"find_module",
"(",
"part",
",",
"path",
")",
"old",
"=",
"sys",
".",
"modules",
".",
"get",
"(",
"part_fqname",
")",
"if",
"old",
"is",
"not",
"None",
":",
"# test modules frequently have name overlap; make sure",
"# we get a fresh copy of anything we are trying to load",
"# from a new path",
"log",
".",
"debug",
"(",
"\"sys.modules has %s as %s\"",
",",
"part_fqname",
",",
"old",
")",
"if",
"(",
"self",
".",
"sameModule",
"(",
"old",
",",
"filename",
")",
"or",
"(",
"self",
".",
"config",
".",
"firstPackageWins",
"and",
"getattr",
"(",
"old",
",",
"'__path__'",
",",
"None",
")",
")",
")",
":",
"mod",
"=",
"old",
"else",
":",
"del",
"sys",
".",
"modules",
"[",
"part_fqname",
"]",
"mod",
"=",
"load_module",
"(",
"part_fqname",
",",
"fh",
",",
"filename",
",",
"desc",
")",
"else",
":",
"mod",
"=",
"load_module",
"(",
"part_fqname",
",",
"fh",
",",
"filename",
",",
"desc",
")",
"finally",
":",
"if",
"fh",
":",
"fh",
".",
"close",
"(",
")",
"release_lock",
"(",
")",
"if",
"parent",
":",
"setattr",
"(",
"parent",
",",
"part",
",",
"mod",
")",
"if",
"hasattr",
"(",
"mod",
",",
"'__path__'",
")",
":",
"path",
"=",
"mod",
".",
"__path__",
"parent",
"=",
"mod",
"return",
"mod"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | extract_wininst_cfg | Extract configuration data from a bdist_wininst .exe
Returns a ConfigParser.RawConfigParser, or None | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def extract_wininst_cfg(dist_filename):
"""Extract configuration data from a bdist_wininst .exe
Returns a ConfigParser.RawConfigParser, or None
"""
f = open(dist_filename,'rb')
try:
endrec = zipfile._EndRecData(f)
if endrec is None:
return None
prepended = (endrec[9] - endrec[5]) - endrec[6]
if prepended < 12: # no wininst data here
return None
f.seek(prepended-12)
import struct, StringIO, ConfigParser
tag, cfglen, bmlen = struct.unpack("<iii",f.read(12))
if tag not in (0x1234567A, 0x1234567B):
return None # not a valid tag
f.seek(prepended-(12+cfglen))
cfg = ConfigParser.RawConfigParser({'version':'','target_version':''})
try:
part = f.read(cfglen)
# part is in bytes, but we need to read up to the first null
# byte.
if sys.version_info >= (2,6):
null_byte = bytes([0])
else:
null_byte = chr(0)
config = part.split(null_byte, 1)[0]
# Now the config is in bytes, but on Python 3, it must be
# unicode for the RawConfigParser, so decode it. Is this the
# right encoding?
config = config.decode('ascii')
cfg.readfp(StringIO.StringIO(config))
except ConfigParser.Error:
return None
if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
return None
return cfg
finally:
f.close() | def extract_wininst_cfg(dist_filename):
"""Extract configuration data from a bdist_wininst .exe
Returns a ConfigParser.RawConfigParser, or None
"""
f = open(dist_filename,'rb')
try:
endrec = zipfile._EndRecData(f)
if endrec is None:
return None
prepended = (endrec[9] - endrec[5]) - endrec[6]
if prepended < 12: # no wininst data here
return None
f.seek(prepended-12)
import struct, StringIO, ConfigParser
tag, cfglen, bmlen = struct.unpack("<iii",f.read(12))
if tag not in (0x1234567A, 0x1234567B):
return None # not a valid tag
f.seek(prepended-(12+cfglen))
cfg = ConfigParser.RawConfigParser({'version':'','target_version':''})
try:
part = f.read(cfglen)
# part is in bytes, but we need to read up to the first null
# byte.
if sys.version_info >= (2,6):
null_byte = bytes([0])
else:
null_byte = chr(0)
config = part.split(null_byte, 1)[0]
# Now the config is in bytes, but on Python 3, it must be
# unicode for the RawConfigParser, so decode it. Is this the
# right encoding?
config = config.decode('ascii')
cfg.readfp(StringIO.StringIO(config))
except ConfigParser.Error:
return None
if not cfg.has_section('metadata') or not cfg.has_section('Setup'):
return None
return cfg
finally:
f.close() | [
"Extract",
"configuration",
"data",
"from",
"a",
"bdist_wininst",
".",
"exe"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L1449-L1493 | [
"def",
"extract_wininst_cfg",
"(",
"dist_filename",
")",
":",
"f",
"=",
"open",
"(",
"dist_filename",
",",
"'rb'",
")",
"try",
":",
"endrec",
"=",
"zipfile",
".",
"_EndRecData",
"(",
"f",
")",
"if",
"endrec",
"is",
"None",
":",
"return",
"None",
"prepended",
"=",
"(",
"endrec",
"[",
"9",
"]",
"-",
"endrec",
"[",
"5",
"]",
")",
"-",
"endrec",
"[",
"6",
"]",
"if",
"prepended",
"<",
"12",
":",
"# no wininst data here",
"return",
"None",
"f",
".",
"seek",
"(",
"prepended",
"-",
"12",
")",
"import",
"struct",
",",
"StringIO",
",",
"ConfigParser",
"tag",
",",
"cfglen",
",",
"bmlen",
"=",
"struct",
".",
"unpack",
"(",
"\"<iii\"",
",",
"f",
".",
"read",
"(",
"12",
")",
")",
"if",
"tag",
"not",
"in",
"(",
"0x1234567A",
",",
"0x1234567B",
")",
":",
"return",
"None",
"# not a valid tag",
"f",
".",
"seek",
"(",
"prepended",
"-",
"(",
"12",
"+",
"cfglen",
")",
")",
"cfg",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
"{",
"'version'",
":",
"''",
",",
"'target_version'",
":",
"''",
"}",
")",
"try",
":",
"part",
"=",
"f",
".",
"read",
"(",
"cfglen",
")",
"# part is in bytes, but we need to read up to the first null",
"# byte.",
"if",
"sys",
".",
"version_info",
">=",
"(",
"2",
",",
"6",
")",
":",
"null_byte",
"=",
"bytes",
"(",
"[",
"0",
"]",
")",
"else",
":",
"null_byte",
"=",
"chr",
"(",
"0",
")",
"config",
"=",
"part",
".",
"split",
"(",
"null_byte",
",",
"1",
")",
"[",
"0",
"]",
"# Now the config is in bytes, but on Python 3, it must be",
"# unicode for the RawConfigParser, so decode it. Is this the",
"# right encoding?",
"config",
"=",
"config",
".",
"decode",
"(",
"'ascii'",
")",
"cfg",
".",
"readfp",
"(",
"StringIO",
".",
"StringIO",
"(",
"config",
")",
")",
"except",
"ConfigParser",
".",
"Error",
":",
"return",
"None",
"if",
"not",
"cfg",
".",
"has_section",
"(",
"'metadata'",
")",
"or",
"not",
"cfg",
".",
"has_section",
"(",
"'Setup'",
")",
":",
"return",
"None",
"return",
"cfg",
"finally",
":",
"f",
".",
"close",
"(",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_script_header | Create a #! line, getting options (if any) from script_text | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def get_script_header(script_text, executable=sys_executable, wininst=False):
"""Create a #! line, getting options (if any) from script_text"""
from distutils.command.build_scripts import first_line_re
# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
if not isinstance(first_line_re.pattern, str):
first_line_re = re.compile(first_line_re.pattern.decode())
first = (script_text+'\n').splitlines()[0]
match = first_line_re.match(first)
options = ''
if match:
options = match.group(1) or ''
if options: options = ' '+options
if wininst:
executable = "python.exe"
else:
executable = nt_quote_arg(executable)
hdr = "#!%(executable)s%(options)s\n" % locals()
if not isascii(hdr):
# Non-ascii path to sys.executable, use -x to prevent warnings
if options:
if options.strip().startswith('-'):
options = ' -x'+options.strip()[1:]
# else: punt, we can't do it, let the warning happen anyway
else:
options = ' -x'
executable = fix_jython_executable(executable, options)
hdr = "#!%(executable)s%(options)s\n" % locals()
return hdr | def get_script_header(script_text, executable=sys_executable, wininst=False):
"""Create a #! line, getting options (if any) from script_text"""
from distutils.command.build_scripts import first_line_re
# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.
if not isinstance(first_line_re.pattern, str):
first_line_re = re.compile(first_line_re.pattern.decode())
first = (script_text+'\n').splitlines()[0]
match = first_line_re.match(first)
options = ''
if match:
options = match.group(1) or ''
if options: options = ' '+options
if wininst:
executable = "python.exe"
else:
executable = nt_quote_arg(executable)
hdr = "#!%(executable)s%(options)s\n" % locals()
if not isascii(hdr):
# Non-ascii path to sys.executable, use -x to prevent warnings
if options:
if options.strip().startswith('-'):
options = ' -x'+options.strip()[1:]
# else: punt, we can't do it, let the warning happen anyway
else:
options = ' -x'
executable = fix_jython_executable(executable, options)
hdr = "#!%(executable)s%(options)s\n" % locals()
return hdr | [
"Create",
"a",
"#!",
"line",
"getting",
"options",
"(",
"if",
"any",
")",
"from",
"script_text"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L1650-L1679 | [
"def",
"get_script_header",
"(",
"script_text",
",",
"executable",
"=",
"sys_executable",
",",
"wininst",
"=",
"False",
")",
":",
"from",
"distutils",
".",
"command",
".",
"build_scripts",
"import",
"first_line_re",
"# first_line_re in Python >=3.1.4 and >=3.2.1 is a bytes pattern.",
"if",
"not",
"isinstance",
"(",
"first_line_re",
".",
"pattern",
",",
"str",
")",
":",
"first_line_re",
"=",
"re",
".",
"compile",
"(",
"first_line_re",
".",
"pattern",
".",
"decode",
"(",
")",
")",
"first",
"=",
"(",
"script_text",
"+",
"'\\n'",
")",
".",
"splitlines",
"(",
")",
"[",
"0",
"]",
"match",
"=",
"first_line_re",
".",
"match",
"(",
"first",
")",
"options",
"=",
"''",
"if",
"match",
":",
"options",
"=",
"match",
".",
"group",
"(",
"1",
")",
"or",
"''",
"if",
"options",
":",
"options",
"=",
"' '",
"+",
"options",
"if",
"wininst",
":",
"executable",
"=",
"\"python.exe\"",
"else",
":",
"executable",
"=",
"nt_quote_arg",
"(",
"executable",
")",
"hdr",
"=",
"\"#!%(executable)s%(options)s\\n\"",
"%",
"locals",
"(",
")",
"if",
"not",
"isascii",
"(",
"hdr",
")",
":",
"# Non-ascii path to sys.executable, use -x to prevent warnings",
"if",
"options",
":",
"if",
"options",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'-'",
")",
":",
"options",
"=",
"' -x'",
"+",
"options",
".",
"strip",
"(",
")",
"[",
"1",
":",
"]",
"# else: punt, we can't do it, let the warning happen anyway",
"else",
":",
"options",
"=",
"' -x'",
"executable",
"=",
"fix_jython_executable",
"(",
"executable",
",",
"options",
")",
"hdr",
"=",
"\"#!%(executable)s%(options)s\\n\"",
"%",
"locals",
"(",
")",
"return",
"hdr"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | uncache_zipdir | Ensure that the importer caches dont have stale info for `path` | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def uncache_zipdir(path):
"""Ensure that the importer caches dont have stale info for `path`"""
from zipimport import _zip_directory_cache as zdc
_uncache(path, zdc)
_uncache(path, sys.path_importer_cache) | def uncache_zipdir(path):
"""Ensure that the importer caches dont have stale info for `path`"""
from zipimport import _zip_directory_cache as zdc
_uncache(path, zdc)
_uncache(path, sys.path_importer_cache) | [
"Ensure",
"that",
"the",
"importer",
"caches",
"dont",
"have",
"stale",
"info",
"for",
"path"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L1688-L1692 | [
"def",
"uncache_zipdir",
"(",
"path",
")",
":",
"from",
"zipimport",
"import",
"_zip_directory_cache",
"as",
"zdc",
"_uncache",
"(",
"path",
",",
"zdc",
")",
"_uncache",
"(",
"path",
",",
"sys",
".",
"path_importer_cache",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | is_sh | Determine if the specified executable is a .sh (contains a #! line) | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def is_sh(executable):
"""Determine if the specified executable is a .sh (contains a #! line)"""
try:
fp = open(executable)
magic = fp.read(2)
fp.close()
except (OSError,IOError): return executable
return magic == '#!' | def is_sh(executable):
"""Determine if the specified executable is a .sh (contains a #! line)"""
try:
fp = open(executable)
magic = fp.read(2)
fp.close()
except (OSError,IOError): return executable
return magic == '#!' | [
"Determine",
"if",
"the",
"specified",
"executable",
"is",
"a",
".",
"sh",
"(",
"contains",
"a",
"#!",
"line",
")"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L1713-L1720 | [
"def",
"is_sh",
"(",
"executable",
")",
":",
"try",
":",
"fp",
"=",
"open",
"(",
"executable",
")",
"magic",
"=",
"fp",
".",
"read",
"(",
"2",
")",
"fp",
".",
"close",
"(",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"return",
"executable",
"return",
"magic",
"==",
"'#!'"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | nt_quote_arg | Quote a command line argument according to Windows parsing rules | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def nt_quote_arg(arg):
"""Quote a command line argument according to Windows parsing rules"""
result = []
needquote = False
nb = 0
needquote = (" " in arg) or ("\t" in arg)
if needquote:
result.append('"')
for c in arg:
if c == '\\':
nb += 1
elif c == '"':
# double preceding backslashes, then add a \"
result.append('\\' * (nb*2) + '\\"')
nb = 0
else:
if nb:
result.append('\\' * nb)
nb = 0
result.append(c)
if nb:
result.append('\\' * nb)
if needquote:
result.append('\\' * nb) # double the trailing backslashes
result.append('"')
return ''.join(result) | def nt_quote_arg(arg):
"""Quote a command line argument according to Windows parsing rules"""
result = []
needquote = False
nb = 0
needquote = (" " in arg) or ("\t" in arg)
if needquote:
result.append('"')
for c in arg:
if c == '\\':
nb += 1
elif c == '"':
# double preceding backslashes, then add a \"
result.append('\\' * (nb*2) + '\\"')
nb = 0
else:
if nb:
result.append('\\' * nb)
nb = 0
result.append(c)
if nb:
result.append('\\' * nb)
if needquote:
result.append('\\' * nb) # double the trailing backslashes
result.append('"')
return ''.join(result) | [
"Quote",
"a",
"command",
"line",
"argument",
"according",
"to",
"Windows",
"parsing",
"rules"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L1722-L1753 | [
"def",
"nt_quote_arg",
"(",
"arg",
")",
":",
"result",
"=",
"[",
"]",
"needquote",
"=",
"False",
"nb",
"=",
"0",
"needquote",
"=",
"(",
"\" \"",
"in",
"arg",
")",
"or",
"(",
"\"\\t\"",
"in",
"arg",
")",
"if",
"needquote",
":",
"result",
".",
"append",
"(",
"'\"'",
")",
"for",
"c",
"in",
"arg",
":",
"if",
"c",
"==",
"'\\\\'",
":",
"nb",
"+=",
"1",
"elif",
"c",
"==",
"'\"'",
":",
"# double preceding backslashes, then add a \\\"",
"result",
".",
"append",
"(",
"'\\\\'",
"*",
"(",
"nb",
"*",
"2",
")",
"+",
"'\\\\\"'",
")",
"nb",
"=",
"0",
"else",
":",
"if",
"nb",
":",
"result",
".",
"append",
"(",
"'\\\\'",
"*",
"nb",
")",
"nb",
"=",
"0",
"result",
".",
"append",
"(",
"c",
")",
"if",
"nb",
":",
"result",
".",
"append",
"(",
"'\\\\'",
"*",
"nb",
")",
"if",
"needquote",
":",
"result",
".",
"append",
"(",
"'\\\\'",
"*",
"nb",
")",
"# double the trailing backslashes",
"result",
".",
"append",
"(",
"'\"'",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | get_script_args | Yield write_script() argument tuples for a distribution's entrypoints | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def get_script_args(dist, executable=sys_executable, wininst=False):
"""Yield write_script() argument tuples for a distribution's entrypoints"""
spec = str(dist.as_requirement())
header = get_script_header("", executable, wininst)
for group in 'console_scripts', 'gui_scripts':
for name, ep in dist.get_entry_map(group).items():
script_text = (
"# EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\n"
"__requires__ = %(spec)r\n"
"import sys\n"
"from pkg_resources import load_entry_point\n"
"\n"
"if __name__ == '__main__':"
"\n"
" sys.exit(\n"
" load_entry_point(%(spec)r, %(group)r, %(name)r)()\n"
" )\n"
) % locals()
if sys.platform=='win32' or wininst:
# On Windows/wininst, add a .py extension and an .exe launcher
if group=='gui_scripts':
ext, launcher = '-script.pyw', 'gui.exe'
old = ['.pyw']
new_header = re.sub('(?i)python.exe','pythonw.exe',header)
else:
ext, launcher = '-script.py', 'cli.exe'
old = ['.py','.pyc','.pyo']
new_header = re.sub('(?i)pythonw.exe','python.exe',header)
if is_64bit():
launcher = launcher.replace(".", "-64.")
else:
launcher = launcher.replace(".", "-32.")
if os.path.exists(new_header[2:-1]) or sys.platform!='win32':
hdr = new_header
else:
hdr = header
yield (name+ext, hdr+script_text, 't', [name+x for x in old])
yield (
name+'.exe', resource_string('setuptools', launcher),
'b' # write in binary mode
)
else:
# On other platforms, we assume the right thing to do is to
# just write the stub with no extension.
yield (name, header+script_text) | def get_script_args(dist, executable=sys_executable, wininst=False):
"""Yield write_script() argument tuples for a distribution's entrypoints"""
spec = str(dist.as_requirement())
header = get_script_header("", executable, wininst)
for group in 'console_scripts', 'gui_scripts':
for name, ep in dist.get_entry_map(group).items():
script_text = (
"# EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\n"
"__requires__ = %(spec)r\n"
"import sys\n"
"from pkg_resources import load_entry_point\n"
"\n"
"if __name__ == '__main__':"
"\n"
" sys.exit(\n"
" load_entry_point(%(spec)r, %(group)r, %(name)r)()\n"
" )\n"
) % locals()
if sys.platform=='win32' or wininst:
# On Windows/wininst, add a .py extension and an .exe launcher
if group=='gui_scripts':
ext, launcher = '-script.pyw', 'gui.exe'
old = ['.pyw']
new_header = re.sub('(?i)python.exe','pythonw.exe',header)
else:
ext, launcher = '-script.py', 'cli.exe'
old = ['.py','.pyc','.pyo']
new_header = re.sub('(?i)pythonw.exe','python.exe',header)
if is_64bit():
launcher = launcher.replace(".", "-64.")
else:
launcher = launcher.replace(".", "-32.")
if os.path.exists(new_header[2:-1]) or sys.platform!='win32':
hdr = new_header
else:
hdr = header
yield (name+ext, hdr+script_text, 't', [name+x for x in old])
yield (
name+'.exe', resource_string('setuptools', launcher),
'b' # write in binary mode
)
else:
# On other platforms, we assume the right thing to do is to
# just write the stub with no extension.
yield (name, header+script_text) | [
"Yield",
"write_script",
"()",
"argument",
"tuples",
"for",
"a",
"distribution",
"s",
"entrypoints"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L1804-L1848 | [
"def",
"get_script_args",
"(",
"dist",
",",
"executable",
"=",
"sys_executable",
",",
"wininst",
"=",
"False",
")",
":",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"header",
"=",
"get_script_header",
"(",
"\"\"",
",",
"executable",
",",
"wininst",
")",
"for",
"group",
"in",
"'console_scripts'",
",",
"'gui_scripts'",
":",
"for",
"name",
",",
"ep",
"in",
"dist",
".",
"get_entry_map",
"(",
"group",
")",
".",
"items",
"(",
")",
":",
"script_text",
"=",
"(",
"\"# EASY-INSTALL-ENTRY-SCRIPT: %(spec)r,%(group)r,%(name)r\\n\"",
"\"__requires__ = %(spec)r\\n\"",
"\"import sys\\n\"",
"\"from pkg_resources import load_entry_point\\n\"",
"\"\\n\"",
"\"if __name__ == '__main__':\"",
"\"\\n\"",
"\" sys.exit(\\n\"",
"\" load_entry_point(%(spec)r, %(group)r, %(name)r)()\\n\"",
"\" )\\n\"",
")",
"%",
"locals",
"(",
")",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"or",
"wininst",
":",
"# On Windows/wininst, add a .py extension and an .exe launcher",
"if",
"group",
"==",
"'gui_scripts'",
":",
"ext",
",",
"launcher",
"=",
"'-script.pyw'",
",",
"'gui.exe'",
"old",
"=",
"[",
"'.pyw'",
"]",
"new_header",
"=",
"re",
".",
"sub",
"(",
"'(?i)python.exe'",
",",
"'pythonw.exe'",
",",
"header",
")",
"else",
":",
"ext",
",",
"launcher",
"=",
"'-script.py'",
",",
"'cli.exe'",
"old",
"=",
"[",
"'.py'",
",",
"'.pyc'",
",",
"'.pyo'",
"]",
"new_header",
"=",
"re",
".",
"sub",
"(",
"'(?i)pythonw.exe'",
",",
"'python.exe'",
",",
"header",
")",
"if",
"is_64bit",
"(",
")",
":",
"launcher",
"=",
"launcher",
".",
"replace",
"(",
"\".\"",
",",
"\"-64.\"",
")",
"else",
":",
"launcher",
"=",
"launcher",
".",
"replace",
"(",
"\".\"",
",",
"\"-32.\"",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"new_header",
"[",
"2",
":",
"-",
"1",
"]",
")",
"or",
"sys",
".",
"platform",
"!=",
"'win32'",
":",
"hdr",
"=",
"new_header",
"else",
":",
"hdr",
"=",
"header",
"yield",
"(",
"name",
"+",
"ext",
",",
"hdr",
"+",
"script_text",
",",
"'t'",
",",
"[",
"name",
"+",
"x",
"for",
"x",
"in",
"old",
"]",
")",
"yield",
"(",
"name",
"+",
"'.exe'",
",",
"resource_string",
"(",
"'setuptools'",
",",
"launcher",
")",
",",
"'b'",
"# write in binary mode",
")",
"else",
":",
"# On other platforms, we assume the right thing to do is to",
"# just write the stub with no extension.",
"yield",
"(",
"name",
",",
"header",
"+",
"script_text",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | easy_install.pseudo_tempname | Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo. | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def pseudo_tempname(self):
"""Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo.
"""
try:
pid = os.getpid()
except:
pid = random.randint(0,sys.maxint)
return os.path.join(self.install_dir, "test-easy-install-%s" % pid) | def pseudo_tempname(self):
"""Return a pseudo-tempname base in the install directory.
This code is intentionally naive; if a malicious party can write to
the target directory you're already in deep doodoo.
"""
try:
pid = os.getpid()
except:
pid = random.randint(0,sys.maxint)
return os.path.join(self.install_dir, "test-easy-install-%s" % pid) | [
"Return",
"a",
"pseudo",
"-",
"tempname",
"base",
"in",
"the",
"install",
"directory",
".",
"This",
"code",
"is",
"intentionally",
"naive",
";",
"if",
"a",
"malicious",
"party",
"can",
"write",
"to",
"the",
"target",
"directory",
"you",
"re",
"already",
"in",
"deep",
"doodoo",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L375-L384 | [
"def",
"pseudo_tempname",
"(",
"self",
")",
":",
"try",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"except",
":",
"pid",
"=",
"random",
".",
"randint",
"(",
"0",
",",
"sys",
".",
"maxint",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"install_dir",
",",
"\"test-easy-install-%s\"",
"%",
"pid",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | easy_install.install_script | Generate a legacy script wrapper and install it | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def install_script(self, dist, script_name, script_text, dev_path=None):
"""Generate a legacy script wrapper and install it"""
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
def get_template(filename):
"""
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
These templates use triple-quotes to escape variable
substitutions so the scripts get the 2to3 treatment when build
on Python 3. The templates cannot use triple-quotes naturally.
"""
raw_bytes = resource_string('setuptools', template_name)
template_str = raw_bytes.decode('utf-8')
clean_template = template_str.replace('"""', '')
return clean_template
if is_script:
template_name = 'script template.py'
if dev_path:
template_name = template_name.replace('.py', ' (dev).py')
script_text = (get_script_header(script_text) +
get_template(template_name) % locals())
self.write_script(script_name, _to_ascii(script_text), 'b') | def install_script(self, dist, script_name, script_text, dev_path=None):
"""Generate a legacy script wrapper and install it"""
spec = str(dist.as_requirement())
is_script = is_python_script(script_text, script_name)
def get_template(filename):
"""
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
These templates use triple-quotes to escape variable
substitutions so the scripts get the 2to3 treatment when build
on Python 3. The templates cannot use triple-quotes naturally.
"""
raw_bytes = resource_string('setuptools', template_name)
template_str = raw_bytes.decode('utf-8')
clean_template = template_str.replace('"""', '')
return clean_template
if is_script:
template_name = 'script template.py'
if dev_path:
template_name = template_name.replace('.py', ' (dev).py')
script_text = (get_script_header(script_text) +
get_template(template_name) % locals())
self.write_script(script_name, _to_ascii(script_text), 'b') | [
"Generate",
"a",
"legacy",
"script",
"wrapper",
"and",
"install",
"it"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L738-L763 | [
"def",
"install_script",
"(",
"self",
",",
"dist",
",",
"script_name",
",",
"script_text",
",",
"dev_path",
"=",
"None",
")",
":",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"is_script",
"=",
"is_python_script",
"(",
"script_text",
",",
"script_name",
")",
"def",
"get_template",
"(",
"filename",
")",
":",
"\"\"\"\n There are a couple of template scripts in the package. This\n function loads one of them and prepares it for use.\n\n These templates use triple-quotes to escape variable\n substitutions so the scripts get the 2to3 treatment when build\n on Python 3. The templates cannot use triple-quotes naturally.\n \"\"\"",
"raw_bytes",
"=",
"resource_string",
"(",
"'setuptools'",
",",
"template_name",
")",
"template_str",
"=",
"raw_bytes",
".",
"decode",
"(",
"'utf-8'",
")",
"clean_template",
"=",
"template_str",
".",
"replace",
"(",
"'\"\"\"'",
",",
"''",
")",
"return",
"clean_template",
"if",
"is_script",
":",
"template_name",
"=",
"'script template.py'",
"if",
"dev_path",
":",
"template_name",
"=",
"template_name",
".",
"replace",
"(",
"'.py'",
",",
"' (dev).py'",
")",
"script_text",
"=",
"(",
"get_script_header",
"(",
"script_text",
")",
"+",
"get_template",
"(",
"template_name",
")",
"%",
"locals",
"(",
")",
")",
"self",
".",
"write_script",
"(",
"script_name",
",",
"_to_ascii",
"(",
"script_text",
")",
",",
"'b'",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | easy_install.check_conflicts | Verify that there are no conflicting "old-style" packages | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def check_conflicts(self, dist):
"""Verify that there are no conflicting "old-style" packages"""
return dist # XXX temporarily disable until new strategy is stable
from imp import find_module, get_suffixes
from glob import glob
blockers = []
names = dict.fromkeys(dist._get_metadata('top_level.txt')) # XXX private attr
exts = {'.pyc':1, '.pyo':1} # get_suffixes() might leave one out
for ext,mode,typ in get_suffixes():
exts[ext] = 1
for path,files in expand_paths([self.install_dir]+self.all_site_dirs):
for filename in files:
base,ext = os.path.splitext(filename)
if base in names:
if not ext:
# no extension, check for package
try:
f, filename, descr = find_module(base, [path])
except ImportError:
continue
else:
if f: f.close()
if filename not in blockers:
blockers.append(filename)
elif ext in exts and base!='site': # XXX ugh
blockers.append(os.path.join(path,filename))
if blockers:
self.found_conflicts(dist, blockers)
return dist | def check_conflicts(self, dist):
"""Verify that there are no conflicting "old-style" packages"""
return dist # XXX temporarily disable until new strategy is stable
from imp import find_module, get_suffixes
from glob import glob
blockers = []
names = dict.fromkeys(dist._get_metadata('top_level.txt')) # XXX private attr
exts = {'.pyc':1, '.pyo':1} # get_suffixes() might leave one out
for ext,mode,typ in get_suffixes():
exts[ext] = 1
for path,files in expand_paths([self.install_dir]+self.all_site_dirs):
for filename in files:
base,ext = os.path.splitext(filename)
if base in names:
if not ext:
# no extension, check for package
try:
f, filename, descr = find_module(base, [path])
except ImportError:
continue
else:
if f: f.close()
if filename not in blockers:
blockers.append(filename)
elif ext in exts and base!='site': # XXX ugh
blockers.append(os.path.join(path,filename))
if blockers:
self.found_conflicts(dist, blockers)
return dist | [
"Verify",
"that",
"there",
"are",
"no",
"conflicting",
"old",
"-",
"style",
"packages"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L956-L989 | [
"def",
"check_conflicts",
"(",
"self",
",",
"dist",
")",
":",
"return",
"dist",
"# XXX temporarily disable until new strategy is stable",
"from",
"imp",
"import",
"find_module",
",",
"get_suffixes",
"from",
"glob",
"import",
"glob",
"blockers",
"=",
"[",
"]",
"names",
"=",
"dict",
".",
"fromkeys",
"(",
"dist",
".",
"_get_metadata",
"(",
"'top_level.txt'",
")",
")",
"# XXX private attr",
"exts",
"=",
"{",
"'.pyc'",
":",
"1",
",",
"'.pyo'",
":",
"1",
"}",
"# get_suffixes() might leave one out",
"for",
"ext",
",",
"mode",
",",
"typ",
"in",
"get_suffixes",
"(",
")",
":",
"exts",
"[",
"ext",
"]",
"=",
"1",
"for",
"path",
",",
"files",
"in",
"expand_paths",
"(",
"[",
"self",
".",
"install_dir",
"]",
"+",
"self",
".",
"all_site_dirs",
")",
":",
"for",
"filename",
"in",
"files",
":",
"base",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"if",
"base",
"in",
"names",
":",
"if",
"not",
"ext",
":",
"# no extension, check for package",
"try",
":",
"f",
",",
"filename",
",",
"descr",
"=",
"find_module",
"(",
"base",
",",
"[",
"path",
"]",
")",
"except",
"ImportError",
":",
"continue",
"else",
":",
"if",
"f",
":",
"f",
".",
"close",
"(",
")",
"if",
"filename",
"not",
"in",
"blockers",
":",
"blockers",
".",
"append",
"(",
"filename",
")",
"elif",
"ext",
"in",
"exts",
"and",
"base",
"!=",
"'site'",
":",
"# XXX ugh",
"blockers",
".",
"append",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
")",
"if",
"blockers",
":",
"self",
".",
"found_conflicts",
"(",
"dist",
",",
"blockers",
")",
"return",
"dist"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | easy_install._set_fetcher_options | When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well. | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def _set_fetcher_options(self, base):
"""
When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well.
"""
# find the fetch options from easy_install and write them out
# to the setup.cfg file.
ei_opts = self.distribution.get_option_dict('easy_install').copy()
fetch_directives = (
'find_links', 'site_dirs', 'index_url', 'optimize',
'site_dirs', 'allow_hosts',
)
fetch_options = {}
for key, val in ei_opts.iteritems():
if key not in fetch_directives: continue
fetch_options[key.replace('_', '-')] = val[1]
# create a settings dictionary suitable for `edit_config`
settings = dict(easy_install=fetch_options)
cfg_filename = os.path.join(base, 'setup.cfg')
setopt.edit_config(cfg_filename, settings) | def _set_fetcher_options(self, base):
"""
When easy_install is about to run bdist_egg on a source dist, that
source dist might have 'setup_requires' directives, requiring
additional fetching. Ensure the fetcher options given to easy_install
are available to that command as well.
"""
# find the fetch options from easy_install and write them out
# to the setup.cfg file.
ei_opts = self.distribution.get_option_dict('easy_install').copy()
fetch_directives = (
'find_links', 'site_dirs', 'index_url', 'optimize',
'site_dirs', 'allow_hosts',
)
fetch_options = {}
for key, val in ei_opts.iteritems():
if key not in fetch_directives: continue
fetch_options[key.replace('_', '-')] = val[1]
# create a settings dictionary suitable for `edit_config`
settings = dict(easy_install=fetch_options)
cfg_filename = os.path.join(base, 'setup.cfg')
setopt.edit_config(cfg_filename, settings) | [
"When",
"easy_install",
"is",
"about",
"to",
"run",
"bdist_egg",
"on",
"a",
"source",
"dist",
"that",
"source",
"dist",
"might",
"have",
"setup_requires",
"directives",
"requiring",
"additional",
"fetching",
".",
"Ensure",
"the",
"fetcher",
"options",
"given",
"to",
"easy_install",
"are",
"available",
"to",
"that",
"command",
"as",
"well",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L1117-L1138 | [
"def",
"_set_fetcher_options",
"(",
"self",
",",
"base",
")",
":",
"# find the fetch options from easy_install and write them out",
"# to the setup.cfg file.",
"ei_opts",
"=",
"self",
".",
"distribution",
".",
"get_option_dict",
"(",
"'easy_install'",
")",
".",
"copy",
"(",
")",
"fetch_directives",
"=",
"(",
"'find_links'",
",",
"'site_dirs'",
",",
"'index_url'",
",",
"'optimize'",
",",
"'site_dirs'",
",",
"'allow_hosts'",
",",
")",
"fetch_options",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"ei_opts",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
"not",
"in",
"fetch_directives",
":",
"continue",
"fetch_options",
"[",
"key",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
"]",
"=",
"val",
"[",
"1",
"]",
"# create a settings dictionary suitable for `edit_config`",
"settings",
"=",
"dict",
"(",
"easy_install",
"=",
"fetch_options",
")",
"cfg_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"base",
",",
"'setup.cfg'",
")",
"setopt",
".",
"edit_config",
"(",
"cfg_filename",
",",
"settings",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | easy_install.create_home_path | Create directories under ~. | environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py | def create_home_path(self):
"""Create directories under ~."""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for name, path in self.config_vars.iteritems():
if path.startswith(home) and not os.path.isdir(path):
self.debug_print("os.makedirs('%s', 0700)" % path)
os.makedirs(path, 0700) | def create_home_path(self):
"""Create directories under ~."""
if not self.user:
return
home = convert_path(os.path.expanduser("~"))
for name, path in self.config_vars.iteritems():
if path.startswith(home) and not os.path.isdir(path):
self.debug_print("os.makedirs('%s', 0700)" % path)
os.makedirs(path, 0700) | [
"Create",
"directories",
"under",
"~",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/easy_install.py#L1306-L1314 | [
"def",
"create_home_path",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"user",
":",
"return",
"home",
"=",
"convert_path",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
")",
"for",
"name",
",",
"path",
"in",
"self",
".",
"config_vars",
".",
"iteritems",
"(",
")",
":",
"if",
"path",
".",
"startswith",
"(",
"home",
")",
"and",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"self",
".",
"debug_print",
"(",
"\"os.makedirs('%s', 0700)\"",
"%",
"path",
")",
"os",
".",
"makedirs",
"(",
"path",
",",
"0700",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | is_archive_file | Return True if `name` is a considered as an archive file. | virtualEnvironment/lib/python2.7/site-packages/pip/download.py | def is_archive_file(name):
"""Return True if `name` is a considered as an archive file."""
archives = (
'.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.whl'
)
ext = splitext(name)[1].lower()
if ext in archives:
return True
return False | def is_archive_file(name):
"""Return True if `name` is a considered as an archive file."""
archives = (
'.zip', '.tar.gz', '.tar.bz2', '.tgz', '.tar', '.whl'
)
ext = splitext(name)[1].lower()
if ext in archives:
return True
return False | [
"Return",
"True",
"if",
"name",
"is",
"a",
"considered",
"as",
"an",
"archive",
"file",
"."
] | tnkteja/myhelp | python | https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/download.py#L452-L460 | [
"def",
"is_archive_file",
"(",
"name",
")",
":",
"archives",
"=",
"(",
"'.zip'",
",",
"'.tar.gz'",
",",
"'.tar.bz2'",
",",
"'.tgz'",
",",
"'.tar'",
",",
"'.whl'",
")",
"ext",
"=",
"splitext",
"(",
"name",
")",
"[",
"1",
"]",
".",
"lower",
"(",
")",
"if",
"ext",
"in",
"archives",
":",
"return",
"True",
"return",
"False"
] | fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb |
test | mutable | return a mutable proxy for the `obj`.
all modify on the proxy will not apply on origin object. | jasily/lang/proxy.py | def mutable(obj):
'''
return a mutable proxy for the `obj`.
all modify on the proxy will not apply on origin object.
'''
base_cls = type(obj)
class Proxy(base_cls):
def __getattribute__(self, name):
try:
return super().__getattribute__(name)
except AttributeError:
return getattr(obj, name)
update_wrapper(Proxy, base_cls, updated = ())
return Proxy() | def mutable(obj):
'''
return a mutable proxy for the `obj`.
all modify on the proxy will not apply on origin object.
'''
base_cls = type(obj)
class Proxy(base_cls):
def __getattribute__(self, name):
try:
return super().__getattribute__(name)
except AttributeError:
return getattr(obj, name)
update_wrapper(Proxy, base_cls, updated = ())
return Proxy() | [
"return",
"a",
"mutable",
"proxy",
"for",
"the",
"obj",
"."
] | Jasily/jasily-python | python | https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/lang/proxy.py#L12-L28 | [
"def",
"mutable",
"(",
"obj",
")",
":",
"base_cls",
"=",
"type",
"(",
"obj",
")",
"class",
"Proxy",
"(",
"base_cls",
")",
":",
"def",
"__getattribute__",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"return",
"super",
"(",
")",
".",
"__getattribute__",
"(",
"name",
")",
"except",
"AttributeError",
":",
"return",
"getattr",
"(",
"obj",
",",
"name",
")",
"update_wrapper",
"(",
"Proxy",
",",
"base_cls",
",",
"updated",
"=",
"(",
")",
")",
"return",
"Proxy",
"(",
")"
] | 1c821a120ebbbbc3c5761f5f1e8a73588059242a |
test | readonly | return a readonly proxy for the `obj`.
all modify on the proxy will not apply on origin object. | jasily/lang/proxy.py | def readonly(obj, *, error_on_set = False):
'''
return a readonly proxy for the `obj`.
all modify on the proxy will not apply on origin object.
'''
base_cls = type(obj)
class ReadonlyProxy(base_cls):
def __getattribute__(self, name):
return getattr(obj, name)
def __setattr__(self, name, value):
if error_on_set:
raise AttributeError('cannot set readonly object.')
update_wrapper(ReadonlyProxy, base_cls, updated = ())
return ReadonlyProxy() | def readonly(obj, *, error_on_set = False):
'''
return a readonly proxy for the `obj`.
all modify on the proxy will not apply on origin object.
'''
base_cls = type(obj)
class ReadonlyProxy(base_cls):
def __getattribute__(self, name):
return getattr(obj, name)
def __setattr__(self, name, value):
if error_on_set:
raise AttributeError('cannot set readonly object.')
update_wrapper(ReadonlyProxy, base_cls, updated = ())
return ReadonlyProxy() | [
"return",
"a",
"readonly",
"proxy",
"for",
"the",
"obj",
"."
] | Jasily/jasily-python | python | https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/lang/proxy.py#L30-L47 | [
"def",
"readonly",
"(",
"obj",
",",
"*",
",",
"error_on_set",
"=",
"False",
")",
":",
"base_cls",
"=",
"type",
"(",
"obj",
")",
"class",
"ReadonlyProxy",
"(",
"base_cls",
")",
":",
"def",
"__getattribute__",
"(",
"self",
",",
"name",
")",
":",
"return",
"getattr",
"(",
"obj",
",",
"name",
")",
"def",
"__setattr__",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"if",
"error_on_set",
":",
"raise",
"AttributeError",
"(",
"'cannot set readonly object.'",
")",
"update_wrapper",
"(",
"ReadonlyProxy",
",",
"base_cls",
",",
"updated",
"=",
"(",
")",
")",
"return",
"ReadonlyProxy",
"(",
")"
] | 1c821a120ebbbbc3c5761f5f1e8a73588059242a |
test | new_output | Create a new code cell with input and output | environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py | def new_output(output_type=None, output_text=None, output_png=None,
output_html=None, output_svg=None, output_latex=None, output_json=None,
output_javascript=None, output_jpeg=None, prompt_number=None,
etype=None, evalue=None, traceback=None):
"""Create a new code cell with input and output"""
output = NotebookNode()
if output_type is not None:
output.output_type = unicode(output_type)
if output_type != 'pyerr':
if output_text is not None:
output.text = unicode(output_text)
if output_png is not None:
output.png = bytes(output_png)
if output_jpeg is not None:
output.jpeg = bytes(output_jpeg)
if output_html is not None:
output.html = unicode(output_html)
if output_svg is not None:
output.svg = unicode(output_svg)
if output_latex is not None:
output.latex = unicode(output_latex)
if output_json is not None:
output.json = unicode(output_json)
if output_javascript is not None:
output.javascript = unicode(output_javascript)
if output_type == u'pyout':
if prompt_number is not None:
output.prompt_number = int(prompt_number)
if output_type == u'pyerr':
if etype is not None:
output.etype = unicode(etype)
if evalue is not None:
output.evalue = unicode(evalue)
if traceback is not None:
output.traceback = [unicode(frame) for frame in list(traceback)]
return output | def new_output(output_type=None, output_text=None, output_png=None,
output_html=None, output_svg=None, output_latex=None, output_json=None,
output_javascript=None, output_jpeg=None, prompt_number=None,
etype=None, evalue=None, traceback=None):
"""Create a new code cell with input and output"""
output = NotebookNode()
if output_type is not None:
output.output_type = unicode(output_type)
if output_type != 'pyerr':
if output_text is not None:
output.text = unicode(output_text)
if output_png is not None:
output.png = bytes(output_png)
if output_jpeg is not None:
output.jpeg = bytes(output_jpeg)
if output_html is not None:
output.html = unicode(output_html)
if output_svg is not None:
output.svg = unicode(output_svg)
if output_latex is not None:
output.latex = unicode(output_latex)
if output_json is not None:
output.json = unicode(output_json)
if output_javascript is not None:
output.javascript = unicode(output_javascript)
if output_type == u'pyout':
if prompt_number is not None:
output.prompt_number = int(prompt_number)
if output_type == u'pyerr':
if etype is not None:
output.etype = unicode(etype)
if evalue is not None:
output.evalue = unicode(evalue)
if traceback is not None:
output.traceback = [unicode(frame) for frame in list(traceback)]
return output | [
"Create",
"a",
"new",
"code",
"cell",
"with",
"input",
"and",
"output"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py#L53-L92 | [
"def",
"new_output",
"(",
"output_type",
"=",
"None",
",",
"output_text",
"=",
"None",
",",
"output_png",
"=",
"None",
",",
"output_html",
"=",
"None",
",",
"output_svg",
"=",
"None",
",",
"output_latex",
"=",
"None",
",",
"output_json",
"=",
"None",
",",
"output_javascript",
"=",
"None",
",",
"output_jpeg",
"=",
"None",
",",
"prompt_number",
"=",
"None",
",",
"etype",
"=",
"None",
",",
"evalue",
"=",
"None",
",",
"traceback",
"=",
"None",
")",
":",
"output",
"=",
"NotebookNode",
"(",
")",
"if",
"output_type",
"is",
"not",
"None",
":",
"output",
".",
"output_type",
"=",
"unicode",
"(",
"output_type",
")",
"if",
"output_type",
"!=",
"'pyerr'",
":",
"if",
"output_text",
"is",
"not",
"None",
":",
"output",
".",
"text",
"=",
"unicode",
"(",
"output_text",
")",
"if",
"output_png",
"is",
"not",
"None",
":",
"output",
".",
"png",
"=",
"bytes",
"(",
"output_png",
")",
"if",
"output_jpeg",
"is",
"not",
"None",
":",
"output",
".",
"jpeg",
"=",
"bytes",
"(",
"output_jpeg",
")",
"if",
"output_html",
"is",
"not",
"None",
":",
"output",
".",
"html",
"=",
"unicode",
"(",
"output_html",
")",
"if",
"output_svg",
"is",
"not",
"None",
":",
"output",
".",
"svg",
"=",
"unicode",
"(",
"output_svg",
")",
"if",
"output_latex",
"is",
"not",
"None",
":",
"output",
".",
"latex",
"=",
"unicode",
"(",
"output_latex",
")",
"if",
"output_json",
"is",
"not",
"None",
":",
"output",
".",
"json",
"=",
"unicode",
"(",
"output_json",
")",
"if",
"output_javascript",
"is",
"not",
"None",
":",
"output",
".",
"javascript",
"=",
"unicode",
"(",
"output_javascript",
")",
"if",
"output_type",
"==",
"u'pyout'",
":",
"if",
"prompt_number",
"is",
"not",
"None",
":",
"output",
".",
"prompt_number",
"=",
"int",
"(",
"prompt_number",
")",
"if",
"output_type",
"==",
"u'pyerr'",
":",
"if",
"etype",
"is",
"not",
"None",
":",
"output",
".",
"etype",
"=",
"unicode",
"(",
"etype",
")",
"if",
"evalue",
"is",
"not",
"None",
":",
"output",
".",
"evalue",
"=",
"unicode",
"(",
"evalue",
")",
"if",
"traceback",
"is",
"not",
"None",
":",
"output",
".",
"traceback",
"=",
"[",
"unicode",
"(",
"frame",
")",
"for",
"frame",
"in",
"list",
"(",
"traceback",
")",
"]",
"return",
"output"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | new_code_cell | Create a new code cell with input and output | environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py | def new_code_cell(input=None, prompt_number=None, outputs=None,
language=u'python', collapsed=False, metadata=None):
"""Create a new code cell with input and output"""
cell = NotebookNode()
cell.cell_type = u'code'
if language is not None:
cell.language = unicode(language)
if input is not None:
cell.input = unicode(input)
if prompt_number is not None:
cell.prompt_number = int(prompt_number)
if outputs is None:
cell.outputs = []
else:
cell.outputs = outputs
if collapsed is not None:
cell.collapsed = bool(collapsed)
cell.metadata = NotebookNode(metadata or {})
return cell | def new_code_cell(input=None, prompt_number=None, outputs=None,
language=u'python', collapsed=False, metadata=None):
"""Create a new code cell with input and output"""
cell = NotebookNode()
cell.cell_type = u'code'
if language is not None:
cell.language = unicode(language)
if input is not None:
cell.input = unicode(input)
if prompt_number is not None:
cell.prompt_number = int(prompt_number)
if outputs is None:
cell.outputs = []
else:
cell.outputs = outputs
if collapsed is not None:
cell.collapsed = bool(collapsed)
cell.metadata = NotebookNode(metadata or {})
return cell | [
"Create",
"a",
"new",
"code",
"cell",
"with",
"input",
"and",
"output"
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py#L95-L114 | [
"def",
"new_code_cell",
"(",
"input",
"=",
"None",
",",
"prompt_number",
"=",
"None",
",",
"outputs",
"=",
"None",
",",
"language",
"=",
"u'python'",
",",
"collapsed",
"=",
"False",
",",
"metadata",
"=",
"None",
")",
":",
"cell",
"=",
"NotebookNode",
"(",
")",
"cell",
".",
"cell_type",
"=",
"u'code'",
"if",
"language",
"is",
"not",
"None",
":",
"cell",
".",
"language",
"=",
"unicode",
"(",
"language",
")",
"if",
"input",
"is",
"not",
"None",
":",
"cell",
".",
"input",
"=",
"unicode",
"(",
"input",
")",
"if",
"prompt_number",
"is",
"not",
"None",
":",
"cell",
".",
"prompt_number",
"=",
"int",
"(",
"prompt_number",
")",
"if",
"outputs",
"is",
"None",
":",
"cell",
".",
"outputs",
"=",
"[",
"]",
"else",
":",
"cell",
".",
"outputs",
"=",
"outputs",
"if",
"collapsed",
"is",
"not",
"None",
":",
"cell",
".",
"collapsed",
"=",
"bool",
"(",
"collapsed",
")",
"cell",
".",
"metadata",
"=",
"NotebookNode",
"(",
"metadata",
"or",
"{",
"}",
")",
"return",
"cell"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | new_text_cell | Create a new text cell. | environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py | def new_text_cell(cell_type, source=None, rendered=None, metadata=None):
"""Create a new text cell."""
cell = NotebookNode()
# VERSIONHACK: plaintext -> raw
# handle never-released plaintext name for raw cells
if cell_type == 'plaintext':
cell_type = 'raw'
if source is not None:
cell.source = unicode(source)
if rendered is not None:
cell.rendered = unicode(rendered)
cell.metadata = NotebookNode(metadata or {})
cell.cell_type = cell_type
return cell | def new_text_cell(cell_type, source=None, rendered=None, metadata=None):
"""Create a new text cell."""
cell = NotebookNode()
# VERSIONHACK: plaintext -> raw
# handle never-released plaintext name for raw cells
if cell_type == 'plaintext':
cell_type = 'raw'
if source is not None:
cell.source = unicode(source)
if rendered is not None:
cell.rendered = unicode(rendered)
cell.metadata = NotebookNode(metadata or {})
cell.cell_type = cell_type
return cell | [
"Create",
"a",
"new",
"text",
"cell",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py#L116-L129 | [
"def",
"new_text_cell",
"(",
"cell_type",
",",
"source",
"=",
"None",
",",
"rendered",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"cell",
"=",
"NotebookNode",
"(",
")",
"# VERSIONHACK: plaintext -> raw",
"# handle never-released plaintext name for raw cells",
"if",
"cell_type",
"==",
"'plaintext'",
":",
"cell_type",
"=",
"'raw'",
"if",
"source",
"is",
"not",
"None",
":",
"cell",
".",
"source",
"=",
"unicode",
"(",
"source",
")",
"if",
"rendered",
"is",
"not",
"None",
":",
"cell",
".",
"rendered",
"=",
"unicode",
"(",
"rendered",
")",
"cell",
".",
"metadata",
"=",
"NotebookNode",
"(",
"metadata",
"or",
"{",
"}",
")",
"cell",
".",
"cell_type",
"=",
"cell_type",
"return",
"cell"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | new_heading_cell | Create a new section cell with a given integer level. | environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py | def new_heading_cell(source=None, rendered=None, level=1, metadata=None):
"""Create a new section cell with a given integer level."""
cell = NotebookNode()
cell.cell_type = u'heading'
if source is not None:
cell.source = unicode(source)
if rendered is not None:
cell.rendered = unicode(rendered)
cell.level = int(level)
cell.metadata = NotebookNode(metadata or {})
return cell | def new_heading_cell(source=None, rendered=None, level=1, metadata=None):
"""Create a new section cell with a given integer level."""
cell = NotebookNode()
cell.cell_type = u'heading'
if source is not None:
cell.source = unicode(source)
if rendered is not None:
cell.rendered = unicode(rendered)
cell.level = int(level)
cell.metadata = NotebookNode(metadata or {})
return cell | [
"Create",
"a",
"new",
"section",
"cell",
"with",
"a",
"given",
"integer",
"level",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py#L132-L142 | [
"def",
"new_heading_cell",
"(",
"source",
"=",
"None",
",",
"rendered",
"=",
"None",
",",
"level",
"=",
"1",
",",
"metadata",
"=",
"None",
")",
":",
"cell",
"=",
"NotebookNode",
"(",
")",
"cell",
".",
"cell_type",
"=",
"u'heading'",
"if",
"source",
"is",
"not",
"None",
":",
"cell",
".",
"source",
"=",
"unicode",
"(",
"source",
")",
"if",
"rendered",
"is",
"not",
"None",
":",
"cell",
".",
"rendered",
"=",
"unicode",
"(",
"rendered",
")",
"cell",
".",
"level",
"=",
"int",
"(",
"level",
")",
"cell",
".",
"metadata",
"=",
"NotebookNode",
"(",
"metadata",
"or",
"{",
"}",
")",
"return",
"cell"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | new_notebook | Create a notebook by name, id and a list of worksheets. | environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py | def new_notebook(name=None, metadata=None, worksheets=None):
"""Create a notebook by name, id and a list of worksheets."""
nb = NotebookNode()
nb.nbformat = nbformat
nb.nbformat_minor = nbformat_minor
if worksheets is None:
nb.worksheets = []
else:
nb.worksheets = list(worksheets)
if metadata is None:
nb.metadata = new_metadata()
else:
nb.metadata = NotebookNode(metadata)
if name is not None:
nb.metadata.name = unicode(name)
return nb | def new_notebook(name=None, metadata=None, worksheets=None):
"""Create a notebook by name, id and a list of worksheets."""
nb = NotebookNode()
nb.nbformat = nbformat
nb.nbformat_minor = nbformat_minor
if worksheets is None:
nb.worksheets = []
else:
nb.worksheets = list(worksheets)
if metadata is None:
nb.metadata = new_metadata()
else:
nb.metadata = NotebookNode(metadata)
if name is not None:
nb.metadata.name = unicode(name)
return nb | [
"Create",
"a",
"notebook",
"by",
"name",
"id",
"and",
"a",
"list",
"of",
"worksheets",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py#L158-L173 | [
"def",
"new_notebook",
"(",
"name",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"worksheets",
"=",
"None",
")",
":",
"nb",
"=",
"NotebookNode",
"(",
")",
"nb",
".",
"nbformat",
"=",
"nbformat",
"nb",
".",
"nbformat_minor",
"=",
"nbformat_minor",
"if",
"worksheets",
"is",
"None",
":",
"nb",
".",
"worksheets",
"=",
"[",
"]",
"else",
":",
"nb",
".",
"worksheets",
"=",
"list",
"(",
"worksheets",
")",
"if",
"metadata",
"is",
"None",
":",
"nb",
".",
"metadata",
"=",
"new_metadata",
"(",
")",
"else",
":",
"nb",
".",
"metadata",
"=",
"NotebookNode",
"(",
"metadata",
")",
"if",
"name",
"is",
"not",
"None",
":",
"nb",
".",
"metadata",
".",
"name",
"=",
"unicode",
"(",
"name",
")",
"return",
"nb"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | new_metadata | Create a new metadata node. | environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py | def new_metadata(name=None, authors=None, license=None, created=None,
modified=None, gistid=None):
"""Create a new metadata node."""
metadata = NotebookNode()
if name is not None:
metadata.name = unicode(name)
if authors is not None:
metadata.authors = list(authors)
if created is not None:
metadata.created = unicode(created)
if modified is not None:
metadata.modified = unicode(modified)
if license is not None:
metadata.license = unicode(license)
if gistid is not None:
metadata.gistid = unicode(gistid)
return metadata | def new_metadata(name=None, authors=None, license=None, created=None,
modified=None, gistid=None):
"""Create a new metadata node."""
metadata = NotebookNode()
if name is not None:
metadata.name = unicode(name)
if authors is not None:
metadata.authors = list(authors)
if created is not None:
metadata.created = unicode(created)
if modified is not None:
metadata.modified = unicode(modified)
if license is not None:
metadata.license = unicode(license)
if gistid is not None:
metadata.gistid = unicode(gistid)
return metadata | [
"Create",
"a",
"new",
"metadata",
"node",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py#L176-L192 | [
"def",
"new_metadata",
"(",
"name",
"=",
"None",
",",
"authors",
"=",
"None",
",",
"license",
"=",
"None",
",",
"created",
"=",
"None",
",",
"modified",
"=",
"None",
",",
"gistid",
"=",
"None",
")",
":",
"metadata",
"=",
"NotebookNode",
"(",
")",
"if",
"name",
"is",
"not",
"None",
":",
"metadata",
".",
"name",
"=",
"unicode",
"(",
"name",
")",
"if",
"authors",
"is",
"not",
"None",
":",
"metadata",
".",
"authors",
"=",
"list",
"(",
"authors",
")",
"if",
"created",
"is",
"not",
"None",
":",
"metadata",
".",
"created",
"=",
"unicode",
"(",
"created",
")",
"if",
"modified",
"is",
"not",
"None",
":",
"metadata",
".",
"modified",
"=",
"unicode",
"(",
"modified",
")",
"if",
"license",
"is",
"not",
"None",
":",
"metadata",
".",
"license",
"=",
"unicode",
"(",
"license",
")",
"if",
"gistid",
"is",
"not",
"None",
":",
"metadata",
".",
"gistid",
"=",
"unicode",
"(",
"gistid",
")",
"return",
"metadata"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | new_author | Create a new author. | environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py | def new_author(name=None, email=None, affiliation=None, url=None):
"""Create a new author."""
author = NotebookNode()
if name is not None:
author.name = unicode(name)
if email is not None:
author.email = unicode(email)
if affiliation is not None:
author.affiliation = unicode(affiliation)
if url is not None:
author.url = unicode(url)
return author | def new_author(name=None, email=None, affiliation=None, url=None):
"""Create a new author."""
author = NotebookNode()
if name is not None:
author.name = unicode(name)
if email is not None:
author.email = unicode(email)
if affiliation is not None:
author.affiliation = unicode(affiliation)
if url is not None:
author.url = unicode(url)
return author | [
"Create",
"a",
"new",
"author",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/nbformat/v3/nbbase.py#L194-L205 | [
"def",
"new_author",
"(",
"name",
"=",
"None",
",",
"email",
"=",
"None",
",",
"affiliation",
"=",
"None",
",",
"url",
"=",
"None",
")",
":",
"author",
"=",
"NotebookNode",
"(",
")",
"if",
"name",
"is",
"not",
"None",
":",
"author",
".",
"name",
"=",
"unicode",
"(",
"name",
")",
"if",
"email",
"is",
"not",
"None",
":",
"author",
".",
"email",
"=",
"unicode",
"(",
"email",
")",
"if",
"affiliation",
"is",
"not",
"None",
":",
"author",
".",
"affiliation",
"=",
"unicode",
"(",
"affiliation",
")",
"if",
"url",
"is",
"not",
"None",
":",
"author",
".",
"url",
"=",
"unicode",
"(",
"url",
")",
"return",
"author"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | embed_kernel | Embed and start an IPython kernel in a given scope.
Parameters
----------
module : ModuleType, optional
The module to load into IPython globals (default: caller)
local_ns : dict, optional
The namespace to load into IPython user namespace (default: caller)
kwargs : various, optional
Further keyword args are relayed to the KernelApp constructor,
allowing configuration of the Kernel. Will only have an effect
on the first embed_kernel call for a given process. | environment/lib/python2.7/site-packages/IPython/__init__.py | def embed_kernel(module=None, local_ns=None, **kwargs):
"""Embed and start an IPython kernel in a given scope.
Parameters
----------
module : ModuleType, optional
The module to load into IPython globals (default: caller)
local_ns : dict, optional
The namespace to load into IPython user namespace (default: caller)
kwargs : various, optional
Further keyword args are relayed to the KernelApp constructor,
allowing configuration of the Kernel. Will only have an effect
on the first embed_kernel call for a given process.
"""
(caller_module, caller_locals) = extract_module_locals(1)
if module is None:
module = caller_module
if local_ns is None:
local_ns = caller_locals
# Only import .zmq when we really need it
from .zmq.ipkernel import embed_kernel as real_embed_kernel
real_embed_kernel(module=module, local_ns=local_ns, **kwargs) | def embed_kernel(module=None, local_ns=None, **kwargs):
"""Embed and start an IPython kernel in a given scope.
Parameters
----------
module : ModuleType, optional
The module to load into IPython globals (default: caller)
local_ns : dict, optional
The namespace to load into IPython user namespace (default: caller)
kwargs : various, optional
Further keyword args are relayed to the KernelApp constructor,
allowing configuration of the Kernel. Will only have an effect
on the first embed_kernel call for a given process.
"""
(caller_module, caller_locals) = extract_module_locals(1)
if module is None:
module = caller_module
if local_ns is None:
local_ns = caller_locals
# Only import .zmq when we really need it
from .zmq.ipkernel import embed_kernel as real_embed_kernel
real_embed_kernel(module=module, local_ns=local_ns, **kwargs) | [
"Embed",
"and",
"start",
"an",
"IPython",
"kernel",
"in",
"a",
"given",
"scope",
".",
"Parameters",
"----------",
"module",
":",
"ModuleType",
"optional",
"The",
"module",
"to",
"load",
"into",
"IPython",
"globals",
"(",
"default",
":",
"caller",
")",
"local_ns",
":",
"dict",
"optional",
"The",
"namespace",
"to",
"load",
"into",
"IPython",
"user",
"namespace",
"(",
"default",
":",
"caller",
")",
"kwargs",
":",
"various",
"optional",
"Further",
"keyword",
"args",
"are",
"relayed",
"to",
"the",
"KernelApp",
"constructor",
"allowing",
"configuration",
"of",
"the",
"Kernel",
".",
"Will",
"only",
"have",
"an",
"effect",
"on",
"the",
"first",
"embed_kernel",
"call",
"for",
"a",
"given",
"process",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/__init__.py#L61-L86 | [
"def",
"embed_kernel",
"(",
"module",
"=",
"None",
",",
"local_ns",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"(",
"caller_module",
",",
"caller_locals",
")",
"=",
"extract_module_locals",
"(",
"1",
")",
"if",
"module",
"is",
"None",
":",
"module",
"=",
"caller_module",
"if",
"local_ns",
"is",
"None",
":",
"local_ns",
"=",
"caller_locals",
"# Only import .zmq when we really need it",
"from",
".",
"zmq",
".",
"ipkernel",
"import",
"embed_kernel",
"as",
"real_embed_kernel",
"real_embed_kernel",
"(",
"module",
"=",
"module",
",",
"local_ns",
"=",
"local_ns",
",",
"*",
"*",
"kwargs",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | _writable_dir | Whether `path` is a directory, to which the user has write access. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def _writable_dir(path):
"""Whether `path` is a directory, to which the user has write access."""
return os.path.isdir(path) and os.access(path, os.W_OK) | def _writable_dir(path):
"""Whether `path` is a directory, to which the user has write access."""
return os.path.isdir(path) and os.access(path, os.W_OK) | [
"Whether",
"path",
"is",
"a",
"directory",
"to",
"which",
"the",
"user",
"has",
"write",
"access",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L38-L40 | [
"def",
"_writable_dir",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
"and",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"W_OK",
")"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
test | unquote_filename | On Windows, remove leading and trailing quotes from filenames. | environment/lib/python2.7/site-packages/IPython/utils/path.py | def unquote_filename(name, win32=(sys.platform=='win32')):
""" On Windows, remove leading and trailing quotes from filenames.
"""
if win32:
if name.startswith(("'", '"')) and name.endswith(("'", '"')):
name = name[1:-1]
return name | def unquote_filename(name, win32=(sys.platform=='win32')):
""" On Windows, remove leading and trailing quotes from filenames.
"""
if win32:
if name.startswith(("'", '"')) and name.endswith(("'", '"')):
name = name[1:-1]
return name | [
"On",
"Windows",
"remove",
"leading",
"and",
"trailing",
"quotes",
"from",
"filenames",
"."
] | cloud9ers/gurumate | python | https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/path.py#L79-L85 | [
"def",
"unquote_filename",
"(",
"name",
",",
"win32",
"=",
"(",
"sys",
".",
"platform",
"==",
"'win32'",
")",
")",
":",
"if",
"win32",
":",
"if",
"name",
".",
"startswith",
"(",
"(",
"\"'\"",
",",
"'\"'",
")",
")",
"and",
"name",
".",
"endswith",
"(",
"(",
"\"'\"",
",",
"'\"'",
")",
")",
":",
"name",
"=",
"name",
"[",
"1",
":",
"-",
"1",
"]",
"return",
"name"
] | 075dc74d1ee62a8c6b7a8bf2b271364f01629d1e |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.