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
CompletionHtml.eventFilter
Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def eventFilter(self, obj, event): """ Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() if self._consecutive_tab == 0 and key in (QtCore.Qt.Key_Tab,): return False elif self._consecutive_tab == 1 and key in (QtCore.Qt.Key_Tab,): # ok , called twice, we grab focus, and show the cursor self._consecutive_tab = self._consecutive_tab+1 self._update_list() return True elif self._consecutive_tab == 2: if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter): self._complete_current() return True if key in (QtCore.Qt.Key_Tab,): self.select_right() self._update_list() return True elif key in ( QtCore.Qt.Key_Down,): self.select_down() self._update_list() return True elif key in (QtCore.Qt.Key_Right,): self.select_right() self._update_list() return True elif key in ( QtCore.Qt.Key_Up,): self.select_up() self._update_list() return True elif key in ( QtCore.Qt.Key_Left,): self.select_left() self._update_list() return True elif key in ( QtCore.Qt.Key_Escape,): self.cancel_completion() return True else : self.cancel_completion() else: self.cancel_completion() elif etype == QtCore.QEvent.FocusOut: self.cancel_completion() return super(CompletionHtml, self).eventFilter(obj, event)
def eventFilter(self, obj, event): """ Reimplemented to handle keyboard input and to auto-hide when the text edit loses focus. """ if obj == self._text_edit: etype = event.type() if etype == QtCore.QEvent.KeyPress: key = event.key() if self._consecutive_tab == 0 and key in (QtCore.Qt.Key_Tab,): return False elif self._consecutive_tab == 1 and key in (QtCore.Qt.Key_Tab,): # ok , called twice, we grab focus, and show the cursor self._consecutive_tab = self._consecutive_tab+1 self._update_list() return True elif self._consecutive_tab == 2: if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter): self._complete_current() return True if key in (QtCore.Qt.Key_Tab,): self.select_right() self._update_list() return True elif key in ( QtCore.Qt.Key_Down,): self.select_down() self._update_list() return True elif key in (QtCore.Qt.Key_Right,): self.select_right() self._update_list() return True elif key in ( QtCore.Qt.Key_Up,): self.select_up() self._update_list() return True elif key in ( QtCore.Qt.Key_Left,): self.select_left() self._update_list() return True elif key in ( QtCore.Qt.Key_Escape,): self.cancel_completion() return True else : self.cancel_completion() else: self.cancel_completion() elif etype == QtCore.QEvent.FocusOut: self.cancel_completion() return super(CompletionHtml, self).eventFilter(obj, event)
[ "Reimplemented", "to", "handle", "keyboard", "input", "and", "to", "auto", "-", "hide", "when", "the", "text", "edit", "loses", "focus", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L148-L198
[ "def", "eventFilter", "(", "self", ",", "obj", ",", "event", ")", ":", "if", "obj", "==", "self", ".", "_text_edit", ":", "etype", "=", "event", ".", "type", "(", ")", "if", "etype", "==", "QtCore", ".", "QEvent", ".", "KeyPress", ":", "key", "=", "event", ".", "key", "(", ")", "if", "self", ".", "_consecutive_tab", "==", "0", "and", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Tab", ",", ")", ":", "return", "False", "elif", "self", ".", "_consecutive_tab", "==", "1", "and", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Tab", ",", ")", ":", "# ok , called twice, we grab focus, and show the cursor", "self", ".", "_consecutive_tab", "=", "self", ".", "_consecutive_tab", "+", "1", "self", ".", "_update_list", "(", ")", "return", "True", "elif", "self", ".", "_consecutive_tab", "==", "2", ":", "if", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Return", ",", "QtCore", ".", "Qt", ".", "Key_Enter", ")", ":", "self", ".", "_complete_current", "(", ")", "return", "True", "if", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Tab", ",", ")", ":", "self", ".", "select_right", "(", ")", "self", ".", "_update_list", "(", ")", "return", "True", "elif", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Down", ",", ")", ":", "self", ".", "select_down", "(", ")", "self", ".", "_update_list", "(", ")", "return", "True", "elif", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Right", ",", ")", ":", "self", ".", "select_right", "(", ")", "self", ".", "_update_list", "(", ")", "return", "True", "elif", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Up", ",", ")", ":", "self", ".", "select_up", "(", ")", "self", ".", "_update_list", "(", ")", "return", "True", "elif", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Left", ",", ")", ":", "self", ".", "select_left", "(", ")", "self", ".", "_update_list", "(", ")", "return", "True", "elif", "key", "in", "(", "QtCore", ".", "Qt", ".", "Key_Escape", ",", ")", ":", "self", ".", "cancel_completion", "(", ")", "return", "True", "else", ":", "self", ".", "cancel_completion", "(", ")", "else", ":", "self", ".", "cancel_completion", "(", ")", "elif", "etype", "==", "QtCore", ".", "QEvent", ".", "FocusOut", ":", "self", ".", "cancel_completion", "(", ")", "return", "super", "(", "CompletionHtml", ",", "self", ")", ".", "eventFilter", "(", "obj", ",", "event", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml.cancel_completion
Cancel the completion should be called when the completer have to be dismissed This reset internal variable, clearing the temporary buffer of the console where the completion are shown.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def cancel_completion(self): """Cancel the completion should be called when the completer have to be dismissed This reset internal variable, clearing the temporary buffer of the console where the completion are shown. """ self._consecutive_tab = 0 self._slice_start = 0 self._console_widget._clear_temporary_buffer() self._index = (0, 0) if(self._sliding_interval): self._sliding_interval = None
def cancel_completion(self): """Cancel the completion should be called when the completer have to be dismissed This reset internal variable, clearing the temporary buffer of the console where the completion are shown. """ self._consecutive_tab = 0 self._slice_start = 0 self._console_widget._clear_temporary_buffer() self._index = (0, 0) if(self._sliding_interval): self._sliding_interval = None
[ "Cancel", "the", "completion" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L203-L216
[ "def", "cancel_completion", "(", "self", ")", ":", "self", ".", "_consecutive_tab", "=", "0", "self", ".", "_slice_start", "=", "0", "self", ".", "_console_widget", ".", "_clear_temporary_buffer", "(", ")", "self", ".", "_index", "=", "(", "0", ",", "0", ")", "if", "(", "self", ".", "_sliding_interval", ")", ":", "self", ".", "_sliding_interval", "=", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml._select_index
Change the selection index, and make sure it stays in the right range A little more complicated than just dooing modulo the number of row columns to be sure to cycle through all element. horizontaly, the element are maped like this : to r <-- a b c d e f --> to g to f <-- g h i j k l --> to m to l <-- m n o p q r --> to a and vertically a d g j m p b e h k n q c f i l o r
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def _select_index(self, row, col): """Change the selection index, and make sure it stays in the right range A little more complicated than just dooing modulo the number of row columns to be sure to cycle through all element. horizontaly, the element are maped like this : to r <-- a b c d e f --> to g to f <-- g h i j k l --> to m to l <-- m n o p q r --> to a and vertically a d g j m p b e h k n q c f i l o r """ nr, nc = self._size nr = nr-1 nc = nc-1 # case 1 if (row > nr and col >= nc) or (row >= nr and col > nc): self._select_index(0, 0) # case 2 elif (row <= 0 and col < 0) or (row < 0 and col <= 0): self._select_index(nr, nc) # case 3 elif row > nr : self._select_index(0, col+1) # case 4 elif row < 0 : self._select_index(nr, col-1) # case 5 elif col > nc : self._select_index(row+1, 0) # case 6 elif col < 0 : self._select_index(row-1, nc) elif 0 <= row and row <= nr and 0 <= col and col <= nc : self._index = (row, col) else : raise NotImplementedError("you'r trying to go where no completion\ have gone before : %d:%d (%d:%d)"%(row, col, nr, nc) )
def _select_index(self, row, col): """Change the selection index, and make sure it stays in the right range A little more complicated than just dooing modulo the number of row columns to be sure to cycle through all element. horizontaly, the element are maped like this : to r <-- a b c d e f --> to g to f <-- g h i j k l --> to m to l <-- m n o p q r --> to a and vertically a d g j m p b e h k n q c f i l o r """ nr, nc = self._size nr = nr-1 nc = nc-1 # case 1 if (row > nr and col >= nc) or (row >= nr and col > nc): self._select_index(0, 0) # case 2 elif (row <= 0 and col < 0) or (row < 0 and col <= 0): self._select_index(nr, nc) # case 3 elif row > nr : self._select_index(0, col+1) # case 4 elif row < 0 : self._select_index(nr, col-1) # case 5 elif col > nc : self._select_index(row+1, 0) # case 6 elif col < 0 : self._select_index(row-1, nc) elif 0 <= row and row <= nr and 0 <= col and col <= nc : self._index = (row, col) else : raise NotImplementedError("you'r trying to go where no completion\ have gone before : %d:%d (%d:%d)"%(row, col, nr, nc) )
[ "Change", "the", "selection", "index", "and", "make", "sure", "it", "stays", "in", "the", "right", "range" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L229-L272
[ "def", "_select_index", "(", "self", ",", "row", ",", "col", ")", ":", "nr", ",", "nc", "=", "self", ".", "_size", "nr", "=", "nr", "-", "1", "nc", "=", "nc", "-", "1", "# case 1", "if", "(", "row", ">", "nr", "and", "col", ">=", "nc", ")", "or", "(", "row", ">=", "nr", "and", "col", ">", "nc", ")", ":", "self", ".", "_select_index", "(", "0", ",", "0", ")", "# case 2", "elif", "(", "row", "<=", "0", "and", "col", "<", "0", ")", "or", "(", "row", "<", "0", "and", "col", "<=", "0", ")", ":", "self", ".", "_select_index", "(", "nr", ",", "nc", ")", "# case 3", "elif", "row", ">", "nr", ":", "self", ".", "_select_index", "(", "0", ",", "col", "+", "1", ")", "# case 4", "elif", "row", "<", "0", ":", "self", ".", "_select_index", "(", "nr", ",", "col", "-", "1", ")", "# case 5", "elif", "col", ">", "nc", ":", "self", ".", "_select_index", "(", "row", "+", "1", ",", "0", ")", "# case 6", "elif", "col", "<", "0", ":", "self", ".", "_select_index", "(", "row", "-", "1", ",", "nc", ")", "elif", "0", "<=", "row", "and", "row", "<=", "nr", "and", "0", "<=", "col", "and", "col", "<=", "nc", ":", "self", ".", "_index", "=", "(", "row", ",", "col", ")", "else", ":", "raise", "NotImplementedError", "(", "\"you'r trying to go where no completion\\\n have gone before : %d:%d (%d:%d)\"", "%", "(", "row", ",", "col", ",", "nr", ",", "nc", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml.select_up
move cursor up
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def select_up(self): """move cursor up""" r, c = self._index self._select_index(r-1, c)
def select_up(self): """move cursor up""" r, c = self._index self._select_index(r-1, c)
[ "move", "cursor", "up" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L282-L285
[ "def", "select_up", "(", "self", ")", ":", "r", ",", "c", "=", "self", ".", "_index", "self", ".", "_select_index", "(", "r", "-", "1", ",", "c", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml.select_down
move cursor down
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def select_down(self): """move cursor down""" r, c = self._index self._select_index(r+1, c)
def select_down(self): """move cursor down""" r, c = self._index self._select_index(r+1, c)
[ "move", "cursor", "down" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L287-L290
[ "def", "select_down", "(", "self", ")", ":", "r", ",", "c", "=", "self", ".", "_index", "self", ".", "_select_index", "(", "r", "+", "1", ",", "c", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml.select_left
move cursor left
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def select_left(self): """move cursor left""" r, c = self._index self._select_index(r, c-1)
def select_left(self): """move cursor left""" r, c = self._index self._select_index(r, c-1)
[ "move", "cursor", "left" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L292-L295
[ "def", "select_left", "(", "self", ")", ":", "r", ",", "c", "=", "self", ".", "_index", "self", ".", "_select_index", "(", "r", ",", "c", "-", "1", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml.select_right
move cursor right
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def select_right(self): """move cursor right""" r, c = self._index self._select_index(r, c+1)
def select_right(self): """move cursor right""" r, c = self._index self._select_index(r, c+1)
[ "move", "cursor", "right" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L297-L300
[ "def", "select_right", "(", "self", ")", ":", "r", ",", "c", "=", "self", ".", "_index", "self", ".", "_select_index", "(", "r", ",", "c", "+", "1", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml.show_items
Shows the completion widget with 'items' at the position specified by 'cursor'.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ if not items : return self._start_position = cursor.position() self._consecutive_tab = 1 items_m, ci = text.compute_item_matrix(items, empty=' ') self._sliding_interval = SlidingInterval(len(items_m)-1) self._items = items_m self._size = (ci['rows_numbers'], ci['columns_numbers']) self._old_cursor = cursor self._index = (0, 0) sjoin = lambda x : [ y.ljust(w, ' ') for y, w in zip(x, ci['columns_width'])] self._justified_items = map(sjoin, items_m) self._update_list(hilight=False)
def show_items(self, cursor, items): """ Shows the completion widget with 'items' at the position specified by 'cursor'. """ if not items : return self._start_position = cursor.position() self._consecutive_tab = 1 items_m, ci = text.compute_item_matrix(items, empty=' ') self._sliding_interval = SlidingInterval(len(items_m)-1) self._items = items_m self._size = (ci['rows_numbers'], ci['columns_numbers']) self._old_cursor = cursor self._index = (0, 0) sjoin = lambda x : [ y.ljust(w, ' ') for y, w in zip(x, ci['columns_width'])] self._justified_items = map(sjoin, items_m) self._update_list(hilight=False)
[ "Shows", "the", "completion", "widget", "with", "items", "at", "the", "position", "specified", "by", "cursor", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L302-L319
[ "def", "show_items", "(", "self", ",", "cursor", ",", "items", ")", ":", "if", "not", "items", ":", "return", "self", ".", "_start_position", "=", "cursor", ".", "position", "(", ")", "self", ".", "_consecutive_tab", "=", "1", "items_m", ",", "ci", "=", "text", ".", "compute_item_matrix", "(", "items", ",", "empty", "=", "' '", ")", "self", ".", "_sliding_interval", "=", "SlidingInterval", "(", "len", "(", "items_m", ")", "-", "1", ")", "self", ".", "_items", "=", "items_m", "self", ".", "_size", "=", "(", "ci", "[", "'rows_numbers'", "]", ",", "ci", "[", "'columns_numbers'", "]", ")", "self", ".", "_old_cursor", "=", "cursor", "self", ".", "_index", "=", "(", "0", ",", "0", ")", "sjoin", "=", "lambda", "x", ":", "[", "y", ".", "ljust", "(", "w", ",", "' '", ")", "for", "y", ",", "w", "in", "zip", "(", "x", ",", "ci", "[", "'columns_width'", "]", ")", "]", "self", ".", "_justified_items", "=", "map", "(", "sjoin", ",", "items_m", ")", "self", ".", "_update_list", "(", "hilight", "=", "False", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml._update_list
update the list of completion and hilight the currently selected completion
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def _update_list(self, hilight=True): """ update the list of completion and hilight the currently selected completion """ self._sliding_interval.current = self._index[0] head = None foot = None if self._sliding_interval.start > 0 : head = '...' if self._sliding_interval.stop < self._sliding_interval._max: foot = '...' items_m = self._justified_items[\ self._sliding_interval.start:\ self._sliding_interval.stop+1\ ] self._console_widget._clear_temporary_buffer() if(hilight): sel = (self._sliding_interval.nth, self._index[1]) else : sel = None strng = html_tableify(items_m, select=sel, header=head, footer=foot) self._console_widget._fill_temporary_buffer(self._old_cursor, strng, html=True)
def _update_list(self, hilight=True): """ update the list of completion and hilight the currently selected completion """ self._sliding_interval.current = self._index[0] head = None foot = None if self._sliding_interval.start > 0 : head = '...' if self._sliding_interval.stop < self._sliding_interval._max: foot = '...' items_m = self._justified_items[\ self._sliding_interval.start:\ self._sliding_interval.stop+1\ ] self._console_widget._clear_temporary_buffer() if(hilight): sel = (self._sliding_interval.nth, self._index[1]) else : sel = None strng = html_tableify(items_m, select=sel, header=head, footer=foot) self._console_widget._fill_temporary_buffer(self._old_cursor, strng, html=True)
[ "update", "the", "list", "of", "completion", "and", "hilight", "the", "currently", "selected", "completion" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L324-L346
[ "def", "_update_list", "(", "self", ",", "hilight", "=", "True", ")", ":", "self", ".", "_sliding_interval", ".", "current", "=", "self", ".", "_index", "[", "0", "]", "head", "=", "None", "foot", "=", "None", "if", "self", ".", "_sliding_interval", ".", "start", ">", "0", ":", "head", "=", "'...'", "if", "self", ".", "_sliding_interval", ".", "stop", "<", "self", ".", "_sliding_interval", ".", "_max", ":", "foot", "=", "'...'", "items_m", "=", "self", ".", "_justified_items", "[", "self", ".", "_sliding_interval", ".", "start", ":", "self", ".", "_sliding_interval", ".", "stop", "+", "1", "]", "self", ".", "_console_widget", ".", "_clear_temporary_buffer", "(", ")", "if", "(", "hilight", ")", ":", "sel", "=", "(", "self", ".", "_sliding_interval", ".", "nth", ",", "self", ".", "_index", "[", "1", "]", ")", "else", ":", "sel", "=", "None", "strng", "=", "html_tableify", "(", "items_m", ",", "select", "=", "sel", ",", "header", "=", "head", ",", "footer", "=", "foot", ")", "self", ".", "_console_widget", ".", "_fill_temporary_buffer", "(", "self", ".", "_old_cursor", ",", "strng", ",", "html", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionHtml._complete_current
Perform the completion with the currently selected item.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py
def _complete_current(self): """ Perform the completion with the currently selected item. """ i = self._index item = self._items[i[0]][i[1]] item = item.strip() if item : self._current_text_cursor().insertText(item) self.cancel_completion()
def _complete_current(self): """ Perform the completion with the currently selected item. """ i = self._index item = self._items[i[0]][i[1]] item = item.strip() if item : self._current_text_cursor().insertText(item) self.cancel_completion()
[ "Perform", "the", "completion", "with", "the", "currently", "selected", "item", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/completion_html.py#L352-L360
[ "def", "_complete_current", "(", "self", ")", ":", "i", "=", "self", ".", "_index", "item", "=", "self", ".", "_items", "[", "i", "[", "0", "]", "]", "[", "i", "[", "1", "]", "]", "item", "=", "item", ".", "strip", "(", ")", "if", "item", ":", "self", ".", "_current_text_cursor", "(", ")", ".", "insertText", "(", "item", ")", "self", ".", "cancel_completion", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
wordfreq
Return a dictionary of words and word counts in a string.
environment/share/doc/ipython/examples/parallel/davinci/wordfreq.py
def wordfreq(text, is_filename=False): """Return a dictionary of words and word counts in a string.""" if is_filename: with open(text) as f: text = f.read() freqs = {} for word in text.split(): lword = word.lower() freqs[lword] = freqs.get(lword, 0) + 1 return freqs
def wordfreq(text, is_filename=False): """Return a dictionary of words and word counts in a string.""" if is_filename: with open(text) as f: text = f.read() freqs = {} for word in text.split(): lword = word.lower() freqs[lword] = freqs.get(lword, 0) + 1 return freqs
[ "Return", "a", "dictionary", "of", "words", "and", "word", "counts", "in", "a", "string", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/davinci/wordfreq.py#L9-L18
[ "def", "wordfreq", "(", "text", ",", "is_filename", "=", "False", ")", ":", "if", "is_filename", ":", "with", "open", "(", "text", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", ")", "freqs", "=", "{", "}", "for", "word", "in", "text", ".", "split", "(", ")", ":", "lword", "=", "word", ".", "lower", "(", ")", "freqs", "[", "lword", "]", "=", "freqs", ".", "get", "(", "lword", ",", "0", ")", "+", "1", "return", "freqs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
print_wordfreq
Print the n most common words and counts in the freqs dict.
environment/share/doc/ipython/examples/parallel/davinci/wordfreq.py
def print_wordfreq(freqs, n=10): """Print the n most common words and counts in the freqs dict.""" words, counts = freqs.keys(), freqs.values() items = zip(counts, words) items.sort(reverse=True) for (count, word) in items[:n]: print(word, count)
def print_wordfreq(freqs, n=10): """Print the n most common words and counts in the freqs dict.""" words, counts = freqs.keys(), freqs.values() items = zip(counts, words) items.sort(reverse=True) for (count, word) in items[:n]: print(word, count)
[ "Print", "the", "n", "most", "common", "words", "and", "counts", "in", "the", "freqs", "dict", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/parallel/davinci/wordfreq.py#L21-L28
[ "def", "print_wordfreq", "(", "freqs", ",", "n", "=", "10", ")", ":", "words", ",", "counts", "=", "freqs", ".", "keys", "(", ")", ",", "freqs", ".", "values", "(", ")", "items", "=", "zip", "(", "counts", ",", "words", ")", "items", ".", "sort", "(", "reverse", "=", "True", ")", "for", "(", "count", ",", "word", ")", "in", "items", "[", ":", "n", "]", ":", "print", "(", "word", ",", "count", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
WinHPCJob.tostring
Return the string representation of the job description XML.
environment/lib/python2.7/site-packages/IPython/parallel/apps/winhpcjob.py
def tostring(self): """Return the string representation of the job description XML.""" root = self.as_element() indent(root) txt = ET.tostring(root, encoding="utf-8") # Now remove the tokens used to order the attributes. txt = re.sub(r'_[A-Z]_','',txt) txt = '<?xml version="1.0" encoding="utf-8"?>\n' + txt return txt
def tostring(self): """Return the string representation of the job description XML.""" root = self.as_element() indent(root) txt = ET.tostring(root, encoding="utf-8") # Now remove the tokens used to order the attributes. txt = re.sub(r'_[A-Z]_','',txt) txt = '<?xml version="1.0" encoding="utf-8"?>\n' + txt return txt
[ "Return", "the", "string", "representation", "of", "the", "job", "description", "XML", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/winhpcjob.py#L144-L152
[ "def", "tostring", "(", "self", ")", ":", "root", "=", "self", ".", "as_element", "(", ")", "indent", "(", "root", ")", "txt", "=", "ET", ".", "tostring", "(", "root", ",", "encoding", "=", "\"utf-8\"", ")", "# Now remove the tokens used to order the attributes.", "txt", "=", "re", ".", "sub", "(", "r'_[A-Z]_'", ",", "''", ",", "txt", ")", "txt", "=", "'<?xml version=\"1.0\" encoding=\"utf-8\"?>\\n'", "+", "txt", "return", "txt" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
WinHPCJob.write
Write the XML job description to a file.
environment/lib/python2.7/site-packages/IPython/parallel/apps/winhpcjob.py
def write(self, filename): """Write the XML job description to a file.""" txt = self.tostring() with open(filename, 'w') as f: f.write(txt)
def write(self, filename): """Write the XML job description to a file.""" txt = self.tostring() with open(filename, 'w') as f: f.write(txt)
[ "Write", "the", "XML", "job", "description", "to", "a", "file", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/winhpcjob.py#L154-L158
[ "def", "write", "(", "self", ",", "filename", ")", ":", "txt", "=", "self", ".", "tostring", "(", ")", "with", "open", "(", "filename", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "txt", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
validate_pin
Validate the given pin against the schema. :param dict pin: The pin to validate: :raises pypebbleapi.schemas.DocumentError: If the pin is not valid.
pypebbleapi/timeline.py
def validate_pin(pin): """ Validate the given pin against the schema. :param dict pin: The pin to validate: :raises pypebbleapi.schemas.DocumentError: If the pin is not valid. """ v = _Validator(schemas.pin) if v.validate(pin): return else: raise schemas.DocumentError(errors=v.errors)
def validate_pin(pin): """ Validate the given pin against the schema. :param dict pin: The pin to validate: :raises pypebbleapi.schemas.DocumentError: If the pin is not valid. """ v = _Validator(schemas.pin) if v.validate(pin): return else: raise schemas.DocumentError(errors=v.errors)
[ "Validate", "the", "given", "pin", "against", "the", "schema", "." ]
youtux/pypebbleapi
python
https://github.com/youtux/pypebbleapi/blob/fe7b49da9c30e4a359cc6245a416862ccb3aa589/pypebbleapi/timeline.py#L57-L67
[ "def", "validate_pin", "(", "pin", ")", ":", "v", "=", "_Validator", "(", "schemas", ".", "pin", ")", "if", "v", ".", "validate", "(", "pin", ")", ":", "return", "else", ":", "raise", "schemas", ".", "DocumentError", "(", "errors", "=", "v", ".", "errors", ")" ]
fe7b49da9c30e4a359cc6245a416862ccb3aa589
test
Timeline.send_shared_pin
Send a shared pin for the given topics. :param list topics: The list of topics. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the validation process failed. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred.
pypebbleapi/timeline.py
def send_shared_pin(self, topics, pin, skip_validation=False): """ Send a shared pin for the given topics. :param list topics: The list of topics. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the validation process failed. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not self.api_key: raise ValueError("You need to specify an api_key.") if not skip_validation: validate_pin(pin) response = _request('PUT', url=self.url_v1('/shared/pins/' + pin['id']), user_agent=self.user_agent, api_key=self.api_key, topics_list=topics, json=pin, ) _raise_for_status(response)
def send_shared_pin(self, topics, pin, skip_validation=False): """ Send a shared pin for the given topics. :param list topics: The list of topics. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the validation process failed. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not self.api_key: raise ValueError("You need to specify an api_key.") if not skip_validation: validate_pin(pin) response = _request('PUT', url=self.url_v1('/shared/pins/' + pin['id']), user_agent=self.user_agent, api_key=self.api_key, topics_list=topics, json=pin, ) _raise_for_status(response)
[ "Send", "a", "shared", "pin", "for", "the", "given", "topics", "." ]
youtux/pypebbleapi
python
https://github.com/youtux/pypebbleapi/blob/fe7b49da9c30e4a359cc6245a416862ccb3aa589/pypebbleapi/timeline.py#L95-L117
[ "def", "send_shared_pin", "(", "self", ",", "topics", ",", "pin", ",", "skip_validation", "=", "False", ")", ":", "if", "not", "self", ".", "api_key", ":", "raise", "ValueError", "(", "\"You need to specify an api_key.\"", ")", "if", "not", "skip_validation", ":", "validate_pin", "(", "pin", ")", "response", "=", "_request", "(", "'PUT'", ",", "url", "=", "self", ".", "url_v1", "(", "'/shared/pins/'", "+", "pin", "[", "'id'", "]", ")", ",", "user_agent", "=", "self", ".", "user_agent", ",", "api_key", "=", "self", ".", "api_key", ",", "topics_list", "=", "topics", ",", "json", "=", "pin", ",", ")", "_raise_for_status", "(", "response", ")" ]
fe7b49da9c30e4a359cc6245a416862ccb3aa589
test
Timeline.delete_shared_pin
Delete a shared pin. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred.
pypebbleapi/timeline.py
def delete_shared_pin(self, pin_id): """ Delete a shared pin. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not self.api_key: raise ValueError("You need to specify an api_key.") response = _request('DELETE', url=self.url_v1('/shared/pins/' + pin_id), user_agent=self.user_agent, api_key=self.api_key, ) _raise_for_status(response)
def delete_shared_pin(self, pin_id): """ Delete a shared pin. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not self.api_key: raise ValueError("You need to specify an api_key.") response = _request('DELETE', url=self.url_v1('/shared/pins/' + pin_id), user_agent=self.user_agent, api_key=self.api_key, ) _raise_for_status(response)
[ "Delete", "a", "shared", "pin", "." ]
youtux/pypebbleapi
python
https://github.com/youtux/pypebbleapi/blob/fe7b49da9c30e4a359cc6245a416862ccb3aa589/pypebbleapi/timeline.py#L119-L134
[ "def", "delete_shared_pin", "(", "self", ",", "pin_id", ")", ":", "if", "not", "self", ".", "api_key", ":", "raise", "ValueError", "(", "\"You need to specify an api_key.\"", ")", "response", "=", "_request", "(", "'DELETE'", ",", "url", "=", "self", ".", "url_v1", "(", "'/shared/pins/'", "+", "pin_id", ")", ",", "user_agent", "=", "self", ".", "user_agent", ",", "api_key", "=", "self", ".", "api_key", ",", ")", "_raise_for_status", "(", "response", ")" ]
fe7b49da9c30e4a359cc6245a416862ccb3aa589
test
Timeline.send_user_pin
Send a user pin. :param str user_token: The token of the user. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the validation process failed. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred.
pypebbleapi/timeline.py
def send_user_pin(self, user_token, pin, skip_validation=False): """ Send a user pin. :param str user_token: The token of the user. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the validation process failed. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not skip_validation: validate_pin(pin) response = _request('PUT', url=self.url_v1('/user/pins/' + pin['id']), user_agent=self.user_agent, user_token=user_token, json=pin, ) _raise_for_status(response)
def send_user_pin(self, user_token, pin, skip_validation=False): """ Send a user pin. :param str user_token: The token of the user. :param dict pin: The pin. :param bool skip_validation: Whether to skip the validation. :raises pypebbleapi.schemas.DocumentError: If the validation process failed. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ if not skip_validation: validate_pin(pin) response = _request('PUT', url=self.url_v1('/user/pins/' + pin['id']), user_agent=self.user_agent, user_token=user_token, json=pin, ) _raise_for_status(response)
[ "Send", "a", "user", "pin", "." ]
youtux/pypebbleapi
python
https://github.com/youtux/pypebbleapi/blob/fe7b49da9c30e4a359cc6245a416862ccb3aa589/pypebbleapi/timeline.py#L136-L155
[ "def", "send_user_pin", "(", "self", ",", "user_token", ",", "pin", ",", "skip_validation", "=", "False", ")", ":", "if", "not", "skip_validation", ":", "validate_pin", "(", "pin", ")", "response", "=", "_request", "(", "'PUT'", ",", "url", "=", "self", ".", "url_v1", "(", "'/user/pins/'", "+", "pin", "[", "'id'", "]", ")", ",", "user_agent", "=", "self", ".", "user_agent", ",", "user_token", "=", "user_token", ",", "json", "=", "pin", ",", ")", "_raise_for_status", "(", "response", ")" ]
fe7b49da9c30e4a359cc6245a416862ccb3aa589
test
Timeline.delete_user_pin
Delete a user pin. :param str user_token: The token of the user. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred.
pypebbleapi/timeline.py
def delete_user_pin(self, user_token, pin_id): """ Delete a user pin. :param str user_token: The token of the user. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('DELETE', url=self.url_v1('/user/pins/' + pin_id), user_agent=self.user_agent, user_token=user_token, ) _raise_for_status(response)
def delete_user_pin(self, user_token, pin_id): """ Delete a user pin. :param str user_token: The token of the user. :param str pin_id: The id of the pin to delete. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('DELETE', url=self.url_v1('/user/pins/' + pin_id), user_agent=self.user_agent, user_token=user_token, ) _raise_for_status(response)
[ "Delete", "a", "user", "pin", "." ]
youtux/pypebbleapi
python
https://github.com/youtux/pypebbleapi/blob/fe7b49da9c30e4a359cc6245a416862ccb3aa589/pypebbleapi/timeline.py#L157-L171
[ "def", "delete_user_pin", "(", "self", ",", "user_token", ",", "pin_id", ")", ":", "response", "=", "_request", "(", "'DELETE'", ",", "url", "=", "self", ".", "url_v1", "(", "'/user/pins/'", "+", "pin_id", ")", ",", "user_agent", "=", "self", ".", "user_agent", ",", "user_token", "=", "user_token", ",", ")", "_raise_for_status", "(", "response", ")" ]
fe7b49da9c30e4a359cc6245a416862ccb3aa589
test
Timeline.subscribe
Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred.
pypebbleapi/timeline.py
def subscribe(self, user_token, topic): """ Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('POST', url=self.url_v1('/user/subscriptions/' + topic), user_agent=self.user_agent, user_token=user_token, ) _raise_for_status(response)
def subscribe(self, user_token, topic): """ Subscribe a user to the given topic. :param str user_token: The token of the user. :param str topic: The topic. :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('POST', url=self.url_v1('/user/subscriptions/' + topic), user_agent=self.user_agent, user_token=user_token, ) _raise_for_status(response)
[ "Subscribe", "a", "user", "to", "the", "given", "topic", "." ]
youtux/pypebbleapi
python
https://github.com/youtux/pypebbleapi/blob/fe7b49da9c30e4a359cc6245a416862ccb3aa589/pypebbleapi/timeline.py#L173-L186
[ "def", "subscribe", "(", "self", ",", "user_token", ",", "topic", ")", ":", "response", "=", "_request", "(", "'POST'", ",", "url", "=", "self", ".", "url_v1", "(", "'/user/subscriptions/'", "+", "topic", ")", ",", "user_agent", "=", "self", ".", "user_agent", ",", "user_token", "=", "user_token", ",", ")", "_raise_for_status", "(", "response", ")" ]
fe7b49da9c30e4a359cc6245a416862ccb3aa589
test
Timeline.list_subscriptions
Get the list of the topics which a user is subscribed to. :param str user_token: The token of the user. :return: The list of the topics. :rtype: list :raises `requests.exceptions.HTTPError`: If an HTTP error occurred.
pypebbleapi/timeline.py
def list_subscriptions(self, user_token): """ Get the list of the topics which a user is subscribed to. :param str user_token: The token of the user. :return: The list of the topics. :rtype: list :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('GET', url=self.url_v1('/user/subscriptions'), user_agent=self.user_agent, user_token=user_token, ) _raise_for_status(response) return response.json()['topics']
def list_subscriptions(self, user_token): """ Get the list of the topics which a user is subscribed to. :param str user_token: The token of the user. :return: The list of the topics. :rtype: list :raises `requests.exceptions.HTTPError`: If an HTTP error occurred. """ response = _request('GET', url=self.url_v1('/user/subscriptions'), user_agent=self.user_agent, user_token=user_token, ) _raise_for_status(response) return response.json()['topics']
[ "Get", "the", "list", "of", "the", "topics", "which", "a", "user", "is", "subscribed", "to", "." ]
youtux/pypebbleapi
python
https://github.com/youtux/pypebbleapi/blob/fe7b49da9c30e4a359cc6245a416862ccb3aa589/pypebbleapi/timeline.py#L203-L219
[ "def", "list_subscriptions", "(", "self", ",", "user_token", ")", ":", "response", "=", "_request", "(", "'GET'", ",", "url", "=", "self", ".", "url_v1", "(", "'/user/subscriptions'", ")", ",", "user_agent", "=", "self", ".", "user_agent", ",", "user_token", "=", "user_token", ",", ")", "_raise_for_status", "(", "response", ")", "return", "response", ".", "json", "(", ")", "[", "'topics'", "]" ]
fe7b49da9c30e4a359cc6245a416862ccb3aa589
test
monitored
Decorate a function to automatically begin and end a task on the progressmonitor. The function must have a parameter called 'monitor'
progressmonitor/__init__.py
def monitored(total: int, name=None, message=None): """ Decorate a function to automatically begin and end a task on the progressmonitor. The function must have a parameter called 'monitor' """ def decorator(f): nonlocal name monitor_index = list(inspect.signature(f).parameters.keys()).index('monitor') if name is None: name=f.__name__ @wraps(f) def wrapper(*args, **kargs): if len(args) > monitor_index: monitor = args[monitor_index] elif 'monitor' in kargs: monitor = kargs['monitor'] else: monitor = kargs['monitor'] = NullMonitor() with monitor.task(total, name, message): f(*args, **kargs) return wrapper return decorator
def monitored(total: int, name=None, message=None): """ Decorate a function to automatically begin and end a task on the progressmonitor. The function must have a parameter called 'monitor' """ def decorator(f): nonlocal name monitor_index = list(inspect.signature(f).parameters.keys()).index('monitor') if name is None: name=f.__name__ @wraps(f) def wrapper(*args, **kargs): if len(args) > monitor_index: monitor = args[monitor_index] elif 'monitor' in kargs: monitor = kargs['monitor'] else: monitor = kargs['monitor'] = NullMonitor() with monitor.task(total, name, message): f(*args, **kargs) return wrapper return decorator
[ "Decorate", "a", "function", "to", "automatically", "begin", "and", "end", "a", "task", "on", "the", "progressmonitor", ".", "The", "function", "must", "have", "a", "parameter", "called", "monitor" ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/__init__.py#L10-L31
[ "def", "monitored", "(", "total", ":", "int", ",", "name", "=", "None", ",", "message", "=", "None", ")", ":", "def", "decorator", "(", "f", ")", ":", "nonlocal", "name", "monitor_index", "=", "list", "(", "inspect", ".", "signature", "(", "f", ")", ".", "parameters", ".", "keys", "(", ")", ")", ".", "index", "(", "'monitor'", ")", "if", "name", "is", "None", ":", "name", "=", "f", ".", "__name__", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kargs", ")", ":", "if", "len", "(", "args", ")", ">", "monitor_index", ":", "monitor", "=", "args", "[", "monitor_index", "]", "elif", "'monitor'", "in", "kargs", ":", "monitor", "=", "kargs", "[", "'monitor'", "]", "else", ":", "monitor", "=", "kargs", "[", "'monitor'", "]", "=", "NullMonitor", "(", ")", "with", "monitor", ".", "task", "(", "total", ",", "name", ",", "message", ")", ":", "f", "(", "*", "args", ",", "*", "*", "kargs", ")", "return", "wrapper", "return", "decorator" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
ProgressMonitor.begin
Call before starting work on a monitor, specifying name and amount of work
progressmonitor/__init__.py
def begin(self, total: int, name=None, message=None): """Call before starting work on a monitor, specifying name and amount of work""" self.total = total message = message or name or "Working..." self.name = name or "ProgressMonitor" self.update(0, message)
def begin(self, total: int, name=None, message=None): """Call before starting work on a monitor, specifying name and amount of work""" self.total = total message = message or name or "Working..." self.name = name or "ProgressMonitor" self.update(0, message)
[ "Call", "before", "starting", "work", "on", "a", "monitor", "specifying", "name", "and", "amount", "of", "work" ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/__init__.py#L72-L77
[ "def", "begin", "(", "self", ",", "total", ":", "int", ",", "name", "=", "None", ",", "message", "=", "None", ")", ":", "self", ".", "total", "=", "total", "message", "=", "message", "or", "name", "or", "\"Working...\"", "self", ".", "name", "=", "name", "or", "\"ProgressMonitor\"", "self", ".", "update", "(", "0", ",", "message", ")" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
ProgressMonitor.task
Wrap code into a begin and end call on this monitor
progressmonitor/__init__.py
def task(self, total: int, name=None, message=None): """Wrap code into a begin and end call on this monitor""" self.begin(total, name, message) try: yield self finally: self.done()
def task(self, total: int, name=None, message=None): """Wrap code into a begin and end call on this monitor""" self.begin(total, name, message) try: yield self finally: self.done()
[ "Wrap", "code", "into", "a", "begin", "and", "end", "call", "on", "this", "monitor" ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/__init__.py#L80-L86
[ "def", "task", "(", "self", ",", "total", ":", "int", ",", "name", "=", "None", ",", "message", "=", "None", ")", ":", "self", ".", "begin", "(", "total", ",", "name", ",", "message", ")", "try", ":", "yield", "self", "finally", ":", "self", ".", "done", "(", ")" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
ProgressMonitor.subtask
Create a submonitor with the given units
progressmonitor/__init__.py
def subtask(self, units: int): """Create a submonitor with the given units""" sm = self.submonitor(units) try: yield sm finally: if sm.total is None: # begin was never called, so the subtask cannot be closed self.update(units) else: sm.done()
def subtask(self, units: int): """Create a submonitor with the given units""" sm = self.submonitor(units) try: yield sm finally: if sm.total is None: # begin was never called, so the subtask cannot be closed self.update(units) else: sm.done()
[ "Create", "a", "submonitor", "with", "the", "given", "units" ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/__init__.py#L89-L99
[ "def", "subtask", "(", "self", ",", "units", ":", "int", ")", ":", "sm", "=", "self", ".", "submonitor", "(", "units", ")", "try", ":", "yield", "sm", "finally", ":", "if", "sm", ".", "total", "is", "None", ":", "# begin was never called, so the subtask cannot be closed", "self", ".", "update", "(", "units", ")", "else", ":", "sm", ".", "done", "(", ")" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
ProgressMonitor.progress
What percentage (range 0-1) of work is done (including submonitors)
progressmonitor/__init__.py
def progress(self)-> float: """What percentage (range 0-1) of work is done (including submonitors)""" if self.total is None: return 0 my_progress = self.worked my_progress += sum(s.progress * weight for (s, weight) in self.sub_monitors.items()) return min(1, my_progress / self.total)
def progress(self)-> float: """What percentage (range 0-1) of work is done (including submonitors)""" if self.total is None: return 0 my_progress = self.worked my_progress += sum(s.progress * weight for (s, weight) in self.sub_monitors.items()) return min(1, my_progress / self.total)
[ "What", "percentage", "(", "range", "0", "-", "1", ")", "of", "work", "is", "done", "(", "including", "submonitors", ")" ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/__init__.py#L102-L109
[ "def", "progress", "(", "self", ")", "->", "float", ":", "if", "self", ".", "total", "is", "None", ":", "return", "0", "my_progress", "=", "self", ".", "worked", "my_progress", "+=", "sum", "(", "s", ".", "progress", "*", "weight", "for", "(", "s", ",", "weight", ")", "in", "self", ".", "sub_monitors", ".", "items", "(", ")", ")", "return", "min", "(", "1", ",", "my_progress", "/", "self", ".", "total", ")" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
ProgressMonitor.update
Increment the monitor with N units worked and an optional message
progressmonitor/__init__.py
def update(self, units: int=1, message: str=None): """Increment the monitor with N units worked and an optional message""" if self.total is None: raise Exception("Cannot call progressmonitor.update before calling begin") self.worked = min(self.total, self.worked+units) if message: self.message = message for listener in self.listeners: listener(self)
def update(self, units: int=1, message: str=None): """Increment the monitor with N units worked and an optional message""" if self.total is None: raise Exception("Cannot call progressmonitor.update before calling begin") self.worked = min(self.total, self.worked+units) if message: self.message = message for listener in self.listeners: listener(self)
[ "Increment", "the", "monitor", "with", "N", "units", "worked", "and", "an", "optional", "message" ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/__init__.py#L111-L119
[ "def", "update", "(", "self", ",", "units", ":", "int", "=", "1", ",", "message", ":", "str", "=", "None", ")", ":", "if", "self", ".", "total", "is", "None", ":", "raise", "Exception", "(", "\"Cannot call progressmonitor.update before calling begin\"", ")", "self", ".", "worked", "=", "min", "(", "self", ".", "total", ",", "self", ".", "worked", "+", "units", ")", "if", "message", ":", "self", ".", "message", "=", "message", "for", "listener", "in", "self", ".", "listeners", ":", "listener", "(", "self", ")" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
ProgressMonitor.submonitor
Create a sub monitor that stands for N units of work in this monitor The sub task should call .begin (or use @monitored / with .task) before calling updates
progressmonitor/__init__.py
def submonitor(self, units: int, *args, **kargs) -> 'ProgressMonitor': """ Create a sub monitor that stands for N units of work in this monitor The sub task should call .begin (or use @monitored / with .task) before calling updates """ submonitor = ProgressMonitor(*args, **kargs) self.sub_monitors[submonitor] = units submonitor.add_listener(self._submonitor_update) return submonitor
def submonitor(self, units: int, *args, **kargs) -> 'ProgressMonitor': """ Create a sub monitor that stands for N units of work in this monitor The sub task should call .begin (or use @monitored / with .task) before calling updates """ submonitor = ProgressMonitor(*args, **kargs) self.sub_monitors[submonitor] = units submonitor.add_listener(self._submonitor_update) return submonitor
[ "Create", "a", "sub", "monitor", "that", "stands", "for", "N", "units", "of", "work", "in", "this", "monitor", "The", "sub", "task", "should", "call", ".", "begin", "(", "or", "use" ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/__init__.py#L129-L137
[ "def", "submonitor", "(", "self", ",", "units", ":", "int", ",", "*", "args", ",", "*", "*", "kargs", ")", "->", "'ProgressMonitor'", ":", "submonitor", "=", "ProgressMonitor", "(", "*", "args", ",", "*", "*", "kargs", ")", "self", ".", "sub_monitors", "[", "submonitor", "]", "=", "units", "submonitor", ".", "add_listener", "(", "self", ".", "_submonitor_update", ")", "return", "submonitor" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
ProgressMonitor.done
Signal that this task is done. This is completely optional and will just call .update with the remaining work.
progressmonitor/__init__.py
def done(self, message: str=None): """ Signal that this task is done. This is completely optional and will just call .update with the remaining work. """ if message is None: message = "{self.name} done".format(**locals()) if self.name else "Done" self.update(units=self.total - self.worked, message=message)
def done(self, message: str=None): """ Signal that this task is done. This is completely optional and will just call .update with the remaining work. """ if message is None: message = "{self.name} done".format(**locals()) if self.name else "Done" self.update(units=self.total - self.worked, message=message)
[ "Signal", "that", "this", "task", "is", "done", ".", "This", "is", "completely", "optional", "and", "will", "just", "call", ".", "update", "with", "the", "remaining", "work", "." ]
amcat/progressmonitor
python
https://github.com/amcat/progressmonitor/blob/d4cabebc95bfd1447120f601c094b20bee954285/progressmonitor/__init__.py#L142-L149
[ "def", "done", "(", "self", ",", "message", ":", "str", "=", "None", ")", ":", "if", "message", "is", "None", ":", "message", "=", "\"{self.name} done\"", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "if", "self", ".", "name", "else", "\"Done\"", "self", ".", "update", "(", "units", "=", "self", ".", "total", "-", "self", ".", "worked", ",", "message", "=", "message", ")" ]
d4cabebc95bfd1447120f601c094b20bee954285
test
page
Print a string, piping through a pager. This version ignores the screen_lines and pager_cmd arguments and uses IPython's payload system instead. Parameters ---------- strng : str Text to page. start : int Starting line at which to place the display. html : str, optional If given, an html string to send as well. auto_html : bool, optional If true, the input string is assumed to be valid reStructuredText and is converted to HTML with docutils. Note that if docutils is not found, this option is silently ignored. Note ---- Only one of the ``html`` and ``auto_html`` options can be given, not both.
environment/lib/python2.7/site-packages/IPython/core/payloadpage.py
def page(strng, start=0, screen_lines=0, pager_cmd=None, html=None, auto_html=False): """Print a string, piping through a pager. This version ignores the screen_lines and pager_cmd arguments and uses IPython's payload system instead. Parameters ---------- strng : str Text to page. start : int Starting line at which to place the display. html : str, optional If given, an html string to send as well. auto_html : bool, optional If true, the input string is assumed to be valid reStructuredText and is converted to HTML with docutils. Note that if docutils is not found, this option is silently ignored. Note ---- Only one of the ``html`` and ``auto_html`` options can be given, not both. """ # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) shell = InteractiveShell.instance() if auto_html: try: # These defaults ensure user configuration variables for docutils # are not loaded, only our config is used here. defaults = {'file_insertion_enabled': 0, 'raw_enabled': 0, '_disable_config': 1} html = publish_string(strng, writer_name='html', settings_overrides=defaults) except: pass payload = dict( source='IPython.zmq.page.page', text=strng, html=html, start_line_number=start ) shell.payload_manager.write_payload(payload)
def page(strng, start=0, screen_lines=0, pager_cmd=None, html=None, auto_html=False): """Print a string, piping through a pager. This version ignores the screen_lines and pager_cmd arguments and uses IPython's payload system instead. Parameters ---------- strng : str Text to page. start : int Starting line at which to place the display. html : str, optional If given, an html string to send as well. auto_html : bool, optional If true, the input string is assumed to be valid reStructuredText and is converted to HTML with docutils. Note that if docutils is not found, this option is silently ignored. Note ---- Only one of the ``html`` and ``auto_html`` options can be given, not both. """ # Some routines may auto-compute start offsets incorrectly and pass a # negative value. Offset to 0 for robustness. start = max(0, start) shell = InteractiveShell.instance() if auto_html: try: # These defaults ensure user configuration variables for docutils # are not loaded, only our config is used here. defaults = {'file_insertion_enabled': 0, 'raw_enabled': 0, '_disable_config': 1} html = publish_string(strng, writer_name='html', settings_overrides=defaults) except: pass payload = dict( source='IPython.zmq.page.page', text=strng, html=html, start_line_number=start ) shell.payload_manager.write_payload(payload)
[ "Print", "a", "string", "piping", "through", "a", "pager", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/payloadpage.py#L37-L90
[ "def", "page", "(", "strng", ",", "start", "=", "0", ",", "screen_lines", "=", "0", ",", "pager_cmd", "=", "None", ",", "html", "=", "None", ",", "auto_html", "=", "False", ")", ":", "# Some routines may auto-compute start offsets incorrectly and pass a", "# negative value. Offset to 0 for robustness.", "start", "=", "max", "(", "0", ",", "start", ")", "shell", "=", "InteractiveShell", ".", "instance", "(", ")", "if", "auto_html", ":", "try", ":", "# These defaults ensure user configuration variables for docutils", "# are not loaded, only our config is used here.", "defaults", "=", "{", "'file_insertion_enabled'", ":", "0", ",", "'raw_enabled'", ":", "0", ",", "'_disable_config'", ":", "1", "}", "html", "=", "publish_string", "(", "strng", ",", "writer_name", "=", "'html'", ",", "settings_overrides", "=", "defaults", ")", "except", ":", "pass", "payload", "=", "dict", "(", "source", "=", "'IPython.zmq.page.page'", ",", "text", "=", "strng", ",", "html", "=", "html", ",", "start_line_number", "=", "start", ")", "shell", ".", "payload_manager", ".", "write_payload", "(", "payload", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InstallRequirement.from_line
Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL.
virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py
def from_line(cls, name, comes_from=None, isolated=False): """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. """ from pip.index import Link url = None if is_url(name): marker_sep = '; ' else: marker_sep = ';' if marker_sep in name: name, markers = name.split(marker_sep, 1) markers = markers.strip() if not markers: markers = None else: markers = None name = name.strip() req = None path = os.path.normpath(os.path.abspath(name)) link = None if is_url(name): link = Link(name) elif (os.path.isdir(path) and (os.path.sep in name or name.startswith('.'))): if not is_installable_dir(path): raise InstallationError( "Directory %r is not installable. File 'setup.py' not " "found." % name ) link = Link(path_to_url(name)) elif is_archive_file(path): if not os.path.isfile(path): logger.warning( 'Requirement %r looks like a filename, but the file does ' 'not exist', name ) link = Link(path_to_url(name)) # it's a local file, dir, or url if link: url = link.url # Handle relative file URLs if link.scheme == 'file' and re.search(r'\.\./', url): url = path_to_url(os.path.normpath(os.path.abspath(link.path))) # wheel file if link.ext == wheel_ext: wheel = Wheel(link.filename) # can raise InvalidWheelFilename if not wheel.supported(): raise UnsupportedWheel( "%s is not a supported wheel on this platform." % wheel.filename ) req = "%s==%s" % (wheel.name, wheel.version) else: # set the req to the egg fragment. when it's not there, this # will become an 'unnamed' requirement req = link.egg_fragment # a requirement specifier else: req = name return cls(req, comes_from, url=url, markers=markers, isolated=isolated)
def from_line(cls, name, comes_from=None, isolated=False): """Creates an InstallRequirement from a name, which might be a requirement, directory containing 'setup.py', filename, or URL. """ from pip.index import Link url = None if is_url(name): marker_sep = '; ' else: marker_sep = ';' if marker_sep in name: name, markers = name.split(marker_sep, 1) markers = markers.strip() if not markers: markers = None else: markers = None name = name.strip() req = None path = os.path.normpath(os.path.abspath(name)) link = None if is_url(name): link = Link(name) elif (os.path.isdir(path) and (os.path.sep in name or name.startswith('.'))): if not is_installable_dir(path): raise InstallationError( "Directory %r is not installable. File 'setup.py' not " "found." % name ) link = Link(path_to_url(name)) elif is_archive_file(path): if not os.path.isfile(path): logger.warning( 'Requirement %r looks like a filename, but the file does ' 'not exist', name ) link = Link(path_to_url(name)) # it's a local file, dir, or url if link: url = link.url # Handle relative file URLs if link.scheme == 'file' and re.search(r'\.\./', url): url = path_to_url(os.path.normpath(os.path.abspath(link.path))) # wheel file if link.ext == wheel_ext: wheel = Wheel(link.filename) # can raise InvalidWheelFilename if not wheel.supported(): raise UnsupportedWheel( "%s is not a supported wheel on this platform." % wheel.filename ) req = "%s==%s" % (wheel.name, wheel.version) else: # set the req to the egg fragment. when it's not there, this # will become an 'unnamed' requirement req = link.egg_fragment # a requirement specifier else: req = name return cls(req, comes_from, url=url, markers=markers, isolated=isolated)
[ "Creates", "an", "InstallRequirement", "from", "a", "name", "which", "might", "be", "a", "requirement", "directory", "containing", "setup", ".", "py", "filename", "or", "URL", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py#L112-L181
[ "def", "from_line", "(", "cls", ",", "name", ",", "comes_from", "=", "None", ",", "isolated", "=", "False", ")", ":", "from", "pip", ".", "index", "import", "Link", "url", "=", "None", "if", "is_url", "(", "name", ")", ":", "marker_sep", "=", "'; '", "else", ":", "marker_sep", "=", "';'", "if", "marker_sep", "in", "name", ":", "name", ",", "markers", "=", "name", ".", "split", "(", "marker_sep", ",", "1", ")", "markers", "=", "markers", ".", "strip", "(", ")", "if", "not", "markers", ":", "markers", "=", "None", "else", ":", "markers", "=", "None", "name", "=", "name", ".", "strip", "(", ")", "req", "=", "None", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "name", ")", ")", "link", "=", "None", "if", "is_url", "(", "name", ")", ":", "link", "=", "Link", "(", "name", ")", "elif", "(", "os", ".", "path", ".", "isdir", "(", "path", ")", "and", "(", "os", ".", "path", ".", "sep", "in", "name", "or", "name", ".", "startswith", "(", "'.'", ")", ")", ")", ":", "if", "not", "is_installable_dir", "(", "path", ")", ":", "raise", "InstallationError", "(", "\"Directory %r is not installable. File 'setup.py' not \"", "\"found.\"", "%", "name", ")", "link", "=", "Link", "(", "path_to_url", "(", "name", ")", ")", "elif", "is_archive_file", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "logger", ".", "warning", "(", "'Requirement %r looks like a filename, but the file does '", "'not exist'", ",", "name", ")", "link", "=", "Link", "(", "path_to_url", "(", "name", ")", ")", "# it's a local file, dir, or url", "if", "link", ":", "url", "=", "link", ".", "url", "# Handle relative file URLs", "if", "link", ".", "scheme", "==", "'file'", "and", "re", ".", "search", "(", "r'\\.\\./'", ",", "url", ")", ":", "url", "=", "path_to_url", "(", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "link", ".", "path", ")", ")", ")", "# wheel file", "if", "link", ".", "ext", "==", "wheel_ext", ":", "wheel", "=", "Wheel", "(", "link", ".", "filename", ")", "# can raise InvalidWheelFilename", "if", "not", "wheel", ".", "supported", "(", ")", ":", "raise", "UnsupportedWheel", "(", "\"%s is not a supported wheel on this platform.\"", "%", "wheel", ".", "filename", ")", "req", "=", "\"%s==%s\"", "%", "(", "wheel", ".", "name", ",", "wheel", ".", "version", ")", "else", ":", "# set the req to the egg fragment. when it's not there, this", "# will become an 'unnamed' requirement", "req", "=", "link", ".", "egg_fragment", "# a requirement specifier", "else", ":", "req", "=", "name", "return", "cls", "(", "req", ",", "comes_from", ",", "url", "=", "url", ",", "markers", "=", "markers", ",", "isolated", "=", "isolated", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
InstallRequirement.correct_build_location
If the build location was a temporary directory, this will move it to a new more permanent location
virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py
def correct_build_location(self): """If the build location was a temporary directory, this will move it to a new more permanent location""" if self.source_dir is not None: return assert self.req is not None assert self._temp_build_dir old_location = self._temp_build_dir new_build_dir = self._ideal_build_dir del self._ideal_build_dir if self.editable: name = self.name.lower() else: name = self.name new_location = os.path.join(new_build_dir, name) if not os.path.exists(new_build_dir): logger.debug('Creating directory %s', new_build_dir) _make_build_dir(new_build_dir) if os.path.exists(new_location): raise InstallationError( 'A package already exists in %s; please remove it to continue' % display_path(new_location)) logger.debug( 'Moving package %s from %s to new location %s', self, display_path(old_location), display_path(new_location), ) shutil.move(old_location, new_location) self._temp_build_dir = new_location self.source_dir = new_location self._egg_info_path = None
def correct_build_location(self): """If the build location was a temporary directory, this will move it to a new more permanent location""" if self.source_dir is not None: return assert self.req is not None assert self._temp_build_dir old_location = self._temp_build_dir new_build_dir = self._ideal_build_dir del self._ideal_build_dir if self.editable: name = self.name.lower() else: name = self.name new_location = os.path.join(new_build_dir, name) if not os.path.exists(new_build_dir): logger.debug('Creating directory %s', new_build_dir) _make_build_dir(new_build_dir) if os.path.exists(new_location): raise InstallationError( 'A package already exists in %s; please remove it to continue' % display_path(new_location)) logger.debug( 'Moving package %s from %s to new location %s', self, display_path(old_location), display_path(new_location), ) shutil.move(old_location, new_location) self._temp_build_dir = new_location self.source_dir = new_location self._egg_info_path = None
[ "If", "the", "build", "location", "was", "a", "temporary", "directory", "this", "will", "move", "it", "to", "a", "new", "more", "permanent", "location" ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py#L235-L264
[ "def", "correct_build_location", "(", "self", ")", ":", "if", "self", ".", "source_dir", "is", "not", "None", ":", "return", "assert", "self", ".", "req", "is", "not", "None", "assert", "self", ".", "_temp_build_dir", "old_location", "=", "self", ".", "_temp_build_dir", "new_build_dir", "=", "self", ".", "_ideal_build_dir", "del", "self", ".", "_ideal_build_dir", "if", "self", ".", "editable", ":", "name", "=", "self", ".", "name", ".", "lower", "(", ")", "else", ":", "name", "=", "self", ".", "name", "new_location", "=", "os", ".", "path", ".", "join", "(", "new_build_dir", ",", "name", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "new_build_dir", ")", ":", "logger", ".", "debug", "(", "'Creating directory %s'", ",", "new_build_dir", ")", "_make_build_dir", "(", "new_build_dir", ")", "if", "os", ".", "path", ".", "exists", "(", "new_location", ")", ":", "raise", "InstallationError", "(", "'A package already exists in %s; please remove it to continue'", "%", "display_path", "(", "new_location", ")", ")", "logger", ".", "debug", "(", "'Moving package %s from %s to new location %s'", ",", "self", ",", "display_path", "(", "old_location", ")", ",", "display_path", "(", "new_location", ")", ",", ")", "shutil", ".", "move", "(", "old_location", ",", "new_location", ")", "self", ".", "_temp_build_dir", "=", "new_location", "self", ".", "source_dir", "=", "new_location", "self", ".", "_egg_info_path", "=", "None" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
InstallRequirement.uninstall
Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv is linked to global site-packages.
virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py
def uninstall(self, auto_confirm=False): """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv is linked to global site-packages. """ if not self.check_if_exists(): raise UninstallationError( "Cannot uninstall requirement %s, not installed" % (self.name,) ) dist = self.satisfied_by or self.conflicts_with paths_to_remove = UninstallPathSet(dist) develop_egg_link = egg_link_path(dist) egg_info_exists = dist.egg_info and os.path.exists(dist.egg_info) # Special case for distutils installed package distutils_egg_info = getattr(dist._provider, 'path', None) if develop_egg_link: # develop egg with open(develop_egg_link, 'r') as fh: link_pointer = os.path.normcase(fh.readline().strip()) assert (link_pointer == dist.location), ( 'Egg-link %s does not match installed location of %s ' '(at %s)' % (link_pointer, self.name, dist.location) ) paths_to_remove.add(develop_egg_link) easy_install_pth = os.path.join(os.path.dirname(develop_egg_link), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, dist.location) elif egg_info_exists and dist.egg_info.endswith('.egg-info'): paths_to_remove.add(dist.egg_info) if dist.has_metadata('installed-files.txt'): for installed_file in dist.get_metadata( 'installed-files.txt').splitlines(): path = os.path.normpath( os.path.join(dist.egg_info, installed_file) ) paths_to_remove.add(path) # FIXME: need a test for this elif block # occurs with --single-version-externally-managed/--record outside # of pip elif dist.has_metadata('top_level.txt'): if dist.has_metadata('namespace_packages.txt'): namespaces = dist.get_metadata('namespace_packages.txt') else: namespaces = [] for top_level_pkg in [ p for p in dist.get_metadata('top_level.txt').splitlines() if p and p not in namespaces]: path = os.path.join(dist.location, top_level_pkg) paths_to_remove.add(path) paths_to_remove.add(path + '.py') paths_to_remove.add(path + '.pyc') elif distutils_egg_info: warnings.warn( "Uninstalling a distutils installed project ({0}) has been " "deprecated and will be removed in a future version. This is " "due to the fact that uninstalling a distutils project will " "only partially uninstall the project.".format(self.name), RemovedInPip8Warning, ) paths_to_remove.add(distutils_egg_info) elif dist.location.endswith('.egg'): # package installed by easy_install # We cannot match on dist.egg_name because it can slightly vary # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg paths_to_remove.add(dist.location) easy_install_egg = os.path.split(dist.location)[1] easy_install_pth = os.path.join(os.path.dirname(dist.location), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg) elif egg_info_exists and dist.egg_info.endswith('.dist-info'): for path in pip.wheel.uninstallation_paths(dist): paths_to_remove.add(path) else: logger.debug( 'Not sure how to uninstall: %s - Check: %s', dist, dist.location) # find distutils scripts= scripts if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'): for script in dist.metadata_listdir('scripts'): if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py paths_to_remove.add(os.path.join(bin_dir, script)) if WINDOWS: paths_to_remove.add(os.path.join(bin_dir, script) + '.bat') # find console_scripts if dist.has_metadata('entry_points.txt'): config = configparser.SafeConfigParser() config.readfp( FakeFile(dist.get_metadata_lines('entry_points.txt')) ) if config.has_section('console_scripts'): for name, value in config.items('console_scripts'): if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py paths_to_remove.add(os.path.join(bin_dir, name)) if WINDOWS: paths_to_remove.add( os.path.join(bin_dir, name) + '.exe' ) paths_to_remove.add( os.path.join(bin_dir, name) + '.exe.manifest' ) paths_to_remove.add( os.path.join(bin_dir, name) + '-script.py' ) paths_to_remove.remove(auto_confirm) self.uninstalled = paths_to_remove
def uninstall(self, auto_confirm=False): """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv is linked to global site-packages. """ if not self.check_if_exists(): raise UninstallationError( "Cannot uninstall requirement %s, not installed" % (self.name,) ) dist = self.satisfied_by or self.conflicts_with paths_to_remove = UninstallPathSet(dist) develop_egg_link = egg_link_path(dist) egg_info_exists = dist.egg_info and os.path.exists(dist.egg_info) # Special case for distutils installed package distutils_egg_info = getattr(dist._provider, 'path', None) if develop_egg_link: # develop egg with open(develop_egg_link, 'r') as fh: link_pointer = os.path.normcase(fh.readline().strip()) assert (link_pointer == dist.location), ( 'Egg-link %s does not match installed location of %s ' '(at %s)' % (link_pointer, self.name, dist.location) ) paths_to_remove.add(develop_egg_link) easy_install_pth = os.path.join(os.path.dirname(develop_egg_link), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, dist.location) elif egg_info_exists and dist.egg_info.endswith('.egg-info'): paths_to_remove.add(dist.egg_info) if dist.has_metadata('installed-files.txt'): for installed_file in dist.get_metadata( 'installed-files.txt').splitlines(): path = os.path.normpath( os.path.join(dist.egg_info, installed_file) ) paths_to_remove.add(path) # FIXME: need a test for this elif block # occurs with --single-version-externally-managed/--record outside # of pip elif dist.has_metadata('top_level.txt'): if dist.has_metadata('namespace_packages.txt'): namespaces = dist.get_metadata('namespace_packages.txt') else: namespaces = [] for top_level_pkg in [ p for p in dist.get_metadata('top_level.txt').splitlines() if p and p not in namespaces]: path = os.path.join(dist.location, top_level_pkg) paths_to_remove.add(path) paths_to_remove.add(path + '.py') paths_to_remove.add(path + '.pyc') elif distutils_egg_info: warnings.warn( "Uninstalling a distutils installed project ({0}) has been " "deprecated and will be removed in a future version. This is " "due to the fact that uninstalling a distutils project will " "only partially uninstall the project.".format(self.name), RemovedInPip8Warning, ) paths_to_remove.add(distutils_egg_info) elif dist.location.endswith('.egg'): # package installed by easy_install # We cannot match on dist.egg_name because it can slightly vary # i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg paths_to_remove.add(dist.location) easy_install_egg = os.path.split(dist.location)[1] easy_install_pth = os.path.join(os.path.dirname(dist.location), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg) elif egg_info_exists and dist.egg_info.endswith('.dist-info'): for path in pip.wheel.uninstallation_paths(dist): paths_to_remove.add(path) else: logger.debug( 'Not sure how to uninstall: %s - Check: %s', dist, dist.location) # find distutils scripts= scripts if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'): for script in dist.metadata_listdir('scripts'): if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py paths_to_remove.add(os.path.join(bin_dir, script)) if WINDOWS: paths_to_remove.add(os.path.join(bin_dir, script) + '.bat') # find console_scripts if dist.has_metadata('entry_points.txt'): config = configparser.SafeConfigParser() config.readfp( FakeFile(dist.get_metadata_lines('entry_points.txt')) ) if config.has_section('console_scripts'): for name, value in config.items('console_scripts'): if dist_in_usersite(dist): bin_dir = bin_user else: bin_dir = bin_py paths_to_remove.add(os.path.join(bin_dir, name)) if WINDOWS: paths_to_remove.add( os.path.join(bin_dir, name) + '.exe' ) paths_to_remove.add( os.path.join(bin_dir, name) + '.exe.manifest' ) paths_to_remove.add( os.path.join(bin_dir, name) + '-script.py' ) paths_to_remove.remove(auto_confirm) self.uninstalled = paths_to_remove
[ "Uninstall", "the", "distribution", "currently", "satisfying", "this", "requirement", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/req/req_install.py#L542-L668
[ "def", "uninstall", "(", "self", ",", "auto_confirm", "=", "False", ")", ":", "if", "not", "self", ".", "check_if_exists", "(", ")", ":", "raise", "UninstallationError", "(", "\"Cannot uninstall requirement %s, not installed\"", "%", "(", "self", ".", "name", ",", ")", ")", "dist", "=", "self", ".", "satisfied_by", "or", "self", ".", "conflicts_with", "paths_to_remove", "=", "UninstallPathSet", "(", "dist", ")", "develop_egg_link", "=", "egg_link_path", "(", "dist", ")", "egg_info_exists", "=", "dist", ".", "egg_info", "and", "os", ".", "path", ".", "exists", "(", "dist", ".", "egg_info", ")", "# Special case for distutils installed package", "distutils_egg_info", "=", "getattr", "(", "dist", ".", "_provider", ",", "'path'", ",", "None", ")", "if", "develop_egg_link", ":", "# develop egg", "with", "open", "(", "develop_egg_link", ",", "'r'", ")", "as", "fh", ":", "link_pointer", "=", "os", ".", "path", ".", "normcase", "(", "fh", ".", "readline", "(", ")", ".", "strip", "(", ")", ")", "assert", "(", "link_pointer", "==", "dist", ".", "location", ")", ",", "(", "'Egg-link %s does not match installed location of %s '", "'(at %s)'", "%", "(", "link_pointer", ",", "self", ".", "name", ",", "dist", ".", "location", ")", ")", "paths_to_remove", ".", "add", "(", "develop_egg_link", ")", "easy_install_pth", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "develop_egg_link", ")", ",", "'easy-install.pth'", ")", "paths_to_remove", ".", "add_pth", "(", "easy_install_pth", ",", "dist", ".", "location", ")", "elif", "egg_info_exists", "and", "dist", ".", "egg_info", ".", "endswith", "(", "'.egg-info'", ")", ":", "paths_to_remove", ".", "add", "(", "dist", ".", "egg_info", ")", "if", "dist", ".", "has_metadata", "(", "'installed-files.txt'", ")", ":", "for", "installed_file", "in", "dist", ".", "get_metadata", "(", "'installed-files.txt'", ")", ".", "splitlines", "(", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "dist", ".", "egg_info", ",", "installed_file", ")", ")", "paths_to_remove", ".", "add", "(", "path", ")", "# FIXME: need a test for this elif block", "# occurs with --single-version-externally-managed/--record outside", "# of pip", "elif", "dist", ".", "has_metadata", "(", "'top_level.txt'", ")", ":", "if", "dist", ".", "has_metadata", "(", "'namespace_packages.txt'", ")", ":", "namespaces", "=", "dist", ".", "get_metadata", "(", "'namespace_packages.txt'", ")", "else", ":", "namespaces", "=", "[", "]", "for", "top_level_pkg", "in", "[", "p", "for", "p", "in", "dist", ".", "get_metadata", "(", "'top_level.txt'", ")", ".", "splitlines", "(", ")", "if", "p", "and", "p", "not", "in", "namespaces", "]", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dist", ".", "location", ",", "top_level_pkg", ")", "paths_to_remove", ".", "add", "(", "path", ")", "paths_to_remove", ".", "add", "(", "path", "+", "'.py'", ")", "paths_to_remove", ".", "add", "(", "path", "+", "'.pyc'", ")", "elif", "distutils_egg_info", ":", "warnings", ".", "warn", "(", "\"Uninstalling a distutils installed project ({0}) has been \"", "\"deprecated and will be removed in a future version. This is \"", "\"due to the fact that uninstalling a distutils project will \"", "\"only partially uninstall the project.\"", ".", "format", "(", "self", ".", "name", ")", ",", "RemovedInPip8Warning", ",", ")", "paths_to_remove", ".", "add", "(", "distutils_egg_info", ")", "elif", "dist", ".", "location", ".", "endswith", "(", "'.egg'", ")", ":", "# package installed by easy_install", "# We cannot match on dist.egg_name because it can slightly vary", "# i.e. setuptools-0.6c11-py2.6.egg vs setuptools-0.6rc11-py2.6.egg", "paths_to_remove", ".", "add", "(", "dist", ".", "location", ")", "easy_install_egg", "=", "os", ".", "path", ".", "split", "(", "dist", ".", "location", ")", "[", "1", "]", "easy_install_pth", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "dist", ".", "location", ")", ",", "'easy-install.pth'", ")", "paths_to_remove", ".", "add_pth", "(", "easy_install_pth", ",", "'./'", "+", "easy_install_egg", ")", "elif", "egg_info_exists", "and", "dist", ".", "egg_info", ".", "endswith", "(", "'.dist-info'", ")", ":", "for", "path", "in", "pip", ".", "wheel", ".", "uninstallation_paths", "(", "dist", ")", ":", "paths_to_remove", ".", "add", "(", "path", ")", "else", ":", "logger", ".", "debug", "(", "'Not sure how to uninstall: %s - Check: %s'", ",", "dist", ",", "dist", ".", "location", ")", "# find distutils scripts= scripts", "if", "dist", ".", "has_metadata", "(", "'scripts'", ")", "and", "dist", ".", "metadata_isdir", "(", "'scripts'", ")", ":", "for", "script", "in", "dist", ".", "metadata_listdir", "(", "'scripts'", ")", ":", "if", "dist_in_usersite", "(", "dist", ")", ":", "bin_dir", "=", "bin_user", "else", ":", "bin_dir", "=", "bin_py", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "script", ")", ")", "if", "WINDOWS", ":", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "script", ")", "+", "'.bat'", ")", "# find console_scripts", "if", "dist", ".", "has_metadata", "(", "'entry_points.txt'", ")", ":", "config", "=", "configparser", ".", "SafeConfigParser", "(", ")", "config", ".", "readfp", "(", "FakeFile", "(", "dist", ".", "get_metadata_lines", "(", "'entry_points.txt'", ")", ")", ")", "if", "config", ".", "has_section", "(", "'console_scripts'", ")", ":", "for", "name", ",", "value", "in", "config", ".", "items", "(", "'console_scripts'", ")", ":", "if", "dist_in_usersite", "(", "dist", ")", ":", "bin_dir", "=", "bin_user", "else", ":", "bin_dir", "=", "bin_py", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "name", ")", ")", "if", "WINDOWS", ":", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "name", ")", "+", "'.exe'", ")", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "name", ")", "+", "'.exe.manifest'", ")", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_dir", ",", "name", ")", "+", "'-script.py'", ")", "paths_to_remove", ".", "remove", "(", "auto_confirm", ")", "self", ".", "uninstalled", "=", "paths_to_remove" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
load_pyconfig_files
Load multiple Python config files, merging each of them in turn. Parameters ========== config_files : list of str List of config files names to load and merge into the config. path : unicode The full path to the location of the config files.
environment/lib/python2.7/site-packages/IPython/config/loader.py
def load_pyconfig_files(config_files, path): """Load multiple Python config files, merging each of them in turn. Parameters ========== config_files : list of str List of config files names to load and merge into the config. path : unicode The full path to the location of the config files. """ config = Config() for cf in config_files: loader = PyFileConfigLoader(cf, path=path) try: next_config = loader.load_config() except ConfigFileNotFound: pass except: raise else: config._merge(next_config) return config
def load_pyconfig_files(config_files, path): """Load multiple Python config files, merging each of them in turn. Parameters ========== config_files : list of str List of config files names to load and merge into the config. path : unicode The full path to the location of the config files. """ config = Config() for cf in config_files: loader = PyFileConfigLoader(cf, path=path) try: next_config = loader.load_config() except ConfigFileNotFound: pass except: raise else: config._merge(next_config) return config
[ "Load", "multiple", "Python", "config", "files", "merging", "each", "of", "them", "in", "turn", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L675-L696
[ "def", "load_pyconfig_files", "(", "config_files", ",", "path", ")", ":", "config", "=", "Config", "(", ")", "for", "cf", "in", "config_files", ":", "loader", "=", "PyFileConfigLoader", "(", "cf", ",", "path", "=", "path", ")", "try", ":", "next_config", "=", "loader", ".", "load_config", "(", ")", "except", "ConfigFileNotFound", ":", "pass", "except", ":", "raise", "else", ":", "config", ".", "_merge", "(", "next_config", ")", "return", "config" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PyFileConfigLoader.load_config
Load the config from a file and return it as a Struct.
environment/lib/python2.7/site-packages/IPython/config/loader.py
def load_config(self): """Load the config from a file and return it as a Struct.""" self.clear() try: self._find_file() except IOError as e: raise ConfigFileNotFound(str(e)) self._read_file_as_dict() self._convert_to_config() return self.config
def load_config(self): """Load the config from a file and return it as a Struct.""" self.clear() try: self._find_file() except IOError as e: raise ConfigFileNotFound(str(e)) self._read_file_as_dict() self._convert_to_config() return self.config
[ "Load", "the", "config", "from", "a", "file", "and", "return", "it", "as", "a", "Struct", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L262-L271
[ "def", "load_config", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "try", ":", "self", ".", "_find_file", "(", ")", "except", "IOError", "as", "e", ":", "raise", "ConfigFileNotFound", "(", "str", "(", "e", ")", ")", "self", ".", "_read_file_as_dict", "(", ")", "self", ".", "_convert_to_config", "(", ")", "return", "self", ".", "config" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PyFileConfigLoader._read_file_as_dict
Load the config file into self.config, with recursive loading.
environment/lib/python2.7/site-packages/IPython/config/loader.py
def _read_file_as_dict(self): """Load the config file into self.config, with recursive loading.""" # This closure is made available in the namespace that is used # to exec the config file. It allows users to call # load_subconfig('myconfig.py') to load config files recursively. # It needs to be a closure because it has references to self.path # and self.config. The sub-config is loaded with the same path # as the parent, but it uses an empty config which is then merged # with the parents. # If a profile is specified, the config file will be loaded # from that profile def load_subconfig(fname, profile=None): # import here to prevent circular imports from IPython.core.profiledir import ProfileDir, ProfileDirError if profile is not None: try: profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), profile, ) except ProfileDirError: return path = profile_dir.location else: path = self.path loader = PyFileConfigLoader(fname, path) try: sub_config = loader.load_config() except ConfigFileNotFound: # Pass silently if the sub config is not there. This happens # when a user s using a profile, but not the default config. pass else: self.config._merge(sub_config) # Again, this needs to be a closure and should be used in config # files to get the config being loaded. def get_config(): return self.config namespace = dict(load_subconfig=load_subconfig, get_config=get_config) fs_encoding = sys.getfilesystemencoding() or 'ascii' conf_filename = self.full_filename.encode(fs_encoding) py3compat.execfile(conf_filename, namespace)
def _read_file_as_dict(self): """Load the config file into self.config, with recursive loading.""" # This closure is made available in the namespace that is used # to exec the config file. It allows users to call # load_subconfig('myconfig.py') to load config files recursively. # It needs to be a closure because it has references to self.path # and self.config. The sub-config is loaded with the same path # as the parent, but it uses an empty config which is then merged # with the parents. # If a profile is specified, the config file will be loaded # from that profile def load_subconfig(fname, profile=None): # import here to prevent circular imports from IPython.core.profiledir import ProfileDir, ProfileDirError if profile is not None: try: profile_dir = ProfileDir.find_profile_dir_by_name( get_ipython_dir(), profile, ) except ProfileDirError: return path = profile_dir.location else: path = self.path loader = PyFileConfigLoader(fname, path) try: sub_config = loader.load_config() except ConfigFileNotFound: # Pass silently if the sub config is not there. This happens # when a user s using a profile, but not the default config. pass else: self.config._merge(sub_config) # Again, this needs to be a closure and should be used in config # files to get the config being loaded. def get_config(): return self.config namespace = dict(load_subconfig=load_subconfig, get_config=get_config) fs_encoding = sys.getfilesystemencoding() or 'ascii' conf_filename = self.full_filename.encode(fs_encoding) py3compat.execfile(conf_filename, namespace)
[ "Load", "the", "config", "file", "into", "self", ".", "config", "with", "recursive", "loading", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L277-L322
[ "def", "_read_file_as_dict", "(", "self", ")", ":", "# This closure is made available in the namespace that is used", "# to exec the config file. It allows users to call", "# load_subconfig('myconfig.py') to load config files recursively.", "# It needs to be a closure because it has references to self.path", "# and self.config. The sub-config is loaded with the same path", "# as the parent, but it uses an empty config which is then merged", "# with the parents.", "# If a profile is specified, the config file will be loaded", "# from that profile", "def", "load_subconfig", "(", "fname", ",", "profile", "=", "None", ")", ":", "# import here to prevent circular imports", "from", "IPython", ".", "core", ".", "profiledir", "import", "ProfileDir", ",", "ProfileDirError", "if", "profile", "is", "not", "None", ":", "try", ":", "profile_dir", "=", "ProfileDir", ".", "find_profile_dir_by_name", "(", "get_ipython_dir", "(", ")", ",", "profile", ",", ")", "except", "ProfileDirError", ":", "return", "path", "=", "profile_dir", ".", "location", "else", ":", "path", "=", "self", ".", "path", "loader", "=", "PyFileConfigLoader", "(", "fname", ",", "path", ")", "try", ":", "sub_config", "=", "loader", ".", "load_config", "(", ")", "except", "ConfigFileNotFound", ":", "# Pass silently if the sub config is not there. This happens", "# when a user s using a profile, but not the default config.", "pass", "else", ":", "self", ".", "config", ".", "_merge", "(", "sub_config", ")", "# Again, this needs to be a closure and should be used in config", "# files to get the config being loaded.", "def", "get_config", "(", ")", ":", "return", "self", ".", "config", "namespace", "=", "dict", "(", "load_subconfig", "=", "load_subconfig", ",", "get_config", "=", "get_config", ")", "fs_encoding", "=", "sys", ".", "getfilesystemencoding", "(", ")", "or", "'ascii'", "conf_filename", "=", "self", ".", "full_filename", ".", "encode", "(", "fs_encoding", ")", "py3compat", ".", "execfile", "(", "conf_filename", ",", "namespace", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CommandLineConfigLoader._exec_config_str
execute self.config.<lhs> = <rhs> * expands ~ with expanduser * tries to assign with raw eval, otherwise assigns with just the string, allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* equivalent are `--C.a=4` and `--C.a='4'`.
environment/lib/python2.7/site-packages/IPython/config/loader.py
def _exec_config_str(self, lhs, rhs): """execute self.config.<lhs> = <rhs> * expands ~ with expanduser * tries to assign with raw eval, otherwise assigns with just the string, allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* equivalent are `--C.a=4` and `--C.a='4'`. """ rhs = os.path.expanduser(rhs) try: # Try to see if regular Python syntax will work. This # won't handle strings as the quote marks are removed # by the system shell. value = eval(rhs) except (NameError, SyntaxError): # This case happens if the rhs is a string. value = rhs exec u'self.config.%s = value' % lhs
def _exec_config_str(self, lhs, rhs): """execute self.config.<lhs> = <rhs> * expands ~ with expanduser * tries to assign with raw eval, otherwise assigns with just the string, allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent. *Not* equivalent are `--C.a=4` and `--C.a='4'`. """ rhs = os.path.expanduser(rhs) try: # Try to see if regular Python syntax will work. This # won't handle strings as the quote marks are removed # by the system shell. value = eval(rhs) except (NameError, SyntaxError): # This case happens if the rhs is a string. value = rhs exec u'self.config.%s = value' % lhs
[ "execute", "self", ".", "config", ".", "<lhs", ">", "=", "<rhs", ">", "*", "expands", "~", "with", "expanduser", "*", "tries", "to", "assign", "with", "raw", "eval", "otherwise", "assigns", "with", "just", "the", "string", "allowing", "--", "C", ".", "a", "=", "foobar", "and", "--", "C", ".", "a", "=", "foobar", "to", "be", "equivalent", ".", "*", "Not", "*", "equivalent", "are", "--", "C", ".", "a", "=", "4", "and", "--", "C", ".", "a", "=", "4", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L336-L354
[ "def", "_exec_config_str", "(", "self", ",", "lhs", ",", "rhs", ")", ":", "rhs", "=", "os", ".", "path", ".", "expanduser", "(", "rhs", ")", "try", ":", "# Try to see if regular Python syntax will work. This", "# won't handle strings as the quote marks are removed", "# by the system shell.", "value", "=", "eval", "(", "rhs", ")", "except", "(", "NameError", ",", "SyntaxError", ")", ":", "# This case happens if the rhs is a string.", "value", "=", "rhs", "exec", "u'self.config.%s = value'", "%", "lhs" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CommandLineConfigLoader._load_flag
update self.config from a flag, which can be a dict or Config
environment/lib/python2.7/site-packages/IPython/config/loader.py
def _load_flag(self, cfg): """update self.config from a flag, which can be a dict or Config""" if isinstance(cfg, (dict, Config)): # don't clobber whole config sections, update # each section from config: for sec,c in cfg.iteritems(): self.config[sec].update(c) else: raise TypeError("Invalid flag: %r" % cfg)
def _load_flag(self, cfg): """update self.config from a flag, which can be a dict or Config""" if isinstance(cfg, (dict, Config)): # don't clobber whole config sections, update # each section from config: for sec,c in cfg.iteritems(): self.config[sec].update(c) else: raise TypeError("Invalid flag: %r" % cfg)
[ "update", "self", ".", "config", "from", "a", "flag", "which", "can", "be", "a", "dict", "or", "Config" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L356-L364
[ "def", "_load_flag", "(", "self", ",", "cfg", ")", ":", "if", "isinstance", "(", "cfg", ",", "(", "dict", ",", "Config", ")", ")", ":", "# don't clobber whole config sections, update", "# each section from config:", "for", "sec", ",", "c", "in", "cfg", ".", "iteritems", "(", ")", ":", "self", ".", "config", "[", "sec", "]", ".", "update", "(", "c", ")", "else", ":", "raise", "TypeError", "(", "\"Invalid flag: %r\"", "%", "cfg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KeyValueConfigLoader._decode_argv
decode argv if bytes, using stin.encoding, falling back on default enc
environment/lib/python2.7/site-packages/IPython/config/loader.py
def _decode_argv(self, argv, enc=None): """decode argv if bytes, using stin.encoding, falling back on default enc""" uargv = [] if enc is None: enc = DEFAULT_ENCODING for arg in argv: if not isinstance(arg, unicode): # only decode if not already decoded arg = arg.decode(enc) uargv.append(arg) return uargv
def _decode_argv(self, argv, enc=None): """decode argv if bytes, using stin.encoding, falling back on default enc""" uargv = [] if enc is None: enc = DEFAULT_ENCODING for arg in argv: if not isinstance(arg, unicode): # only decode if not already decoded arg = arg.decode(enc) uargv.append(arg) return uargv
[ "decode", "argv", "if", "bytes", "using", "stin", ".", "encoding", "falling", "back", "on", "default", "enc" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L437-L447
[ "def", "_decode_argv", "(", "self", ",", "argv", ",", "enc", "=", "None", ")", ":", "uargv", "=", "[", "]", "if", "enc", "is", "None", ":", "enc", "=", "DEFAULT_ENCODING", "for", "arg", "in", "argv", ":", "if", "not", "isinstance", "(", "arg", ",", "unicode", ")", ":", "# only decode if not already decoded", "arg", "=", "arg", ".", "decode", "(", "enc", ")", "uargv", ".", "append", "(", "arg", ")", "return", "uargv" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KeyValueConfigLoader.load_config
Parse the configuration and generate the Config object. After loading, any arguments that are not key-value or flags will be stored in self.extra_args - a list of unparsed command-line arguments. This is used for arguments such as input files or subcommands. Parameters ---------- argv : list, optional A list that has the form of sys.argv[1:] which has unicode elements of the form u"key=value". If this is None (default), then self.argv will be used. aliases : dict A dict of aliases for configurable traits. Keys are the short aliases, Values are the resolved trait. Of the form: `{'alias' : 'Configurable.trait'}` flags : dict A dict of flags, keyed by str name. Values can be Config objects or dicts. When the flag is triggered, The config is loaded as `self.config.update(cfg)`.
environment/lib/python2.7/site-packages/IPython/config/loader.py
def load_config(self, argv=None, aliases=None, flags=None): """Parse the configuration and generate the Config object. After loading, any arguments that are not key-value or flags will be stored in self.extra_args - a list of unparsed command-line arguments. This is used for arguments such as input files or subcommands. Parameters ---------- argv : list, optional A list that has the form of sys.argv[1:] which has unicode elements of the form u"key=value". If this is None (default), then self.argv will be used. aliases : dict A dict of aliases for configurable traits. Keys are the short aliases, Values are the resolved trait. Of the form: `{'alias' : 'Configurable.trait'}` flags : dict A dict of flags, keyed by str name. Values can be Config objects or dicts. When the flag is triggered, The config is loaded as `self.config.update(cfg)`. """ from IPython.config.configurable import Configurable self.clear() if argv is None: argv = self.argv if aliases is None: aliases = self.aliases if flags is None: flags = self.flags # ensure argv is a list of unicode strings: uargv = self._decode_argv(argv) for idx,raw in enumerate(uargv): # strip leading '-' item = raw.lstrip('-') if raw == '--': # don't parse arguments after '--' # this is useful for relaying arguments to scripts, e.g. # ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py self.extra_args.extend(uargv[idx+1:]) break if kv_pattern.match(raw): lhs,rhs = item.split('=',1) # Substitute longnames for aliases. if lhs in aliases: lhs = aliases[lhs] if '.' not in lhs: # probably a mistyped alias, but not technically illegal warn.warn("Unrecognized alias: '%s', it will probably have no effect."%lhs) try: self._exec_config_str(lhs, rhs) except Exception: raise ArgumentError("Invalid argument: '%s'" % raw) elif flag_pattern.match(raw): if item in flags: cfg,help = flags[item] self._load_flag(cfg) else: raise ArgumentError("Unrecognized flag: '%s'"%raw) elif raw.startswith('-'): kv = '--'+item if kv_pattern.match(kv): raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv)) else: raise ArgumentError("Invalid argument: '%s'"%raw) else: # keep all args that aren't valid in a list, # in case our parent knows what to do with them. self.extra_args.append(item) return self.config
def load_config(self, argv=None, aliases=None, flags=None): """Parse the configuration and generate the Config object. After loading, any arguments that are not key-value or flags will be stored in self.extra_args - a list of unparsed command-line arguments. This is used for arguments such as input files or subcommands. Parameters ---------- argv : list, optional A list that has the form of sys.argv[1:] which has unicode elements of the form u"key=value". If this is None (default), then self.argv will be used. aliases : dict A dict of aliases for configurable traits. Keys are the short aliases, Values are the resolved trait. Of the form: `{'alias' : 'Configurable.trait'}` flags : dict A dict of flags, keyed by str name. Values can be Config objects or dicts. When the flag is triggered, The config is loaded as `self.config.update(cfg)`. """ from IPython.config.configurable import Configurable self.clear() if argv is None: argv = self.argv if aliases is None: aliases = self.aliases if flags is None: flags = self.flags # ensure argv is a list of unicode strings: uargv = self._decode_argv(argv) for idx,raw in enumerate(uargv): # strip leading '-' item = raw.lstrip('-') if raw == '--': # don't parse arguments after '--' # this is useful for relaying arguments to scripts, e.g. # ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py self.extra_args.extend(uargv[idx+1:]) break if kv_pattern.match(raw): lhs,rhs = item.split('=',1) # Substitute longnames for aliases. if lhs in aliases: lhs = aliases[lhs] if '.' not in lhs: # probably a mistyped alias, but not technically illegal warn.warn("Unrecognized alias: '%s', it will probably have no effect."%lhs) try: self._exec_config_str(lhs, rhs) except Exception: raise ArgumentError("Invalid argument: '%s'" % raw) elif flag_pattern.match(raw): if item in flags: cfg,help = flags[item] self._load_flag(cfg) else: raise ArgumentError("Unrecognized flag: '%s'"%raw) elif raw.startswith('-'): kv = '--'+item if kv_pattern.match(kv): raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv)) else: raise ArgumentError("Invalid argument: '%s'"%raw) else: # keep all args that aren't valid in a list, # in case our parent knows what to do with them. self.extra_args.append(item) return self.config
[ "Parse", "the", "configuration", "and", "generate", "the", "Config", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L450-L525
[ "def", "load_config", "(", "self", ",", "argv", "=", "None", ",", "aliases", "=", "None", ",", "flags", "=", "None", ")", ":", "from", "IPython", ".", "config", ".", "configurable", "import", "Configurable", "self", ".", "clear", "(", ")", "if", "argv", "is", "None", ":", "argv", "=", "self", ".", "argv", "if", "aliases", "is", "None", ":", "aliases", "=", "self", ".", "aliases", "if", "flags", "is", "None", ":", "flags", "=", "self", ".", "flags", "# ensure argv is a list of unicode strings:", "uargv", "=", "self", ".", "_decode_argv", "(", "argv", ")", "for", "idx", ",", "raw", "in", "enumerate", "(", "uargv", ")", ":", "# strip leading '-'", "item", "=", "raw", ".", "lstrip", "(", "'-'", ")", "if", "raw", "==", "'--'", ":", "# don't parse arguments after '--'", "# this is useful for relaying arguments to scripts, e.g.", "# ipython -i foo.py --pylab=qt -- args after '--' go-to-foo.py", "self", ".", "extra_args", ".", "extend", "(", "uargv", "[", "idx", "+", "1", ":", "]", ")", "break", "if", "kv_pattern", ".", "match", "(", "raw", ")", ":", "lhs", ",", "rhs", "=", "item", ".", "split", "(", "'='", ",", "1", ")", "# Substitute longnames for aliases.", "if", "lhs", "in", "aliases", ":", "lhs", "=", "aliases", "[", "lhs", "]", "if", "'.'", "not", "in", "lhs", ":", "# probably a mistyped alias, but not technically illegal", "warn", ".", "warn", "(", "\"Unrecognized alias: '%s', it will probably have no effect.\"", "%", "lhs", ")", "try", ":", "self", ".", "_exec_config_str", "(", "lhs", ",", "rhs", ")", "except", "Exception", ":", "raise", "ArgumentError", "(", "\"Invalid argument: '%s'\"", "%", "raw", ")", "elif", "flag_pattern", ".", "match", "(", "raw", ")", ":", "if", "item", "in", "flags", ":", "cfg", ",", "help", "=", "flags", "[", "item", "]", "self", ".", "_load_flag", "(", "cfg", ")", "else", ":", "raise", "ArgumentError", "(", "\"Unrecognized flag: '%s'\"", "%", "raw", ")", "elif", "raw", ".", "startswith", "(", "'-'", ")", ":", "kv", "=", "'--'", "+", "item", "if", "kv_pattern", ".", "match", "(", "kv", ")", ":", "raise", "ArgumentError", "(", "\"Invalid argument: '%s', did you mean '%s'?\"", "%", "(", "raw", ",", "kv", ")", ")", "else", ":", "raise", "ArgumentError", "(", "\"Invalid argument: '%s'\"", "%", "raw", ")", "else", ":", "# keep all args that aren't valid in a list,", "# in case our parent knows what to do with them.", "self", ".", "extra_args", ".", "append", "(", "item", ")", "return", "self", ".", "config" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ArgParseConfigLoader.load_config
Parse command line arguments and return as a Config object. Parameters ---------- args : optional, list If given, a list with the structure of sys.argv[1:] to parse arguments from. If not given, the instance's self.argv attribute (given at construction time) is used.
environment/lib/python2.7/site-packages/IPython/config/loader.py
def load_config(self, argv=None, aliases=None, flags=None): """Parse command line arguments and return as a Config object. Parameters ---------- args : optional, list If given, a list with the structure of sys.argv[1:] to parse arguments from. If not given, the instance's self.argv attribute (given at construction time) is used.""" self.clear() if argv is None: argv = self.argv if aliases is None: aliases = self.aliases if flags is None: flags = self.flags self._create_parser(aliases, flags) self._parse_args(argv) self._convert_to_config() return self.config
def load_config(self, argv=None, aliases=None, flags=None): """Parse command line arguments and return as a Config object. Parameters ---------- args : optional, list If given, a list with the structure of sys.argv[1:] to parse arguments from. If not given, the instance's self.argv attribute (given at construction time) is used.""" self.clear() if argv is None: argv = self.argv if aliases is None: aliases = self.aliases if flags is None: flags = self.flags self._create_parser(aliases, flags) self._parse_args(argv) self._convert_to_config() return self.config
[ "Parse", "command", "line", "arguments", "and", "return", "as", "a", "Config", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L567-L587
[ "def", "load_config", "(", "self", ",", "argv", "=", "None", ",", "aliases", "=", "None", ",", "flags", "=", "None", ")", ":", "self", ".", "clear", "(", ")", "if", "argv", "is", "None", ":", "argv", "=", "self", ".", "argv", "if", "aliases", "is", "None", ":", "aliases", "=", "self", ".", "aliases", "if", "flags", "is", "None", ":", "flags", "=", "self", ".", "flags", "self", ".", "_create_parser", "(", "aliases", ",", "flags", ")", "self", ".", "_parse_args", "(", "argv", ")", "self", ".", "_convert_to_config", "(", ")", "return", "self", ".", "config" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ArgParseConfigLoader._parse_args
self.parser->self.parsed_data
environment/lib/python2.7/site-packages/IPython/config/loader.py
def _parse_args(self, args): """self.parser->self.parsed_data""" # decode sys.argv to support unicode command-line options enc = DEFAULT_ENCODING uargs = [py3compat.cast_unicode(a, enc) for a in args] self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
def _parse_args(self, args): """self.parser->self.parsed_data""" # decode sys.argv to support unicode command-line options enc = DEFAULT_ENCODING uargs = [py3compat.cast_unicode(a, enc) for a in args] self.parsed_data, self.extra_args = self.parser.parse_known_args(uargs)
[ "self", ".", "parser", "-", ">", "self", ".", "parsed_data" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L602-L607
[ "def", "_parse_args", "(", "self", ",", "args", ")", ":", "# decode sys.argv to support unicode command-line options", "enc", "=", "DEFAULT_ENCODING", "uargs", "=", "[", "py3compat", ".", "cast_unicode", "(", "a", ",", "enc", ")", "for", "a", "in", "args", "]", "self", ".", "parsed_data", ",", "self", ".", "extra_args", "=", "self", ".", "parser", ".", "parse_known_args", "(", "uargs", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ArgParseConfigLoader._convert_to_config
self.parsed_data->self.config
environment/lib/python2.7/site-packages/IPython/config/loader.py
def _convert_to_config(self): """self.parsed_data->self.config""" for k, v in vars(self.parsed_data).iteritems(): exec "self.config.%s = v"%k in locals(), globals()
def _convert_to_config(self): """self.parsed_data->self.config""" for k, v in vars(self.parsed_data).iteritems(): exec "self.config.%s = v"%k in locals(), globals()
[ "self", ".", "parsed_data", "-", ">", "self", ".", "config" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L609-L612
[ "def", "_convert_to_config", "(", "self", ")", ":", "for", "k", ",", "v", "in", "vars", "(", "self", ".", "parsed_data", ")", ".", "iteritems", "(", ")", ":", "exec", "\"self.config.%s = v\"", "%", "k", "in", "locals", "(", ")", ",", "globals", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KVArgParseConfigLoader._convert_to_config
self.parsed_data->self.config, parse unrecognized extra args via KVLoader.
environment/lib/python2.7/site-packages/IPython/config/loader.py
def _convert_to_config(self): """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" # remove subconfigs list from namespace before transforming the Namespace if '_flags' in self.parsed_data: subcs = self.parsed_data._flags del self.parsed_data._flags else: subcs = [] for k, v in vars(self.parsed_data).iteritems(): if v is None: # it was a flag that shares the name of an alias subcs.append(self.alias_flags[k]) else: # eval the KV assignment self._exec_config_str(k, v) for subc in subcs: self._load_flag(subc) if self.extra_args: sub_parser = KeyValueConfigLoader() sub_parser.load_config(self.extra_args) self.config._merge(sub_parser.config) self.extra_args = sub_parser.extra_args
def _convert_to_config(self): """self.parsed_data->self.config, parse unrecognized extra args via KVLoader.""" # remove subconfigs list from namespace before transforming the Namespace if '_flags' in self.parsed_data: subcs = self.parsed_data._flags del self.parsed_data._flags else: subcs = [] for k, v in vars(self.parsed_data).iteritems(): if v is None: # it was a flag that shares the name of an alias subcs.append(self.alias_flags[k]) else: # eval the KV assignment self._exec_config_str(k, v) for subc in subcs: self._load_flag(subc) if self.extra_args: sub_parser = KeyValueConfigLoader() sub_parser.load_config(self.extra_args) self.config._merge(sub_parser.config) self.extra_args = sub_parser.extra_args
[ "self", ".", "parsed_data", "-", ">", "self", ".", "config", "parse", "unrecognized", "extra", "args", "via", "KVLoader", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/config/loader.py#L648-L672
[ "def", "_convert_to_config", "(", "self", ")", ":", "# remove subconfigs list from namespace before transforming the Namespace", "if", "'_flags'", "in", "self", ".", "parsed_data", ":", "subcs", "=", "self", ".", "parsed_data", ".", "_flags", "del", "self", ".", "parsed_data", ".", "_flags", "else", ":", "subcs", "=", "[", "]", "for", "k", ",", "v", "in", "vars", "(", "self", ".", "parsed_data", ")", ".", "iteritems", "(", ")", ":", "if", "v", "is", "None", ":", "# it was a flag that shares the name of an alias", "subcs", ".", "append", "(", "self", ".", "alias_flags", "[", "k", "]", ")", "else", ":", "# eval the KV assignment", "self", ".", "_exec_config_str", "(", "k", ",", "v", ")", "for", "subc", "in", "subcs", ":", "self", ".", "_load_flag", "(", "subc", ")", "if", "self", ".", "extra_args", ":", "sub_parser", "=", "KeyValueConfigLoader", "(", ")", "sub_parser", ".", "load_config", "(", "self", ".", "extra_args", ")", "self", ".", "config", ".", "_merge", "(", "sub_parser", ".", "config", ")", "self", ".", "extra_args", "=", "sub_parser", ".", "extra_args" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
find_module
imp.find_module variant that only return path of module. The `imp.find_module` returns a filehandle that we are not interested in. Also we ignore any bytecode files that `imp.find_module` finds. Parameters ---------- name : str name of module to locate path : list of str list of paths to search for `name`. If path=None then search sys.path Returns ------- filename : str Return full path of module or None if module is missing or does not have .py or .pyw extension
environment/lib/python2.7/site-packages/IPython/utils/module_paths.py
def find_module(name, path=None): """imp.find_module variant that only return path of module. The `imp.find_module` returns a filehandle that we are not interested in. Also we ignore any bytecode files that `imp.find_module` finds. Parameters ---------- name : str name of module to locate path : list of str list of paths to search for `name`. If path=None then search sys.path Returns ------- filename : str Return full path of module or None if module is missing or does not have .py or .pyw extension """ if name is None: return None try: file, filename, _ = imp.find_module(name, path) except ImportError: return None if file is None: return filename else: file.close() if os.path.splitext(filename)[1] in [".py", "pyc"]: return filename else: return None
def find_module(name, path=None): """imp.find_module variant that only return path of module. The `imp.find_module` returns a filehandle that we are not interested in. Also we ignore any bytecode files that `imp.find_module` finds. Parameters ---------- name : str name of module to locate path : list of str list of paths to search for `name`. If path=None then search sys.path Returns ------- filename : str Return full path of module or None if module is missing or does not have .py or .pyw extension """ if name is None: return None try: file, filename, _ = imp.find_module(name, path) except ImportError: return None if file is None: return filename else: file.close() if os.path.splitext(filename)[1] in [".py", "pyc"]: return filename else: return None
[ "imp", ".", "find_module", "variant", "that", "only", "return", "path", "of", "module", ".", "The", "imp", ".", "find_module", "returns", "a", "filehandle", "that", "we", "are", "not", "interested", "in", ".", "Also", "we", "ignore", "any", "bytecode", "files", "that", "imp", ".", "find_module", "finds", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/module_paths.py#L48-L80
[ "def", "find_module", "(", "name", ",", "path", "=", "None", ")", ":", "if", "name", "is", "None", ":", "return", "None", "try", ":", "file", ",", "filename", ",", "_", "=", "imp", ".", "find_module", "(", "name", ",", "path", ")", "except", "ImportError", ":", "return", "None", "if", "file", "is", "None", ":", "return", "filename", "else", ":", "file", ".", "close", "(", ")", "if", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "1", "]", "in", "[", "\".py\"", ",", "\"pyc\"", "]", ":", "return", "filename", "else", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_init
Get __init__ file path for module directory Parameters ---------- dirname : str Find the __init__ file in directory `dirname` Returns ------- init_path : str Path to __init__ file
environment/lib/python2.7/site-packages/IPython/utils/module_paths.py
def get_init(dirname): """Get __init__ file path for module directory Parameters ---------- dirname : str Find the __init__ file in directory `dirname` Returns ------- init_path : str Path to __init__ file """ fbase = os.path.join(dirname, "__init__") for ext in [".py", ".pyw"]: fname = fbase + ext if os.path.isfile(fname): return fname
def get_init(dirname): """Get __init__ file path for module directory Parameters ---------- dirname : str Find the __init__ file in directory `dirname` Returns ------- init_path : str Path to __init__ file """ fbase = os.path.join(dirname, "__init__") for ext in [".py", ".pyw"]: fname = fbase + ext if os.path.isfile(fname): return fname
[ "Get", "__init__", "file", "path", "for", "module", "directory", "Parameters", "----------", "dirname", ":", "str", "Find", "the", "__init__", "file", "in", "directory", "dirname" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/module_paths.py#L82-L99
[ "def", "get_init", "(", "dirname", ")", ":", "fbase", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "\"__init__\"", ")", "for", "ext", "in", "[", "\".py\"", ",", "\".pyw\"", "]", ":", "fname", "=", "fbase", "+", "ext", "if", "os", ".", "path", ".", "isfile", "(", "fname", ")", ":", "return", "fname" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
find_mod
Find module `module_name` on sys.path Return the path to module `module_name`. If `module_name` refers to a module directory then return path to __init__ file. Return full path of module or None if module is missing or does not have .py or .pyw extension. We are not interested in running bytecode. Parameters ---------- module_name : str Returns ------- modulepath : str Path to module `module_name`.
environment/lib/python2.7/site-packages/IPython/utils/module_paths.py
def find_mod(module_name): """Find module `module_name` on sys.path Return the path to module `module_name`. If `module_name` refers to a module directory then return path to __init__ file. Return full path of module or None if module is missing or does not have .py or .pyw extension. We are not interested in running bytecode. Parameters ---------- module_name : str Returns ------- modulepath : str Path to module `module_name`. """ parts = module_name.split(".") basepath = find_module(parts[0]) for submodname in parts[1:]: basepath = find_module(submodname, [basepath]) if basepath and os.path.isdir(basepath): basepath = get_init(basepath) return basepath
def find_mod(module_name): """Find module `module_name` on sys.path Return the path to module `module_name`. If `module_name` refers to a module directory then return path to __init__ file. Return full path of module or None if module is missing or does not have .py or .pyw extension. We are not interested in running bytecode. Parameters ---------- module_name : str Returns ------- modulepath : str Path to module `module_name`. """ parts = module_name.split(".") basepath = find_module(parts[0]) for submodname in parts[1:]: basepath = find_module(submodname, [basepath]) if basepath and os.path.isdir(basepath): basepath = get_init(basepath) return basepath
[ "Find", "module", "module_name", "on", "sys", ".", "path", "Return", "the", "path", "to", "module", "module_name", ".", "If", "module_name", "refers", "to", "a", "module", "directory", "then", "return", "path", "to", "__init__", "file", ".", "Return", "full", "path", "of", "module", "or", "None", "if", "module", "is", "missing", "or", "does", "not", "have", ".", "py", "or", ".", "pyw", "extension", ".", "We", "are", "not", "interested", "in", "running", "bytecode", ".", "Parameters", "----------", "module_name", ":", "str", "Returns", "-------", "modulepath", ":", "str", "Path", "to", "module", "module_name", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/module_paths.py#L102-L125
[ "def", "find_mod", "(", "module_name", ")", ":", "parts", "=", "module_name", ".", "split", "(", "\".\"", ")", "basepath", "=", "find_module", "(", "parts", "[", "0", "]", ")", "for", "submodname", "in", "parts", "[", "1", ":", "]", ":", "basepath", "=", "find_module", "(", "submodname", ",", "[", "basepath", "]", ")", "if", "basepath", "and", "os", ".", "path", ".", "isdir", "(", "basepath", ")", ":", "basepath", "=", "get_init", "(", "basepath", ")", "return", "basepath" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseLauncher.on_stop
Register a callback to be called with this Launcher's stop_data when the process actually finishes.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def on_stop(self, f): """Register a callback to be called with this Launcher's stop_data when the process actually finishes. """ if self.state=='after': return f(self.stop_data) else: self.stop_callbacks.append(f)
def on_stop(self, f): """Register a callback to be called with this Launcher's stop_data when the process actually finishes. """ if self.state=='after': return f(self.stop_data) else: self.stop_callbacks.append(f)
[ "Register", "a", "callback", "to", "be", "called", "with", "this", "Launcher", "s", "stop_data", "when", "the", "process", "actually", "finishes", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L169-L176
[ "def", "on_stop", "(", "self", ",", "f", ")", ":", "if", "self", ".", "state", "==", "'after'", ":", "return", "f", "(", "self", ".", "stop_data", ")", "else", ":", "self", ".", "stop_callbacks", ".", "append", "(", "f", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseLauncher.notify_start
Call this to trigger startup actions. This logs the process startup and sets the state to 'running'. It is a pass-through so it can be used as a callback.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def notify_start(self, data): """Call this to trigger startup actions. This logs the process startup and sets the state to 'running'. It is a pass-through so it can be used as a callback. """ self.log.debug('Process %r started: %r', self.args[0], data) self.start_data = data self.state = 'running' return data
def notify_start(self, data): """Call this to trigger startup actions. This logs the process startup and sets the state to 'running'. It is a pass-through so it can be used as a callback. """ self.log.debug('Process %r started: %r', self.args[0], data) self.start_data = data self.state = 'running' return data
[ "Call", "this", "to", "trigger", "startup", "actions", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L178-L188
[ "def", "notify_start", "(", "self", ",", "data", ")", ":", "self", ".", "log", ".", "debug", "(", "'Process %r started: %r'", ",", "self", ".", "args", "[", "0", "]", ",", "data", ")", "self", ".", "start_data", "=", "data", "self", ".", "state", "=", "'running'", "return", "data" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseLauncher.notify_stop
Call this to trigger process stop actions. This logs the process stopping and sets the state to 'after'. Call this to trigger callbacks registered via :meth:`on_stop`.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def notify_stop(self, data): """Call this to trigger process stop actions. This logs the process stopping and sets the state to 'after'. Call this to trigger callbacks registered via :meth:`on_stop`.""" self.log.debug('Process %r stopped: %r', self.args[0], data) self.stop_data = data self.state = 'after' for i in range(len(self.stop_callbacks)): d = self.stop_callbacks.pop() d(data) return data
def notify_stop(self, data): """Call this to trigger process stop actions. This logs the process stopping and sets the state to 'after'. Call this to trigger callbacks registered via :meth:`on_stop`.""" self.log.debug('Process %r stopped: %r', self.args[0], data) self.stop_data = data self.state = 'after' for i in range(len(self.stop_callbacks)): d = self.stop_callbacks.pop() d(data) return data
[ "Call", "this", "to", "trigger", "process", "stop", "actions", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L190-L202
[ "def", "notify_stop", "(", "self", ",", "data", ")", ":", "self", ".", "log", ".", "debug", "(", "'Process %r stopped: %r'", ",", "self", ".", "args", "[", "0", "]", ",", "data", ")", "self", ".", "stop_data", "=", "data", "self", ".", "state", "=", "'after'", "for", "i", "in", "range", "(", "len", "(", "self", ".", "stop_callbacks", ")", ")", ":", "d", "=", "self", ".", "stop_callbacks", ".", "pop", "(", ")", "d", "(", "data", ")", "return", "data" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
LocalProcessLauncher.interrupt_then_kill
Send INT, wait a delay and then send KILL.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def interrupt_then_kill(self, delay=2.0): """Send INT, wait a delay and then send KILL.""" try: self.signal(SIGINT) except Exception: self.log.debug("interrupt failed") pass self.killer = ioloop.DelayedCallback(lambda : self.signal(SIGKILL), delay*1000, self.loop) self.killer.start()
def interrupt_then_kill(self, delay=2.0): """Send INT, wait a delay and then send KILL.""" try: self.signal(SIGINT) except Exception: self.log.debug("interrupt failed") pass self.killer = ioloop.DelayedCallback(lambda : self.signal(SIGKILL), delay*1000, self.loop) self.killer.start()
[ "Send", "INT", "wait", "a", "delay", "and", "then", "send", "KILL", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L300-L308
[ "def", "interrupt_then_kill", "(", "self", ",", "delay", "=", "2.0", ")", ":", "try", ":", "self", ".", "signal", "(", "SIGINT", ")", "except", "Exception", ":", "self", ".", "log", ".", "debug", "(", "\"interrupt failed\"", ")", "pass", "self", ".", "killer", "=", "ioloop", ".", "DelayedCallback", "(", "lambda", ":", "self", ".", "signal", "(", "SIGKILL", ")", ",", "delay", "*", "1000", ",", "self", ".", "loop", ")", "self", ".", "killer", ".", "start", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
LocalEngineSetLauncher.start
Start n engines by profile or profile_dir.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def start(self, n): """Start n engines by profile or profile_dir.""" dlist = [] for i in range(n): if i > 0: time.sleep(self.delay) el = self.launcher_class(work_dir=self.work_dir, config=self.config, log=self.log, profile_dir=self.profile_dir, cluster_id=self.cluster_id, ) # Copy the engine args over to each engine launcher. el.engine_cmd = copy.deepcopy(self.engine_cmd) el.engine_args = copy.deepcopy(self.engine_args) el.on_stop(self._notice_engine_stopped) d = el.start() self.launchers[i] = el dlist.append(d) self.notify_start(dlist) return dlist
def start(self, n): """Start n engines by profile or profile_dir.""" dlist = [] for i in range(n): if i > 0: time.sleep(self.delay) el = self.launcher_class(work_dir=self.work_dir, config=self.config, log=self.log, profile_dir=self.profile_dir, cluster_id=self.cluster_id, ) # Copy the engine args over to each engine launcher. el.engine_cmd = copy.deepcopy(self.engine_cmd) el.engine_args = copy.deepcopy(self.engine_args) el.on_stop(self._notice_engine_stopped) d = el.start() self.launchers[i] = el dlist.append(d) self.notify_start(dlist) return dlist
[ "Start", "n", "engines", "by", "profile", "or", "profile_dir", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L382-L400
[ "def", "start", "(", "self", ",", "n", ")", ":", "dlist", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "if", "i", ">", "0", ":", "time", ".", "sleep", "(", "self", ".", "delay", ")", "el", "=", "self", ".", "launcher_class", "(", "work_dir", "=", "self", ".", "work_dir", ",", "config", "=", "self", ".", "config", ",", "log", "=", "self", ".", "log", ",", "profile_dir", "=", "self", ".", "profile_dir", ",", "cluster_id", "=", "self", ".", "cluster_id", ",", ")", "# Copy the engine args over to each engine launcher.", "el", ".", "engine_cmd", "=", "copy", ".", "deepcopy", "(", "self", ".", "engine_cmd", ")", "el", ".", "engine_args", "=", "copy", ".", "deepcopy", "(", "self", ".", "engine_args", ")", "el", ".", "on_stop", "(", "self", ".", "_notice_engine_stopped", ")", "d", "=", "el", ".", "start", "(", ")", "self", ".", "launchers", "[", "i", "]", "=", "el", "dlist", ".", "append", "(", "d", ")", "self", ".", "notify_start", "(", "dlist", ")", "return", "dlist" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MPILauncher.find_args
Build self.args using all the fields.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def find_args(self): """Build self.args using all the fields.""" return self.mpi_cmd + ['-n', str(self.n)] + self.mpi_args + \ self.program + self.program_args
def find_args(self): """Build self.args using all the fields.""" return self.mpi_cmd + ['-n', str(self.n)] + self.mpi_args + \ self.program + self.program_args
[ "Build", "self", ".", "args", "using", "all", "the", "fields", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L466-L469
[ "def", "find_args", "(", "self", ")", ":", "return", "self", ".", "mpi_cmd", "+", "[", "'-n'", ",", "str", "(", "self", ".", "n", ")", "]", "+", "self", ".", "mpi_args", "+", "self", ".", "program", "+", "self", ".", "program_args" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MPILauncher.start
Start n instances of the program using mpiexec.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def start(self, n): """Start n instances of the program using mpiexec.""" self.n = n return super(MPILauncher, self).start()
def start(self, n): """Start n instances of the program using mpiexec.""" self.n = n return super(MPILauncher, self).start()
[ "Start", "n", "instances", "of", "the", "program", "using", "mpiexec", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L471-L474
[ "def", "start", "(", "self", ",", "n", ")", ":", "self", ".", "n", "=", "n", "return", "super", "(", "MPILauncher", ",", "self", ")", ".", "start", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
MPIEngineSetLauncher.start
Start n engines by profile or profile_dir.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def start(self, n): """Start n engines by profile or profile_dir.""" self.n = n return super(MPIEngineSetLauncher, self).start(n)
def start(self, n): """Start n engines by profile or profile_dir.""" self.n = n return super(MPIEngineSetLauncher, self).start(n)
[ "Start", "n", "engines", "by", "profile", "or", "profile_dir", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L510-L513
[ "def", "start", "(", "self", ",", "n", ")", ":", "self", ".", "n", "=", "n", "return", "super", "(", "MPIEngineSetLauncher", ",", "self", ")", ".", "start", "(", "n", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SSHLauncher._send_file
send a single file
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def _send_file(self, local, remote): """send a single file""" remote = "%s:%s" % (self.location, remote) for i in range(10): if not os.path.exists(local): self.log.debug("waiting for %s" % local) time.sleep(1) else: break self.log.info("sending %s to %s", local, remote) check_output(self.scp_cmd + [local, remote])
def _send_file(self, local, remote): """send a single file""" remote = "%s:%s" % (self.location, remote) for i in range(10): if not os.path.exists(local): self.log.debug("waiting for %s" % local) time.sleep(1) else: break self.log.info("sending %s to %s", local, remote) check_output(self.scp_cmd + [local, remote])
[ "send", "a", "single", "file" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L589-L599
[ "def", "_send_file", "(", "self", ",", "local", ",", "remote", ")", ":", "remote", "=", "\"%s:%s\"", "%", "(", "self", ".", "location", ",", "remote", ")", "for", "i", "in", "range", "(", "10", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "local", ")", ":", "self", ".", "log", ".", "debug", "(", "\"waiting for %s\"", "%", "local", ")", "time", ".", "sleep", "(", "1", ")", "else", ":", "break", "self", ".", "log", ".", "info", "(", "\"sending %s to %s\"", ",", "local", ",", "remote", ")", "check_output", "(", "self", ".", "scp_cmd", "+", "[", "local", ",", "remote", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SSHLauncher.send_files
send our files (called before start)
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def send_files(self): """send our files (called before start)""" if not self.to_send: return for local_file, remote_file in self.to_send: self._send_file(local_file, remote_file)
def send_files(self): """send our files (called before start)""" if not self.to_send: return for local_file, remote_file in self.to_send: self._send_file(local_file, remote_file)
[ "send", "our", "files", "(", "called", "before", "start", ")" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L601-L606
[ "def", "send_files", "(", "self", ")", ":", "if", "not", "self", ".", "to_send", ":", "return", "for", "local_file", ",", "remote_file", "in", "self", ".", "to_send", ":", "self", ".", "_send_file", "(", "local_file", ",", "remote_file", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SSHLauncher._fetch_file
fetch a single file
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def _fetch_file(self, remote, local): """fetch a single file""" full_remote = "%s:%s" % (self.location, remote) self.log.info("fetching %s from %s", local, full_remote) for i in range(10): # wait up to 10s for remote file to exist check = check_output(self.ssh_cmd + self.ssh_args + \ [self.location, 'test -e', remote, "&& echo 'yes' || echo 'no'"]) check = check.strip() if check == 'no': time.sleep(1) elif check == 'yes': break check_output(self.scp_cmd + [full_remote, local])
def _fetch_file(self, remote, local): """fetch a single file""" full_remote = "%s:%s" % (self.location, remote) self.log.info("fetching %s from %s", local, full_remote) for i in range(10): # wait up to 10s for remote file to exist check = check_output(self.ssh_cmd + self.ssh_args + \ [self.location, 'test -e', remote, "&& echo 'yes' || echo 'no'"]) check = check.strip() if check == 'no': time.sleep(1) elif check == 'yes': break check_output(self.scp_cmd + [full_remote, local])
[ "fetch", "a", "single", "file" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L608-L621
[ "def", "_fetch_file", "(", "self", ",", "remote", ",", "local", ")", ":", "full_remote", "=", "\"%s:%s\"", "%", "(", "self", ".", "location", ",", "remote", ")", "self", ".", "log", ".", "info", "(", "\"fetching %s from %s\"", ",", "local", ",", "full_remote", ")", "for", "i", "in", "range", "(", "10", ")", ":", "# wait up to 10s for remote file to exist", "check", "=", "check_output", "(", "self", ".", "ssh_cmd", "+", "self", ".", "ssh_args", "+", "[", "self", ".", "location", ",", "'test -e'", ",", "remote", ",", "\"&& echo 'yes' || echo 'no'\"", "]", ")", "check", "=", "check", ".", "strip", "(", ")", "if", "check", "==", "'no'", ":", "time", ".", "sleep", "(", "1", ")", "elif", "check", "==", "'yes'", ":", "break", "check_output", "(", "self", ".", "scp_cmd", "+", "[", "full_remote", ",", "local", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SSHLauncher.fetch_files
fetch remote files (called after start)
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def fetch_files(self): """fetch remote files (called after start)""" if not self.to_fetch: return for remote_file, local_file in self.to_fetch: self._fetch_file(remote_file, local_file)
def fetch_files(self): """fetch remote files (called after start)""" if not self.to_fetch: return for remote_file, local_file in self.to_fetch: self._fetch_file(remote_file, local_file)
[ "fetch", "remote", "files", "(", "called", "after", "start", ")" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L623-L628
[ "def", "fetch_files", "(", "self", ")", ":", "if", "not", "self", ".", "to_fetch", ":", "return", "for", "remote_file", ",", "local_file", "in", "self", ".", "to_fetch", ":", "self", ".", "_fetch_file", "(", "remote_file", ",", "local_file", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SSHClusterLauncher._remote_profile_dir_default
turns /home/you/.ipython/profile_foo into .ipython/profile_foo
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def _remote_profile_dir_default(self): """turns /home/you/.ipython/profile_foo into .ipython/profile_foo """ home = get_home_dir() if not home.endswith('/'): home = home+'/' if self.profile_dir.startswith(home): return self.profile_dir[len(home):] else: return self.profile_dir
def _remote_profile_dir_default(self): """turns /home/you/.ipython/profile_foo into .ipython/profile_foo """ home = get_home_dir() if not home.endswith('/'): home = home+'/' if self.profile_dir.startswith(home): return self.profile_dir[len(home):] else: return self.profile_dir
[ "turns", "/", "home", "/", "you", "/", ".", "ipython", "/", "profile_foo", "into", ".", "ipython", "/", "profile_foo" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L654-L664
[ "def", "_remote_profile_dir_default", "(", "self", ")", ":", "home", "=", "get_home_dir", "(", ")", "if", "not", "home", ".", "endswith", "(", "'/'", ")", ":", "home", "=", "home", "+", "'/'", "if", "self", ".", "profile_dir", ".", "startswith", "(", "home", ")", ":", "return", "self", ".", "profile_dir", "[", "len", "(", "home", ")", ":", "]", "else", ":", "return", "self", ".", "profile_dir" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SSHEngineSetLauncher.engine_count
determine engine count from `engines` dict
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def engine_count(self): """determine engine count from `engines` dict""" count = 0 for n in self.engines.itervalues(): if isinstance(n, (tuple,list)): n,args = n count += n return count
def engine_count(self): """determine engine count from `engines` dict""" count = 0 for n in self.engines.itervalues(): if isinstance(n, (tuple,list)): n,args = n count += n return count
[ "determine", "engine", "count", "from", "engines", "dict" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L733-L740
[ "def", "engine_count", "(", "self", ")", ":", "count", "=", "0", "for", "n", "in", "self", ".", "engines", ".", "itervalues", "(", ")", ":", "if", "isinstance", "(", "n", ",", "(", "tuple", ",", "list", ")", ")", ":", "n", ",", "args", "=", "n", "count", "+=", "n", "return", "count" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
SSHEngineSetLauncher.start
Start engines by profile or profile_dir. `n` is ignored, and the `engines` config property is used instead.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def start(self, n): """Start engines by profile or profile_dir. `n` is ignored, and the `engines` config property is used instead. """ dlist = [] for host, n in self.engines.iteritems(): if isinstance(n, (tuple, list)): n, args = n else: args = copy.deepcopy(self.engine_args) if '@' in host: user,host = host.split('@',1) else: user=None for i in range(n): if i > 0: time.sleep(self.delay) el = self.launcher_class(work_dir=self.work_dir, config=self.config, log=self.log, profile_dir=self.profile_dir, cluster_id=self.cluster_id, ) if i > 0: # only send files for the first engine on each host el.to_send = [] # Copy the engine args over to each engine launcher. el.engine_cmd = self.engine_cmd el.engine_args = args el.on_stop(self._notice_engine_stopped) d = el.start(user=user, hostname=host) self.launchers[ "%s/%i" % (host,i) ] = el dlist.append(d) self.notify_start(dlist) return dlist
def start(self, n): """Start engines by profile or profile_dir. `n` is ignored, and the `engines` config property is used instead. """ dlist = [] for host, n in self.engines.iteritems(): if isinstance(n, (tuple, list)): n, args = n else: args = copy.deepcopy(self.engine_args) if '@' in host: user,host = host.split('@',1) else: user=None for i in range(n): if i > 0: time.sleep(self.delay) el = self.launcher_class(work_dir=self.work_dir, config=self.config, log=self.log, profile_dir=self.profile_dir, cluster_id=self.cluster_id, ) if i > 0: # only send files for the first engine on each host el.to_send = [] # Copy the engine args over to each engine launcher. el.engine_cmd = self.engine_cmd el.engine_args = args el.on_stop(self._notice_engine_stopped) d = el.start(user=user, hostname=host) self.launchers[ "%s/%i" % (host,i) ] = el dlist.append(d) self.notify_start(dlist) return dlist
[ "Start", "engines", "by", "profile", "or", "profile_dir", ".", "n", "is", "ignored", "and", "the", "engines", "config", "property", "is", "used", "instead", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L742-L776
[ "def", "start", "(", "self", ",", "n", ")", ":", "dlist", "=", "[", "]", "for", "host", ",", "n", "in", "self", ".", "engines", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "n", ",", "(", "tuple", ",", "list", ")", ")", ":", "n", ",", "args", "=", "n", "else", ":", "args", "=", "copy", ".", "deepcopy", "(", "self", ".", "engine_args", ")", "if", "'@'", "in", "host", ":", "user", ",", "host", "=", "host", ".", "split", "(", "'@'", ",", "1", ")", "else", ":", "user", "=", "None", "for", "i", "in", "range", "(", "n", ")", ":", "if", "i", ">", "0", ":", "time", ".", "sleep", "(", "self", ".", "delay", ")", "el", "=", "self", ".", "launcher_class", "(", "work_dir", "=", "self", ".", "work_dir", ",", "config", "=", "self", ".", "config", ",", "log", "=", "self", ".", "log", ",", "profile_dir", "=", "self", ".", "profile_dir", ",", "cluster_id", "=", "self", ".", "cluster_id", ",", ")", "if", "i", ">", "0", ":", "# only send files for the first engine on each host", "el", ".", "to_send", "=", "[", "]", "# Copy the engine args over to each engine launcher.", "el", ".", "engine_cmd", "=", "self", ".", "engine_cmd", "el", ".", "engine_args", "=", "args", "el", ".", "on_stop", "(", "self", ".", "_notice_engine_stopped", ")", "d", "=", "el", ".", "start", "(", "user", "=", "user", ",", "hostname", "=", "host", ")", "self", ".", "launchers", "[", "\"%s/%i\"", "%", "(", "host", ",", "i", ")", "]", "=", "el", "dlist", ".", "append", "(", "d", ")", "self", ".", "notify_start", "(", "dlist", ")", "return", "dlist" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
WindowsHPCLauncher.start
Start n copies of the process using the Win HPC job scheduler.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def start(self, n): """Start n copies of the process using the Win HPC job scheduler.""" self.write_job_file(n) args = [ 'submit', '/jobfile:%s' % self.job_file, '/scheduler:%s' % self.scheduler ] self.log.debug("Starting Win HPC Job: %s" % (self.job_cmd + ' ' + ' '.join(args),)) output = check_output([self.job_cmd]+args, env=os.environ, cwd=self.work_dir, stderr=STDOUT ) job_id = self.parse_job_id(output) self.notify_start(job_id) return job_id
def start(self, n): """Start n copies of the process using the Win HPC job scheduler.""" self.write_job_file(n) args = [ 'submit', '/jobfile:%s' % self.job_file, '/scheduler:%s' % self.scheduler ] self.log.debug("Starting Win HPC Job: %s" % (self.job_cmd + ' ' + ' '.join(args),)) output = check_output([self.job_cmd]+args, env=os.environ, cwd=self.work_dir, stderr=STDOUT ) job_id = self.parse_job_id(output) self.notify_start(job_id) return job_id
[ "Start", "n", "copies", "of", "the", "process", "using", "the", "Win", "HPC", "job", "scheduler", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L868-L885
[ "def", "start", "(", "self", ",", "n", ")", ":", "self", ".", "write_job_file", "(", "n", ")", "args", "=", "[", "'submit'", ",", "'/jobfile:%s'", "%", "self", ".", "job_file", ",", "'/scheduler:%s'", "%", "self", ".", "scheduler", "]", "self", ".", "log", ".", "debug", "(", "\"Starting Win HPC Job: %s\"", "%", "(", "self", ".", "job_cmd", "+", "' '", "+", "' '", ".", "join", "(", "args", ")", ",", ")", ")", "output", "=", "check_output", "(", "[", "self", ".", "job_cmd", "]", "+", "args", ",", "env", "=", "os", ".", "environ", ",", "cwd", "=", "self", ".", "work_dir", ",", "stderr", "=", "STDOUT", ")", "job_id", "=", "self", ".", "parse_job_id", "(", "output", ")", "self", ".", "notify_start", "(", "job_id", ")", "return", "job_id" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BatchSystemLauncher._context_default
load the default context with the default values for the basic keys because the _trait_changed methods only load the context if they are set to something other than the default value.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def _context_default(self): """load the default context with the default values for the basic keys because the _trait_changed methods only load the context if they are set to something other than the default value. """ return dict(n=1, queue=u'', profile_dir=u'', cluster_id=u'')
def _context_default(self): """load the default context with the default values for the basic keys because the _trait_changed methods only load the context if they are set to something other than the default value. """ return dict(n=1, queue=u'', profile_dir=u'', cluster_id=u'')
[ "load", "the", "default", "context", "with", "the", "default", "values", "for", "the", "basic", "keys" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L1039-L1045
[ "def", "_context_default", "(", "self", ")", ":", "return", "dict", "(", "n", "=", "1", ",", "queue", "=", "u''", ",", "profile_dir", "=", "u''", ",", "cluster_id", "=", "u''", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BatchSystemLauncher.parse_job_id
Take the output of the submit command and return the job id.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def parse_job_id(self, output): """Take the output of the submit command and return the job id.""" m = self.job_id_regexp.search(output) if m is not None: job_id = m.group() else: raise LauncherError("Job id couldn't be determined: %s" % output) self.job_id = job_id self.log.info('Job submitted with job id: %r', job_id) return job_id
def parse_job_id(self, output): """Take the output of the submit command and return the job id.""" m = self.job_id_regexp.search(output) if m is not None: job_id = m.group() else: raise LauncherError("Job id couldn't be determined: %s" % output) self.job_id = job_id self.log.info('Job submitted with job id: %r', job_id) return job_id
[ "Take", "the", "output", "of", "the", "submit", "command", "and", "return", "the", "job", "id", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L1060-L1069
[ "def", "parse_job_id", "(", "self", ",", "output", ")", ":", "m", "=", "self", ".", "job_id_regexp", ".", "search", "(", "output", ")", "if", "m", "is", "not", "None", ":", "job_id", "=", "m", ".", "group", "(", ")", "else", ":", "raise", "LauncherError", "(", "\"Job id couldn't be determined: %s\"", "%", "output", ")", "self", ".", "job_id", "=", "job_id", "self", ".", "log", ".", "info", "(", "'Job submitted with job id: %r'", ",", "job_id", ")", "return", "job_id" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BatchSystemLauncher.write_batch_script
Instantiate and write the batch script to the work_dir.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def write_batch_script(self, n): """Instantiate and write the batch script to the work_dir.""" self.n = n # first priority is batch_template if set if self.batch_template_file and not self.batch_template: # second priority is batch_template_file with open(self.batch_template_file) as f: self.batch_template = f.read() if not self.batch_template: # third (last) priority is default_template self.batch_template = self.default_template # add jobarray or queue lines to user-specified template # note that this is *only* when user did not specify a template. # print self.job_array_regexp.search(self.batch_template) if not self.job_array_regexp.search(self.batch_template): self.log.debug("adding job array settings to batch script") firstline, rest = self.batch_template.split('\n',1) self.batch_template = u'\n'.join([firstline, self.job_array_template, rest]) # print self.queue_regexp.search(self.batch_template) if self.queue and not self.queue_regexp.search(self.batch_template): self.log.debug("adding PBS queue settings to batch script") firstline, rest = self.batch_template.split('\n',1) self.batch_template = u'\n'.join([firstline, self.queue_template, rest]) script_as_string = self.formatter.format(self.batch_template, **self.context) self.log.debug('Writing batch script: %s', self.batch_file) with open(self.batch_file, 'w') as f: f.write(script_as_string) os.chmod(self.batch_file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
def write_batch_script(self, n): """Instantiate and write the batch script to the work_dir.""" self.n = n # first priority is batch_template if set if self.batch_template_file and not self.batch_template: # second priority is batch_template_file with open(self.batch_template_file) as f: self.batch_template = f.read() if not self.batch_template: # third (last) priority is default_template self.batch_template = self.default_template # add jobarray or queue lines to user-specified template # note that this is *only* when user did not specify a template. # print self.job_array_regexp.search(self.batch_template) if not self.job_array_regexp.search(self.batch_template): self.log.debug("adding job array settings to batch script") firstline, rest = self.batch_template.split('\n',1) self.batch_template = u'\n'.join([firstline, self.job_array_template, rest]) # print self.queue_regexp.search(self.batch_template) if self.queue and not self.queue_regexp.search(self.batch_template): self.log.debug("adding PBS queue settings to batch script") firstline, rest = self.batch_template.split('\n',1) self.batch_template = u'\n'.join([firstline, self.queue_template, rest]) script_as_string = self.formatter.format(self.batch_template, **self.context) self.log.debug('Writing batch script: %s', self.batch_file) with open(self.batch_file, 'w') as f: f.write(script_as_string) os.chmod(self.batch_file, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
[ "Instantiate", "and", "write", "the", "batch", "script", "to", "the", "work_dir", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L1071-L1102
[ "def", "write_batch_script", "(", "self", ",", "n", ")", ":", "self", ".", "n", "=", "n", "# first priority is batch_template if set", "if", "self", ".", "batch_template_file", "and", "not", "self", ".", "batch_template", ":", "# second priority is batch_template_file", "with", "open", "(", "self", ".", "batch_template_file", ")", "as", "f", ":", "self", ".", "batch_template", "=", "f", ".", "read", "(", ")", "if", "not", "self", ".", "batch_template", ":", "# third (last) priority is default_template", "self", ".", "batch_template", "=", "self", ".", "default_template", "# add jobarray or queue lines to user-specified template", "# note that this is *only* when user did not specify a template.", "# print self.job_array_regexp.search(self.batch_template)", "if", "not", "self", ".", "job_array_regexp", ".", "search", "(", "self", ".", "batch_template", ")", ":", "self", ".", "log", ".", "debug", "(", "\"adding job array settings to batch script\"", ")", "firstline", ",", "rest", "=", "self", ".", "batch_template", ".", "split", "(", "'\\n'", ",", "1", ")", "self", ".", "batch_template", "=", "u'\\n'", ".", "join", "(", "[", "firstline", ",", "self", ".", "job_array_template", ",", "rest", "]", ")", "# print self.queue_regexp.search(self.batch_template)", "if", "self", ".", "queue", "and", "not", "self", ".", "queue_regexp", ".", "search", "(", "self", ".", "batch_template", ")", ":", "self", ".", "log", ".", "debug", "(", "\"adding PBS queue settings to batch script\"", ")", "firstline", ",", "rest", "=", "self", ".", "batch_template", ".", "split", "(", "'\\n'", ",", "1", ")", "self", ".", "batch_template", "=", "u'\\n'", ".", "join", "(", "[", "firstline", ",", "self", ".", "queue_template", ",", "rest", "]", ")", "script_as_string", "=", "self", ".", "formatter", ".", "format", "(", "self", ".", "batch_template", ",", "*", "*", "self", ".", "context", ")", "self", ".", "log", ".", "debug", "(", "'Writing batch script: %s'", ",", "self", ".", "batch_file", ")", "with", "open", "(", "self", ".", "batch_file", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "script_as_string", ")", "os", ".", "chmod", "(", "self", ".", "batch_file", ",", "stat", ".", "S_IRUSR", "|", "stat", ".", "S_IWUSR", "|", "stat", ".", "S_IXUSR", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BatchSystemLauncher.start
Start n copies of the process using a batch system.
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def start(self, n): """Start n copies of the process using a batch system.""" self.log.debug("Starting %s: %r", self.__class__.__name__, self.args) # Here we save profile_dir in the context so they # can be used in the batch script template as {profile_dir} self.write_batch_script(n) output = check_output(self.args, env=os.environ) job_id = self.parse_job_id(output) self.notify_start(job_id) return job_id
def start(self, n): """Start n copies of the process using a batch system.""" self.log.debug("Starting %s: %r", self.__class__.__name__, self.args) # Here we save profile_dir in the context so they # can be used in the batch script template as {profile_dir} self.write_batch_script(n) output = check_output(self.args, env=os.environ) job_id = self.parse_job_id(output) self.notify_start(job_id) return job_id
[ "Start", "n", "copies", "of", "the", "process", "using", "a", "batch", "system", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L1104-L1114
[ "def", "start", "(", "self", ",", "n", ")", ":", "self", ".", "log", ".", "debug", "(", "\"Starting %s: %r\"", ",", "self", ".", "__class__", ".", "__name__", ",", "self", ".", "args", ")", "# Here we save profile_dir in the context so they", "# can be used in the batch script template as {profile_dir}", "self", ".", "write_batch_script", "(", "n", ")", "output", "=", "check_output", "(", "self", ".", "args", ",", "env", "=", "os", ".", "environ", ")", "job_id", "=", "self", ".", "parse_job_id", "(", "output", ")", "self", ".", "notify_start", "(", "job_id", ")", "return", "job_id" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
LSFLauncher.start
Start n copies of the process using LSF batch system. This cant inherit from the base class because bsub expects to be piped a shell script in order to honor the #BSUB directives : bsub < script
environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py
def start(self, n): """Start n copies of the process using LSF batch system. This cant inherit from the base class because bsub expects to be piped a shell script in order to honor the #BSUB directives : bsub < script """ # Here we save profile_dir in the context so they # can be used in the batch script template as {profile_dir} self.write_batch_script(n) #output = check_output(self.args, env=os.environ) piped_cmd = self.args[0]+'<\"'+self.args[1]+'\"' self.log.debug("Starting %s: %s", self.__class__.__name__, piped_cmd) p = Popen(piped_cmd, shell=True,env=os.environ,stdout=PIPE) output,err = p.communicate() job_id = self.parse_job_id(output) self.notify_start(job_id) return job_id
def start(self, n): """Start n copies of the process using LSF batch system. This cant inherit from the base class because bsub expects to be piped a shell script in order to honor the #BSUB directives : bsub < script """ # Here we save profile_dir in the context so they # can be used in the batch script template as {profile_dir} self.write_batch_script(n) #output = check_output(self.args, env=os.environ) piped_cmd = self.args[0]+'<\"'+self.args[1]+'\"' self.log.debug("Starting %s: %s", self.__class__.__name__, piped_cmd) p = Popen(piped_cmd, shell=True,env=os.environ,stdout=PIPE) output,err = p.communicate() job_id = self.parse_job_id(output) self.notify_start(job_id) return job_id
[ "Start", "n", "copies", "of", "the", "process", "using", "LSF", "batch", "system", ".", "This", "cant", "inherit", "from", "the", "base", "class", "because", "bsub", "expects", "to", "be", "piped", "a", "shell", "script", "in", "order", "to", "honor", "the", "#BSUB", "directives", ":", "bsub", "<", "script" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/launcher.py#L1227-L1243
[ "def", "start", "(", "self", ",", "n", ")", ":", "# Here we save profile_dir in the context so they", "# can be used in the batch script template as {profile_dir}", "self", ".", "write_batch_script", "(", "n", ")", "#output = check_output(self.args, env=os.environ)", "piped_cmd", "=", "self", ".", "args", "[", "0", "]", "+", "'<\\\"'", "+", "self", ".", "args", "[", "1", "]", "+", "'\\\"'", "self", ".", "log", ".", "debug", "(", "\"Starting %s: %s\"", ",", "self", ".", "__class__", ".", "__name__", ",", "piped_cmd", ")", "p", "=", "Popen", "(", "piped_cmd", ",", "shell", "=", "True", ",", "env", "=", "os", ".", "environ", ",", "stdout", "=", "PIPE", ")", "output", ",", "err", "=", "p", ".", "communicate", "(", ")", "job_id", "=", "self", ".", "parse_job_id", "(", "output", ")", "self", ".", "notify_start", "(", "job_id", ")", "return", "job_id" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
check_filemode
Return True if 'file' matches ('permission') which should be entered in octal.
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/linux2/files.py
def check_filemode(filepath, mode): """Return True if 'file' matches ('permission') which should be entered in octal. """ filemode = stat.S_IMODE(os.stat(filepath).st_mode) return (oct(filemode) == mode)
def check_filemode(filepath, mode): """Return True if 'file' matches ('permission') which should be entered in octal. """ filemode = stat.S_IMODE(os.stat(filepath).st_mode) return (oct(filemode) == mode)
[ "Return", "True", "if", "file", "matches", "(", "permission", ")", "which", "should", "be", "entered", "in", "octal", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/linux2/files.py#L147-L152
[ "def", "check_filemode", "(", "filepath", ",", "mode", ")", ":", "filemode", "=", "stat", ".", "S_IMODE", "(", "os", ".", "stat", "(", "filepath", ")", ".", "st_mode", ")", "return", "(", "oct", "(", "filemode", ")", "==", "mode", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._context_menu_make
Reimplemented to return a custom context menu for images.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _context_menu_make(self, pos): """ Reimplemented to return a custom context menu for images. """ format = self._control.cursorForPosition(pos).charFormat() name = format.stringProperty(QtGui.QTextFormat.ImageName) if name: menu = QtGui.QMenu() menu.addAction('Copy Image', lambda: self._copy_image(name)) menu.addAction('Save Image As...', lambda: self._save_image(name)) menu.addSeparator() svg = self._name_to_svg_map.get(name, None) if svg is not None: menu.addSeparator() menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg)) menu.addAction('Save SVG As...', lambda: save_svg(svg, self._control)) else: menu = super(RichIPythonWidget, self)._context_menu_make(pos) return menu
def _context_menu_make(self, pos): """ Reimplemented to return a custom context menu for images. """ format = self._control.cursorForPosition(pos).charFormat() name = format.stringProperty(QtGui.QTextFormat.ImageName) if name: menu = QtGui.QMenu() menu.addAction('Copy Image', lambda: self._copy_image(name)) menu.addAction('Save Image As...', lambda: self._save_image(name)) menu.addSeparator() svg = self._name_to_svg_map.get(name, None) if svg is not None: menu.addSeparator() menu.addAction('Copy SVG', lambda: svg_to_clipboard(svg)) menu.addAction('Save SVG As...', lambda: save_svg(svg, self._control)) else: menu = super(RichIPythonWidget, self)._context_menu_make(pos) return menu
[ "Reimplemented", "to", "return", "a", "custom", "context", "menu", "for", "images", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L78-L98
[ "def", "_context_menu_make", "(", "self", ",", "pos", ")", ":", "format", "=", "self", ".", "_control", ".", "cursorForPosition", "(", "pos", ")", ".", "charFormat", "(", ")", "name", "=", "format", ".", "stringProperty", "(", "QtGui", ".", "QTextFormat", ".", "ImageName", ")", "if", "name", ":", "menu", "=", "QtGui", ".", "QMenu", "(", ")", "menu", ".", "addAction", "(", "'Copy Image'", ",", "lambda", ":", "self", ".", "_copy_image", "(", "name", ")", ")", "menu", ".", "addAction", "(", "'Save Image As...'", ",", "lambda", ":", "self", ".", "_save_image", "(", "name", ")", ")", "menu", ".", "addSeparator", "(", ")", "svg", "=", "self", ".", "_name_to_svg_map", ".", "get", "(", "name", ",", "None", ")", "if", "svg", "is", "not", "None", ":", "menu", ".", "addSeparator", "(", ")", "menu", ".", "addAction", "(", "'Copy SVG'", ",", "lambda", ":", "svg_to_clipboard", "(", "svg", ")", ")", "menu", ".", "addAction", "(", "'Save SVG As...'", ",", "lambda", ":", "save_svg", "(", "svg", ",", "self", ".", "_control", ")", ")", "else", ":", "menu", "=", "super", "(", "RichIPythonWidget", ",", "self", ")", ".", "_context_menu_make", "(", "pos", ")", "return", "menu" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._pre_image_append
Append the Out[] prompt and make the output nicer Shared code for some the following if statement
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _pre_image_append(self, msg, prompt_number): """ Append the Out[] prompt and make the output nicer Shared code for some the following if statement """ self.log.debug("pyout: %s", msg.get('content', '')) self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) self._append_plain_text('\n', True)
def _pre_image_append(self, msg, prompt_number): """ Append the Out[] prompt and make the output nicer Shared code for some the following if statement """ self.log.debug("pyout: %s", msg.get('content', '')) self._append_plain_text(self.output_sep, True) self._append_html(self._make_out_prompt(prompt_number), True) self._append_plain_text('\n', True)
[ "Append", "the", "Out", "[]", "prompt", "and", "make", "the", "output", "nicer" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L103-L111
[ "def", "_pre_image_append", "(", "self", ",", "msg", ",", "prompt_number", ")", ":", "self", ".", "log", ".", "debug", "(", "\"pyout: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "self", ".", "_append_plain_text", "(", "self", ".", "output_sep", ",", "True", ")", "self", ".", "_append_html", "(", "self", ".", "_make_out_prompt", "(", "prompt_number", ")", ",", "True", ")", "self", ".", "_append_plain_text", "(", "'\\n'", ",", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._handle_pyout
Overridden to handle rich data types, like SVG.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _handle_pyout(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data.has_key('image/svg+xml'): self._pre_image_append(msg, prompt_number) self._append_svg(data['image/svg+xml'], True) self._append_html(self.output_sep2, True) elif data.has_key('image/png'): self._pre_image_append(msg, prompt_number) self._append_png(decodestring(data['image/png'].encode('ascii')), True) self._append_html(self.output_sep2, True) elif data.has_key('image/jpeg') and self._jpg_supported: self._pre_image_append(msg, prompt_number) self._append_jpg(decodestring(data['image/jpeg'].encode('ascii')), True) self._append_html(self.output_sep2, True) else: # Default back to the plain text representation. return super(RichIPythonWidget, self)._handle_pyout(msg)
def _handle_pyout(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): content = msg['content'] prompt_number = content.get('execution_count', 0) data = content['data'] if data.has_key('image/svg+xml'): self._pre_image_append(msg, prompt_number) self._append_svg(data['image/svg+xml'], True) self._append_html(self.output_sep2, True) elif data.has_key('image/png'): self._pre_image_append(msg, prompt_number) self._append_png(decodestring(data['image/png'].encode('ascii')), True) self._append_html(self.output_sep2, True) elif data.has_key('image/jpeg') and self._jpg_supported: self._pre_image_append(msg, prompt_number) self._append_jpg(decodestring(data['image/jpeg'].encode('ascii')), True) self._append_html(self.output_sep2, True) else: # Default back to the plain text representation. return super(RichIPythonWidget, self)._handle_pyout(msg)
[ "Overridden", "to", "handle", "rich", "data", "types", "like", "SVG", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L113-L134
[ "def", "_handle_pyout", "(", "self", ",", "msg", ")", ":", "if", "not", "self", ".", "_hidden", "and", "self", ".", "_is_from_this_session", "(", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "prompt_number", "=", "content", ".", "get", "(", "'execution_count'", ",", "0", ")", "data", "=", "content", "[", "'data'", "]", "if", "data", ".", "has_key", "(", "'image/svg+xml'", ")", ":", "self", ".", "_pre_image_append", "(", "msg", ",", "prompt_number", ")", "self", ".", "_append_svg", "(", "data", "[", "'image/svg+xml'", "]", ",", "True", ")", "self", ".", "_append_html", "(", "self", ".", "output_sep2", ",", "True", ")", "elif", "data", ".", "has_key", "(", "'image/png'", ")", ":", "self", ".", "_pre_image_append", "(", "msg", ",", "prompt_number", ")", "self", ".", "_append_png", "(", "decodestring", "(", "data", "[", "'image/png'", "]", ".", "encode", "(", "'ascii'", ")", ")", ",", "True", ")", "self", ".", "_append_html", "(", "self", ".", "output_sep2", ",", "True", ")", "elif", "data", ".", "has_key", "(", "'image/jpeg'", ")", "and", "self", ".", "_jpg_supported", ":", "self", ".", "_pre_image_append", "(", "msg", ",", "prompt_number", ")", "self", ".", "_append_jpg", "(", "decodestring", "(", "data", "[", "'image/jpeg'", "]", ".", "encode", "(", "'ascii'", ")", ")", ",", "True", ")", "self", ".", "_append_html", "(", "self", ".", "output_sep2", ",", "True", ")", "else", ":", "# Default back to the plain text representation.", "return", "super", "(", "RichIPythonWidget", ",", "self", ")", ".", "_handle_pyout", "(", "msg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._handle_display_data
Overridden to handle rich data types, like SVG.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _handle_display_data(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] # Try to use the svg or html representations. # FIXME: Is this the right ordering of things to try? if data.has_key('image/svg+xml'): self.log.debug("display: %s", msg.get('content', '')) svg = data['image/svg+xml'] self._append_svg(svg, True) elif data.has_key('image/png'): self.log.debug("display: %s", msg.get('content', '')) # PNG data is base64 encoded as it passes over the network # in a JSON structure so we decode it. png = decodestring(data['image/png'].encode('ascii')) self._append_png(png, True) elif data.has_key('image/jpeg') and self._jpg_supported: self.log.debug("display: %s", msg.get('content', '')) jpg = decodestring(data['image/jpeg'].encode('ascii')) self._append_jpg(jpg, True) else: # Default back to the plain text representation. return super(RichIPythonWidget, self)._handle_display_data(msg)
def _handle_display_data(self, msg): """ Overridden to handle rich data types, like SVG. """ if not self._hidden and self._is_from_this_session(msg): source = msg['content']['source'] data = msg['content']['data'] metadata = msg['content']['metadata'] # Try to use the svg or html representations. # FIXME: Is this the right ordering of things to try? if data.has_key('image/svg+xml'): self.log.debug("display: %s", msg.get('content', '')) svg = data['image/svg+xml'] self._append_svg(svg, True) elif data.has_key('image/png'): self.log.debug("display: %s", msg.get('content', '')) # PNG data is base64 encoded as it passes over the network # in a JSON structure so we decode it. png = decodestring(data['image/png'].encode('ascii')) self._append_png(png, True) elif data.has_key('image/jpeg') and self._jpg_supported: self.log.debug("display: %s", msg.get('content', '')) jpg = decodestring(data['image/jpeg'].encode('ascii')) self._append_jpg(jpg, True) else: # Default back to the plain text representation. return super(RichIPythonWidget, self)._handle_display_data(msg)
[ "Overridden", "to", "handle", "rich", "data", "types", "like", "SVG", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L136-L161
[ "def", "_handle_display_data", "(", "self", ",", "msg", ")", ":", "if", "not", "self", ".", "_hidden", "and", "self", ".", "_is_from_this_session", "(", "msg", ")", ":", "source", "=", "msg", "[", "'content'", "]", "[", "'source'", "]", "data", "=", "msg", "[", "'content'", "]", "[", "'data'", "]", "metadata", "=", "msg", "[", "'content'", "]", "[", "'metadata'", "]", "# Try to use the svg or html representations.", "# FIXME: Is this the right ordering of things to try?", "if", "data", ".", "has_key", "(", "'image/svg+xml'", ")", ":", "self", ".", "log", ".", "debug", "(", "\"display: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "svg", "=", "data", "[", "'image/svg+xml'", "]", "self", ".", "_append_svg", "(", "svg", ",", "True", ")", "elif", "data", ".", "has_key", "(", "'image/png'", ")", ":", "self", ".", "log", ".", "debug", "(", "\"display: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "# PNG data is base64 encoded as it passes over the network", "# in a JSON structure so we decode it.", "png", "=", "decodestring", "(", "data", "[", "'image/png'", "]", ".", "encode", "(", "'ascii'", ")", ")", "self", ".", "_append_png", "(", "png", ",", "True", ")", "elif", "data", ".", "has_key", "(", "'image/jpeg'", ")", "and", "self", ".", "_jpg_supported", ":", "self", ".", "log", ".", "debug", "(", "\"display: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "jpg", "=", "decodestring", "(", "data", "[", "'image/jpeg'", "]", ".", "encode", "(", "'ascii'", ")", ")", "self", ".", "_append_jpg", "(", "jpg", ",", "True", ")", "else", ":", "# Default back to the plain text representation.", "return", "super", "(", "RichIPythonWidget", ",", "self", ")", ".", "_handle_display_data", "(", "msg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._append_jpg
Append raw JPG data to the widget.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _append_jpg(self, jpg, before_prompt=False): """ Append raw JPG data to the widget.""" self._append_custom(self._insert_jpg, jpg, before_prompt)
def _append_jpg(self, jpg, before_prompt=False): """ Append raw JPG data to the widget.""" self._append_custom(self._insert_jpg, jpg, before_prompt)
[ "Append", "raw", "JPG", "data", "to", "the", "widget", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L167-L169
[ "def", "_append_jpg", "(", "self", ",", "jpg", ",", "before_prompt", "=", "False", ")", ":", "self", ".", "_append_custom", "(", "self", ".", "_insert_jpg", ",", "jpg", ",", "before_prompt", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._append_png
Append raw PNG data to the widget.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _append_png(self, png, before_prompt=False): """ Append raw PNG data to the widget. """ self._append_custom(self._insert_png, png, before_prompt)
def _append_png(self, png, before_prompt=False): """ Append raw PNG data to the widget. """ self._append_custom(self._insert_png, png, before_prompt)
[ "Append", "raw", "PNG", "data", "to", "the", "widget", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L171-L174
[ "def", "_append_png", "(", "self", ",", "png", ",", "before_prompt", "=", "False", ")", ":", "self", ".", "_append_custom", "(", "self", ".", "_insert_png", ",", "png", ",", "before_prompt", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._append_svg
Append raw SVG data to the widget.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _append_svg(self, svg, before_prompt=False): """ Append raw SVG data to the widget. """ self._append_custom(self._insert_svg, svg, before_prompt)
def _append_svg(self, svg, before_prompt=False): """ Append raw SVG data to the widget. """ self._append_custom(self._insert_svg, svg, before_prompt)
[ "Append", "raw", "SVG", "data", "to", "the", "widget", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L176-L179
[ "def", "_append_svg", "(", "self", ",", "svg", ",", "before_prompt", "=", "False", ")", ":", "self", ".", "_append_custom", "(", "self", ".", "_insert_svg", ",", "svg", ",", "before_prompt", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._add_image
Adds the specified QImage to the document and returns a QTextImageFormat that references it.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _add_image(self, image): """ Adds the specified QImage to the document and returns a QTextImageFormat that references it. """ document = self._control.document() name = str(image.cacheKey()) document.addResource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(name), image) format = QtGui.QTextImageFormat() format.setName(name) return format
def _add_image(self, image): """ Adds the specified QImage to the document and returns a QTextImageFormat that references it. """ document = self._control.document() name = str(image.cacheKey()) document.addResource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(name), image) format = QtGui.QTextImageFormat() format.setName(name) return format
[ "Adds", "the", "specified", "QImage", "to", "the", "document", "and", "returns", "a", "QTextImageFormat", "that", "references", "it", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L181-L191
[ "def", "_add_image", "(", "self", ",", "image", ")", ":", "document", "=", "self", ".", "_control", ".", "document", "(", ")", "name", "=", "str", "(", "image", ".", "cacheKey", "(", ")", ")", "document", ".", "addResource", "(", "QtGui", ".", "QTextDocument", ".", "ImageResource", ",", "QtCore", ".", "QUrl", "(", "name", ")", ",", "image", ")", "format", "=", "QtGui", ".", "QTextImageFormat", "(", ")", "format", ".", "setName", "(", "name", ")", "return", "format" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._copy_image
Copies the ImageResource with 'name' to the clipboard.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _copy_image(self, name): """ Copies the ImageResource with 'name' to the clipboard. """ image = self._get_image(name) QtGui.QApplication.clipboard().setImage(image)
def _copy_image(self, name): """ Copies the ImageResource with 'name' to the clipboard. """ image = self._get_image(name) QtGui.QApplication.clipboard().setImage(image)
[ "Copies", "the", "ImageResource", "with", "name", "to", "the", "clipboard", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L193-L197
[ "def", "_copy_image", "(", "self", ",", "name", ")", ":", "image", "=", "self", ".", "_get_image", "(", "name", ")", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setImage", "(", "image", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._get_image
Returns the QImage stored as the ImageResource with 'name'.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _get_image(self, name): """ Returns the QImage stored as the ImageResource with 'name'. """ document = self._control.document() image = document.resource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(name)) return image
def _get_image(self, name): """ Returns the QImage stored as the ImageResource with 'name'. """ document = self._control.document() image = document.resource(QtGui.QTextDocument.ImageResource, QtCore.QUrl(name)) return image
[ "Returns", "the", "QImage", "stored", "as", "the", "ImageResource", "with", "name", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L199-L205
[ "def", "_get_image", "(", "self", ",", "name", ")", ":", "document", "=", "self", ".", "_control", ".", "document", "(", ")", "image", "=", "document", ".", "resource", "(", "QtGui", ".", "QTextDocument", ".", "ImageResource", ",", "QtCore", ".", "QUrl", "(", "name", ")", ")", "return", "image" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._get_image_tag
Return (X)HTML mark-up for the image-tag given by match. Parameters ---------- match : re.SRE_Match A match to an HTML image tag as exported by Qt, with match.group("Name") containing the matched image ID. path : string|None, optional [default None] If not None, specifies a path to which supporting files may be written (e.g., for linked images). If None, all images are to be included inline. format : "png"|"svg"|"jpg", optional [default "png"] Format for returned or referenced images.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _get_image_tag(self, match, path = None, format = "png"): """ Return (X)HTML mark-up for the image-tag given by match. Parameters ---------- match : re.SRE_Match A match to an HTML image tag as exported by Qt, with match.group("Name") containing the matched image ID. path : string|None, optional [default None] If not None, specifies a path to which supporting files may be written (e.g., for linked images). If None, all images are to be included inline. format : "png"|"svg"|"jpg", optional [default "png"] Format for returned or referenced images. """ if format in ("png","jpg"): try: image = self._get_image(match.group("name")) except KeyError: return "<b>Couldn't find image %s</b>" % match.group("name") if path is not None: if not os.path.exists(path): os.mkdir(path) relpath = os.path.basename(path) if image.save("%s/qt_img%s.%s" % (path, match.group("name"), format), "PNG"): return '<img src="%s/qt_img%s.%s">' % (relpath, match.group("name"),format) else: return "<b>Couldn't save image!</b>" else: ba = QtCore.QByteArray() buffer_ = QtCore.QBuffer(ba) buffer_.open(QtCore.QIODevice.WriteOnly) image.save(buffer_, format.upper()) buffer_.close() return '<img src="data:image/%s;base64,\n%s\n" />' % ( format,re.sub(r'(.{60})',r'\1\n',str(ba.toBase64()))) elif format == "svg": try: svg = str(self._name_to_svg_map[match.group("name")]) except KeyError: if not self._svg_warning_displayed: QtGui.QMessageBox.warning(self, 'Error converting PNG to SVG.', 'Cannot convert a PNG to SVG. To fix this, add this ' 'to your ipython config:\n\n' '\tc.InlineBackendConfig.figure_format = \'svg\'\n\n' 'And regenerate the figures.', QtGui.QMessageBox.Ok) self._svg_warning_displayed = True return ("<b>Cannot convert a PNG to SVG.</b> " "To fix this, add this to your config: " "<span>c.InlineBackendConfig.figure_format = 'svg'</span> " "and regenerate the figures.") # Not currently checking path, because it's tricky to find a # cross-browser way to embed external SVG images (e.g., via # object or embed tags). # Chop stand-alone header from matplotlib SVG offset = svg.find("<svg") assert(offset > -1) return svg[offset:] else: return '<b>Unrecognized image format</b>'
def _get_image_tag(self, match, path = None, format = "png"): """ Return (X)HTML mark-up for the image-tag given by match. Parameters ---------- match : re.SRE_Match A match to an HTML image tag as exported by Qt, with match.group("Name") containing the matched image ID. path : string|None, optional [default None] If not None, specifies a path to which supporting files may be written (e.g., for linked images). If None, all images are to be included inline. format : "png"|"svg"|"jpg", optional [default "png"] Format for returned or referenced images. """ if format in ("png","jpg"): try: image = self._get_image(match.group("name")) except KeyError: return "<b>Couldn't find image %s</b>" % match.group("name") if path is not None: if not os.path.exists(path): os.mkdir(path) relpath = os.path.basename(path) if image.save("%s/qt_img%s.%s" % (path, match.group("name"), format), "PNG"): return '<img src="%s/qt_img%s.%s">' % (relpath, match.group("name"),format) else: return "<b>Couldn't save image!</b>" else: ba = QtCore.QByteArray() buffer_ = QtCore.QBuffer(ba) buffer_.open(QtCore.QIODevice.WriteOnly) image.save(buffer_, format.upper()) buffer_.close() return '<img src="data:image/%s;base64,\n%s\n" />' % ( format,re.sub(r'(.{60})',r'\1\n',str(ba.toBase64()))) elif format == "svg": try: svg = str(self._name_to_svg_map[match.group("name")]) except KeyError: if not self._svg_warning_displayed: QtGui.QMessageBox.warning(self, 'Error converting PNG to SVG.', 'Cannot convert a PNG to SVG. To fix this, add this ' 'to your ipython config:\n\n' '\tc.InlineBackendConfig.figure_format = \'svg\'\n\n' 'And regenerate the figures.', QtGui.QMessageBox.Ok) self._svg_warning_displayed = True return ("<b>Cannot convert a PNG to SVG.</b> " "To fix this, add this to your config: " "<span>c.InlineBackendConfig.figure_format = 'svg'</span> " "and regenerate the figures.") # Not currently checking path, because it's tricky to find a # cross-browser way to embed external SVG images (e.g., via # object or embed tags). # Chop stand-alone header from matplotlib SVG offset = svg.find("<svg") assert(offset > -1) return svg[offset:] else: return '<b>Unrecognized image format</b>'
[ "Return", "(", "X", ")", "HTML", "mark", "-", "up", "for", "the", "image", "-", "tag", "given", "by", "match", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L207-L277
[ "def", "_get_image_tag", "(", "self", ",", "match", ",", "path", "=", "None", ",", "format", "=", "\"png\"", ")", ":", "if", "format", "in", "(", "\"png\"", ",", "\"jpg\"", ")", ":", "try", ":", "image", "=", "self", ".", "_get_image", "(", "match", ".", "group", "(", "\"name\"", ")", ")", "except", "KeyError", ":", "return", "\"<b>Couldn't find image %s</b>\"", "%", "match", ".", "group", "(", "\"name\"", ")", "if", "path", "is", "not", "None", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "os", ".", "mkdir", "(", "path", ")", "relpath", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "image", ".", "save", "(", "\"%s/qt_img%s.%s\"", "%", "(", "path", ",", "match", ".", "group", "(", "\"name\"", ")", ",", "format", ")", ",", "\"PNG\"", ")", ":", "return", "'<img src=\"%s/qt_img%s.%s\">'", "%", "(", "relpath", ",", "match", ".", "group", "(", "\"name\"", ")", ",", "format", ")", "else", ":", "return", "\"<b>Couldn't save image!</b>\"", "else", ":", "ba", "=", "QtCore", ".", "QByteArray", "(", ")", "buffer_", "=", "QtCore", ".", "QBuffer", "(", "ba", ")", "buffer_", ".", "open", "(", "QtCore", ".", "QIODevice", ".", "WriteOnly", ")", "image", ".", "save", "(", "buffer_", ",", "format", ".", "upper", "(", ")", ")", "buffer_", ".", "close", "(", ")", "return", "'<img src=\"data:image/%s;base64,\\n%s\\n\" />'", "%", "(", "format", ",", "re", ".", "sub", "(", "r'(.{60})'", ",", "r'\\1\\n'", ",", "str", "(", "ba", ".", "toBase64", "(", ")", ")", ")", ")", "elif", "format", "==", "\"svg\"", ":", "try", ":", "svg", "=", "str", "(", "self", ".", "_name_to_svg_map", "[", "match", ".", "group", "(", "\"name\"", ")", "]", ")", "except", "KeyError", ":", "if", "not", "self", ".", "_svg_warning_displayed", ":", "QtGui", ".", "QMessageBox", ".", "warning", "(", "self", ",", "'Error converting PNG to SVG.'", ",", "'Cannot convert a PNG to SVG. To fix this, add this '", "'to your ipython config:\\n\\n'", "'\\tc.InlineBackendConfig.figure_format = \\'svg\\'\\n\\n'", "'And regenerate the figures.'", ",", "QtGui", ".", "QMessageBox", ".", "Ok", ")", "self", ".", "_svg_warning_displayed", "=", "True", "return", "(", "\"<b>Cannot convert a PNG to SVG.</b> \"", "\"To fix this, add this to your config: \"", "\"<span>c.InlineBackendConfig.figure_format = 'svg'</span> \"", "\"and regenerate the figures.\"", ")", "# Not currently checking path, because it's tricky to find a", "# cross-browser way to embed external SVG images (e.g., via", "# object or embed tags).", "# Chop stand-alone header from matplotlib SVG", "offset", "=", "svg", ".", "find", "(", "\"<svg\"", ")", "assert", "(", "offset", ">", "-", "1", ")", "return", "svg", "[", "offset", ":", "]", "else", ":", "return", "'<b>Unrecognized image format</b>'" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._insert_img
insert a raw image, jpg or png
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _insert_img(self, cursor, img, fmt): """ insert a raw image, jpg or png """ try: image = QtGui.QImage() image.loadFromData(img, fmt.upper()) except ValueError: self._insert_plain_text(cursor, 'Received invalid %s data.'%fmt) else: format = self._add_image(image) cursor.insertBlock() cursor.insertImage(format) cursor.insertBlock()
def _insert_img(self, cursor, img, fmt): """ insert a raw image, jpg or png """ try: image = QtGui.QImage() image.loadFromData(img, fmt.upper()) except ValueError: self._insert_plain_text(cursor, 'Received invalid %s data.'%fmt) else: format = self._add_image(image) cursor.insertBlock() cursor.insertImage(format) cursor.insertBlock()
[ "insert", "a", "raw", "image", "jpg", "or", "png" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L288-L299
[ "def", "_insert_img", "(", "self", ",", "cursor", ",", "img", ",", "fmt", ")", ":", "try", ":", "image", "=", "QtGui", ".", "QImage", "(", ")", "image", ".", "loadFromData", "(", "img", ",", "fmt", ".", "upper", "(", ")", ")", "except", "ValueError", ":", "self", ".", "_insert_plain_text", "(", "cursor", ",", "'Received invalid %s data.'", "%", "fmt", ")", "else", ":", "format", "=", "self", ".", "_add_image", "(", "image", ")", "cursor", ".", "insertBlock", "(", ")", "cursor", ".", "insertImage", "(", "format", ")", "cursor", ".", "insertBlock", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._insert_svg
Insert raw SVG data into the widet.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _insert_svg(self, cursor, svg): """ Insert raw SVG data into the widet. """ try: image = svg_to_image(svg) except ValueError: self._insert_plain_text(cursor, 'Received invalid SVG data.') else: format = self._add_image(image) self._name_to_svg_map[format.name()] = svg cursor.insertBlock() cursor.insertImage(format) cursor.insertBlock()
def _insert_svg(self, cursor, svg): """ Insert raw SVG data into the widet. """ try: image = svg_to_image(svg) except ValueError: self._insert_plain_text(cursor, 'Received invalid SVG data.') else: format = self._add_image(image) self._name_to_svg_map[format.name()] = svg cursor.insertBlock() cursor.insertImage(format) cursor.insertBlock()
[ "Insert", "raw", "SVG", "data", "into", "the", "widet", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L301-L313
[ "def", "_insert_svg", "(", "self", ",", "cursor", ",", "svg", ")", ":", "try", ":", "image", "=", "svg_to_image", "(", "svg", ")", "except", "ValueError", ":", "self", ".", "_insert_plain_text", "(", "cursor", ",", "'Received invalid SVG data.'", ")", "else", ":", "format", "=", "self", ".", "_add_image", "(", "image", ")", "self", ".", "_name_to_svg_map", "[", "format", ".", "name", "(", ")", "]", "=", "svg", "cursor", ".", "insertBlock", "(", ")", "cursor", ".", "insertImage", "(", "format", ")", "cursor", ".", "insertBlock", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RichIPythonWidget._save_image
Shows a save dialog for the ImageResource with 'name'.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py
def _save_image(self, name, format='PNG'): """ Shows a save dialog for the ImageResource with 'name'. """ dialog = QtGui.QFileDialog(self._control, 'Save Image') dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix(format.lower()) dialog.setNameFilter('%s file (*.%s)' % (format, format.lower())) if dialog.exec_(): filename = dialog.selectedFiles()[0] image = self._get_image(name) image.save(filename, format)
def _save_image(self, name, format='PNG'): """ Shows a save dialog for the ImageResource with 'name'. """ dialog = QtGui.QFileDialog(self._control, 'Save Image') dialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) dialog.setDefaultSuffix(format.lower()) dialog.setNameFilter('%s file (*.%s)' % (format, format.lower())) if dialog.exec_(): filename = dialog.selectedFiles()[0] image = self._get_image(name) image.save(filename, format)
[ "Shows", "a", "save", "dialog", "for", "the", "ImageResource", "with", "name", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/rich_ipython_widget.py#L315-L325
[ "def", "_save_image", "(", "self", ",", "name", ",", "format", "=", "'PNG'", ")", ":", "dialog", "=", "QtGui", ".", "QFileDialog", "(", "self", ".", "_control", ",", "'Save Image'", ")", "dialog", ".", "setAcceptMode", "(", "QtGui", ".", "QFileDialog", ".", "AcceptSave", ")", "dialog", ".", "setDefaultSuffix", "(", "format", ".", "lower", "(", ")", ")", "dialog", ".", "setNameFilter", "(", "'%s file (*.%s)'", "%", "(", "format", ",", "format", ".", "lower", "(", ")", ")", ")", "if", "dialog", ".", "exec_", "(", ")", ":", "filename", "=", "dialog", ".", "selectedFiles", "(", ")", "[", "0", "]", "image", "=", "self", ".", "_get_image", "(", "name", ")", "image", ".", "save", "(", "filename", ",", "format", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
safe_unicode
unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on.
environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py
def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return unicode(e) except UnicodeError: pass try: return py3compat.str_to_unicode(str(e)) except UnicodeError: pass try: return py3compat.str_to_unicode(repr(e)) except UnicodeError: pass return u'Unrecoverably corrupt evalue'
def safe_unicode(e): """unicode(e) with various fallbacks. Used for exceptions, which may not be safe to call unicode() on. """ try: return unicode(e) except UnicodeError: pass try: return py3compat.str_to_unicode(str(e)) except UnicodeError: pass try: return py3compat.str_to_unicode(repr(e)) except UnicodeError: pass return u'Unrecoverably corrupt evalue'
[ "unicode", "(", "e", ")", "with", "various", "fallbacks", ".", "Used", "for", "exceptions", "which", "may", "not", "be", "safe", "to", "call", "unicode", "()", "on", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L440-L459
[ "def", "safe_unicode", "(", "e", ")", ":", "try", ":", "return", "unicode", "(", "e", ")", "except", "UnicodeError", ":", "pass", "try", ":", "return", "py3compat", ".", "str_to_unicode", "(", "str", "(", "e", ")", ")", "except", "UnicodeError", ":", "pass", "try", ":", "return", "py3compat", ".", "str_to_unicode", "(", "repr", "(", "e", ")", ")", "except", "UnicodeError", ":", "pass", "return", "u'Unrecoverably corrupt evalue'" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQInteractiveShell._exit_now_changed
stop eventloop when exit_now fires
environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py
def _exit_now_changed(self, name, old, new): """stop eventloop when exit_now fires""" if new: loop = ioloop.IOLoop.instance() loop.add_timeout(time.time()+0.1, loop.stop)
def _exit_now_changed(self, name, old, new): """stop eventloop when exit_now fires""" if new: loop = ioloop.IOLoop.instance() loop.add_timeout(time.time()+0.1, loop.stop)
[ "stop", "eventloop", "when", "exit_now", "fires" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L481-L485
[ "def", "_exit_now_changed", "(", "self", ",", "name", ",", "old", ",", "new", ")", ":", "if", "new", ":", "loop", "=", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", "loop", ".", "add_timeout", "(", "time", ".", "time", "(", ")", "+", "0.1", ",", "loop", ".", "stop", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQInteractiveShell.init_environment
Configure the user's environment.
environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py
def init_environment(self): """Configure the user's environment. """ env = os.environ # These two ensure 'ls' produces nice coloring on BSD-derived systems env['TERM'] = 'xterm-color' env['CLICOLOR'] = '1' # Since normal pagers don't work at all (over pexpect we don't have # single-key control of the subprocess), try to disable paging in # subprocesses as much as possible. env['PAGER'] = 'cat' env['GIT_PAGER'] = 'cat' # And install the payload version of page. install_payload_page()
def init_environment(self): """Configure the user's environment. """ env = os.environ # These two ensure 'ls' produces nice coloring on BSD-derived systems env['TERM'] = 'xterm-color' env['CLICOLOR'] = '1' # Since normal pagers don't work at all (over pexpect we don't have # single-key control of the subprocess), try to disable paging in # subprocesses as much as possible. env['PAGER'] = 'cat' env['GIT_PAGER'] = 'cat' # And install the payload version of page. install_payload_page()
[ "Configure", "the", "user", "s", "environment", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L494-L509
[ "def", "init_environment", "(", "self", ")", ":", "env", "=", "os", ".", "environ", "# These two ensure 'ls' produces nice coloring on BSD-derived systems", "env", "[", "'TERM'", "]", "=", "'xterm-color'", "env", "[", "'CLICOLOR'", "]", "=", "'1'", "# Since normal pagers don't work at all (over pexpect we don't have", "# single-key control of the subprocess), try to disable paging in", "# subprocesses as much as possible.", "env", "[", "'PAGER'", "]", "=", "'cat'", "env", "[", "'GIT_PAGER'", "]", "=", "'cat'", "# And install the payload version of page.", "install_payload_page", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQInteractiveShell.auto_rewrite_input
Called to show the auto-rewritten input for autocall and friends. FIXME: this payload is currently not correctly processed by the frontend.
environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py
def auto_rewrite_input(self, cmd): """Called to show the auto-rewritten input for autocall and friends. FIXME: this payload is currently not correctly processed by the frontend. """ new = self.prompt_manager.render('rewrite') + cmd payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', transformed_input=new, ) self.payload_manager.write_payload(payload)
def auto_rewrite_input(self, cmd): """Called to show the auto-rewritten input for autocall and friends. FIXME: this payload is currently not correctly processed by the frontend. """ new = self.prompt_manager.render('rewrite') + cmd payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input', transformed_input=new, ) self.payload_manager.write_payload(payload)
[ "Called", "to", "show", "the", "auto", "-", "rewritten", "input", "for", "autocall", "and", "friends", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L511-L522
[ "def", "auto_rewrite_input", "(", "self", ",", "cmd", ")", ":", "new", "=", "self", ".", "prompt_manager", ".", "render", "(", "'rewrite'", ")", "+", "cmd", "payload", "=", "dict", "(", "source", "=", "'IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input'", ",", "transformed_input", "=", "new", ",", ")", "self", ".", "payload_manager", ".", "write_payload", "(", "payload", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQInteractiveShell.ask_exit
Engage the exit actions.
environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py
def ask_exit(self): """Engage the exit actions.""" self.exit_now = True payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', exit=True, keepkernel=self.keepkernel_on_exit, ) self.payload_manager.write_payload(payload)
def ask_exit(self): """Engage the exit actions.""" self.exit_now = True payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit', exit=True, keepkernel=self.keepkernel_on_exit, ) self.payload_manager.write_payload(payload)
[ "Engage", "the", "exit", "actions", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L524-L532
[ "def", "ask_exit", "(", "self", ")", ":", "self", ".", "exit_now", "=", "True", "payload", "=", "dict", "(", "source", "=", "'IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit'", ",", "exit", "=", "True", ",", "keepkernel", "=", "self", ".", "keepkernel_on_exit", ",", ")", "self", ".", "payload_manager", ".", "write_payload", "(", "payload", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ZMQInteractiveShell.set_next_input
Send the specified text to the frontend to be presented at the next input cell.
environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py
def set_next_input(self, text): """Send the specified text to the frontend to be presented at the next input cell.""" payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', text=text ) self.payload_manager.write_payload(payload)
def set_next_input(self, text): """Send the specified text to the frontend to be presented at the next input cell.""" payload = dict( source='IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input', text=text ) self.payload_manager.write_payload(payload)
[ "Send", "the", "specified", "text", "to", "the", "frontend", "to", "be", "presented", "at", "the", "next", "input", "cell", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/zmqshell.py#L562-L569
[ "def", "set_next_input", "(", "self", ",", "text", ")", ":", "payload", "=", "dict", "(", "source", "=", "'IPython.zmq.zmqshell.ZMQInteractiveShell.set_next_input'", ",", "text", "=", "text", ")", "self", ".", "payload_manager", ".", "write_payload", "(", "payload", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
check_running
CHECK if process (default=apache2) is not running
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/httpd.py
def check_running(process_name="apache2"): ''' CHECK if process (default=apache2) is not running ''' if not gurumate.base.get_pid_list(process_name): fail("Apache process '%s' doesn't seem to be working" % process_name) return False #unreachable return True
def check_running(process_name="apache2"): ''' CHECK if process (default=apache2) is not running ''' if not gurumate.base.get_pid_list(process_name): fail("Apache process '%s' doesn't seem to be working" % process_name) return False #unreachable return True
[ "CHECK", "if", "process", "(", "default", "=", "apache2", ")", "is", "not", "running" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/httpd.py#L8-L15
[ "def", "check_running", "(", "process_name", "=", "\"apache2\"", ")", ":", "if", "not", "gurumate", ".", "base", ".", "get_pid_list", "(", "process_name", ")", ":", "fail", "(", "\"Apache process '%s' doesn't seem to be working\"", "%", "process_name", ")", "return", "False", "#unreachable", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_listening_ports
returns a list of listening ports for running process (default=apache2)
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/httpd.py
def get_listening_ports(process_name="apache2"): ''' returns a list of listening ports for running process (default=apache2) ''' ports = set() for _, address_info in gurumate.base.get_listening_ports(process_name): ports.add(address_info[1]) return list(ports)
def get_listening_ports(process_name="apache2"): ''' returns a list of listening ports for running process (default=apache2) ''' ports = set() for _, address_info in gurumate.base.get_listening_ports(process_name): ports.add(address_info[1]) return list(ports)
[ "returns", "a", "list", "of", "listening", "ports", "for", "running", "process", "(", "default", "=", "apache2", ")" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/httpd.py#L26-L33
[ "def", "get_listening_ports", "(", "process_name", "=", "\"apache2\"", ")", ":", "ports", "=", "set", "(", ")", "for", "_", ",", "address_info", "in", "gurumate", ".", "base", ".", "get_listening_ports", "(", "process_name", ")", ":", "ports", ".", "add", "(", "address_info", "[", "1", "]", ")", "return", "list", "(", "ports", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
HandyConfigParser.read
Read a filename as UTF-8 configuration data.
virtualEnvironment/lib/python2.7/site-packages/coverage/config.py
def read(self, filename): """Read a filename as UTF-8 configuration data.""" kwargs = {} if sys.version_info >= (3, 2): kwargs['encoding'] = "utf-8" return configparser.RawConfigParser.read(self, filename, **kwargs)
def read(self, filename): """Read a filename as UTF-8 configuration data.""" kwargs = {} if sys.version_info >= (3, 2): kwargs['encoding'] = "utf-8" return configparser.RawConfigParser.read(self, filename, **kwargs)
[ "Read", "a", "filename", "as", "UTF", "-", "8", "configuration", "data", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L16-L21
[ "def", "read", "(", "self", ",", "filename", ")", ":", "kwargs", "=", "{", "}", "if", "sys", ".", "version_info", ">=", "(", "3", ",", "2", ")", ":", "kwargs", "[", "'encoding'", "]", "=", "\"utf-8\"", "return", "configparser", ".", "RawConfigParser", ".", "read", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
HandyConfigParser.getlist
Read a list of strings. The value of `section` and `option` is treated as a comma- and newline- separated list of strings. Each value is stripped of whitespace. Returns the list of strings.
virtualEnvironment/lib/python2.7/site-packages/coverage/config.py
def getlist(self, section, option): """Read a list of strings. The value of `section` and `option` is treated as a comma- and newline- separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, option) values = [] for value_line in value_list.split('\n'): for value in value_line.split(','): value = value.strip() if value: values.append(value) return values
def getlist(self, section, option): """Read a list of strings. The value of `section` and `option` is treated as a comma- and newline- separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, option) values = [] for value_line in value_list.split('\n'): for value in value_line.split(','): value = value.strip() if value: values.append(value) return values
[ "Read", "a", "list", "of", "strings", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L44-L60
[ "def", "getlist", "(", "self", ",", "section", ",", "option", ")", ":", "value_list", "=", "self", ".", "get", "(", "section", ",", "option", ")", "values", "=", "[", "]", "for", "value_line", "in", "value_list", ".", "split", "(", "'\\n'", ")", ":", "for", "value", "in", "value_line", ".", "split", "(", "','", ")", ":", "value", "=", "value", ".", "strip", "(", ")", "if", "value", ":", "values", ".", "append", "(", "value", ")", "return", "values" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
HandyConfigParser.getlinelist
Read a list of full-line strings. The value of `section` and `option` is treated as a newline-separated list of strings. Each value is stripped of whitespace. Returns the list of strings.
virtualEnvironment/lib/python2.7/site-packages/coverage/config.py
def getlinelist(self, section, option): """Read a list of full-line strings. The value of `section` and `option` is treated as a newline-separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, option) return list(filter(None, value_list.split('\n')))
def getlinelist(self, section, option): """Read a list of full-line strings. The value of `section` and `option` is treated as a newline-separated list of strings. Each value is stripped of whitespace. Returns the list of strings. """ value_list = self.get(section, option) return list(filter(None, value_list.split('\n')))
[ "Read", "a", "list", "of", "full", "-", "line", "strings", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L62-L72
[ "def", "getlinelist", "(", "self", ",", "section", ",", "option", ")", ":", "value_list", "=", "self", ".", "get", "(", "section", ",", "option", ")", "return", "list", "(", "filter", "(", "None", ",", "value_list", ".", "split", "(", "'\\n'", ")", ")", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageConfig.from_environment
Read configuration from the `env_var` environment variable.
virtualEnvironment/lib/python2.7/site-packages/coverage/config.py
def from_environment(self, env_var): """Read configuration from the `env_var` environment variable.""" # Timidity: for nose users, read an environment variable. This is a # cheap hack, since the rest of the command line arguments aren't # recognized, but it solves some users' problems. env = os.environ.get(env_var, '') if env: self.timid = ('--timid' in env)
def from_environment(self, env_var): """Read configuration from the `env_var` environment variable.""" # Timidity: for nose users, read an environment variable. This is a # cheap hack, since the rest of the command line arguments aren't # recognized, but it solves some users' problems. env = os.environ.get(env_var, '') if env: self.timid = ('--timid' in env)
[ "Read", "configuration", "from", "the", "env_var", "environment", "variable", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L137-L144
[ "def", "from_environment", "(", "self", ",", "env_var", ")", ":", "# Timidity: for nose users, read an environment variable. This is a", "# cheap hack, since the rest of the command line arguments aren't", "# recognized, but it solves some users' problems.", "env", "=", "os", ".", "environ", ".", "get", "(", "env_var", ",", "''", ")", "if", "env", ":", "self", ".", "timid", "=", "(", "'--timid'", "in", "env", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageConfig.from_args
Read config values from `kwargs`.
virtualEnvironment/lib/python2.7/site-packages/coverage/config.py
def from_args(self, **kwargs): """Read config values from `kwargs`.""" for k, v in iitems(kwargs): if v is not None: if k in self.MUST_BE_LIST and isinstance(v, string_class): v = [v] setattr(self, k, v)
def from_args(self, **kwargs): """Read config values from `kwargs`.""" for k, v in iitems(kwargs): if v is not None: if k in self.MUST_BE_LIST and isinstance(v, string_class): v = [v] setattr(self, k, v)
[ "Read", "config", "values", "from", "kwargs", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L148-L154
[ "def", "from_args", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "k", ",", "v", "in", "iitems", "(", "kwargs", ")", ":", "if", "v", "is", "not", "None", ":", "if", "k", "in", "self", ".", "MUST_BE_LIST", "and", "isinstance", "(", "v", ",", "string_class", ")", ":", "v", "=", "[", "v", "]", "setattr", "(", "self", ",", "k", ",", "v", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageConfig.from_file
Read configuration from a .rc file. `filename` is a file name to read.
virtualEnvironment/lib/python2.7/site-packages/coverage/config.py
def from_file(self, filename): """Read configuration from a .rc file. `filename` is a file name to read. """ self.attempted_config_files.append(filename) cp = HandyConfigParser() files_read = cp.read(filename) if files_read is not None: # return value changed in 2.4 self.config_files.extend(files_read) for option_spec in self.CONFIG_FILE_OPTIONS: self.set_attr_from_config_option(cp, *option_spec) # [paths] is special if cp.has_section('paths'): for option in cp.options('paths'): self.paths[option] = cp.getlist('paths', option)
def from_file(self, filename): """Read configuration from a .rc file. `filename` is a file name to read. """ self.attempted_config_files.append(filename) cp = HandyConfigParser() files_read = cp.read(filename) if files_read is not None: # return value changed in 2.4 self.config_files.extend(files_read) for option_spec in self.CONFIG_FILE_OPTIONS: self.set_attr_from_config_option(cp, *option_spec) # [paths] is special if cp.has_section('paths'): for option in cp.options('paths'): self.paths[option] = cp.getlist('paths', option)
[ "Read", "configuration", "from", "a", ".", "rc", "file", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L156-L175
[ "def", "from_file", "(", "self", ",", "filename", ")", ":", "self", ".", "attempted_config_files", ".", "append", "(", "filename", ")", "cp", "=", "HandyConfigParser", "(", ")", "files_read", "=", "cp", ".", "read", "(", "filename", ")", "if", "files_read", "is", "not", "None", ":", "# return value changed in 2.4", "self", ".", "config_files", ".", "extend", "(", "files_read", ")", "for", "option_spec", "in", "self", ".", "CONFIG_FILE_OPTIONS", ":", "self", ".", "set_attr_from_config_option", "(", "cp", ",", "*", "option_spec", ")", "# [paths] is special", "if", "cp", ".", "has_section", "(", "'paths'", ")", ":", "for", "option", "in", "cp", ".", "options", "(", "'paths'", ")", ":", "self", ".", "paths", "[", "option", "]", "=", "cp", ".", "getlist", "(", "'paths'", ",", "option", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
CoverageConfig.set_attr_from_config_option
Set an attribute on self if it exists in the ConfigParser.
virtualEnvironment/lib/python2.7/site-packages/coverage/config.py
def set_attr_from_config_option(self, cp, attr, where, type_=''): """Set an attribute on self if it exists in the ConfigParser.""" section, option = where.split(":") if cp.has_option(section, option): method = getattr(cp, 'get'+type_) setattr(self, attr, method(section, option))
def set_attr_from_config_option(self, cp, attr, where, type_=''): """Set an attribute on self if it exists in the ConfigParser.""" section, option = where.split(":") if cp.has_option(section, option): method = getattr(cp, 'get'+type_) setattr(self, attr, method(section, option))
[ "Set", "an", "attribute", "on", "self", "if", "it", "exists", "in", "the", "ConfigParser", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/coverage/config.py#L208-L213
[ "def", "set_attr_from_config_option", "(", "self", ",", "cp", ",", "attr", ",", "where", ",", "type_", "=", "''", ")", ":", "section", ",", "option", "=", "where", ".", "split", "(", "\":\"", ")", "if", "cp", ".", "has_option", "(", "section", ",", "option", ")", ":", "method", "=", "getattr", "(", "cp", ",", "'get'", "+", "type_", ")", "setattr", "(", "self", ",", "attr", ",", "method", "(", "section", ",", "option", ")", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
expand_user
Expand '~'-style usernames in strings. This is similar to :func:`os.path.expanduser`, but it computes and returns extra information that will be useful if the input was being used in computing completions, and you wish to return the completions with the original '~' instead of its expanded value. Parameters ---------- path : str String to be expanded. If no ~ is present, the output is the same as the input. Returns ------- newpath : str Result of ~ expansion in the input path. tilde_expand : bool Whether any expansion was performed or not. tilde_val : str The value that ~ was replaced with.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def expand_user(path): """Expand '~'-style usernames in strings. This is similar to :func:`os.path.expanduser`, but it computes and returns extra information that will be useful if the input was being used in computing completions, and you wish to return the completions with the original '~' instead of its expanded value. Parameters ---------- path : str String to be expanded. If no ~ is present, the output is the same as the input. Returns ------- newpath : str Result of ~ expansion in the input path. tilde_expand : bool Whether any expansion was performed or not. tilde_val : str The value that ~ was replaced with. """ # Default values tilde_expand = False tilde_val = '' newpath = path if path.startswith('~'): tilde_expand = True rest = len(path)-1 newpath = os.path.expanduser(path) if rest: tilde_val = newpath[:-rest] else: tilde_val = newpath return newpath, tilde_expand, tilde_val
def expand_user(path): """Expand '~'-style usernames in strings. This is similar to :func:`os.path.expanduser`, but it computes and returns extra information that will be useful if the input was being used in computing completions, and you wish to return the completions with the original '~' instead of its expanded value. Parameters ---------- path : str String to be expanded. If no ~ is present, the output is the same as the input. Returns ------- newpath : str Result of ~ expansion in the input path. tilde_expand : bool Whether any expansion was performed or not. tilde_val : str The value that ~ was replaced with. """ # Default values tilde_expand = False tilde_val = '' newpath = path if path.startswith('~'): tilde_expand = True rest = len(path)-1 newpath = os.path.expanduser(path) if rest: tilde_val = newpath[:-rest] else: tilde_val = newpath return newpath, tilde_expand, tilde_val
[ "Expand", "~", "-", "style", "usernames", "in", "strings", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L132-L169
[ "def", "expand_user", "(", "path", ")", ":", "# Default values", "tilde_expand", "=", "False", "tilde_val", "=", "''", "newpath", "=", "path", "if", "path", ".", "startswith", "(", "'~'", ")", ":", "tilde_expand", "=", "True", "rest", "=", "len", "(", "path", ")", "-", "1", "newpath", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "rest", ":", "tilde_val", "=", "newpath", "[", ":", "-", "rest", "]", "else", ":", "tilde_val", "=", "newpath", "return", "newpath", ",", "tilde_expand", ",", "tilde_val" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
CompletionSplitter.delims
Set the delimiters for line splitting.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def delims(self, delims): """Set the delimiters for line splitting.""" expr = '[' + ''.join('\\'+ c for c in delims) + ']' self._delim_re = re.compile(expr) self._delims = delims self._delim_expr = expr
def delims(self, delims): """Set the delimiters for line splitting.""" expr = '[' + ''.join('\\'+ c for c in delims) + ']' self._delim_re = re.compile(expr) self._delims = delims self._delim_expr = expr
[ "Set", "the", "delimiters", "for", "line", "splitting", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L225-L230
[ "def", "delims", "(", "self", ",", "delims", ")", ":", "expr", "=", "'['", "+", "''", ".", "join", "(", "'\\\\'", "+", "c", "for", "c", "in", "delims", ")", "+", "']'", "self", ".", "_delim_re", "=", "re", ".", "compile", "(", "expr", ")", "self", ".", "_delims", "=", "delims", "self", ".", "_delim_expr", "=", "expr" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e