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
CompletionSplitter.split_line
Split a line of text with a cursor at the given position.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def split_line(self, line, cursor_pos=None): """Split a line of text with a cursor at the given position. """ l = line if cursor_pos is None else line[:cursor_pos] return self._delim_re.split(l)[-1]
def split_line(self, line, cursor_pos=None): """Split a line of text with a cursor at the given position. """ l = line if cursor_pos is None else line[:cursor_pos] return self._delim_re.split(l)[-1]
[ "Split", "a", "line", "of", "text", "with", "a", "cursor", "at", "the", "given", "position", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L232-L236
[ "def", "split_line", "(", "self", ",", "line", ",", "cursor_pos", "=", "None", ")", ":", "l", "=", "line", "if", "cursor_pos", "is", "None", "else", "line", "[", ":", "cursor_pos", "]", "return", "self", ".", "_delim_re", ".", "split", "(", "l", ")", "[", "-", "1", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Completer.global_matches
Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match. """ #print 'Completer->global_matches, txt=%r' % text # dbg matches = [] match_append = matches.append n = len(text) for lst in [keyword.kwlist, __builtin__.__dict__.keys(), self.namespace.keys(), self.global_namespace.keys()]: for word in lst: if word[:n] == text and word != "__builtins__": match_append(word) return matches
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace or self.global_namespace that match. """ #print 'Completer->global_matches, txt=%r' % text # dbg matches = [] match_append = matches.append n = len(text) for lst in [keyword.kwlist, __builtin__.__dict__.keys(), self.namespace.keys(), self.global_namespace.keys()]: for word in lst: if word[:n] == text and word != "__builtins__": match_append(word) return matches
[ "Compute", "matches", "when", "text", "is", "a", "simple", "name", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L306-L324
[ "def", "global_matches", "(", "self", ",", "text", ")", ":", "#print 'Completer->global_matches, txt=%r' % text # dbg", "matches", "=", "[", "]", "match_append", "=", "matches", ".", "append", "n", "=", "len", "(", "text", ")", "for", "lst", "in", "[", "keyword", ".", "kwlist", ",", "__builtin__", ".", "__dict__", ".", "keys", "(", ")", ",", "self", ".", "namespace", ".", "keys", "(", ")", ",", "self", ".", "global_namespace", ".", "keys", "(", ")", "]", ":", "for", "word", "in", "lst", ":", "if", "word", "[", ":", "n", "]", "==", "text", "and", "word", "!=", "\"__builtins__\"", ":", "match_append", "(", "word", ")", "return", "matches" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Completer.attr_matches
Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg # Another option, seems to work great. Catches things like ''.<tab> m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) if m: expr, attr = m.group(1, 3) elif self.greedy: m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) if not m2: return [] expr, attr = m2.group(1,2) else: return [] try: obj = eval(expr, self.namespace) except: try: obj = eval(expr, self.global_namespace) except: return [] if self.limit_to__all__ and hasattr(obj, '__all__'): words = get__all__entries(obj) else: words = dir2(obj) try: words = generics.complete_object(obj, words) except TryNext: pass except Exception: # Silence errors from completion function #raise # dbg pass # Build match list to return n = len(attr) res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] return res
def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class members are are also considered.) WARNING: this can still invoke arbitrary C code, if an object with a __getattr__ hook is evaluated. """ #io.rprint('Completer->attr_matches, txt=%r' % text) # dbg # Another option, seems to work great. Catches things like ''.<tab> m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) if m: expr, attr = m.group(1, 3) elif self.greedy: m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) if not m2: return [] expr, attr = m2.group(1,2) else: return [] try: obj = eval(expr, self.namespace) except: try: obj = eval(expr, self.global_namespace) except: return [] if self.limit_to__all__ and hasattr(obj, '__all__'): words = get__all__entries(obj) else: words = dir2(obj) try: words = generics.complete_object(obj, words) except TryNext: pass except Exception: # Silence errors from completion function #raise # dbg pass # Build match list to return n = len(attr) res = ["%s.%s" % (expr, w) for w in words if w[:n] == attr ] return res
[ "Compute", "matches", "when", "text", "contains", "a", "dot", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L326-L378
[ "def", "attr_matches", "(", "self", ",", "text", ")", ":", "#io.rprint('Completer->attr_matches, txt=%r' % text) # dbg", "# Another option, seems to work great. Catches things like ''.<tab>", "m", "=", "re", ".", "match", "(", "r\"(\\S+(\\.\\w+)*)\\.(\\w*)$\"", ",", "text", ")", "if", "m", ":", "expr", ",", "attr", "=", "m", ".", "group", "(", "1", ",", "3", ")", "elif", "self", ".", "greedy", ":", "m2", "=", "re", ".", "match", "(", "r\"(.+)\\.(\\w*)$\"", ",", "self", ".", "line_buffer", ")", "if", "not", "m2", ":", "return", "[", "]", "expr", ",", "attr", "=", "m2", ".", "group", "(", "1", ",", "2", ")", "else", ":", "return", "[", "]", "try", ":", "obj", "=", "eval", "(", "expr", ",", "self", ".", "namespace", ")", "except", ":", "try", ":", "obj", "=", "eval", "(", "expr", ",", "self", ".", "global_namespace", ")", "except", ":", "return", "[", "]", "if", "self", ".", "limit_to__all__", "and", "hasattr", "(", "obj", ",", "'__all__'", ")", ":", "words", "=", "get__all__entries", "(", "obj", ")", "else", ":", "words", "=", "dir2", "(", "obj", ")", "try", ":", "words", "=", "generics", ".", "complete_object", "(", "obj", ",", "words", ")", "except", "TryNext", ":", "pass", "except", "Exception", ":", "# Silence errors from completion function", "#raise # dbg", "pass", "# Build match list to return", "n", "=", "len", "(", "attr", ")", "res", "=", "[", "\"%s.%s\"", "%", "(", "expr", ",", "w", ")", "for", "w", "in", "words", "if", "w", "[", ":", "n", "]", "==", "attr", "]", "return", "res" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter._greedy_changed
update the splitter and readline delims when greedy is changed
environment/lib/python2.7/site-packages/IPython/core/completer.py
def _greedy_changed(self, name, old, new): """update the splitter and readline delims when greedy is changed""" if new: self.splitter.delims = GREEDY_DELIMS else: self.splitter.delims = DELIMS if self.readline: self.readline.set_completer_delims(self.splitter.delims)
def _greedy_changed(self, name, old, new): """update the splitter and readline delims when greedy is changed""" if new: self.splitter.delims = GREEDY_DELIMS else: self.splitter.delims = DELIMS if self.readline: self.readline.set_completer_delims(self.splitter.delims)
[ "update", "the", "splitter", "and", "readline", "delims", "when", "greedy", "is", "changed" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L394-L402
[ "def", "_greedy_changed", "(", "self", ",", "name", ",", "old", ",", "new", ")", ":", "if", "new", ":", "self", ".", "splitter", ".", "delims", "=", "GREEDY_DELIMS", "else", ":", "self", ".", "splitter", ".", "delims", "=", "DELIMS", "if", "self", ".", "readline", ":", "self", ".", "readline", ".", "set_completer_delims", "(", "self", ".", "splitter", ".", "delims", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter.file_matches
Match filenames, expanding ~USER type strings. Most of the seemingly convoluted logic in this completer is an attempt to handle filenames with spaces in them. And yet it's not quite perfect, because Python's readline doesn't expose all of the GNU readline details needed for this to be done correctly. For a filename with a space in it, the printed completions will be only the parts after what's already been typed (instead of the full completions, as is normally done). I don't think with the current (as of Python 2.3) Python readline it's possible to do better.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def file_matches(self, text): """Match filenames, expanding ~USER type strings. Most of the seemingly convoluted logic in this completer is an attempt to handle filenames with spaces in them. And yet it's not quite perfect, because Python's readline doesn't expose all of the GNU readline details needed for this to be done correctly. For a filename with a space in it, the printed completions will be only the parts after what's already been typed (instead of the full completions, as is normally done). I don't think with the current (as of Python 2.3) Python readline it's possible to do better.""" #io.rprint('Completer->file_matches: <%r>' % text) # dbg # chars that require escaping with backslash - i.e. chars # that readline treats incorrectly as delimiters, but we # don't want to treat as delimiters in filename matching # when escaped with backslash if text.startswith('!'): text = text[1:] text_prefix = '!' else: text_prefix = '' text_until_cursor = self.text_until_cursor # track strings with open quotes open_quotes = has_open_quotes(text_until_cursor) if '(' in text_until_cursor or '[' in text_until_cursor: lsplit = text else: try: # arg_split ~ shlex.split, but with unicode bugs fixed by us lsplit = arg_split(text_until_cursor)[-1] except ValueError: # typically an unmatched ", or backslash without escaped char. if open_quotes: lsplit = text_until_cursor.split(open_quotes)[-1] else: return [] except IndexError: # tab pressed on empty line lsplit = "" if not open_quotes and lsplit != protect_filename(lsplit): # if protectables are found, do matching on the whole escaped name has_protectables = True text0,text = text,lsplit else: has_protectables = False text = os.path.expanduser(text) if text == "": return [text_prefix + protect_filename(f) for f in self.glob("*")] # Compute the matches from the filesystem m0 = self.clean_glob(text.replace('\\','')) if has_protectables: # If we had protectables, we need to revert our changes to the # beginning of filename so that we don't double-write the part # of the filename we have so far len_lsplit = len(lsplit) matches = [text_prefix + text0 + protect_filename(f[len_lsplit:]) for f in m0] else: if open_quotes: # if we have a string with an open quote, we don't need to # protect the names at all (and we _shouldn't_, as it # would cause bugs when the filesystem call is made). matches = m0 else: matches = [text_prefix + protect_filename(f) for f in m0] #io.rprint('mm', matches) # dbg # Mark directories in input list by appending '/' to their names. matches = [x+'/' if os.path.isdir(x) else x for x in matches] return matches
def file_matches(self, text): """Match filenames, expanding ~USER type strings. Most of the seemingly convoluted logic in this completer is an attempt to handle filenames with spaces in them. And yet it's not quite perfect, because Python's readline doesn't expose all of the GNU readline details needed for this to be done correctly. For a filename with a space in it, the printed completions will be only the parts after what's already been typed (instead of the full completions, as is normally done). I don't think with the current (as of Python 2.3) Python readline it's possible to do better.""" #io.rprint('Completer->file_matches: <%r>' % text) # dbg # chars that require escaping with backslash - i.e. chars # that readline treats incorrectly as delimiters, but we # don't want to treat as delimiters in filename matching # when escaped with backslash if text.startswith('!'): text = text[1:] text_prefix = '!' else: text_prefix = '' text_until_cursor = self.text_until_cursor # track strings with open quotes open_quotes = has_open_quotes(text_until_cursor) if '(' in text_until_cursor or '[' in text_until_cursor: lsplit = text else: try: # arg_split ~ shlex.split, but with unicode bugs fixed by us lsplit = arg_split(text_until_cursor)[-1] except ValueError: # typically an unmatched ", or backslash without escaped char. if open_quotes: lsplit = text_until_cursor.split(open_quotes)[-1] else: return [] except IndexError: # tab pressed on empty line lsplit = "" if not open_quotes and lsplit != protect_filename(lsplit): # if protectables are found, do matching on the whole escaped name has_protectables = True text0,text = text,lsplit else: has_protectables = False text = os.path.expanduser(text) if text == "": return [text_prefix + protect_filename(f) for f in self.glob("*")] # Compute the matches from the filesystem m0 = self.clean_glob(text.replace('\\','')) if has_protectables: # If we had protectables, we need to revert our changes to the # beginning of filename so that we don't double-write the part # of the filename we have so far len_lsplit = len(lsplit) matches = [text_prefix + text0 + protect_filename(f[len_lsplit:]) for f in m0] else: if open_quotes: # if we have a string with an open quote, we don't need to # protect the names at all (and we _shouldn't_, as it # would cause bugs when the filesystem call is made). matches = m0 else: matches = [text_prefix + protect_filename(f) for f in m0] #io.rprint('mm', matches) # dbg # Mark directories in input list by appending '/' to their names. matches = [x+'/' if os.path.isdir(x) else x for x in matches] return matches
[ "Match", "filenames", "expanding", "~USER", "type", "strings", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L521-L602
[ "def", "file_matches", "(", "self", ",", "text", ")", ":", "#io.rprint('Completer->file_matches: <%r>' % text) # dbg", "# chars that require escaping with backslash - i.e. chars", "# that readline treats incorrectly as delimiters, but we", "# don't want to treat as delimiters in filename matching", "# when escaped with backslash", "if", "text", ".", "startswith", "(", "'!'", ")", ":", "text", "=", "text", "[", "1", ":", "]", "text_prefix", "=", "'!'", "else", ":", "text_prefix", "=", "''", "text_until_cursor", "=", "self", ".", "text_until_cursor", "# track strings with open quotes", "open_quotes", "=", "has_open_quotes", "(", "text_until_cursor", ")", "if", "'('", "in", "text_until_cursor", "or", "'['", "in", "text_until_cursor", ":", "lsplit", "=", "text", "else", ":", "try", ":", "# arg_split ~ shlex.split, but with unicode bugs fixed by us", "lsplit", "=", "arg_split", "(", "text_until_cursor", ")", "[", "-", "1", "]", "except", "ValueError", ":", "# typically an unmatched \", or backslash without escaped char.", "if", "open_quotes", ":", "lsplit", "=", "text_until_cursor", ".", "split", "(", "open_quotes", ")", "[", "-", "1", "]", "else", ":", "return", "[", "]", "except", "IndexError", ":", "# tab pressed on empty line", "lsplit", "=", "\"\"", "if", "not", "open_quotes", "and", "lsplit", "!=", "protect_filename", "(", "lsplit", ")", ":", "# if protectables are found, do matching on the whole escaped name", "has_protectables", "=", "True", "text0", ",", "text", "=", "text", ",", "lsplit", "else", ":", "has_protectables", "=", "False", "text", "=", "os", ".", "path", ".", "expanduser", "(", "text", ")", "if", "text", "==", "\"\"", ":", "return", "[", "text_prefix", "+", "protect_filename", "(", "f", ")", "for", "f", "in", "self", ".", "glob", "(", "\"*\"", ")", "]", "# Compute the matches from the filesystem", "m0", "=", "self", ".", "clean_glob", "(", "text", ".", "replace", "(", "'\\\\'", ",", "''", ")", ")", "if", "has_protectables", ":", "# If we had protectables, we need to revert our changes to the", "# beginning of filename so that we don't double-write the part", "# of the filename we have so far", "len_lsplit", "=", "len", "(", "lsplit", ")", "matches", "=", "[", "text_prefix", "+", "text0", "+", "protect_filename", "(", "f", "[", "len_lsplit", ":", "]", ")", "for", "f", "in", "m0", "]", "else", ":", "if", "open_quotes", ":", "# if we have a string with an open quote, we don't need to", "# protect the names at all (and we _shouldn't_, as it", "# would cause bugs when the filesystem call is made).", "matches", "=", "m0", "else", ":", "matches", "=", "[", "text_prefix", "+", "protect_filename", "(", "f", ")", "for", "f", "in", "m0", "]", "#io.rprint('mm', matches) # dbg", "# Mark directories in input list by appending '/' to their names.", "matches", "=", "[", "x", "+", "'/'", "if", "os", ".", "path", ".", "isdir", "(", "x", ")", "else", "x", "for", "x", "in", "matches", "]", "return", "matches" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter.magic_matches
Match magics
environment/lib/python2.7/site-packages/IPython/core/completer.py
def magic_matches(self, text): """Match magics""" #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg # Get all shell magics now rather than statically, so magics loaded at # runtime show up too. lsm = self.shell.magics_manager.lsmagic() line_magics = lsm['line'] cell_magics = lsm['cell'] pre = self.magic_escape pre2 = pre+pre # Completion logic: # - user gives %%: only do cell magics # - user gives %: do both line and cell magics # - no prefix: do both # In other words, line magics are skipped if the user gives %% explicitly bare_text = text.lstrip(pre) comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] if not text.startswith(pre2): comp += [ pre+m for m in line_magics if m.startswith(bare_text)] return comp
def magic_matches(self, text): """Match magics""" #print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg # Get all shell magics now rather than statically, so magics loaded at # runtime show up too. lsm = self.shell.magics_manager.lsmagic() line_magics = lsm['line'] cell_magics = lsm['cell'] pre = self.magic_escape pre2 = pre+pre # Completion logic: # - user gives %%: only do cell magics # - user gives %: do both line and cell magics # - no prefix: do both # In other words, line magics are skipped if the user gives %% explicitly bare_text = text.lstrip(pre) comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] if not text.startswith(pre2): comp += [ pre+m for m in line_magics if m.startswith(bare_text)] return comp
[ "Match", "magics" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L604-L624
[ "def", "magic_matches", "(", "self", ",", "text", ")", ":", "#print 'Completer->magic_matches:',text,'lb',self.text_until_cursor # dbg", "# Get all shell magics now rather than statically, so magics loaded at", "# runtime show up too.", "lsm", "=", "self", ".", "shell", ".", "magics_manager", ".", "lsmagic", "(", ")", "line_magics", "=", "lsm", "[", "'line'", "]", "cell_magics", "=", "lsm", "[", "'cell'", "]", "pre", "=", "self", ".", "magic_escape", "pre2", "=", "pre", "+", "pre", "# Completion logic:", "# - user gives %%: only do cell magics", "# - user gives %: do both line and cell magics", "# - no prefix: do both", "# In other words, line magics are skipped if the user gives %% explicitly", "bare_text", "=", "text", ".", "lstrip", "(", "pre", ")", "comp", "=", "[", "pre2", "+", "m", "for", "m", "in", "cell_magics", "if", "m", ".", "startswith", "(", "bare_text", ")", "]", "if", "not", "text", ".", "startswith", "(", "pre2", ")", ":", "comp", "+=", "[", "pre", "+", "m", "for", "m", "in", "line_magics", "if", "m", ".", "startswith", "(", "bare_text", ")", "]", "return", "comp" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter.alias_matches
Match internal system aliases
environment/lib/python2.7/site-packages/IPython/core/completer.py
def alias_matches(self, text): """Match internal system aliases""" #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg # if we are not in the first 'item', alias matching # doesn't make sense - unless we are starting with 'sudo' command. main_text = self.text_until_cursor.lstrip() if ' ' in main_text and not main_text.startswith('sudo'): return [] text = os.path.expanduser(text) aliases = self.alias_table.keys() if text == '': return aliases else: return [a for a in aliases if a.startswith(text)]
def alias_matches(self, text): """Match internal system aliases""" #print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg # if we are not in the first 'item', alias matching # doesn't make sense - unless we are starting with 'sudo' command. main_text = self.text_until_cursor.lstrip() if ' ' in main_text and not main_text.startswith('sudo'): return [] text = os.path.expanduser(text) aliases = self.alias_table.keys() if text == '': return aliases else: return [a for a in aliases if a.startswith(text)]
[ "Match", "internal", "system", "aliases" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L626-L640
[ "def", "alias_matches", "(", "self", ",", "text", ")", ":", "#print 'Completer->alias_matches:',text,'lb',self.text_until_cursor # dbg", "# if we are not in the first 'item', alias matching", "# doesn't make sense - unless we are starting with 'sudo' command.", "main_text", "=", "self", ".", "text_until_cursor", ".", "lstrip", "(", ")", "if", "' '", "in", "main_text", "and", "not", "main_text", ".", "startswith", "(", "'sudo'", ")", ":", "return", "[", "]", "text", "=", "os", ".", "path", ".", "expanduser", "(", "text", ")", "aliases", "=", "self", ".", "alias_table", ".", "keys", "(", ")", "if", "text", "==", "''", ":", "return", "aliases", "else", ":", "return", "[", "a", "for", "a", "in", "aliases", "if", "a", ".", "startswith", "(", "text", ")", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter.python_matches
Match attributes or global python names
environment/lib/python2.7/site-packages/IPython/core/completer.py
def python_matches(self,text): """Match attributes or global python names""" #io.rprint('Completer->python_matches, txt=%r' % text) # dbg if "." in text: try: matches = self.attr_matches(text) if text.endswith('.') and self.omit__names: if self.omit__names == 1: # true if txt is _not_ a __ name, false otherwise: no__name = (lambda txt: re.match(r'.*\.__.*?__',txt) is None) else: # true if txt is _not_ a _ name, false otherwise: no__name = (lambda txt: re.match(r'.*\._.*?',txt) is None) matches = filter(no__name, matches) except NameError: # catches <undefined attributes>.<tab> matches = [] else: matches = self.global_matches(text) return matches
def python_matches(self,text): """Match attributes or global python names""" #io.rprint('Completer->python_matches, txt=%r' % text) # dbg if "." in text: try: matches = self.attr_matches(text) if text.endswith('.') and self.omit__names: if self.omit__names == 1: # true if txt is _not_ a __ name, false otherwise: no__name = (lambda txt: re.match(r'.*\.__.*?__',txt) is None) else: # true if txt is _not_ a _ name, false otherwise: no__name = (lambda txt: re.match(r'.*\._.*?',txt) is None) matches = filter(no__name, matches) except NameError: # catches <undefined attributes>.<tab> matches = [] else: matches = self.global_matches(text) return matches
[ "Match", "attributes", "or", "global", "python", "names" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L642-L665
[ "def", "python_matches", "(", "self", ",", "text", ")", ":", "#io.rprint('Completer->python_matches, txt=%r' % text) # dbg", "if", "\".\"", "in", "text", ":", "try", ":", "matches", "=", "self", ".", "attr_matches", "(", "text", ")", "if", "text", ".", "endswith", "(", "'.'", ")", "and", "self", ".", "omit__names", ":", "if", "self", ".", "omit__names", "==", "1", ":", "# true if txt is _not_ a __ name, false otherwise:", "no__name", "=", "(", "lambda", "txt", ":", "re", ".", "match", "(", "r'.*\\.__.*?__'", ",", "txt", ")", "is", "None", ")", "else", ":", "# true if txt is _not_ a _ name, false otherwise:", "no__name", "=", "(", "lambda", "txt", ":", "re", ".", "match", "(", "r'.*\\._.*?'", ",", "txt", ")", "is", "None", ")", "matches", "=", "filter", "(", "no__name", ",", "matches", ")", "except", "NameError", ":", "# catches <undefined attributes>.<tab>", "matches", "=", "[", "]", "else", ":", "matches", "=", "self", ".", "global_matches", "(", "text", ")", "return", "matches" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter._default_arguments
Return the list of default arguments of obj if it is callable, or empty list otherwise.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def _default_arguments(self, obj): """Return the list of default arguments of obj if it is callable, or empty list otherwise.""" if not (inspect.isfunction(obj) or inspect.ismethod(obj)): # for classes, check for __init__,__new__ if inspect.isclass(obj): obj = (getattr(obj,'__init__',None) or getattr(obj,'__new__',None)) # for all others, check if they are __call__able elif hasattr(obj, '__call__'): obj = obj.__call__ # XXX: is there a way to handle the builtins ? try: args,_,_1,defaults = inspect.getargspec(obj) if defaults: return args[-len(defaults):] except TypeError: pass return []
def _default_arguments(self, obj): """Return the list of default arguments of obj if it is callable, or empty list otherwise.""" if not (inspect.isfunction(obj) or inspect.ismethod(obj)): # for classes, check for __init__,__new__ if inspect.isclass(obj): obj = (getattr(obj,'__init__',None) or getattr(obj,'__new__',None)) # for all others, check if they are __call__able elif hasattr(obj, '__call__'): obj = obj.__call__ # XXX: is there a way to handle the builtins ? try: args,_,_1,defaults = inspect.getargspec(obj) if defaults: return args[-len(defaults):] except TypeError: pass return []
[ "Return", "the", "list", "of", "default", "arguments", "of", "obj", "if", "it", "is", "callable", "or", "empty", "list", "otherwise", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L667-L685
[ "def", "_default_arguments", "(", "self", ",", "obj", ")", ":", "if", "not", "(", "inspect", ".", "isfunction", "(", "obj", ")", "or", "inspect", ".", "ismethod", "(", "obj", ")", ")", ":", "# for classes, check for __init__,__new__", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "obj", "=", "(", "getattr", "(", "obj", ",", "'__init__'", ",", "None", ")", "or", "getattr", "(", "obj", ",", "'__new__'", ",", "None", ")", ")", "# for all others, check if they are __call__able", "elif", "hasattr", "(", "obj", ",", "'__call__'", ")", ":", "obj", "=", "obj", ".", "__call__", "# XXX: is there a way to handle the builtins ?", "try", ":", "args", ",", "_", ",", "_1", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "obj", ")", "if", "defaults", ":", "return", "args", "[", "-", "len", "(", "defaults", ")", ":", "]", "except", "TypeError", ":", "pass", "return", "[", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter.python_func_kw_matches
Match named parameters (kwargs) of the last open function
environment/lib/python2.7/site-packages/IPython/core/completer.py
def python_func_kw_matches(self,text): """Match named parameters (kwargs) of the last open function""" if "." in text: # a parameter cannot be dotted return [] try: regexp = self.__funcParamsRegex except AttributeError: regexp = self.__funcParamsRegex = re.compile(r''' '.*?(?<!\\)' | # single quoted strings or ".*?(?<!\\)" | # double quoted strings or \w+ | # identifier \S # other characters ''', re.VERBOSE | re.DOTALL) # 1. find the nearest identifier that comes before an unclosed # parenthesis before the cursor # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" tokens = regexp.findall(self.text_until_cursor) tokens.reverse() iterTokens = iter(tokens); openPar = 0 for token in iterTokens: if token == ')': openPar -= 1 elif token == '(': openPar += 1 if openPar > 0: # found the last unclosed parenthesis break else: return [] # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) ids = [] isId = re.compile(r'\w+$').match while True: try: ids.append(iterTokens.next()) if not isId(ids[-1]): ids.pop(); break if not iterTokens.next() == '.': break except StopIteration: break # lookup the candidate callable matches either using global_matches # or attr_matches for dotted names if len(ids) == 1: callableMatches = self.global_matches(ids[0]) else: callableMatches = self.attr_matches('.'.join(ids[::-1])) argMatches = [] for callableMatch in callableMatches: try: namedArgs = self._default_arguments(eval(callableMatch, self.namespace)) except: continue for namedArg in namedArgs: if namedArg.startswith(text): argMatches.append("%s=" %namedArg) return argMatches
def python_func_kw_matches(self,text): """Match named parameters (kwargs) of the last open function""" if "." in text: # a parameter cannot be dotted return [] try: regexp = self.__funcParamsRegex except AttributeError: regexp = self.__funcParamsRegex = re.compile(r''' '.*?(?<!\\)' | # single quoted strings or ".*?(?<!\\)" | # double quoted strings or \w+ | # identifier \S # other characters ''', re.VERBOSE | re.DOTALL) # 1. find the nearest identifier that comes before an unclosed # parenthesis before the cursor # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" tokens = regexp.findall(self.text_until_cursor) tokens.reverse() iterTokens = iter(tokens); openPar = 0 for token in iterTokens: if token == ')': openPar -= 1 elif token == '(': openPar += 1 if openPar > 0: # found the last unclosed parenthesis break else: return [] # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) ids = [] isId = re.compile(r'\w+$').match while True: try: ids.append(iterTokens.next()) if not isId(ids[-1]): ids.pop(); break if not iterTokens.next() == '.': break except StopIteration: break # lookup the candidate callable matches either using global_matches # or attr_matches for dotted names if len(ids) == 1: callableMatches = self.global_matches(ids[0]) else: callableMatches = self.attr_matches('.'.join(ids[::-1])) argMatches = [] for callableMatch in callableMatches: try: namedArgs = self._default_arguments(eval(callableMatch, self.namespace)) except: continue for namedArg in namedArgs: if namedArg.startswith(text): argMatches.append("%s=" %namedArg) return argMatches
[ "Match", "named", "parameters", "(", "kwargs", ")", "of", "the", "last", "open", "function" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L687-L744
[ "def", "python_func_kw_matches", "(", "self", ",", "text", ")", ":", "if", "\".\"", "in", "text", ":", "# a parameter cannot be dotted", "return", "[", "]", "try", ":", "regexp", "=", "self", ".", "__funcParamsRegex", "except", "AttributeError", ":", "regexp", "=", "self", ".", "__funcParamsRegex", "=", "re", ".", "compile", "(", "r'''\n '.*?(?<!\\\\)' | # single quoted strings or\n \".*?(?<!\\\\)\" | # double quoted strings or\n \\w+ | # identifier\n \\S # other characters\n '''", ",", "re", ".", "VERBOSE", "|", "re", ".", "DOTALL", ")", "# 1. find the nearest identifier that comes before an unclosed", "# parenthesis before the cursor", "# e.g. for \"foo (1+bar(x), pa<cursor>,a=1)\", the candidate is \"foo\"", "tokens", "=", "regexp", ".", "findall", "(", "self", ".", "text_until_cursor", ")", "tokens", ".", "reverse", "(", ")", "iterTokens", "=", "iter", "(", "tokens", ")", "openPar", "=", "0", "for", "token", "in", "iterTokens", ":", "if", "token", "==", "')'", ":", "openPar", "-=", "1", "elif", "token", "==", "'('", ":", "openPar", "+=", "1", "if", "openPar", ">", "0", ":", "# found the last unclosed parenthesis", "break", "else", ":", "return", "[", "]", "# 2. Concatenate dotted names (\"foo.bar\" for \"foo.bar(x, pa\" )", "ids", "=", "[", "]", "isId", "=", "re", ".", "compile", "(", "r'\\w+$'", ")", ".", "match", "while", "True", ":", "try", ":", "ids", ".", "append", "(", "iterTokens", ".", "next", "(", ")", ")", "if", "not", "isId", "(", "ids", "[", "-", "1", "]", ")", ":", "ids", ".", "pop", "(", ")", "break", "if", "not", "iterTokens", ".", "next", "(", ")", "==", "'.'", ":", "break", "except", "StopIteration", ":", "break", "# lookup the candidate callable matches either using global_matches", "# or attr_matches for dotted names", "if", "len", "(", "ids", ")", "==", "1", ":", "callableMatches", "=", "self", ".", "global_matches", "(", "ids", "[", "0", "]", ")", "else", ":", "callableMatches", "=", "self", ".", "attr_matches", "(", "'.'", ".", "join", "(", "ids", "[", ":", ":", "-", "1", "]", ")", ")", "argMatches", "=", "[", "]", "for", "callableMatch", "in", "callableMatches", ":", "try", ":", "namedArgs", "=", "self", ".", "_default_arguments", "(", "eval", "(", "callableMatch", ",", "self", ".", "namespace", ")", ")", "except", ":", "continue", "for", "namedArg", "in", "namedArgs", ":", "if", "namedArg", ".", "startswith", "(", "text", ")", ":", "argMatches", ".", "append", "(", "\"%s=\"", "%", "namedArg", ")", "return", "argMatches" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter.complete
Find completions for the given text and line context. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Note that both the text and the line_buffer are optional, but at least one of them must be given. Parameters ---------- text : string, optional Text to perform the completion on. If not given, the line buffer is split using the instance's CompletionSplitter object. line_buffer : string, optional If not given, the completer attempts to obtain the current line buffer via readline. This keyword allows clients which are requesting for text completions in non-readline contexts to inform the completer of the entire text. cursor_pos : int, optional Index of the cursor in the full line buffer. Should be provided by remote frontends where kernel has no access to frontend state. Returns ------- text : str Text that was actually used in the completion. matches : list A list of completion matches.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def complete(self, text=None, line_buffer=None, cursor_pos=None): """Find completions for the given text and line context. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Note that both the text and the line_buffer are optional, but at least one of them must be given. Parameters ---------- text : string, optional Text to perform the completion on. If not given, the line buffer is split using the instance's CompletionSplitter object. line_buffer : string, optional If not given, the completer attempts to obtain the current line buffer via readline. This keyword allows clients which are requesting for text completions in non-readline contexts to inform the completer of the entire text. cursor_pos : int, optional Index of the cursor in the full line buffer. Should be provided by remote frontends where kernel has no access to frontend state. Returns ------- text : str Text that was actually used in the completion. matches : list A list of completion matches. """ #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg # if the cursor position isn't given, the only sane assumption we can # make is that it's at the end of the line (the common case) if cursor_pos is None: cursor_pos = len(line_buffer) if text is None else len(text) # if text is either None or an empty string, rely on the line buffer if not text: text = self.splitter.split_line(line_buffer, cursor_pos) # If no line buffer is given, assume the input text is all there was if line_buffer is None: line_buffer = text self.line_buffer = line_buffer self.text_until_cursor = self.line_buffer[:cursor_pos] #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg # Start with a clean slate of completions self.matches[:] = [] custom_res = self.dispatch_custom_completer(text) if custom_res is not None: # did custom completers produce something? self.matches = custom_res else: # Extend the list of completions with the results of each # matcher, so we return results to the user from all # namespaces. if self.merge_completions: self.matches = [] for matcher in self.matchers: try: self.matches.extend(matcher(text)) except: # Show the ugly traceback if the matcher causes an # exception, but do NOT crash the kernel! sys.excepthook(*sys.exc_info()) else: for matcher in self.matchers: self.matches = matcher(text) if self.matches: break # FIXME: we should extend our api to return a dict with completions for # different types of objects. The rlcomplete() method could then # simply collapse the dict into a list for readline, but we'd have # richer completion semantics in other evironments. self.matches = sorted(set(self.matches)) #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg return text, self.matches
def complete(self, text=None, line_buffer=None, cursor_pos=None): """Find completions for the given text and line context. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Note that both the text and the line_buffer are optional, but at least one of them must be given. Parameters ---------- text : string, optional Text to perform the completion on. If not given, the line buffer is split using the instance's CompletionSplitter object. line_buffer : string, optional If not given, the completer attempts to obtain the current line buffer via readline. This keyword allows clients which are requesting for text completions in non-readline contexts to inform the completer of the entire text. cursor_pos : int, optional Index of the cursor in the full line buffer. Should be provided by remote frontends where kernel has no access to frontend state. Returns ------- text : str Text that was actually used in the completion. matches : list A list of completion matches. """ #io.rprint('\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg # if the cursor position isn't given, the only sane assumption we can # make is that it's at the end of the line (the common case) if cursor_pos is None: cursor_pos = len(line_buffer) if text is None else len(text) # if text is either None or an empty string, rely on the line buffer if not text: text = self.splitter.split_line(line_buffer, cursor_pos) # If no line buffer is given, assume the input text is all there was if line_buffer is None: line_buffer = text self.line_buffer = line_buffer self.text_until_cursor = self.line_buffer[:cursor_pos] #io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg # Start with a clean slate of completions self.matches[:] = [] custom_res = self.dispatch_custom_completer(text) if custom_res is not None: # did custom completers produce something? self.matches = custom_res else: # Extend the list of completions with the results of each # matcher, so we return results to the user from all # namespaces. if self.merge_completions: self.matches = [] for matcher in self.matchers: try: self.matches.extend(matcher(text)) except: # Show the ugly traceback if the matcher causes an # exception, but do NOT crash the kernel! sys.excepthook(*sys.exc_info()) else: for matcher in self.matchers: self.matches = matcher(text) if self.matches: break # FIXME: we should extend our api to return a dict with completions for # different types of objects. The rlcomplete() method could then # simply collapse the dict into a list for readline, but we'd have # richer completion semantics in other evironments. self.matches = sorted(set(self.matches)) #io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg return text, self.matches
[ "Find", "completions", "for", "the", "given", "text", "and", "line", "context", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L789-L871
[ "def", "complete", "(", "self", ",", "text", "=", "None", ",", "line_buffer", "=", "None", ",", "cursor_pos", "=", "None", ")", ":", "#io.rprint('\\nCOMP1 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg", "# if the cursor position isn't given, the only sane assumption we can", "# make is that it's at the end of the line (the common case)", "if", "cursor_pos", "is", "None", ":", "cursor_pos", "=", "len", "(", "line_buffer", ")", "if", "text", "is", "None", "else", "len", "(", "text", ")", "# if text is either None or an empty string, rely on the line buffer", "if", "not", "text", ":", "text", "=", "self", ".", "splitter", ".", "split_line", "(", "line_buffer", ",", "cursor_pos", ")", "# If no line buffer is given, assume the input text is all there was", "if", "line_buffer", "is", "None", ":", "line_buffer", "=", "text", "self", ".", "line_buffer", "=", "line_buffer", "self", ".", "text_until_cursor", "=", "self", ".", "line_buffer", "[", ":", "cursor_pos", "]", "#io.rprint('COMP2 %r %r %r' % (text, line_buffer, cursor_pos)) # dbg", "# Start with a clean slate of completions", "self", ".", "matches", "[", ":", "]", "=", "[", "]", "custom_res", "=", "self", ".", "dispatch_custom_completer", "(", "text", ")", "if", "custom_res", "is", "not", "None", ":", "# did custom completers produce something?", "self", ".", "matches", "=", "custom_res", "else", ":", "# Extend the list of completions with the results of each", "# matcher, so we return results to the user from all", "# namespaces.", "if", "self", ".", "merge_completions", ":", "self", ".", "matches", "=", "[", "]", "for", "matcher", "in", "self", ".", "matchers", ":", "try", ":", "self", ".", "matches", ".", "extend", "(", "matcher", "(", "text", ")", ")", "except", ":", "# Show the ugly traceback if the matcher causes an", "# exception, but do NOT crash the kernel!", "sys", ".", "excepthook", "(", "*", "sys", ".", "exc_info", "(", ")", ")", "else", ":", "for", "matcher", "in", "self", ".", "matchers", ":", "self", ".", "matches", "=", "matcher", "(", "text", ")", "if", "self", ".", "matches", ":", "break", "# FIXME: we should extend our api to return a dict with completions for", "# different types of objects. The rlcomplete() method could then", "# simply collapse the dict into a list for readline, but we'd have", "# richer completion semantics in other evironments.", "self", ".", "matches", "=", "sorted", "(", "set", "(", "self", ".", "matches", ")", ")", "#io.rprint('COMP TEXT, MATCHES: %r, %r' % (text, self.matches)) # dbg", "return", "text", ",", "self", ".", "matches" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPCompleter.rlcomplete
Return the state-th possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Parameters ---------- text : string Text to perform the completion on. state : int Counter used by readline.
environment/lib/python2.7/site-packages/IPython/core/completer.py
def rlcomplete(self, text, state): """Return the state-th possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Parameters ---------- text : string Text to perform the completion on. state : int Counter used by readline. """ if state==0: self.line_buffer = line_buffer = self.readline.get_line_buffer() cursor_pos = self.readline.get_endidx() #io.rprint("\nRLCOMPLETE: %r %r %r" % # (text, line_buffer, cursor_pos) ) # dbg # if there is only a tab on a line with only whitespace, instead of # the mostly useless 'do you want to see all million completions' # message, just do the right thing and give the user his tab! # Incidentally, this enables pasting of tabbed text from an editor # (as long as autoindent is off). # It should be noted that at least pyreadline still shows file # completions - is there a way around it? # don't apply this on 'dumb' terminals, such as emacs buffers, so # we don't interfere with their own tab-completion mechanism. if not (self.dumb_terminal or line_buffer.strip()): self.readline.insert_text('\t') sys.stdout.flush() return None # Note: debugging exceptions that may occur in completion is very # tricky, because readline unconditionally silences them. So if # during development you suspect a bug in the completion code, turn # this flag on temporarily by uncommenting the second form (don't # flip the value in the first line, as the '# dbg' marker can be # automatically detected and is used elsewhere). DEBUG = False #DEBUG = True # dbg if DEBUG: try: self.complete(text, line_buffer, cursor_pos) except: import traceback; traceback.print_exc() else: # The normal production version is here # This method computes the self.matches array self.complete(text, line_buffer, cursor_pos) try: return self.matches[state] except IndexError: return None
def rlcomplete(self, text, state): """Return the state-th possible completion for 'text'. This is called successively with state == 0, 1, 2, ... until it returns None. The completion should begin with 'text'. Parameters ---------- text : string Text to perform the completion on. state : int Counter used by readline. """ if state==0: self.line_buffer = line_buffer = self.readline.get_line_buffer() cursor_pos = self.readline.get_endidx() #io.rprint("\nRLCOMPLETE: %r %r %r" % # (text, line_buffer, cursor_pos) ) # dbg # if there is only a tab on a line with only whitespace, instead of # the mostly useless 'do you want to see all million completions' # message, just do the right thing and give the user his tab! # Incidentally, this enables pasting of tabbed text from an editor # (as long as autoindent is off). # It should be noted that at least pyreadline still shows file # completions - is there a way around it? # don't apply this on 'dumb' terminals, such as emacs buffers, so # we don't interfere with their own tab-completion mechanism. if not (self.dumb_terminal or line_buffer.strip()): self.readline.insert_text('\t') sys.stdout.flush() return None # Note: debugging exceptions that may occur in completion is very # tricky, because readline unconditionally silences them. So if # during development you suspect a bug in the completion code, turn # this flag on temporarily by uncommenting the second form (don't # flip the value in the first line, as the '# dbg' marker can be # automatically detected and is used elsewhere). DEBUG = False #DEBUG = True # dbg if DEBUG: try: self.complete(text, line_buffer, cursor_pos) except: import traceback; traceback.print_exc() else: # The normal production version is here # This method computes the self.matches array self.complete(text, line_buffer, cursor_pos) try: return self.matches[state] except IndexError: return None
[ "Return", "the", "state", "-", "th", "possible", "completion", "for", "text", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/completer.py#L873-L933
[ "def", "rlcomplete", "(", "self", ",", "text", ",", "state", ")", ":", "if", "state", "==", "0", ":", "self", ".", "line_buffer", "=", "line_buffer", "=", "self", ".", "readline", ".", "get_line_buffer", "(", ")", "cursor_pos", "=", "self", ".", "readline", ".", "get_endidx", "(", ")", "#io.rprint(\"\\nRLCOMPLETE: %r %r %r\" %", "# (text, line_buffer, cursor_pos) ) # dbg", "# if there is only a tab on a line with only whitespace, instead of", "# the mostly useless 'do you want to see all million completions'", "# message, just do the right thing and give the user his tab!", "# Incidentally, this enables pasting of tabbed text from an editor", "# (as long as autoindent is off).", "# It should be noted that at least pyreadline still shows file", "# completions - is there a way around it?", "# don't apply this on 'dumb' terminals, such as emacs buffers, so", "# we don't interfere with their own tab-completion mechanism.", "if", "not", "(", "self", ".", "dumb_terminal", "or", "line_buffer", ".", "strip", "(", ")", ")", ":", "self", ".", "readline", ".", "insert_text", "(", "'\\t'", ")", "sys", ".", "stdout", ".", "flush", "(", ")", "return", "None", "# Note: debugging exceptions that may occur in completion is very", "# tricky, because readline unconditionally silences them. So if", "# during development you suspect a bug in the completion code, turn", "# this flag on temporarily by uncommenting the second form (don't", "# flip the value in the first line, as the '# dbg' marker can be", "# automatically detected and is used elsewhere).", "DEBUG", "=", "False", "#DEBUG = True # dbg", "if", "DEBUG", ":", "try", ":", "self", ".", "complete", "(", "text", ",", "line_buffer", ",", "cursor_pos", ")", "except", ":", "import", "traceback", "traceback", ".", "print_exc", "(", ")", "else", ":", "# The normal production version is here", "# This method computes the self.matches array", "self", ".", "complete", "(", "text", ",", "line_buffer", ",", "cursor_pos", ")", "try", ":", "return", "self", ".", "matches", "[", "state", "]", "except", "IndexError", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DictDB._match_one
Check if a specific record matches tests.
environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py
def _match_one(self, rec, tests): """Check if a specific record matches tests.""" for key,test in tests.iteritems(): if not test(rec.get(key, None)): return False return True
def _match_one(self, rec, tests): """Check if a specific record matches tests.""" for key,test in tests.iteritems(): if not test(rec.get(key, None)): return False return True
[ "Check", "if", "a", "specific", "record", "matches", "tests", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py#L104-L109
[ "def", "_match_one", "(", "self", ",", "rec", ",", "tests", ")", ":", "for", "key", ",", "test", "in", "tests", ".", "iteritems", "(", ")", ":", "if", "not", "test", "(", "rec", ".", "get", "(", "key", ",", "None", ")", ")", ":", "return", "False", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DictDB._match
Find all the matches for a check dict.
environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py
def _match(self, check): """Find all the matches for a check dict.""" matches = [] tests = {} for k,v in check.iteritems(): if isinstance(v, dict): tests[k] = CompositeFilter(v) else: tests[k] = lambda o: o==v for rec in self._records.itervalues(): if self._match_one(rec, tests): matches.append(copy(rec)) return matches
def _match(self, check): """Find all the matches for a check dict.""" matches = [] tests = {} for k,v in check.iteritems(): if isinstance(v, dict): tests[k] = CompositeFilter(v) else: tests[k] = lambda o: o==v for rec in self._records.itervalues(): if self._match_one(rec, tests): matches.append(copy(rec)) return matches
[ "Find", "all", "the", "matches", "for", "a", "check", "dict", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py#L111-L124
[ "def", "_match", "(", "self", ",", "check", ")", ":", "matches", "=", "[", "]", "tests", "=", "{", "}", "for", "k", ",", "v", "in", "check", ".", "iteritems", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "tests", "[", "k", "]", "=", "CompositeFilter", "(", "v", ")", "else", ":", "tests", "[", "k", "]", "=", "lambda", "o", ":", "o", "==", "v", "for", "rec", "in", "self", ".", "_records", ".", "itervalues", "(", ")", ":", "if", "self", ".", "_match_one", "(", "rec", ",", "tests", ")", ":", "matches", ".", "append", "(", "copy", "(", "rec", ")", ")", "return", "matches" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DictDB._extract_subdict
extract subdict of keys
environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py
def _extract_subdict(self, rec, keys): """extract subdict of keys""" d = {} d['msg_id'] = rec['msg_id'] for key in keys: d[key] = rec[key] return copy(d)
def _extract_subdict(self, rec, keys): """extract subdict of keys""" d = {} d['msg_id'] = rec['msg_id'] for key in keys: d[key] = rec[key] return copy(d)
[ "extract", "subdict", "of", "keys" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py#L126-L132
[ "def", "_extract_subdict", "(", "self", ",", "rec", ",", "keys", ")", ":", "d", "=", "{", "}", "d", "[", "'msg_id'", "]", "=", "rec", "[", "'msg_id'", "]", "for", "key", "in", "keys", ":", "d", "[", "key", "]", "=", "rec", "[", "key", "]", "return", "copy", "(", "d", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DictDB.add_record
Add a new Task Record, by msg_id.
environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" if self._records.has_key(msg_id): raise KeyError("Already have msg_id %r"%(msg_id)) self._records[msg_id] = rec
def add_record(self, msg_id, rec): """Add a new Task Record, by msg_id.""" if self._records.has_key(msg_id): raise KeyError("Already have msg_id %r"%(msg_id)) self._records[msg_id] = rec
[ "Add", "a", "new", "Task", "Record", "by", "msg_id", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py#L134-L138
[ "def", "add_record", "(", "self", ",", "msg_id", ",", "rec", ")", ":", "if", "self", ".", "_records", ".", "has_key", "(", "msg_id", ")", ":", "raise", "KeyError", "(", "\"Already have msg_id %r\"", "%", "(", "msg_id", ")", ")", "self", ".", "_records", "[", "msg_id", "]", "=", "rec" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DictDB.get_record
Get a specific Task Record, by msg_id.
environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" if not msg_id in self._records: raise KeyError("No such msg_id %r"%(msg_id)) return copy(self._records[msg_id])
def get_record(self, msg_id): """Get a specific Task Record, by msg_id.""" if not msg_id in self._records: raise KeyError("No such msg_id %r"%(msg_id)) return copy(self._records[msg_id])
[ "Get", "a", "specific", "Task", "Record", "by", "msg_id", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py#L140-L144
[ "def", "get_record", "(", "self", ",", "msg_id", ")", ":", "if", "not", "msg_id", "in", "self", ".", "_records", ":", "raise", "KeyError", "(", "\"No such msg_id %r\"", "%", "(", "msg_id", ")", ")", "return", "copy", "(", "self", ".", "_records", "[", "msg_id", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DictDB.drop_matching_records
Remove a record from the DB.
environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py
def drop_matching_records(self, check): """Remove a record from the DB.""" matches = self._match(check) for m in matches: del self._records[m['msg_id']]
def drop_matching_records(self, check): """Remove a record from the DB.""" matches = self._match(check) for m in matches: del self._records[m['msg_id']]
[ "Remove", "a", "record", "from", "the", "DB", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py#L150-L154
[ "def", "drop_matching_records", "(", "self", ",", "check", ")", ":", "matches", "=", "self", ".", "_match", "(", "check", ")", "for", "m", "in", "matches", ":", "del", "self", ".", "_records", "[", "m", "[", "'msg_id'", "]", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DictDB.find_records
Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id will *always* be included.
environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id will *always* be included. """ matches = self._match(check) if keys: return [ self._extract_subdict(rec, keys) for rec in matches ] else: return matches
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to extract. msg_id will *always* be included. """ matches = self._match(check) if keys: return [ self._extract_subdict(rec, keys) for rec in matches ] else: return matches
[ "Find", "records", "matching", "a", "query", "dict", "optionally", "extracting", "subset", "of", "keys", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py#L161-L179
[ "def", "find_records", "(", "self", ",", "check", ",", "keys", "=", "None", ")", ":", "matches", "=", "self", ".", "_match", "(", "check", ")", "if", "keys", ":", "return", "[", "self", ".", "_extract_subdict", "(", "rec", ",", "keys", ")", "for", "rec", "in", "matches", "]", "else", ":", "return", "matches" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DictDB.get_history
get all msg_ids, ordered by time submitted.
environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py
def get_history(self): """get all msg_ids, ordered by time submitted.""" msg_ids = self._records.keys() return sorted(msg_ids, key=lambda m: self._records[m]['submitted'])
def get_history(self): """get all msg_ids, ordered by time submitted.""" msg_ids = self._records.keys() return sorted(msg_ids, key=lambda m: self._records[m]['submitted'])
[ "get", "all", "msg_ids", "ordered", "by", "time", "submitted", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/controller/dictdb.py#L182-L185
[ "def", "get_history", "(", "self", ")", ":", "msg_ids", "=", "self", ".", "_records", ".", "keys", "(", ")", "return", "sorted", "(", "msg_ids", ",", "key", "=", "lambda", "m", ":", "self", ".", "_records", "[", "m", "]", "[", "'submitted'", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DisplayHook.quiet
Should we silence the display hook because of ';'?
environment/lib/python2.7/site-packages/IPython/core/displayhook.py
def quiet(self): """Should we silence the display hook because of ';'?""" # do not print output if input ends in ';' try: cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] if cell.rstrip().endswith(';'): return True except IndexError: # some uses of ipshellembed may fail here pass return False
def quiet(self): """Should we silence the display hook because of ';'?""" # do not print output if input ends in ';' try: cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] if cell.rstrip().endswith(';'): return True except IndexError: # some uses of ipshellembed may fail here pass return False
[ "Should", "we", "silence", "the", "display", "hook", "because", "of", ";", "?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/displayhook.py#L95-L105
[ "def", "quiet", "(", "self", ")", ":", "# do not print output if input ends in ';'", "try", ":", "cell", "=", "self", ".", "shell", ".", "history_manager", ".", "input_hist_parsed", "[", "self", ".", "prompt_count", "]", "if", "cell", ".", "rstrip", "(", ")", ".", "endswith", "(", "';'", ")", ":", "return", "True", "except", "IndexError", ":", "# some uses of ipshellembed may fail here", "pass", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DisplayHook.write_output_prompt
Write the output prompt. The default implementation simply writes the prompt to ``io.stdout``.
environment/lib/python2.7/site-packages/IPython/core/displayhook.py
def write_output_prompt(self): """Write the output prompt. The default implementation simply writes the prompt to ``io.stdout``. """ # Use write, not print which adds an extra space. io.stdout.write(self.shell.separate_out) outprompt = self.shell.prompt_manager.render('out') if self.do_full_cache: io.stdout.write(outprompt)
def write_output_prompt(self): """Write the output prompt. The default implementation simply writes the prompt to ``io.stdout``. """ # Use write, not print which adds an extra space. io.stdout.write(self.shell.separate_out) outprompt = self.shell.prompt_manager.render('out') if self.do_full_cache: io.stdout.write(outprompt)
[ "Write", "the", "output", "prompt", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/displayhook.py#L111-L121
[ "def", "write_output_prompt", "(", "self", ")", ":", "# Use write, not print which adds an extra space.", "io", ".", "stdout", ".", "write", "(", "self", ".", "shell", ".", "separate_out", ")", "outprompt", "=", "self", ".", "shell", ".", "prompt_manager", ".", "render", "(", "'out'", ")", "if", "self", ".", "do_full_cache", ":", "io", ".", "stdout", ".", "write", "(", "outprompt", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DisplayHook.write_format_data
Write the format data dict to the frontend. This default version of this method simply writes the plain text representation of the object to ``io.stdout``. Subclasses should override this method to send the entire `format_dict` to the frontends. Parameters ---------- format_dict : dict The format dict for the object passed to `sys.displayhook`.
environment/lib/python2.7/site-packages/IPython/core/displayhook.py
def write_format_data(self, format_dict): """Write the format data dict to the frontend. This default version of this method simply writes the plain text representation of the object to ``io.stdout``. Subclasses should override this method to send the entire `format_dict` to the frontends. Parameters ---------- format_dict : dict The format dict for the object passed to `sys.displayhook`. """ # We want to print because we want to always make sure we have a # newline, even if all the prompt separators are ''. This is the # standard IPython behavior. result_repr = format_dict['text/plain'] if '\n' in result_repr: # So that multi-line strings line up with the left column of # the screen, instead of having the output prompt mess up # their first line. # We use the prompt template instead of the expanded prompt # because the expansion may add ANSI escapes that will interfere # with our ability to determine whether or not we should add # a newline. prompt_template = self.shell.prompt_manager.out_template if prompt_template and not prompt_template.endswith('\n'): # But avoid extraneous empty lines. result_repr = '\n' + result_repr print >>io.stdout, result_repr
def write_format_data(self, format_dict): """Write the format data dict to the frontend. This default version of this method simply writes the plain text representation of the object to ``io.stdout``. Subclasses should override this method to send the entire `format_dict` to the frontends. Parameters ---------- format_dict : dict The format dict for the object passed to `sys.displayhook`. """ # We want to print because we want to always make sure we have a # newline, even if all the prompt separators are ''. This is the # standard IPython behavior. result_repr = format_dict['text/plain'] if '\n' in result_repr: # So that multi-line strings line up with the left column of # the screen, instead of having the output prompt mess up # their first line. # We use the prompt template instead of the expanded prompt # because the expansion may add ANSI escapes that will interfere # with our ability to determine whether or not we should add # a newline. prompt_template = self.shell.prompt_manager.out_template if prompt_template and not prompt_template.endswith('\n'): # But avoid extraneous empty lines. result_repr = '\n' + result_repr print >>io.stdout, result_repr
[ "Write", "the", "format", "data", "dict", "to", "the", "frontend", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/displayhook.py#L152-L182
[ "def", "write_format_data", "(", "self", ",", "format_dict", ")", ":", "# We want to print because we want to always make sure we have a", "# newline, even if all the prompt separators are ''. This is the", "# standard IPython behavior.", "result_repr", "=", "format_dict", "[", "'text/plain'", "]", "if", "'\\n'", "in", "result_repr", ":", "# So that multi-line strings line up with the left column of", "# the screen, instead of having the output prompt mess up", "# their first line.", "# We use the prompt template instead of the expanded prompt", "# because the expansion may add ANSI escapes that will interfere", "# with our ability to determine whether or not we should add", "# a newline.", "prompt_template", "=", "self", ".", "shell", ".", "prompt_manager", ".", "out_template", "if", "prompt_template", "and", "not", "prompt_template", ".", "endswith", "(", "'\\n'", ")", ":", "# But avoid extraneous empty lines.", "result_repr", "=", "'\\n'", "+", "result_repr", "print", ">>", "io", ".", "stdout", ",", "result_repr" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DisplayHook.update_user_ns
Update user_ns with various things like _, __, _1, etc.
environment/lib/python2.7/site-packages/IPython/core/displayhook.py
def update_user_ns(self, result): """Update user_ns with various things like _, __, _1, etc.""" # Avoid recursive reference when displaying _oh/Out if result is not self.shell.user_ns['_oh']: if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: warn('Output cache limit (currently '+ `self.cache_size`+' entries) hit.\n' 'Flushing cache and resetting history counter...\n' 'The only history variables available will be _,__,___ and _1\n' 'with the current result.') self.flush() # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise # we cause buggy behavior for things like gettext). if '_' not in __builtin__.__dict__: self.___ = self.__ self.__ = self._ self._ = result self.shell.push({'_':self._, '__':self.__, '___':self.___}, interactive=False) # hackish access to top-level namespace to create _1,_2... dynamically to_main = {} if self.do_full_cache: new_result = '_'+`self.prompt_count` to_main[new_result] = result self.shell.push(to_main, interactive=False) self.shell.user_ns['_oh'][self.prompt_count] = result
def update_user_ns(self, result): """Update user_ns with various things like _, __, _1, etc.""" # Avoid recursive reference when displaying _oh/Out if result is not self.shell.user_ns['_oh']: if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: warn('Output cache limit (currently '+ `self.cache_size`+' entries) hit.\n' 'Flushing cache and resetting history counter...\n' 'The only history variables available will be _,__,___ and _1\n' 'with the current result.') self.flush() # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise # we cause buggy behavior for things like gettext). if '_' not in __builtin__.__dict__: self.___ = self.__ self.__ = self._ self._ = result self.shell.push({'_':self._, '__':self.__, '___':self.___}, interactive=False) # hackish access to top-level namespace to create _1,_2... dynamically to_main = {} if self.do_full_cache: new_result = '_'+`self.prompt_count` to_main[new_result] = result self.shell.push(to_main, interactive=False) self.shell.user_ns['_oh'][self.prompt_count] = result
[ "Update", "user_ns", "with", "various", "things", "like", "_", "__", "_1", "etc", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/displayhook.py#L184-L214
[ "def", "update_user_ns", "(", "self", ",", "result", ")", ":", "# Avoid recursive reference when displaying _oh/Out", "if", "result", "is", "not", "self", ".", "shell", ".", "user_ns", "[", "'_oh'", "]", ":", "if", "len", "(", "self", ".", "shell", ".", "user_ns", "[", "'_oh'", "]", ")", ">=", "self", ".", "cache_size", "and", "self", ".", "do_full_cache", ":", "warn", "(", "'Output cache limit (currently '", "+", "`self.cache_size`", "+", "' entries) hit.\\n'", "'Flushing cache and resetting history counter...\\n'", "'The only history variables available will be _,__,___ and _1\\n'", "'with the current result.'", ")", "self", ".", "flush", "(", ")", "# Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise", "# we cause buggy behavior for things like gettext).", "if", "'_'", "not", "in", "__builtin__", ".", "__dict__", ":", "self", ".", "___", "=", "self", ".", "__", "self", ".", "__", "=", "self", ".", "_", "self", ".", "_", "=", "result", "self", ".", "shell", ".", "push", "(", "{", "'_'", ":", "self", ".", "_", ",", "'__'", ":", "self", ".", "__", ",", "'___'", ":", "self", ".", "___", "}", ",", "interactive", "=", "False", ")", "# hackish access to top-level namespace to create _1,_2... dynamically", "to_main", "=", "{", "}", "if", "self", ".", "do_full_cache", ":", "new_result", "=", "'_'", "+", "`self.prompt_count`", "to_main", "[", "new_result", "]", "=", "result", "self", ".", "shell", ".", "push", "(", "to_main", ",", "interactive", "=", "False", ")", "self", ".", "shell", ".", "user_ns", "[", "'_oh'", "]", "[", "self", ".", "prompt_count", "]", "=", "result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DisplayHook.log_output
Log the output.
environment/lib/python2.7/site-packages/IPython/core/displayhook.py
def log_output(self, format_dict): """Log the output.""" if self.shell.logger.log_output: self.shell.logger.log_write(format_dict['text/plain'], 'output') self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ format_dict['text/plain']
def log_output(self, format_dict): """Log the output.""" if self.shell.logger.log_output: self.shell.logger.log_write(format_dict['text/plain'], 'output') self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ format_dict['text/plain']
[ "Log", "the", "output", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/displayhook.py#L216-L221
[ "def", "log_output", "(", "self", ",", "format_dict", ")", ":", "if", "self", ".", "shell", ".", "logger", ".", "log_output", ":", "self", ".", "shell", ".", "logger", ".", "log_write", "(", "format_dict", "[", "'text/plain'", "]", ",", "'output'", ")", "self", ".", "shell", ".", "history_manager", ".", "output_hist_reprs", "[", "self", ".", "prompt_count", "]", "=", "format_dict", "[", "'text/plain'", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
DisplayHook.finish_displayhook
Finish up all displayhook activities.
environment/lib/python2.7/site-packages/IPython/core/displayhook.py
def finish_displayhook(self): """Finish up all displayhook activities.""" io.stdout.write(self.shell.separate_out2) io.stdout.flush()
def finish_displayhook(self): """Finish up all displayhook activities.""" io.stdout.write(self.shell.separate_out2) io.stdout.flush()
[ "Finish", "up", "all", "displayhook", "activities", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/displayhook.py#L223-L226
[ "def", "finish_displayhook", "(", "self", ")", ":", "io", ".", "stdout", ".", "write", "(", "self", ".", "shell", ".", "separate_out2", ")", "io", ".", "stdout", ".", "flush", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
load_ipython_extension
Load the extension in IPython.
environment/lib/python2.7/site-packages/IPython/extensions/storemagic.py
def load_ipython_extension(ip): """Load the extension in IPython.""" global _loaded if not _loaded: plugin = StoreMagic(shell=ip, config=ip.config) ip.plugin_manager.register_plugin('storemagic', plugin) _loaded = True
def load_ipython_extension(ip): """Load the extension in IPython.""" global _loaded if not _loaded: plugin = StoreMagic(shell=ip, config=ip.config) ip.plugin_manager.register_plugin('storemagic', plugin) _loaded = True
[ "Load", "the", "extension", "in", "IPython", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/extensions/storemagic.py#L228-L234
[ "def", "load_ipython_extension", "(", "ip", ")", ":", "global", "_loaded", "if", "not", "_loaded", ":", "plugin", "=", "StoreMagic", "(", "shell", "=", "ip", ",", "config", "=", "ip", ".", "config", ")", "ip", ".", "plugin_manager", ".", "register_plugin", "(", "'storemagic'", ",", "plugin", ")", "_loaded", "=", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Freezable.raise_if_freezed
raise `InvalidOperationException` if is freezed.
jasily/utils/objects.py
def raise_if_freezed(self): '''raise `InvalidOperationException` if is freezed.''' if self.is_freezed: name = type(self).__name__ raise InvalidOperationException('obj {name} is freezed.'.format(name=name))
def raise_if_freezed(self): '''raise `InvalidOperationException` if is freezed.''' if self.is_freezed: name = type(self).__name__ raise InvalidOperationException('obj {name} is freezed.'.format(name=name))
[ "raise", "InvalidOperationException", "if", "is", "freezed", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/utils/objects.py#L25-L29
[ "def", "raise_if_freezed", "(", "self", ")", ":", "if", "self", ".", "is_freezed", ":", "name", "=", "type", "(", "self", ")", ".", "__name__", "raise", "InvalidOperationException", "(", "'obj {name} is freezed.'", ".", "format", "(", "name", "=", "name", ")", ")" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
mysql_timestamp_converter
Convert a MySQL TIMESTAMP to a Timestamp object.
environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/times.py
def mysql_timestamp_converter(s): """Convert a MySQL TIMESTAMP to a Timestamp object.""" # MySQL>4.1 returns TIMESTAMP in the same format as DATETIME if s[4] == '-': return DateTime_or_None(s) s = s + "0"*(14-len(s)) # padding parts = map(int, filter(None, (s[:4],s[4:6],s[6:8], s[8:10],s[10:12],s[12:14]))) try: return Timestamp(*parts) except (SystemExit, KeyboardInterrupt): raise except: return None
def mysql_timestamp_converter(s): """Convert a MySQL TIMESTAMP to a Timestamp object.""" # MySQL>4.1 returns TIMESTAMP in the same format as DATETIME if s[4] == '-': return DateTime_or_None(s) s = s + "0"*(14-len(s)) # padding parts = map(int, filter(None, (s[:4],s[4:6],s[6:8], s[8:10],s[10:12],s[12:14]))) try: return Timestamp(*parts) except (SystemExit, KeyboardInterrupt): raise except: return None
[ "Convert", "a", "MySQL", "TIMESTAMP", "to", "a", "Timestamp", "object", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/MySQL_python-1.2.4c1-py2.7-linux-x86_64.egg/MySQLdb/times.py#L99-L111
[ "def", "mysql_timestamp_converter", "(", "s", ")", ":", "# MySQL>4.1 returns TIMESTAMP in the same format as DATETIME", "if", "s", "[", "4", "]", "==", "'-'", ":", "return", "DateTime_or_None", "(", "s", ")", "s", "=", "s", "+", "\"0\"", "*", "(", "14", "-", "len", "(", "s", ")", ")", "# padding", "parts", "=", "map", "(", "int", ",", "filter", "(", "None", ",", "(", "s", "[", ":", "4", "]", ",", "s", "[", "4", ":", "6", "]", ",", "s", "[", "6", ":", "8", "]", ",", "s", "[", "8", ":", "10", "]", ",", "s", "[", "10", ":", "12", "]", ",", "s", "[", "12", ":", "14", "]", ")", ")", ")", "try", ":", "return", "Timestamp", "(", "*", "parts", ")", "except", "(", "SystemExit", ",", "KeyboardInterrupt", ")", ":", "raise", "except", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
APIBase.make_envelope
body_elements: <list> of etree.Elements or <None>
dirtyebay/client.py
def make_envelope(self, body_elements=None): """ body_elements: <list> of etree.Elements or <None> """ soap = self.get_soap_el_factory() body_elements = body_elements or [] body = soap.Body(*body_elements) header = self.get_soap_header() if header is not None: elements = [header, body] else: elements = [body] return soap.Envelope( #{ # '{%s}encodingStyle' % namespaces.SOAP_1_2: ( # 'http://www.w3.org/2001/12/soap-encoding') #}, *elements )
def make_envelope(self, body_elements=None): """ body_elements: <list> of etree.Elements or <None> """ soap = self.get_soap_el_factory() body_elements = body_elements or [] body = soap.Body(*body_elements) header = self.get_soap_header() if header is not None: elements = [header, body] else: elements = [body] return soap.Envelope( #{ # '{%s}encodingStyle' % namespaces.SOAP_1_2: ( # 'http://www.w3.org/2001/12/soap-encoding') #}, *elements )
[ "body_elements", ":", "<list", ">", "of", "etree", ".", "Elements", "or", "<None", ">" ]
anentropic/dirtyebay
python
https://github.com/anentropic/dirtyebay/blob/c3194932360445563cfe0c7e034e41f09358c7eb/dirtyebay/client.py#L263-L281
[ "def", "make_envelope", "(", "self", ",", "body_elements", "=", "None", ")", ":", "soap", "=", "self", ".", "get_soap_el_factory", "(", ")", "body_elements", "=", "body_elements", "or", "[", "]", "body", "=", "soap", ".", "Body", "(", "*", "body_elements", ")", "header", "=", "self", ".", "get_soap_header", "(", ")", "if", "header", "is", "not", "None", ":", "elements", "=", "[", "header", ",", "body", "]", "else", ":", "elements", "=", "[", "body", "]", "return", "soap", ".", "Envelope", "(", "#{", "# '{%s}encodingStyle' % namespaces.SOAP_1_2: (", "# 'http://www.w3.org/2001/12/soap-encoding')", "#},", "*", "elements", ")" ]
c3194932360445563cfe0c7e034e41f09358c7eb
test
embed_kernel
Embed and start an IPython kernel in a given scope. Parameters ---------- module : ModuleType, optional The module to load into IPython globals (default: caller) local_ns : dict, optional The namespace to load into IPython user namespace (default: caller) kwargs : various, optional Further keyword args are relayed to the KernelApp constructor, allowing configuration of the Kernel. Will only have an effect on the first embed_kernel call for a given process.
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def embed_kernel(module=None, local_ns=None, **kwargs): """Embed and start an IPython kernel in a given scope. Parameters ---------- module : ModuleType, optional The module to load into IPython globals (default: caller) local_ns : dict, optional The namespace to load into IPython user namespace (default: caller) kwargs : various, optional Further keyword args are relayed to the KernelApp constructor, allowing configuration of the Kernel. Will only have an effect on the first embed_kernel call for a given process. """ # get the app if it exists, or set it up if it doesn't if IPKernelApp.initialized(): app = IPKernelApp.instance() else: app = IPKernelApp.instance(**kwargs) app.initialize([]) # Undo unnecessary sys module mangling from init_sys_modules. # This would not be necessary if we could prevent it # in the first place by using a different InteractiveShell # subclass, as in the regular embed case. main = app.kernel.shell._orig_sys_modules_main_mod if main is not None: sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main # load the calling scope if not given (caller_module, caller_locals) = extract_module_locals(1) if module is None: module = caller_module if local_ns is None: local_ns = caller_locals app.kernel.user_module = module app.kernel.user_ns = local_ns app.shell.set_completer_frame() app.start()
def embed_kernel(module=None, local_ns=None, **kwargs): """Embed and start an IPython kernel in a given scope. Parameters ---------- module : ModuleType, optional The module to load into IPython globals (default: caller) local_ns : dict, optional The namespace to load into IPython user namespace (default: caller) kwargs : various, optional Further keyword args are relayed to the KernelApp constructor, allowing configuration of the Kernel. Will only have an effect on the first embed_kernel call for a given process. """ # get the app if it exists, or set it up if it doesn't if IPKernelApp.initialized(): app = IPKernelApp.instance() else: app = IPKernelApp.instance(**kwargs) app.initialize([]) # Undo unnecessary sys module mangling from init_sys_modules. # This would not be necessary if we could prevent it # in the first place by using a different InteractiveShell # subclass, as in the regular embed case. main = app.kernel.shell._orig_sys_modules_main_mod if main is not None: sys.modules[app.kernel.shell._orig_sys_modules_main_name] = main # load the calling scope if not given (caller_module, caller_locals) = extract_module_locals(1) if module is None: module = caller_module if local_ns is None: local_ns = caller_locals app.kernel.user_module = module app.kernel.user_ns = local_ns app.shell.set_completer_frame() app.start()
[ "Embed", "and", "start", "an", "IPython", "kernel", "in", "a", "given", "scope", ".", "Parameters", "----------", "module", ":", "ModuleType", "optional", "The", "module", "to", "load", "into", "IPython", "globals", "(", "default", ":", "caller", ")", "local_ns", ":", "dict", "optional", "The", "namespace", "to", "load", "into", "IPython", "user", "namespace", "(", "default", ":", "caller", ")", "kwargs", ":", "various", "optional", "Further", "keyword", "args", "are", "relayed", "to", "the", "KernelApp", "constructor", "allowing", "configuration", "of", "the", "Kernel", ".", "Will", "only", "have", "an", "effect", "on", "the", "first", "embed_kernel", "call", "for", "a", "given", "process", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L872-L912
[ "def", "embed_kernel", "(", "module", "=", "None", ",", "local_ns", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# get the app if it exists, or set it up if it doesn't", "if", "IPKernelApp", ".", "initialized", "(", ")", ":", "app", "=", "IPKernelApp", ".", "instance", "(", ")", "else", ":", "app", "=", "IPKernelApp", ".", "instance", "(", "*", "*", "kwargs", ")", "app", ".", "initialize", "(", "[", "]", ")", "# Undo unnecessary sys module mangling from init_sys_modules.", "# This would not be necessary if we could prevent it", "# in the first place by using a different InteractiveShell", "# subclass, as in the regular embed case.", "main", "=", "app", ".", "kernel", ".", "shell", ".", "_orig_sys_modules_main_mod", "if", "main", "is", "not", "None", ":", "sys", ".", "modules", "[", "app", ".", "kernel", ".", "shell", ".", "_orig_sys_modules_main_name", "]", "=", "main", "# load the calling scope if not given", "(", "caller_module", ",", "caller_locals", ")", "=", "extract_module_locals", "(", "1", ")", "if", "module", "is", "None", ":", "module", "=", "caller_module", "if", "local_ns", "is", "None", ":", "local_ns", "=", "caller_locals", "app", ".", "kernel", ".", "user_module", "=", "module", "app", ".", "kernel", ".", "user_ns", "=", "local_ns", "app", ".", "shell", ".", "set_completer_frame", "(", ")", "app", ".", "start", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel._eventloop_changed
schedule call to eventloop from IOLoop
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def _eventloop_changed(self, name, old, new): """schedule call to eventloop from IOLoop""" loop = ioloop.IOLoop.instance() loop.add_timeout(time.time()+0.1, self.enter_eventloop)
def _eventloop_changed(self, name, old, new): """schedule call to eventloop from IOLoop""" loop = ioloop.IOLoop.instance() loop.add_timeout(time.time()+0.1, self.enter_eventloop)
[ "schedule", "call", "to", "eventloop", "from", "IOLoop" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L72-L75
[ "def", "_eventloop_changed", "(", "self", ",", "name", ",", "old", ",", "new", ")", ":", "loop", "=", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", "loop", ".", "add_timeout", "(", "time", ".", "time", "(", ")", "+", "0.1", ",", "self", ".", "enter_eventloop", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel.dispatch_control
dispatch control requests
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def dispatch_control(self, msg): """dispatch control requests""" idents,msg = self.session.feed_identities(msg, copy=False) try: msg = self.session.unserialize(msg, content=True, copy=False) except: self.log.error("Invalid Control Message", exc_info=True) return self.log.debug("Control received: %s", msg) header = msg['header'] msg_id = header['msg_id'] msg_type = header['msg_type'] handler = self.control_handlers.get(msg_type, None) if handler is None: self.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", msg_type) else: try: handler(self.control_stream, idents, msg) except Exception: self.log.error("Exception in control handler:", exc_info=True)
def dispatch_control(self, msg): """dispatch control requests""" idents,msg = self.session.feed_identities(msg, copy=False) try: msg = self.session.unserialize(msg, content=True, copy=False) except: self.log.error("Invalid Control Message", exc_info=True) return self.log.debug("Control received: %s", msg) header = msg['header'] msg_id = header['msg_id'] msg_type = header['msg_type'] handler = self.control_handlers.get(msg_type, None) if handler is None: self.log.error("UNKNOWN CONTROL MESSAGE TYPE: %r", msg_type) else: try: handler(self.control_stream, idents, msg) except Exception: self.log.error("Exception in control handler:", exc_info=True)
[ "dispatch", "control", "requests" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L169-L191
[ "def", "dispatch_control", "(", "self", ",", "msg", ")", ":", "idents", ",", "msg", "=", "self", ".", "session", ".", "feed_identities", "(", "msg", ",", "copy", "=", "False", ")", "try", ":", "msg", "=", "self", ".", "session", ".", "unserialize", "(", "msg", ",", "content", "=", "True", ",", "copy", "=", "False", ")", "except", ":", "self", ".", "log", ".", "error", "(", "\"Invalid Control Message\"", ",", "exc_info", "=", "True", ")", "return", "self", ".", "log", ".", "debug", "(", "\"Control received: %s\"", ",", "msg", ")", "header", "=", "msg", "[", "'header'", "]", "msg_id", "=", "header", "[", "'msg_id'", "]", "msg_type", "=", "header", "[", "'msg_type'", "]", "handler", "=", "self", ".", "control_handlers", ".", "get", "(", "msg_type", ",", "None", ")", "if", "handler", "is", "None", ":", "self", ".", "log", ".", "error", "(", "\"UNKNOWN CONTROL MESSAGE TYPE: %r\"", ",", "msg_type", ")", "else", ":", "try", ":", "handler", "(", "self", ".", "control_stream", ",", "idents", ",", "msg", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"Exception in control handler:\"", ",", "exc_info", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel.dispatch_shell
dispatch shell requests
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def dispatch_shell(self, stream, msg): """dispatch shell requests""" # flush control requests first if self.control_stream: self.control_stream.flush() idents,msg = self.session.feed_identities(msg, copy=False) try: msg = self.session.unserialize(msg, content=True, copy=False) except: self.log.error("Invalid Message", exc_info=True) return header = msg['header'] msg_id = header['msg_id'] msg_type = msg['header']['msg_type'] # Print some info about this message and leave a '--->' marker, so it's # easier to trace visually the message chain when debugging. Each # handler prints its message at the end. self.log.debug('\n*** MESSAGE TYPE:%s***', msg_type) self.log.debug(' Content: %s\n --->\n ', msg['content']) if msg_id in self.aborted: self.aborted.remove(msg_id) # is it safe to assume a msg_id will not be resubmitted? reply_type = msg_type.split('_')[0] + '_reply' status = {'status' : 'aborted'} sub = {'engine' : self.ident} sub.update(status) reply_msg = self.session.send(stream, reply_type, subheader=sub, content=status, parent=msg, ident=idents) return handler = self.shell_handlers.get(msg_type, None) if handler is None: self.log.error("UNKNOWN MESSAGE TYPE: %r", msg_type) else: # ensure default_int_handler during handler call sig = signal(SIGINT, default_int_handler) try: handler(stream, idents, msg) except Exception: self.log.error("Exception in message handler:", exc_info=True) finally: signal(SIGINT, sig)
def dispatch_shell(self, stream, msg): """dispatch shell requests""" # flush control requests first if self.control_stream: self.control_stream.flush() idents,msg = self.session.feed_identities(msg, copy=False) try: msg = self.session.unserialize(msg, content=True, copy=False) except: self.log.error("Invalid Message", exc_info=True) return header = msg['header'] msg_id = header['msg_id'] msg_type = msg['header']['msg_type'] # Print some info about this message and leave a '--->' marker, so it's # easier to trace visually the message chain when debugging. Each # handler prints its message at the end. self.log.debug('\n*** MESSAGE TYPE:%s***', msg_type) self.log.debug(' Content: %s\n --->\n ', msg['content']) if msg_id in self.aborted: self.aborted.remove(msg_id) # is it safe to assume a msg_id will not be resubmitted? reply_type = msg_type.split('_')[0] + '_reply' status = {'status' : 'aborted'} sub = {'engine' : self.ident} sub.update(status) reply_msg = self.session.send(stream, reply_type, subheader=sub, content=status, parent=msg, ident=idents) return handler = self.shell_handlers.get(msg_type, None) if handler is None: self.log.error("UNKNOWN MESSAGE TYPE: %r", msg_type) else: # ensure default_int_handler during handler call sig = signal(SIGINT, default_int_handler) try: handler(stream, idents, msg) except Exception: self.log.error("Exception in message handler:", exc_info=True) finally: signal(SIGINT, sig)
[ "dispatch", "shell", "requests" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L193-L238
[ "def", "dispatch_shell", "(", "self", ",", "stream", ",", "msg", ")", ":", "# flush control requests first", "if", "self", ".", "control_stream", ":", "self", ".", "control_stream", ".", "flush", "(", ")", "idents", ",", "msg", "=", "self", ".", "session", ".", "feed_identities", "(", "msg", ",", "copy", "=", "False", ")", "try", ":", "msg", "=", "self", ".", "session", ".", "unserialize", "(", "msg", ",", "content", "=", "True", ",", "copy", "=", "False", ")", "except", ":", "self", ".", "log", ".", "error", "(", "\"Invalid Message\"", ",", "exc_info", "=", "True", ")", "return", "header", "=", "msg", "[", "'header'", "]", "msg_id", "=", "header", "[", "'msg_id'", "]", "msg_type", "=", "msg", "[", "'header'", "]", "[", "'msg_type'", "]", "# Print some info about this message and leave a '--->' marker, so it's", "# easier to trace visually the message chain when debugging. Each", "# handler prints its message at the end.", "self", ".", "log", ".", "debug", "(", "'\\n*** MESSAGE TYPE:%s***'", ",", "msg_type", ")", "self", ".", "log", ".", "debug", "(", "' Content: %s\\n --->\\n '", ",", "msg", "[", "'content'", "]", ")", "if", "msg_id", "in", "self", ".", "aborted", ":", "self", ".", "aborted", ".", "remove", "(", "msg_id", ")", "# is it safe to assume a msg_id will not be resubmitted?", "reply_type", "=", "msg_type", ".", "split", "(", "'_'", ")", "[", "0", "]", "+", "'_reply'", "status", "=", "{", "'status'", ":", "'aborted'", "}", "sub", "=", "{", "'engine'", ":", "self", ".", "ident", "}", "sub", ".", "update", "(", "status", ")", "reply_msg", "=", "self", ".", "session", ".", "send", "(", "stream", ",", "reply_type", ",", "subheader", "=", "sub", ",", "content", "=", "status", ",", "parent", "=", "msg", ",", "ident", "=", "idents", ")", "return", "handler", "=", "self", ".", "shell_handlers", ".", "get", "(", "msg_type", ",", "None", ")", "if", "handler", "is", "None", ":", "self", ".", "log", ".", "error", "(", "\"UNKNOWN MESSAGE TYPE: %r\"", ",", "msg_type", ")", "else", ":", "# ensure default_int_handler during handler call", "sig", "=", "signal", "(", "SIGINT", ",", "default_int_handler", ")", "try", ":", "handler", "(", "stream", ",", "idents", ",", "msg", ")", "except", "Exception", ":", "self", ".", "log", ".", "error", "(", "\"Exception in message handler:\"", ",", "exc_info", "=", "True", ")", "finally", ":", "signal", "(", "SIGINT", ",", "sig", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel.enter_eventloop
enter eventloop
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def enter_eventloop(self): """enter eventloop""" self.log.info("entering eventloop") # restore default_int_handler signal(SIGINT, default_int_handler) while self.eventloop is not None: try: self.eventloop(self) except KeyboardInterrupt: # Ctrl-C shouldn't crash the kernel self.log.error("KeyboardInterrupt caught in kernel") continue else: # eventloop exited cleanly, this means we should stop (right?) self.eventloop = None break self.log.info("exiting eventloop") # if eventloop exits, IOLoop should stop ioloop.IOLoop.instance().stop()
def enter_eventloop(self): """enter eventloop""" self.log.info("entering eventloop") # restore default_int_handler signal(SIGINT, default_int_handler) while self.eventloop is not None: try: self.eventloop(self) except KeyboardInterrupt: # Ctrl-C shouldn't crash the kernel self.log.error("KeyboardInterrupt caught in kernel") continue else: # eventloop exited cleanly, this means we should stop (right?) self.eventloop = None break self.log.info("exiting eventloop") # if eventloop exits, IOLoop should stop ioloop.IOLoop.instance().stop()
[ "enter", "eventloop" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L240-L258
[ "def", "enter_eventloop", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"entering eventloop\"", ")", "# restore default_int_handler", "signal", "(", "SIGINT", ",", "default_int_handler", ")", "while", "self", ".", "eventloop", "is", "not", "None", ":", "try", ":", "self", ".", "eventloop", "(", "self", ")", "except", "KeyboardInterrupt", ":", "# Ctrl-C shouldn't crash the kernel", "self", ".", "log", ".", "error", "(", "\"KeyboardInterrupt caught in kernel\"", ")", "continue", "else", ":", "# eventloop exited cleanly, this means we should stop (right?)", "self", ".", "eventloop", "=", "None", "break", "self", ".", "log", ".", "info", "(", "\"exiting eventloop\"", ")", "# if eventloop exits, IOLoop should stop", "ioloop", ".", "IOLoop", ".", "instance", "(", ")", ".", "stop", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel.start
register dispatchers for streams
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def start(self): """register dispatchers for streams""" self.shell.exit_now = False if self.control_stream: self.control_stream.on_recv(self.dispatch_control, copy=False) def make_dispatcher(stream): def dispatcher(msg): return self.dispatch_shell(stream, msg) return dispatcher for s in self.shell_streams: s.on_recv(make_dispatcher(s), copy=False)
def start(self): """register dispatchers for streams""" self.shell.exit_now = False if self.control_stream: self.control_stream.on_recv(self.dispatch_control, copy=False) def make_dispatcher(stream): def dispatcher(msg): return self.dispatch_shell(stream, msg) return dispatcher for s in self.shell_streams: s.on_recv(make_dispatcher(s), copy=False)
[ "register", "dispatchers", "for", "streams" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L260-L272
[ "def", "start", "(", "self", ")", ":", "self", ".", "shell", ".", "exit_now", "=", "False", "if", "self", ".", "control_stream", ":", "self", ".", "control_stream", ".", "on_recv", "(", "self", ".", "dispatch_control", ",", "copy", "=", "False", ")", "def", "make_dispatcher", "(", "stream", ")", ":", "def", "dispatcher", "(", "msg", ")", ":", "return", "self", ".", "dispatch_shell", "(", "stream", ",", "msg", ")", "return", "dispatcher", "for", "s", "in", "self", ".", "shell_streams", ":", "s", ".", "on_recv", "(", "make_dispatcher", "(", "s", ")", ",", "copy", "=", "False", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel.do_one_iteration
step eventloop just once
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def do_one_iteration(self): """step eventloop just once""" if self.control_stream: self.control_stream.flush() for stream in self.shell_streams: # handle at most one request per iteration stream.flush(zmq.POLLIN, 1) stream.flush(zmq.POLLOUT)
def do_one_iteration(self): """step eventloop just once""" if self.control_stream: self.control_stream.flush() for stream in self.shell_streams: # handle at most one request per iteration stream.flush(zmq.POLLIN, 1) stream.flush(zmq.POLLOUT)
[ "step", "eventloop", "just", "once" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L274-L281
[ "def", "do_one_iteration", "(", "self", ")", ":", "if", "self", ".", "control_stream", ":", "self", ".", "control_stream", ".", "flush", "(", ")", "for", "stream", "in", "self", ".", "shell_streams", ":", "# handle at most one request per iteration", "stream", ".", "flush", "(", "zmq", ".", "POLLIN", ",", "1", ")", "stream", ".", "flush", "(", "zmq", ".", "POLLOUT", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel._publish_pyin
Publish the code request on the pyin stream.
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def _publish_pyin(self, code, parent, execution_count): """Publish the code request on the pyin stream.""" self.session.send(self.iopub_socket, u'pyin', {u'code':code, u'execution_count': execution_count}, parent=parent, ident=self._topic('pyin') )
def _publish_pyin(self, code, parent, execution_count): """Publish the code request on the pyin stream.""" self.session.send(self.iopub_socket, u'pyin', {u'code':code, u'execution_count': execution_count}, parent=parent, ident=self._topic('pyin') )
[ "Publish", "the", "code", "request", "on", "the", "pyin", "stream", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L304-L310
[ "def", "_publish_pyin", "(", "self", ",", "code", ",", "parent", ",", "execution_count", ")", ":", "self", ".", "session", ".", "send", "(", "self", ".", "iopub_socket", ",", "u'pyin'", ",", "{", "u'code'", ":", "code", ",", "u'execution_count'", ":", "execution_count", "}", ",", "parent", "=", "parent", ",", "ident", "=", "self", ".", "_topic", "(", "'pyin'", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel._publish_status
send status (busy/idle) on IOPub
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def _publish_status(self, status, parent=None): """send status (busy/idle) on IOPub""" self.session.send(self.iopub_socket, u'status', {u'execution_state': status}, parent=parent, ident=self._topic('status'), )
def _publish_status(self, status, parent=None): """send status (busy/idle) on IOPub""" self.session.send(self.iopub_socket, u'status', {u'execution_state': status}, parent=parent, ident=self._topic('status'), )
[ "send", "status", "(", "busy", "/", "idle", ")", "on", "IOPub" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L312-L319
[ "def", "_publish_status", "(", "self", ",", "status", ",", "parent", "=", "None", ")", ":", "self", ".", "session", ".", "send", "(", "self", ".", "iopub_socket", ",", "u'status'", ",", "{", "u'execution_state'", ":", "status", "}", ",", "parent", "=", "parent", ",", "ident", "=", "self", ".", "_topic", "(", "'status'", ")", ",", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel.execute_request
handle an execute_request
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def execute_request(self, stream, ident, parent): """handle an execute_request""" self._publish_status(u'busy', parent) try: content = parent[u'content'] code = content[u'code'] silent = content[u'silent'] except: self.log.error("Got bad msg: ") self.log.error("%s", parent) return sub = self._make_subheader() shell = self.shell # we'll need this a lot here # Replace raw_input. Note that is not sufficient to replace # raw_input in the user namespace. if content.get('allow_stdin', False): raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) else: raw_input = lambda prompt='' : self._no_raw_input() if py3compat.PY3: __builtin__.input = raw_input else: __builtin__.raw_input = raw_input # Set the parent message of the display hook and out streams. shell.displayhook.set_parent(parent) shell.display_pub.set_parent(parent) sys.stdout.set_parent(parent) sys.stderr.set_parent(parent) # Re-broadcast our input for the benefit of listening clients, and # start computing output if not silent: self._publish_pyin(code, parent, shell.execution_count) reply_content = {} try: # FIXME: the shell calls the exception handler itself. shell.run_cell(code, store_history=not silent, silent=silent) except: status = u'error' # FIXME: this code right now isn't being used yet by default, # because the run_cell() call above directly fires off exception # reporting. This code, therefore, is only active in the scenario # where runlines itself has an unhandled exception. We need to # uniformize this, for all exception construction to come from a # single location in the codbase. etype, evalue, tb = sys.exc_info() tb_list = traceback.format_exception(etype, evalue, tb) reply_content.update(shell._showtraceback(etype, evalue, tb_list)) else: status = u'ok' reply_content[u'status'] = status # Return the execution counter so clients can display prompts reply_content['execution_count'] = shell.execution_count - 1 # FIXME - fish exception info out of shell, possibly left there by # runlines. We'll need to clean up this logic later. if shell._reply_content is not None: reply_content.update(shell._reply_content) e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='execute') reply_content['engine_info'] = e_info # reset after use shell._reply_content = None # At this point, we can tell whether the main code execution succeeded # or not. If it did, we proceed to evaluate user_variables/expressions if reply_content['status'] == 'ok': reply_content[u'user_variables'] = \ shell.user_variables(content.get(u'user_variables', [])) reply_content[u'user_expressions'] = \ shell.user_expressions(content.get(u'user_expressions', {})) else: # If there was an error, don't even try to compute variables or # expressions reply_content[u'user_variables'] = {} reply_content[u'user_expressions'] = {} # Payloads should be retrieved regardless of outcome, so we can both # recover partial output (that could have been generated early in a # block, before an error) and clear the payload system always. reply_content[u'payload'] = shell.payload_manager.read_payload() # Be agressive about clearing the payload because we don't want # it to sit in memory until the next execute_request comes in. shell.payload_manager.clear_payload() # Flush output before sending the reply. sys.stdout.flush() sys.stderr.flush() # FIXME: on rare occasions, the flush doesn't seem to make it to the # clients... This seems to mitigate the problem, but we definitely need # to better understand what's going on. if self._execute_sleep: time.sleep(self._execute_sleep) # Send the reply. reply_content = json_clean(reply_content) sub['status'] = reply_content['status'] if reply_content['status'] == 'error' and \ reply_content['ename'] == 'UnmetDependency': sub['dependencies_met'] = False reply_msg = self.session.send(stream, u'execute_reply', reply_content, parent, subheader=sub, ident=ident) self.log.debug("%s", reply_msg) if not silent and reply_msg['content']['status'] == u'error': self._abort_queues() self._publish_status(u'idle', parent)
def execute_request(self, stream, ident, parent): """handle an execute_request""" self._publish_status(u'busy', parent) try: content = parent[u'content'] code = content[u'code'] silent = content[u'silent'] except: self.log.error("Got bad msg: ") self.log.error("%s", parent) return sub = self._make_subheader() shell = self.shell # we'll need this a lot here # Replace raw_input. Note that is not sufficient to replace # raw_input in the user namespace. if content.get('allow_stdin', False): raw_input = lambda prompt='': self._raw_input(prompt, ident, parent) else: raw_input = lambda prompt='' : self._no_raw_input() if py3compat.PY3: __builtin__.input = raw_input else: __builtin__.raw_input = raw_input # Set the parent message of the display hook and out streams. shell.displayhook.set_parent(parent) shell.display_pub.set_parent(parent) sys.stdout.set_parent(parent) sys.stderr.set_parent(parent) # Re-broadcast our input for the benefit of listening clients, and # start computing output if not silent: self._publish_pyin(code, parent, shell.execution_count) reply_content = {} try: # FIXME: the shell calls the exception handler itself. shell.run_cell(code, store_history=not silent, silent=silent) except: status = u'error' # FIXME: this code right now isn't being used yet by default, # because the run_cell() call above directly fires off exception # reporting. This code, therefore, is only active in the scenario # where runlines itself has an unhandled exception. We need to # uniformize this, for all exception construction to come from a # single location in the codbase. etype, evalue, tb = sys.exc_info() tb_list = traceback.format_exception(etype, evalue, tb) reply_content.update(shell._showtraceback(etype, evalue, tb_list)) else: status = u'ok' reply_content[u'status'] = status # Return the execution counter so clients can display prompts reply_content['execution_count'] = shell.execution_count - 1 # FIXME - fish exception info out of shell, possibly left there by # runlines. We'll need to clean up this logic later. if shell._reply_content is not None: reply_content.update(shell._reply_content) e_info = dict(engine_uuid=self.ident, engine_id=self.int_id, method='execute') reply_content['engine_info'] = e_info # reset after use shell._reply_content = None # At this point, we can tell whether the main code execution succeeded # or not. If it did, we proceed to evaluate user_variables/expressions if reply_content['status'] == 'ok': reply_content[u'user_variables'] = \ shell.user_variables(content.get(u'user_variables', [])) reply_content[u'user_expressions'] = \ shell.user_expressions(content.get(u'user_expressions', {})) else: # If there was an error, don't even try to compute variables or # expressions reply_content[u'user_variables'] = {} reply_content[u'user_expressions'] = {} # Payloads should be retrieved regardless of outcome, so we can both # recover partial output (that could have been generated early in a # block, before an error) and clear the payload system always. reply_content[u'payload'] = shell.payload_manager.read_payload() # Be agressive about clearing the payload because we don't want # it to sit in memory until the next execute_request comes in. shell.payload_manager.clear_payload() # Flush output before sending the reply. sys.stdout.flush() sys.stderr.flush() # FIXME: on rare occasions, the flush doesn't seem to make it to the # clients... This seems to mitigate the problem, but we definitely need # to better understand what's going on. if self._execute_sleep: time.sleep(self._execute_sleep) # Send the reply. reply_content = json_clean(reply_content) sub['status'] = reply_content['status'] if reply_content['status'] == 'error' and \ reply_content['ename'] == 'UnmetDependency': sub['dependencies_met'] = False reply_msg = self.session.send(stream, u'execute_reply', reply_content, parent, subheader=sub, ident=ident) self.log.debug("%s", reply_msg) if not silent and reply_msg['content']['status'] == u'error': self._abort_queues() self._publish_status(u'idle', parent)
[ "handle", "an", "execute_request" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L322-L442
[ "def", "execute_request", "(", "self", ",", "stream", ",", "ident", ",", "parent", ")", ":", "self", ".", "_publish_status", "(", "u'busy'", ",", "parent", ")", "try", ":", "content", "=", "parent", "[", "u'content'", "]", "code", "=", "content", "[", "u'code'", "]", "silent", "=", "content", "[", "u'silent'", "]", "except", ":", "self", ".", "log", ".", "error", "(", "\"Got bad msg: \"", ")", "self", ".", "log", ".", "error", "(", "\"%s\"", ",", "parent", ")", "return", "sub", "=", "self", ".", "_make_subheader", "(", ")", "shell", "=", "self", ".", "shell", "# we'll need this a lot here", "# Replace raw_input. Note that is not sufficient to replace", "# raw_input in the user namespace.", "if", "content", ".", "get", "(", "'allow_stdin'", ",", "False", ")", ":", "raw_input", "=", "lambda", "prompt", "=", "''", ":", "self", ".", "_raw_input", "(", "prompt", ",", "ident", ",", "parent", ")", "else", ":", "raw_input", "=", "lambda", "prompt", "=", "''", ":", "self", ".", "_no_raw_input", "(", ")", "if", "py3compat", ".", "PY3", ":", "__builtin__", ".", "input", "=", "raw_input", "else", ":", "__builtin__", ".", "raw_input", "=", "raw_input", "# Set the parent message of the display hook and out streams.", "shell", ".", "displayhook", ".", "set_parent", "(", "parent", ")", "shell", ".", "display_pub", ".", "set_parent", "(", "parent", ")", "sys", ".", "stdout", ".", "set_parent", "(", "parent", ")", "sys", ".", "stderr", ".", "set_parent", "(", "parent", ")", "# Re-broadcast our input for the benefit of listening clients, and", "# start computing output", "if", "not", "silent", ":", "self", ".", "_publish_pyin", "(", "code", ",", "parent", ",", "shell", ".", "execution_count", ")", "reply_content", "=", "{", "}", "try", ":", "# FIXME: the shell calls the exception handler itself.", "shell", ".", "run_cell", "(", "code", ",", "store_history", "=", "not", "silent", ",", "silent", "=", "silent", ")", "except", ":", "status", "=", "u'error'", "# FIXME: this code right now isn't being used yet by default,", "# because the run_cell() call above directly fires off exception", "# reporting. This code, therefore, is only active in the scenario", "# where runlines itself has an unhandled exception. We need to", "# uniformize this, for all exception construction to come from a", "# single location in the codbase.", "etype", ",", "evalue", ",", "tb", "=", "sys", ".", "exc_info", "(", ")", "tb_list", "=", "traceback", ".", "format_exception", "(", "etype", ",", "evalue", ",", "tb", ")", "reply_content", ".", "update", "(", "shell", ".", "_showtraceback", "(", "etype", ",", "evalue", ",", "tb_list", ")", ")", "else", ":", "status", "=", "u'ok'", "reply_content", "[", "u'status'", "]", "=", "status", "# Return the execution counter so clients can display prompts", "reply_content", "[", "'execution_count'", "]", "=", "shell", ".", "execution_count", "-", "1", "# FIXME - fish exception info out of shell, possibly left there by", "# runlines. We'll need to clean up this logic later.", "if", "shell", ".", "_reply_content", "is", "not", "None", ":", "reply_content", ".", "update", "(", "shell", ".", "_reply_content", ")", "e_info", "=", "dict", "(", "engine_uuid", "=", "self", ".", "ident", ",", "engine_id", "=", "self", ".", "int_id", ",", "method", "=", "'execute'", ")", "reply_content", "[", "'engine_info'", "]", "=", "e_info", "# reset after use", "shell", ".", "_reply_content", "=", "None", "# At this point, we can tell whether the main code execution succeeded", "# or not. If it did, we proceed to evaluate user_variables/expressions", "if", "reply_content", "[", "'status'", "]", "==", "'ok'", ":", "reply_content", "[", "u'user_variables'", "]", "=", "shell", ".", "user_variables", "(", "content", ".", "get", "(", "u'user_variables'", ",", "[", "]", ")", ")", "reply_content", "[", "u'user_expressions'", "]", "=", "shell", ".", "user_expressions", "(", "content", ".", "get", "(", "u'user_expressions'", ",", "{", "}", ")", ")", "else", ":", "# If there was an error, don't even try to compute variables or", "# expressions", "reply_content", "[", "u'user_variables'", "]", "=", "{", "}", "reply_content", "[", "u'user_expressions'", "]", "=", "{", "}", "# Payloads should be retrieved regardless of outcome, so we can both", "# recover partial output (that could have been generated early in a", "# block, before an error) and clear the payload system always.", "reply_content", "[", "u'payload'", "]", "=", "shell", ".", "payload_manager", ".", "read_payload", "(", ")", "# Be agressive about clearing the payload because we don't want", "# it to sit in memory until the next execute_request comes in.", "shell", ".", "payload_manager", ".", "clear_payload", "(", ")", "# Flush output before sending the reply.", "sys", ".", "stdout", ".", "flush", "(", ")", "sys", ".", "stderr", ".", "flush", "(", ")", "# FIXME: on rare occasions, the flush doesn't seem to make it to the", "# clients... This seems to mitigate the problem, but we definitely need", "# to better understand what's going on.", "if", "self", ".", "_execute_sleep", ":", "time", ".", "sleep", "(", "self", ".", "_execute_sleep", ")", "# Send the reply.", "reply_content", "=", "json_clean", "(", "reply_content", ")", "sub", "[", "'status'", "]", "=", "reply_content", "[", "'status'", "]", "if", "reply_content", "[", "'status'", "]", "==", "'error'", "and", "reply_content", "[", "'ename'", "]", "==", "'UnmetDependency'", ":", "sub", "[", "'dependencies_met'", "]", "=", "False", "reply_msg", "=", "self", ".", "session", ".", "send", "(", "stream", ",", "u'execute_reply'", ",", "reply_content", ",", "parent", ",", "subheader", "=", "sub", ",", "ident", "=", "ident", ")", "self", ".", "log", ".", "debug", "(", "\"%s\"", ",", "reply_msg", ")", "if", "not", "silent", "and", "reply_msg", "[", "'content'", "]", "[", "'status'", "]", "==", "u'error'", ":", "self", ".", "_abort_queues", "(", ")", "self", ".", "_publish_status", "(", "u'idle'", ",", "parent", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel.abort_request
abort a specifig msg by id
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def abort_request(self, stream, ident, parent): """abort a specifig msg by id""" msg_ids = parent['content'].get('msg_ids', None) if isinstance(msg_ids, basestring): msg_ids = [msg_ids] if not msg_ids: self.abort_queues() for mid in msg_ids: self.aborted.add(str(mid)) content = dict(status='ok') reply_msg = self.session.send(stream, 'abort_reply', content=content, parent=parent, ident=ident) self.log.debug("%s", reply_msg)
def abort_request(self, stream, ident, parent): """abort a specifig msg by id""" msg_ids = parent['content'].get('msg_ids', None) if isinstance(msg_ids, basestring): msg_ids = [msg_ids] if not msg_ids: self.abort_queues() for mid in msg_ids: self.aborted.add(str(mid)) content = dict(status='ok') reply_msg = self.session.send(stream, 'abort_reply', content=content, parent=parent, ident=ident) self.log.debug("%s", reply_msg)
[ "abort", "a", "specifig", "msg", "by", "id" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L612-L625
[ "def", "abort_request", "(", "self", ",", "stream", ",", "ident", ",", "parent", ")", ":", "msg_ids", "=", "parent", "[", "'content'", "]", ".", "get", "(", "'msg_ids'", ",", "None", ")", "if", "isinstance", "(", "msg_ids", ",", "basestring", ")", ":", "msg_ids", "=", "[", "msg_ids", "]", "if", "not", "msg_ids", ":", "self", ".", "abort_queues", "(", ")", "for", "mid", "in", "msg_ids", ":", "self", ".", "aborted", ".", "add", "(", "str", "(", "mid", ")", ")", "content", "=", "dict", "(", "status", "=", "'ok'", ")", "reply_msg", "=", "self", ".", "session", ".", "send", "(", "stream", ",", "'abort_reply'", ",", "content", "=", "content", ",", "parent", "=", "parent", ",", "ident", "=", "ident", ")", "self", ".", "log", ".", "debug", "(", "\"%s\"", ",", "reply_msg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel.clear_request
Clear our namespace.
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def clear_request(self, stream, idents, parent): """Clear our namespace.""" self.shell.reset(False) msg = self.session.send(stream, 'clear_reply', ident=idents, parent=parent, content = dict(status='ok'))
def clear_request(self, stream, idents, parent): """Clear our namespace.""" self.shell.reset(False) msg = self.session.send(stream, 'clear_reply', ident=idents, parent=parent, content = dict(status='ok'))
[ "Clear", "our", "namespace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L627-L631
[ "def", "clear_request", "(", "self", ",", "stream", ",", "idents", ",", "parent", ")", ":", "self", ".", "shell", ".", "reset", "(", "False", ")", "msg", "=", "self", ".", "session", ".", "send", "(", "stream", ",", "'clear_reply'", ",", "ident", "=", "idents", ",", "parent", "=", "parent", ",", "content", "=", "dict", "(", "status", "=", "'ok'", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel._topic
prefixed topic for IOPub messages
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def _topic(self, topic): """prefixed topic for IOPub messages""" if self.int_id >= 0: base = "engine.%i" % self.int_id else: base = "kernel.%s" % self.ident return py3compat.cast_bytes("%s.%s" % (base, topic))
def _topic(self, topic): """prefixed topic for IOPub messages""" if self.int_id >= 0: base = "engine.%i" % self.int_id else: base = "kernel.%s" % self.ident return py3compat.cast_bytes("%s.%s" % (base, topic))
[ "prefixed", "topic", "for", "IOPub", "messages" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L647-L654
[ "def", "_topic", "(", "self", ",", "topic", ")", ":", "if", "self", ".", "int_id", ">=", "0", ":", "base", "=", "\"engine.%i\"", "%", "self", ".", "int_id", "else", ":", "base", "=", "\"kernel.%s\"", "%", "self", ".", "ident", "return", "py3compat", ".", "cast_bytes", "(", "\"%s.%s\"", "%", "(", "base", ",", "topic", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Kernel._at_shutdown
Actions taken at shutdown by the kernel, called by python's atexit.
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def _at_shutdown(self): """Actions taken at shutdown by the kernel, called by python's atexit. """ # io.rprint("Kernel at_shutdown") # dbg if self._shutdown_message is not None: self.session.send(self.iopub_socket, self._shutdown_message, ident=self._topic('shutdown')) self.log.debug("%s", self._shutdown_message) [ s.flush(zmq.POLLOUT) for s in self.shell_streams ]
def _at_shutdown(self): """Actions taken at shutdown by the kernel, called by python's atexit. """ # io.rprint("Kernel at_shutdown") # dbg if self._shutdown_message is not None: self.session.send(self.iopub_socket, self._shutdown_message, ident=self._topic('shutdown')) self.log.debug("%s", self._shutdown_message) [ s.flush(zmq.POLLOUT) for s in self.shell_streams ]
[ "Actions", "taken", "at", "shutdown", "by", "the", "kernel", "called", "by", "python", "s", "atexit", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L763-L770
[ "def", "_at_shutdown", "(", "self", ")", ":", "# io.rprint(\"Kernel at_shutdown\") # dbg", "if", "self", ".", "_shutdown_message", "is", "not", "None", ":", "self", ".", "session", ".", "send", "(", "self", ".", "iopub_socket", ",", "self", ".", "_shutdown_message", ",", "ident", "=", "self", ".", "_topic", "(", "'shutdown'", ")", ")", "self", ".", "log", ".", "debug", "(", "\"%s\"", ",", "self", ".", "_shutdown_message", ")", "[", "s", ".", "flush", "(", "zmq", ".", "POLLOUT", ")", "for", "s", "in", "self", ".", "shell_streams", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IPKernelApp.init_gui_pylab
Enable GUI event loop integration, taking pylab into account.
environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py
def init_gui_pylab(self): """Enable GUI event loop integration, taking pylab into account.""" # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab` # to ensure that any exception is printed straight to stderr. # Normally _showtraceback associates the reply with an execution, # which means frontends will never draw it, as this exception # is not associated with any execute request. shell = self.shell _showtraceback = shell._showtraceback try: # replace pyerr-sending traceback with stderr def print_tb(etype, evalue, stb): print ("GUI event loop or pylab initialization failed", file=io.stderr) print (shell.InteractiveTB.stb2text(stb), file=io.stderr) shell._showtraceback = print_tb InteractiveShellApp.init_gui_pylab(self) finally: shell._showtraceback = _showtraceback
def init_gui_pylab(self): """Enable GUI event loop integration, taking pylab into account.""" # Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab` # to ensure that any exception is printed straight to stderr. # Normally _showtraceback associates the reply with an execution, # which means frontends will never draw it, as this exception # is not associated with any execute request. shell = self.shell _showtraceback = shell._showtraceback try: # replace pyerr-sending traceback with stderr def print_tb(etype, evalue, stb): print ("GUI event loop or pylab initialization failed", file=io.stderr) print (shell.InteractiveTB.stb2text(stb), file=io.stderr) shell._showtraceback = print_tb InteractiveShellApp.init_gui_pylab(self) finally: shell._showtraceback = _showtraceback
[ "Enable", "GUI", "event", "loop", "integration", "taking", "pylab", "into", "account", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/ipkernel.py#L825-L845
[ "def", "init_gui_pylab", "(", "self", ")", ":", "# Provide a wrapper for :meth:`InteractiveShellApp.init_gui_pylab`", "# to ensure that any exception is printed straight to stderr.", "# Normally _showtraceback associates the reply with an execution,", "# which means frontends will never draw it, as this exception", "# is not associated with any execute request.", "shell", "=", "self", ".", "shell", "_showtraceback", "=", "shell", ".", "_showtraceback", "try", ":", "# replace pyerr-sending traceback with stderr", "def", "print_tb", "(", "etype", ",", "evalue", ",", "stb", ")", ":", "print", "(", "\"GUI event loop or pylab initialization failed\"", ",", "file", "=", "io", ".", "stderr", ")", "print", "(", "shell", ".", "InteractiveTB", ".", "stb2text", "(", "stb", ")", ",", "file", "=", "io", ".", "stderr", ")", "shell", ".", "_showtraceback", "=", "print_tb", "InteractiveShellApp", ".", "init_gui_pylab", "(", "self", ")", "finally", ":", "shell", ".", "_showtraceback", "=", "_showtraceback" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Slicer.slices
Create equal sized slices of the file. The last slice may be larger than the others. args: * size (int): The full size to be sliced. * n (int): The number of slices to return. returns: A list of `FileSlice` objects of length (n).
fileslice.py
def slices(self, size, n=3): ''' Create equal sized slices of the file. The last slice may be larger than the others. args: * size (int): The full size to be sliced. * n (int): The number of slices to return. returns: A list of `FileSlice` objects of length (n). ''' if n <= 0: raise ValueError('n must be greater than 0') if size < n: raise ValueError('size argument cannot be less than n argument') slice_size = size // n last_slice_size = size - (n-1) * slice_size t = [self(c, slice_size) for c in range(0, (n-1)*slice_size, slice_size)] t.append(self((n-1)*slice_size, last_slice_size)) return t
def slices(self, size, n=3): ''' Create equal sized slices of the file. The last slice may be larger than the others. args: * size (int): The full size to be sliced. * n (int): The number of slices to return. returns: A list of `FileSlice` objects of length (n). ''' if n <= 0: raise ValueError('n must be greater than 0') if size < n: raise ValueError('size argument cannot be less than n argument') slice_size = size // n last_slice_size = size - (n-1) * slice_size t = [self(c, slice_size) for c in range(0, (n-1)*slice_size, slice_size)] t.append(self((n-1)*slice_size, last_slice_size)) return t
[ "Create", "equal", "sized", "slices", "of", "the", "file", ".", "The", "last", "slice", "may", "be", "larger", "than", "the", "others", ".", "args", ":", "*", "size", "(", "int", ")", ":", "The", "full", "size", "to", "be", "sliced", ".", "*", "n", "(", "int", ")", ":", "The", "number", "of", "slices", "to", "return", ".", "returns", ":", "A", "list", "of", "FileSlice", "objects", "of", "length", "(", "n", ")", "." ]
alghafli/fileslice
python
https://github.com/alghafli/fileslice/blob/ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2/fileslice.py#L74-L93
[ "def", "slices", "(", "self", ",", "size", ",", "n", "=", "3", ")", ":", "if", "n", "<=", "0", ":", "raise", "ValueError", "(", "'n must be greater than 0'", ")", "if", "size", "<", "n", ":", "raise", "ValueError", "(", "'size argument cannot be less than n argument'", ")", "slice_size", "=", "size", "//", "n", "last_slice_size", "=", "size", "-", "(", "n", "-", "1", ")", "*", "slice_size", "t", "=", "[", "self", "(", "c", ",", "slice_size", ")", "for", "c", "in", "range", "(", "0", ",", "(", "n", "-", "1", ")", "*", "slice_size", ",", "slice_size", ")", "]", "t", ".", "append", "(", "self", "(", "(", "n", "-", "1", ")", "*", "slice_size", ",", "last_slice_size", ")", ")", "return", "t" ]
ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2
test
FileSlice.seek
Same as `file.seek()` but for the slice. Returns a value between `self.start` and `self.size` inclusive. raises: ValueError if the new seek position is not between 0 and `self.size`.
fileslice.py
def seek(self, offset, whence=0): ''' Same as `file.seek()` but for the slice. Returns a value between `self.start` and `self.size` inclusive. raises: ValueError if the new seek position is not between 0 and `self.size`. ''' if self.closed: raise ValueError('I/O operation on closed file.') if whence == SEEK_SET: pos = offset elif whence == SEEK_CUR: pos = self.pos + offset elif whence == SEEK_END: pos = self.size + offset if not 0 <= pos <= self.size: raise ValueError('new position ({}) will fall outside the file slice range (0-{})'.format(pos, self.size)) self.pos = pos return self.pos
def seek(self, offset, whence=0): ''' Same as `file.seek()` but for the slice. Returns a value between `self.start` and `self.size` inclusive. raises: ValueError if the new seek position is not between 0 and `self.size`. ''' if self.closed: raise ValueError('I/O operation on closed file.') if whence == SEEK_SET: pos = offset elif whence == SEEK_CUR: pos = self.pos + offset elif whence == SEEK_END: pos = self.size + offset if not 0 <= pos <= self.size: raise ValueError('new position ({}) will fall outside the file slice range (0-{})'.format(pos, self.size)) self.pos = pos return self.pos
[ "Same", "as", "file", ".", "seek", "()", "but", "for", "the", "slice", ".", "Returns", "a", "value", "between", "self", ".", "start", "and", "self", ".", "size", "inclusive", ".", "raises", ":", "ValueError", "if", "the", "new", "seek", "position", "is", "not", "between", "0", "and", "self", ".", "size", "." ]
alghafli/fileslice
python
https://github.com/alghafli/fileslice/blob/ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2/fileslice.py#L167-L190
[ "def", "seek", "(", "self", ",", "offset", ",", "whence", "=", "0", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "'I/O operation on closed file.'", ")", "if", "whence", "==", "SEEK_SET", ":", "pos", "=", "offset", "elif", "whence", "==", "SEEK_CUR", ":", "pos", "=", "self", ".", "pos", "+", "offset", "elif", "whence", "==", "SEEK_END", ":", "pos", "=", "self", ".", "size", "+", "offset", "if", "not", "0", "<=", "pos", "<=", "self", ".", "size", ":", "raise", "ValueError", "(", "'new position ({}) will fall outside the file slice range (0-{})'", ".", "format", "(", "pos", ",", "self", ".", "size", ")", ")", "self", ".", "pos", "=", "pos", "return", "self", ".", "pos" ]
ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2
test
FileSlice.read
Same as `file.read()` but for the slice. Does not read beyond `self.end`.
fileslice.py
def read(self, size=-1): ''' Same as `file.read()` but for the slice. Does not read beyond `self.end`. ''' if self.closed: raise ValueError('I/O operation on closed file.') if size == -1 or size > self.size - self.pos: size = self.size - self.pos with self.lock: self.f.seek(self.start + self.pos) result = self.f.read(size) self.seek(self.pos + size) return result
def read(self, size=-1): ''' Same as `file.read()` but for the slice. Does not read beyond `self.end`. ''' if self.closed: raise ValueError('I/O operation on closed file.') if size == -1 or size > self.size - self.pos: size = self.size - self.pos with self.lock: self.f.seek(self.start + self.pos) result = self.f.read(size) self.seek(self.pos + size) return result
[ "Same", "as", "file", ".", "read", "()", "but", "for", "the", "slice", ".", "Does", "not", "read", "beyond", "self", ".", "end", "." ]
alghafli/fileslice
python
https://github.com/alghafli/fileslice/blob/ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2/fileslice.py#L192-L208
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "'I/O operation on closed file.'", ")", "if", "size", "==", "-", "1", "or", "size", ">", "self", ".", "size", "-", "self", ".", "pos", ":", "size", "=", "self", ".", "size", "-", "self", ".", "pos", "with", "self", ".", "lock", ":", "self", ".", "f", ".", "seek", "(", "self", ".", "start", "+", "self", ".", "pos", ")", "result", "=", "self", ".", "f", ".", "read", "(", "size", ")", "self", ".", "seek", "(", "self", ".", "pos", "+", "size", ")", "return", "result" ]
ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2
test
FileSlice.write
Same as `file.write()` but for the slice. raises: EOFError if the new seek position is > `self.size`.
fileslice.py
def write(self, b): ''' Same as `file.write()` but for the slice. raises: EOFError if the new seek position is > `self.size`. ''' if self.closed: raise ValueError('I/O operation on closed file.') if self.pos + len(b) > self.size: raise EOFError('new position ({}) will fall outside the file slice range (0-{})'.format(self.pos + len(b), self.size)) with self.lock: self.f.seek(self.start + self.pos) result = self.f.write(b) self.seek(self.pos + len(b)) return result
def write(self, b): ''' Same as `file.write()` but for the slice. raises: EOFError if the new seek position is > `self.size`. ''' if self.closed: raise ValueError('I/O operation on closed file.') if self.pos + len(b) > self.size: raise EOFError('new position ({}) will fall outside the file slice range (0-{})'.format(self.pos + len(b), self.size)) with self.lock: self.f.seek(self.start + self.pos) result = self.f.write(b) self.seek(self.pos + len(b)) return result
[ "Same", "as", "file", ".", "write", "()", "but", "for", "the", "slice", ".", "raises", ":", "EOFError", "if", "the", "new", "seek", "position", "is", ">", "self", ".", "size", "." ]
alghafli/fileslice
python
https://github.com/alghafli/fileslice/blob/ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2/fileslice.py#L210-L228
[ "def", "write", "(", "self", ",", "b", ")", ":", "if", "self", ".", "closed", ":", "raise", "ValueError", "(", "'I/O operation on closed file.'", ")", "if", "self", ".", "pos", "+", "len", "(", "b", ")", ">", "self", ".", "size", ":", "raise", "EOFError", "(", "'new position ({}) will fall outside the file slice range (0-{})'", ".", "format", "(", "self", ".", "pos", "+", "len", "(", "b", ")", ",", "self", ".", "size", ")", ")", "with", "self", ".", "lock", ":", "self", ".", "f", ".", "seek", "(", "self", ".", "start", "+", "self", ".", "pos", ")", "result", "=", "self", ".", "f", ".", "write", "(", "b", ")", "self", ".", "seek", "(", "self", ".", "pos", "+", "len", "(", "b", ")", ")", "return", "result" ]
ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2
test
FileSlice.writelines
Same as `file.writelines()` but for the slice. raises: EOFError if the new seek position is > `self.size`.
fileslice.py
def writelines(self, lines): ''' Same as `file.writelines()` but for the slice. raises: EOFError if the new seek position is > `self.size`. ''' lines = b''.join(lines) self.write(lines)
def writelines(self, lines): ''' Same as `file.writelines()` but for the slice. raises: EOFError if the new seek position is > `self.size`. ''' lines = b''.join(lines) self.write(lines)
[ "Same", "as", "file", ".", "writelines", "()", "but", "for", "the", "slice", ".", "raises", ":", "EOFError", "if", "the", "new", "seek", "position", "is", ">", "self", ".", "size", "." ]
alghafli/fileslice
python
https://github.com/alghafli/fileslice/blob/ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2/fileslice.py#L230-L238
[ "def", "writelines", "(", "self", ",", "lines", ")", ":", "lines", "=", "b''", ".", "join", "(", "lines", ")", "self", ".", "write", "(", "lines", ")" ]
ada4cb2a1bb78a3d7f7b43fc81f6a1921f8d41c2
test
IsolationPlugin.configure
Configure plugin.
environment/lib/python2.7/site-packages/nose/plugins/isolate.py
def configure(self, options, conf): """Configure plugin. """ Plugin.configure(self, options, conf) self._mod_stack = []
def configure(self, options, conf): """Configure plugin. """ Plugin.configure(self, options, conf) self._mod_stack = []
[ "Configure", "plugin", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/isolate.py#L58-L62
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "Plugin", ".", "configure", "(", "self", ",", "options", ",", "conf", ")", "self", ".", "_mod_stack", "=", "[", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IsolationPlugin.beforeContext
Copy sys.modules onto my mod stack
environment/lib/python2.7/site-packages/nose/plugins/isolate.py
def beforeContext(self): """Copy sys.modules onto my mod stack """ mods = sys.modules.copy() self._mod_stack.append(mods)
def beforeContext(self): """Copy sys.modules onto my mod stack """ mods = sys.modules.copy() self._mod_stack.append(mods)
[ "Copy", "sys", ".", "modules", "onto", "my", "mod", "stack" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/isolate.py#L64-L68
[ "def", "beforeContext", "(", "self", ")", ":", "mods", "=", "sys", ".", "modules", ".", "copy", "(", ")", "self", ".", "_mod_stack", ".", "append", "(", "mods", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
IsolationPlugin.afterContext
Pop my mod stack and restore sys.modules to the state it was in when mod stack was pushed.
environment/lib/python2.7/site-packages/nose/plugins/isolate.py
def afterContext(self): """Pop my mod stack and restore sys.modules to the state it was in when mod stack was pushed. """ mods = self._mod_stack.pop() to_del = [ m for m in sys.modules.keys() if m not in mods ] if to_del: log.debug('removing sys modules entries: %s', to_del) for mod in to_del: del sys.modules[mod] sys.modules.update(mods)
def afterContext(self): """Pop my mod stack and restore sys.modules to the state it was in when mod stack was pushed. """ mods = self._mod_stack.pop() to_del = [ m for m in sys.modules.keys() if m not in mods ] if to_del: log.debug('removing sys modules entries: %s', to_del) for mod in to_del: del sys.modules[mod] sys.modules.update(mods)
[ "Pop", "my", "mod", "stack", "and", "restore", "sys", ".", "modules", "to", "the", "state", "it", "was", "in", "when", "mod", "stack", "was", "pushed", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/isolate.py#L70-L80
[ "def", "afterContext", "(", "self", ")", ":", "mods", "=", "self", ".", "_mod_stack", ".", "pop", "(", ")", "to_del", "=", "[", "m", "for", "m", "in", "sys", ".", "modules", ".", "keys", "(", ")", "if", "m", "not", "in", "mods", "]", "if", "to_del", ":", "log", ".", "debug", "(", "'removing sys modules entries: %s'", ",", "to_del", ")", "for", "mod", "in", "to_del", ":", "del", "sys", ".", "modules", "[", "mod", "]", "sys", ".", "modules", ".", "update", "(", "mods", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
absdir
Return absolute, normalized path to directory, if it exists; None otherwise.
environment/lib/python2.7/site-packages/nose/util.py
def absdir(path): """Return absolute, normalized path to directory, if it exists; None otherwise. """ if not os.path.isabs(path): path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(), path))) if path is None or not os.path.isdir(path): return None return path
def absdir(path): """Return absolute, normalized path to directory, if it exists; None otherwise. """ if not os.path.isabs(path): path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(), path))) if path is None or not os.path.isdir(path): return None return path
[ "Return", "absolute", "normalized", "path", "to", "directory", "if", "it", "exists", ";", "None", "otherwise", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L87-L96
[ "def", "absdir", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "path", ")", ")", ")", "if", "path", "is", "None", "or", "not", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "return", "None", "return", "path" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
absfile
Return absolute, normalized path to file (optionally in directory where), or None if the file can't be found either in where or the current working directory.
environment/lib/python2.7/site-packages/nose/util.py
def absfile(path, where=None): """Return absolute, normalized path to file (optionally in directory where), or None if the file can't be found either in where or the current working directory. """ orig = path if where is None: where = os.getcwd() if isinstance(where, list) or isinstance(where, tuple): for maybe_path in where: maybe_abs = absfile(path, maybe_path) if maybe_abs is not None: return maybe_abs return None if not os.path.isabs(path): path = os.path.normpath(os.path.abspath(os.path.join(where, path))) if path is None or not os.path.exists(path): if where != os.getcwd(): # try the cwd instead path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(), orig))) if path is None or not os.path.exists(path): return None if os.path.isdir(path): # might want an __init__.py from pacakge init = os.path.join(path,'__init__.py') if os.path.isfile(init): return init elif os.path.isfile(path): return path return None
def absfile(path, where=None): """Return absolute, normalized path to file (optionally in directory where), or None if the file can't be found either in where or the current working directory. """ orig = path if where is None: where = os.getcwd() if isinstance(where, list) or isinstance(where, tuple): for maybe_path in where: maybe_abs = absfile(path, maybe_path) if maybe_abs is not None: return maybe_abs return None if not os.path.isabs(path): path = os.path.normpath(os.path.abspath(os.path.join(where, path))) if path is None or not os.path.exists(path): if where != os.getcwd(): # try the cwd instead path = os.path.normpath(os.path.abspath(os.path.join(os.getcwd(), orig))) if path is None or not os.path.exists(path): return None if os.path.isdir(path): # might want an __init__.py from pacakge init = os.path.join(path,'__init__.py') if os.path.isfile(init): return init elif os.path.isfile(path): return path return None
[ "Return", "absolute", "normalized", "path", "to", "file", "(", "optionally", "in", "directory", "where", ")", "or", "None", "if", "the", "file", "can", "t", "be", "found", "either", "in", "where", "or", "the", "current", "working", "directory", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L99-L129
[ "def", "absfile", "(", "path", ",", "where", "=", "None", ")", ":", "orig", "=", "path", "if", "where", "is", "None", ":", "where", "=", "os", ".", "getcwd", "(", ")", "if", "isinstance", "(", "where", ",", "list", ")", "or", "isinstance", "(", "where", ",", "tuple", ")", ":", "for", "maybe_path", "in", "where", ":", "maybe_abs", "=", "absfile", "(", "path", ",", "maybe_path", ")", "if", "maybe_abs", "is", "not", "None", ":", "return", "maybe_abs", "return", "None", "if", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "where", ",", "path", ")", ")", ")", "if", "path", "is", "None", "or", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "if", "where", "!=", "os", ".", "getcwd", "(", ")", ":", "# try the cwd instead", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "orig", ")", ")", ")", "if", "path", "is", "None", "or", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "None", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "# might want an __init__.py from pacakge", "init", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'__init__.py'", ")", "if", "os", ".", "path", ".", "isfile", "(", "init", ")", ":", "return", "init", "elif", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "return", "path", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
file_like
A name is file-like if it is a path that exists, or it has a directory part, or it ends in .py, or it isn't a legal python identifier.
environment/lib/python2.7/site-packages/nose/util.py
def file_like(name): """A name is file-like if it is a path that exists, or it has a directory part, or it ends in .py, or it isn't a legal python identifier. """ return (os.path.exists(name) or os.path.dirname(name) or name.endswith('.py') or not ident_re.match(os.path.splitext(name)[0]))
def file_like(name): """A name is file-like if it is a path that exists, or it has a directory part, or it ends in .py, or it isn't a legal python identifier. """ return (os.path.exists(name) or os.path.dirname(name) or name.endswith('.py') or not ident_re.match(os.path.splitext(name)[0]))
[ "A", "name", "is", "file", "-", "like", "if", "it", "is", "a", "path", "that", "exists", "or", "it", "has", "a", "directory", "part", "or", "it", "ends", "in", ".", "py", "or", "it", "isn", "t", "a", "legal", "python", "identifier", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L139-L147
[ "def", "file_like", "(", "name", ")", ":", "return", "(", "os", ".", "path", ".", "exists", "(", "name", ")", "or", "os", ".", "path", ".", "dirname", "(", "name", ")", "or", "name", ".", "endswith", "(", "'.py'", ")", "or", "not", "ident_re", ".", "match", "(", "os", ".", "path", ".", "splitext", "(", "name", ")", "[", "0", "]", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
isclass
Is obj a class? Inspect's isclass is too liberal and returns True for objects that can't be subclasses of anything.
environment/lib/python2.7/site-packages/nose/util.py
def isclass(obj): """Is obj a class? Inspect's isclass is too liberal and returns True for objects that can't be subclasses of anything. """ obj_type = type(obj) return obj_type in class_types or issubclass(obj_type, type)
def isclass(obj): """Is obj a class? Inspect's isclass is too liberal and returns True for objects that can't be subclasses of anything. """ obj_type = type(obj) return obj_type in class_types or issubclass(obj_type, type)
[ "Is", "obj", "a", "class?", "Inspect", "s", "isclass", "is", "too", "liberal", "and", "returns", "True", "for", "objects", "that", "can", "t", "be", "subclasses", "of", "anything", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L163-L168
[ "def", "isclass", "(", "obj", ")", ":", "obj_type", "=", "type", "(", "obj", ")", "return", "obj_type", "in", "class_types", "or", "issubclass", "(", "obj_type", ",", "type", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ispackage
Is this path a package directory? >>> ispackage('nose') True >>> ispackage('unit_tests') False >>> ispackage('nose/plugins') True >>> ispackage('nose/loader.py') False
environment/lib/python2.7/site-packages/nose/util.py
def ispackage(path): """ Is this path a package directory? >>> ispackage('nose') True >>> ispackage('unit_tests') False >>> ispackage('nose/plugins') True >>> ispackage('nose/loader.py') False """ if os.path.isdir(path): # at least the end of the path must be a legal python identifier # and __init__.py[co] must exist end = os.path.basename(path) if ident_re.match(end): for init in ('__init__.py', '__init__.pyc', '__init__.pyo'): if os.path.isfile(os.path.join(path, init)): return True if sys.platform.startswith('java') and \ os.path.isfile(os.path.join(path, '__init__$py.class')): return True return False
def ispackage(path): """ Is this path a package directory? >>> ispackage('nose') True >>> ispackage('unit_tests') False >>> ispackage('nose/plugins') True >>> ispackage('nose/loader.py') False """ if os.path.isdir(path): # at least the end of the path must be a legal python identifier # and __init__.py[co] must exist end = os.path.basename(path) if ident_re.match(end): for init in ('__init__.py', '__init__.pyc', '__init__.pyo'): if os.path.isfile(os.path.join(path, init)): return True if sys.platform.startswith('java') and \ os.path.isfile(os.path.join(path, '__init__$py.class')): return True return False
[ "Is", "this", "path", "a", "package", "directory?" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L180-L204
[ "def", "ispackage", "(", "path", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "# at least the end of the path must be a legal python identifier", "# and __init__.py[co] must exist", "end", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "if", "ident_re", ".", "match", "(", "end", ")", ":", "for", "init", "in", "(", "'__init__.py'", ",", "'__init__.pyc'", ",", "'__init__.pyo'", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "init", ")", ")", ":", "return", "True", "if", "sys", ".", "platform", ".", "startswith", "(", "'java'", ")", "and", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "path", ",", "'__init__$py.class'", ")", ")", ":", "return", "True", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
getfilename
Find the python source file for a package, relative to a particular directory (defaults to current working directory if not given).
environment/lib/python2.7/site-packages/nose/util.py
def getfilename(package, relativeTo=None): """Find the python source file for a package, relative to a particular directory (defaults to current working directory if not given). """ if relativeTo is None: relativeTo = os.getcwd() path = os.path.join(relativeTo, os.sep.join(package.split('.'))) suffixes = ('/__init__.py', '.py') for suffix in suffixes: filename = path + suffix if os.path.exists(filename): return filename return None
def getfilename(package, relativeTo=None): """Find the python source file for a package, relative to a particular directory (defaults to current working directory if not given). """ if relativeTo is None: relativeTo = os.getcwd() path = os.path.join(relativeTo, os.sep.join(package.split('.'))) suffixes = ('/__init__.py', '.py') for suffix in suffixes: filename = path + suffix if os.path.exists(filename): return filename return None
[ "Find", "the", "python", "source", "file", "for", "a", "package", "relative", "to", "a", "particular", "directory", "(", "defaults", "to", "current", "working", "directory", "if", "not", "given", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L226-L239
[ "def", "getfilename", "(", "package", ",", "relativeTo", "=", "None", ")", ":", "if", "relativeTo", "is", "None", ":", "relativeTo", "=", "os", ".", "getcwd", "(", ")", "path", "=", "os", ".", "path", ".", "join", "(", "relativeTo", ",", "os", ".", "sep", ".", "join", "(", "package", ".", "split", "(", "'.'", ")", ")", ")", "suffixes", "=", "(", "'/__init__.py'", ",", "'.py'", ")", "for", "suffix", "in", "suffixes", ":", "filename", "=", "path", "+", "suffix", "if", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "return", "filename", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
getpackage
Find the full dotted package name for a given python source file name. Returns None if the file is not a python source file. >>> getpackage('foo.py') 'foo' >>> getpackage('biff/baf.py') 'baf' >>> getpackage('nose/util.py') 'nose.util' Works for directories too. >>> getpackage('nose') 'nose' >>> getpackage('nose/plugins') 'nose.plugins' And __init__ files stuck onto directories >>> getpackage('nose/plugins/__init__.py') 'nose.plugins' Absolute paths also work. >>> path = os.path.abspath(os.path.join('nose', 'plugins')) >>> getpackage(path) 'nose.plugins'
environment/lib/python2.7/site-packages/nose/util.py
def getpackage(filename): """ Find the full dotted package name for a given python source file name. Returns None if the file is not a python source file. >>> getpackage('foo.py') 'foo' >>> getpackage('biff/baf.py') 'baf' >>> getpackage('nose/util.py') 'nose.util' Works for directories too. >>> getpackage('nose') 'nose' >>> getpackage('nose/plugins') 'nose.plugins' And __init__ files stuck onto directories >>> getpackage('nose/plugins/__init__.py') 'nose.plugins' Absolute paths also work. >>> path = os.path.abspath(os.path.join('nose', 'plugins')) >>> getpackage(path) 'nose.plugins' """ src_file = src(filename) if not src_file.endswith('.py') and not ispackage(src_file): return None base, ext = os.path.splitext(os.path.basename(src_file)) if base == '__init__': mod_parts = [] else: mod_parts = [base] path, part = os.path.split(os.path.split(src_file)[0]) while part: if ispackage(os.path.join(path, part)): mod_parts.append(part) else: break path, part = os.path.split(path) mod_parts.reverse() return '.'.join(mod_parts)
def getpackage(filename): """ Find the full dotted package name for a given python source file name. Returns None if the file is not a python source file. >>> getpackage('foo.py') 'foo' >>> getpackage('biff/baf.py') 'baf' >>> getpackage('nose/util.py') 'nose.util' Works for directories too. >>> getpackage('nose') 'nose' >>> getpackage('nose/plugins') 'nose.plugins' And __init__ files stuck onto directories >>> getpackage('nose/plugins/__init__.py') 'nose.plugins' Absolute paths also work. >>> path = os.path.abspath(os.path.join('nose', 'plugins')) >>> getpackage(path) 'nose.plugins' """ src_file = src(filename) if not src_file.endswith('.py') and not ispackage(src_file): return None base, ext = os.path.splitext(os.path.basename(src_file)) if base == '__init__': mod_parts = [] else: mod_parts = [base] path, part = os.path.split(os.path.split(src_file)[0]) while part: if ispackage(os.path.join(path, part)): mod_parts.append(part) else: break path, part = os.path.split(path) mod_parts.reverse() return '.'.join(mod_parts)
[ "Find", "the", "full", "dotted", "package", "name", "for", "a", "given", "python", "source", "file", "name", ".", "Returns", "None", "if", "the", "file", "is", "not", "a", "python", "source", "file", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L242-L288
[ "def", "getpackage", "(", "filename", ")", ":", "src_file", "=", "src", "(", "filename", ")", "if", "not", "src_file", ".", "endswith", "(", "'.py'", ")", "and", "not", "ispackage", "(", "src_file", ")", ":", "return", "None", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "src_file", ")", ")", "if", "base", "==", "'__init__'", ":", "mod_parts", "=", "[", "]", "else", ":", "mod_parts", "=", "[", "base", "]", "path", ",", "part", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "split", "(", "src_file", ")", "[", "0", "]", ")", "while", "part", ":", "if", "ispackage", "(", "os", ".", "path", ".", "join", "(", "path", ",", "part", ")", ")", ":", "mod_parts", ".", "append", "(", "part", ")", "else", ":", "break", "path", ",", "part", "=", "os", ".", "path", ".", "split", "(", "path", ")", "mod_parts", ".", "reverse", "(", ")", "return", "'.'", ".", "join", "(", "mod_parts", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
ln
Draw a 70-char-wide divider, with label in the middle. >>> ln('hello there') '---------------------------- hello there -----------------------------'
environment/lib/python2.7/site-packages/nose/util.py
def ln(label): """Draw a 70-char-wide divider, with label in the middle. >>> ln('hello there') '---------------------------- hello there -----------------------------' """ label_len = len(label) + 2 chunk = (70 - label_len) // 2 out = '%s %s %s' % ('-' * chunk, label, '-' * chunk) pad = 70 - len(out) if pad > 0: out = out + ('-' * pad) return out
def ln(label): """Draw a 70-char-wide divider, with label in the middle. >>> ln('hello there') '---------------------------- hello there -----------------------------' """ label_len = len(label) + 2 chunk = (70 - label_len) // 2 out = '%s %s %s' % ('-' * chunk, label, '-' * chunk) pad = 70 - len(out) if pad > 0: out = out + ('-' * pad) return out
[ "Draw", "a", "70", "-", "char", "-", "wide", "divider", "with", "label", "in", "the", "middle", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L291-L303
[ "def", "ln", "(", "label", ")", ":", "label_len", "=", "len", "(", "label", ")", "+", "2", "chunk", "=", "(", "70", "-", "label_len", ")", "//", "2", "out", "=", "'%s %s %s'", "%", "(", "'-'", "*", "chunk", ",", "label", ",", "'-'", "*", "chunk", ")", "pad", "=", "70", "-", "len", "(", "out", ")", "if", "pad", ">", "0", ":", "out", "=", "out", "+", "(", "'-'", "*", "pad", ")", "return", "out" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
try_run
Given a list of possible method names, try to run them with the provided object. Keep going until something works. Used to run setup/teardown methods for module, package, and function tests.
environment/lib/python2.7/site-packages/nose/util.py
def try_run(obj, names): """Given a list of possible method names, try to run them with the provided object. Keep going until something works. Used to run setup/teardown methods for module, package, and function tests. """ for name in names: func = getattr(obj, name, None) if func is not None: if type(obj) == types.ModuleType: # py.test compatibility try: args, varargs, varkw, defaults = inspect.getargspec(func) except TypeError: # Not a function. If it's callable, call it anyway if hasattr(func, '__call__'): func = func.__call__ try: args, varargs, varkw, defaults = \ inspect.getargspec(func) args.pop(0) # pop the self off except TypeError: raise TypeError("Attribute %s of %r is not a python " "function. Only functions or callables" " may be used as fixtures." % (name, obj)) if len(args): log.debug("call fixture %s.%s(%s)", obj, name, obj) return func(obj) log.debug("call fixture %s.%s", obj, name) return func()
def try_run(obj, names): """Given a list of possible method names, try to run them with the provided object. Keep going until something works. Used to run setup/teardown methods for module, package, and function tests. """ for name in names: func = getattr(obj, name, None) if func is not None: if type(obj) == types.ModuleType: # py.test compatibility try: args, varargs, varkw, defaults = inspect.getargspec(func) except TypeError: # Not a function. If it's callable, call it anyway if hasattr(func, '__call__'): func = func.__call__ try: args, varargs, varkw, defaults = \ inspect.getargspec(func) args.pop(0) # pop the self off except TypeError: raise TypeError("Attribute %s of %r is not a python " "function. Only functions or callables" " may be used as fixtures." % (name, obj)) if len(args): log.debug("call fixture %s.%s(%s)", obj, name, obj) return func(obj) log.debug("call fixture %s.%s", obj, name) return func()
[ "Given", "a", "list", "of", "possible", "method", "names", "try", "to", "run", "them", "with", "the", "provided", "object", ".", "Keep", "going", "until", "something", "works", ".", "Used", "to", "run", "setup", "/", "teardown", "methods", "for", "module", "package", "and", "function", "tests", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L449-L478
[ "def", "try_run", "(", "obj", ",", "names", ")", ":", "for", "name", "in", "names", ":", "func", "=", "getattr", "(", "obj", ",", "name", ",", "None", ")", "if", "func", "is", "not", "None", ":", "if", "type", "(", "obj", ")", "==", "types", ".", "ModuleType", ":", "# py.test compatibility", "try", ":", "args", ",", "varargs", ",", "varkw", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "func", ")", "except", "TypeError", ":", "# Not a function. If it's callable, call it anyway", "if", "hasattr", "(", "func", ",", "'__call__'", ")", ":", "func", "=", "func", ".", "__call__", "try", ":", "args", ",", "varargs", ",", "varkw", ",", "defaults", "=", "inspect", ".", "getargspec", "(", "func", ")", "args", ".", "pop", "(", "0", ")", "# pop the self off", "except", "TypeError", ":", "raise", "TypeError", "(", "\"Attribute %s of %r is not a python \"", "\"function. Only functions or callables\"", "\" may be used as fixtures.\"", "%", "(", "name", ",", "obj", ")", ")", "if", "len", "(", "args", ")", ":", "log", ".", "debug", "(", "\"call fixture %s.%s(%s)\"", ",", "obj", ",", "name", ",", "obj", ")", "return", "func", "(", "obj", ")", "log", ".", "debug", "(", "\"call fixture %s.%s\"", ",", "obj", ",", "name", ")", "return", "func", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
src
Find the python source file for a .pyc, .pyo or $py.class file on jython. Returns the filename provided if it is not a python source file.
environment/lib/python2.7/site-packages/nose/util.py
def src(filename): """Find the python source file for a .pyc, .pyo or $py.class file on jython. Returns the filename provided if it is not a python source file. """ if filename is None: return filename if sys.platform.startswith('java') and filename.endswith('$py.class'): return '.'.join((filename[:-9], 'py')) base, ext = os.path.splitext(filename) if ext in ('.pyc', '.pyo', '.py'): return '.'.join((base, 'py')) return filename
def src(filename): """Find the python source file for a .pyc, .pyo or $py.class file on jython. Returns the filename provided if it is not a python source file. """ if filename is None: return filename if sys.platform.startswith('java') and filename.endswith('$py.class'): return '.'.join((filename[:-9], 'py')) base, ext = os.path.splitext(filename) if ext in ('.pyc', '.pyo', '.py'): return '.'.join((base, 'py')) return filename
[ "Find", "the", "python", "source", "file", "for", "a", ".", "pyc", ".", "pyo", "or", "$py", ".", "class", "file", "on", "jython", ".", "Returns", "the", "filename", "provided", "if", "it", "is", "not", "a", "python", "source", "file", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L481-L493
[ "def", "src", "(", "filename", ")", ":", "if", "filename", "is", "None", ":", "return", "filename", "if", "sys", ".", "platform", ".", "startswith", "(", "'java'", ")", "and", "filename", ".", "endswith", "(", "'$py.class'", ")", ":", "return", "'.'", ".", "join", "(", "(", "filename", "[", ":", "-", "9", "]", ",", "'py'", ")", ")", "base", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "in", "(", "'.pyc'", ",", "'.pyo'", ",", "'.py'", ")", ":", "return", "'.'", ".", "join", "(", "(", "base", ",", "'py'", ")", ")", "return", "filename" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
regex_last_key
Sort key function factory that puts items that match a regular expression last. >>> from nose.config import Config >>> from nose.pyversion import sort_list >>> c = Config() >>> regex = c.testMatch >>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.py'] >>> sort_list(entries, regex_last_key(regex)) >>> entries ['.', '..', 'foo.py', 'lib', 'src', 'a_test', 'test']
environment/lib/python2.7/site-packages/nose/util.py
def regex_last_key(regex): """Sort key function factory that puts items that match a regular expression last. >>> from nose.config import Config >>> from nose.pyversion import sort_list >>> c = Config() >>> regex = c.testMatch >>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.py'] >>> sort_list(entries, regex_last_key(regex)) >>> entries ['.', '..', 'foo.py', 'lib', 'src', 'a_test', 'test'] """ def k(obj): if regex.search(obj): return (1, obj) return (0, obj) return k
def regex_last_key(regex): """Sort key function factory that puts items that match a regular expression last. >>> from nose.config import Config >>> from nose.pyversion import sort_list >>> c = Config() >>> regex = c.testMatch >>> entries = ['.', '..', 'a_test', 'src', 'lib', 'test', 'foo.py'] >>> sort_list(entries, regex_last_key(regex)) >>> entries ['.', '..', 'foo.py', 'lib', 'src', 'a_test', 'test'] """ def k(obj): if regex.search(obj): return (1, obj) return (0, obj) return k
[ "Sort", "key", "function", "factory", "that", "puts", "items", "that", "match", "a", "regular", "expression", "last", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L496-L513
[ "def", "regex_last_key", "(", "regex", ")", ":", "def", "k", "(", "obj", ")", ":", "if", "regex", ".", "search", "(", "obj", ")", ":", "return", "(", "1", ",", "obj", ")", "return", "(", "0", ",", "obj", ")", "return", "k" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
tolist
Convert a value that may be a list or a (possibly comma-separated) string into a list. The exception: None is returned as None, not [None]. >>> tolist(["one", "two"]) ['one', 'two'] >>> tolist("hello") ['hello'] >>> tolist("separate,values, with, commas, spaces , are ,ok") ['separate', 'values', 'with', 'commas', 'spaces', 'are', 'ok']
environment/lib/python2.7/site-packages/nose/util.py
def tolist(val): """Convert a value that may be a list or a (possibly comma-separated) string into a list. The exception: None is returned as None, not [None]. >>> tolist(["one", "two"]) ['one', 'two'] >>> tolist("hello") ['hello'] >>> tolist("separate,values, with, commas, spaces , are ,ok") ['separate', 'values', 'with', 'commas', 'spaces', 'are', 'ok'] """ if val is None: return None try: # might already be a list val.extend([]) return val except AttributeError: pass # might be a string try: return re.split(r'\s*,\s*', val) except TypeError: # who knows... return list(val)
def tolist(val): """Convert a value that may be a list or a (possibly comma-separated) string into a list. The exception: None is returned as None, not [None]. >>> tolist(["one", "two"]) ['one', 'two'] >>> tolist("hello") ['hello'] >>> tolist("separate,values, with, commas, spaces , are ,ok") ['separate', 'values', 'with', 'commas', 'spaces', 'are', 'ok'] """ if val is None: return None try: # might already be a list val.extend([]) return val except AttributeError: pass # might be a string try: return re.split(r'\s*,\s*', val) except TypeError: # who knows... return list(val)
[ "Convert", "a", "value", "that", "may", "be", "a", "list", "or", "a", "(", "possibly", "comma", "-", "separated", ")", "string", "into", "a", "list", ".", "The", "exception", ":", "None", "is", "returned", "as", "None", "not", "[", "None", "]", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L516-L540
[ "def", "tolist", "(", "val", ")", ":", "if", "val", "is", "None", ":", "return", "None", "try", ":", "# might already be a list", "val", ".", "extend", "(", "[", "]", ")", "return", "val", "except", "AttributeError", ":", "pass", "# might be a string", "try", ":", "return", "re", ".", "split", "(", "r'\\s*,\\s*'", ",", "val", ")", "except", "TypeError", ":", "# who knows...", "return", "list", "(", "val", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
transplant_func
Make a function imported from module A appear as if it is located in module B. >>> from pprint import pprint >>> pprint.__module__ 'pprint' >>> pp = transplant_func(pprint, __name__) >>> pp.__module__ 'nose.util' The original function is not modified. >>> pprint.__module__ 'pprint' Calling the transplanted function calls the original. >>> pp([1, 2]) [1, 2] >>> pprint([1,2]) [1, 2]
environment/lib/python2.7/site-packages/nose/util.py
def transplant_func(func, module): """ Make a function imported from module A appear as if it is located in module B. >>> from pprint import pprint >>> pprint.__module__ 'pprint' >>> pp = transplant_func(pprint, __name__) >>> pp.__module__ 'nose.util' The original function is not modified. >>> pprint.__module__ 'pprint' Calling the transplanted function calls the original. >>> pp([1, 2]) [1, 2] >>> pprint([1,2]) [1, 2] """ from nose.tools import make_decorator def newfunc(*arg, **kw): return func(*arg, **kw) newfunc = make_decorator(func)(newfunc) newfunc.__module__ = module return newfunc
def transplant_func(func, module): """ Make a function imported from module A appear as if it is located in module B. >>> from pprint import pprint >>> pprint.__module__ 'pprint' >>> pp = transplant_func(pprint, __name__) >>> pp.__module__ 'nose.util' The original function is not modified. >>> pprint.__module__ 'pprint' Calling the transplanted function calls the original. >>> pp([1, 2]) [1, 2] >>> pprint([1,2]) [1, 2] """ from nose.tools import make_decorator def newfunc(*arg, **kw): return func(*arg, **kw) newfunc = make_decorator(func)(newfunc) newfunc.__module__ = module return newfunc
[ "Make", "a", "function", "imported", "from", "module", "A", "appear", "as", "if", "it", "is", "located", "in", "module", "B", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L595-L626
[ "def", "transplant_func", "(", "func", ",", "module", ")", ":", "from", "nose", ".", "tools", "import", "make_decorator", "def", "newfunc", "(", "*", "arg", ",", "*", "*", "kw", ")", ":", "return", "func", "(", "*", "arg", ",", "*", "*", "kw", ")", "newfunc", "=", "make_decorator", "(", "func", ")", "(", "newfunc", ")", "newfunc", ".", "__module__", "=", "module", "return", "newfunc" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
transplant_class
Make a class appear to reside in `module`, rather than the module in which it is actually defined. >>> from nose.failure import Failure >>> Failure.__module__ 'nose.failure' >>> Nf = transplant_class(Failure, __name__) >>> Nf.__module__ 'nose.util' >>> Nf.__name__ 'Failure'
environment/lib/python2.7/site-packages/nose/util.py
def transplant_class(cls, module): """ Make a class appear to reside in `module`, rather than the module in which it is actually defined. >>> from nose.failure import Failure >>> Failure.__module__ 'nose.failure' >>> Nf = transplant_class(Failure, __name__) >>> Nf.__module__ 'nose.util' >>> Nf.__name__ 'Failure' """ class C(cls): pass C.__module__ = module C.__name__ = cls.__name__ return C
def transplant_class(cls, module): """ Make a class appear to reside in `module`, rather than the module in which it is actually defined. >>> from nose.failure import Failure >>> Failure.__module__ 'nose.failure' >>> Nf = transplant_class(Failure, __name__) >>> Nf.__module__ 'nose.util' >>> Nf.__name__ 'Failure' """ class C(cls): pass C.__module__ = module C.__name__ = cls.__name__ return C
[ "Make", "a", "class", "appear", "to", "reside", "in", "module", "rather", "than", "the", "module", "in", "which", "it", "is", "actually", "defined", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/util.py#L629-L648
[ "def", "transplant_class", "(", "cls", ",", "module", ")", ":", "class", "C", "(", "cls", ")", ":", "pass", "C", ".", "__module__", "=", "module", "C", ".", "__name__", "=", "cls", ".", "__name__", "return", "C" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
virtual_memory
System virtual memory as a namedtuple.
environment/lib/python2.7/site-packages/psutil/_psosx.py
def virtual_memory(): """System virtual memory as a namedtuple.""" total, active, inactive, wired, free = _psutil_osx.get_virtual_mem() avail = inactive + free used = active + inactive + wired percent = usage_percent((total - avail), total, _round=1) return nt_virtmem_info(total, avail, percent, used, free, active, inactive, wired)
def virtual_memory(): """System virtual memory as a namedtuple.""" total, active, inactive, wired, free = _psutil_osx.get_virtual_mem() avail = inactive + free used = active + inactive + wired percent = usage_percent((total - avail), total, _round=1) return nt_virtmem_info(total, avail, percent, used, free, active, inactive, wired)
[ "System", "virtual", "memory", "as", "a", "namedtuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L43-L50
[ "def", "virtual_memory", "(", ")", ":", "total", ",", "active", ",", "inactive", ",", "wired", ",", "free", "=", "_psutil_osx", ".", "get_virtual_mem", "(", ")", "avail", "=", "inactive", "+", "free", "used", "=", "active", "+", "inactive", "+", "wired", "percent", "=", "usage_percent", "(", "(", "total", "-", "avail", ")", ",", "total", ",", "_round", "=", "1", ")", "return", "nt_virtmem_info", "(", "total", ",", "avail", ",", "percent", ",", "used", ",", "free", ",", "active", ",", "inactive", ",", "wired", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
swap_memory
Swap system memory as a (total, used, free, sin, sout) tuple.
environment/lib/python2.7/site-packages/psutil/_psosx.py
def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" total, used, free, sin, sout = _psutil_osx.get_swap_mem() percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, sin, sout)
def swap_memory(): """Swap system memory as a (total, used, free, sin, sout) tuple.""" total, used, free, sin, sout = _psutil_osx.get_swap_mem() percent = usage_percent(used, total, _round=1) return nt_swapmeminfo(total, used, free, percent, sin, sout)
[ "Swap", "system", "memory", "as", "a", "(", "total", "used", "free", "sin", "sout", ")", "tuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L52-L56
[ "def", "swap_memory", "(", ")", ":", "total", ",", "used", ",", "free", ",", "sin", ",", "sout", "=", "_psutil_osx", ".", "get_swap_mem", "(", ")", "percent", "=", "usage_percent", "(", "used", ",", "total", ",", "_round", "=", "1", ")", "return", "nt_swapmeminfo", "(", "total", ",", "used", ",", "free", ",", "percent", ",", "sin", ",", "sout", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_system_cpu_times
Return system CPU times as a namedtuple.
environment/lib/python2.7/site-packages/psutil/_psosx.py
def get_system_cpu_times(): """Return system CPU times as a namedtuple.""" user, nice, system, idle = _psutil_osx.get_system_cpu_times() return _cputimes_ntuple(user, nice, system, idle)
def get_system_cpu_times(): """Return system CPU times as a namedtuple.""" user, nice, system, idle = _psutil_osx.get_system_cpu_times() return _cputimes_ntuple(user, nice, system, idle)
[ "Return", "system", "CPU", "times", "as", "a", "namedtuple", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L58-L61
[ "def", "get_system_cpu_times", "(", ")", ":", "user", ",", "nice", ",", "system", ",", "idle", "=", "_psutil_osx", ".", "get_system_cpu_times", "(", ")", "return", "_cputimes_ntuple", "(", "user", ",", "nice", ",", "system", ",", "idle", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_system_per_cpu_times
Return system CPU times as a named tuple
environment/lib/python2.7/site-packages/psutil/_psosx.py
def get_system_per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in _psutil_osx.get_system_per_cpu_times(): user, nice, system, idle = cpu_t item = _cputimes_ntuple(user, nice, system, idle) ret.append(item) return ret
def get_system_per_cpu_times(): """Return system CPU times as a named tuple""" ret = [] for cpu_t in _psutil_osx.get_system_per_cpu_times(): user, nice, system, idle = cpu_t item = _cputimes_ntuple(user, nice, system, idle) ret.append(item) return ret
[ "Return", "system", "CPU", "times", "as", "a", "named", "tuple" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L63-L70
[ "def", "get_system_per_cpu_times", "(", ")", ":", "ret", "=", "[", "]", "for", "cpu_t", "in", "_psutil_osx", ".", "get_system_per_cpu_times", "(", ")", ":", "user", ",", "nice", ",", "system", ",", "idle", "=", "cpu_t", "item", "=", "_cputimes_ntuple", "(", "user", ",", "nice", ",", "system", ",", "idle", ")", "ret", ".", "append", "(", "item", ")", "return", "ret" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_process_cmdline
Return process cmdline as a list of arguments.
environment/lib/python2.7/site-packages/psutil/_psosx.py
def get_process_cmdline(self): """Return process cmdline as a list of arguments.""" if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._process_name) return _psutil_osx.get_process_cmdline(self.pid)
def get_process_cmdline(self): """Return process cmdline as a list of arguments.""" if not pid_exists(self.pid): raise NoSuchProcess(self.pid, self._process_name) return _psutil_osx.get_process_cmdline(self.pid)
[ "Return", "process", "cmdline", "as", "a", "list", "of", "arguments", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L154-L158
[ "def", "get_process_cmdline", "(", "self", ")", ":", "if", "not", "pid_exists", "(", "self", ".", "pid", ")", ":", "raise", "NoSuchProcess", "(", "self", ".", "pid", ",", "self", ".", "_process_name", ")", "return", "_psutil_osx", ".", "get_process_cmdline", "(", "self", ".", "pid", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_memory_info
Return a tuple with the process' RSS and VMS size.
environment/lib/python2.7/site-packages/psutil/_psosx.py
def get_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms = _psutil_osx.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
def get_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms = _psutil_osx.get_process_memory_info(self.pid)[:2] return nt_meminfo(rss, vms)
[ "Return", "a", "tuple", "with", "the", "process", "RSS", "and", "VMS", "size", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L188-L191
[ "def", "get_memory_info", "(", "self", ")", ":", "rss", ",", "vms", "=", "_psutil_osx", ".", "get_process_memory_info", "(", "self", ".", "pid", ")", "[", ":", "2", "]", "return", "nt_meminfo", "(", "rss", ",", "vms", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_ext_memory_info
Return a tuple with the process' RSS and VMS size.
environment/lib/python2.7/site-packages/psutil/_psosx.py
def get_ext_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms, pfaults, pageins = _psutil_osx.get_process_memory_info(self.pid) return self._nt_ext_mem(rss, vms, pfaults * _PAGESIZE, pageins * _PAGESIZE)
def get_ext_memory_info(self): """Return a tuple with the process' RSS and VMS size.""" rss, vms, pfaults, pageins = _psutil_osx.get_process_memory_info(self.pid) return self._nt_ext_mem(rss, vms, pfaults * _PAGESIZE, pageins * _PAGESIZE)
[ "Return", "a", "tuple", "with", "the", "process", "RSS", "and", "VMS", "size", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L196-L201
[ "def", "get_ext_memory_info", "(", "self", ")", ":", "rss", ",", "vms", ",", "pfaults", ",", "pageins", "=", "_psutil_osx", ".", "get_process_memory_info", "(", "self", ".", "pid", ")", "return", "self", ".", "_nt_ext_mem", "(", "rss", ",", "vms", ",", "pfaults", "*", "_PAGESIZE", ",", "pageins", "*", "_PAGESIZE", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_open_files
Return files opened by process.
environment/lib/python2.7/site-packages/psutil/_psosx.py
def get_open_files(self): """Return files opened by process.""" if self.pid == 0: return [] files = [] rawlist = _psutil_osx.get_process_open_files(self.pid) for path, fd in rawlist: if isfile_strict(path): ntuple = nt_openfile(path, fd) files.append(ntuple) return files
def get_open_files(self): """Return files opened by process.""" if self.pid == 0: return [] files = [] rawlist = _psutil_osx.get_process_open_files(self.pid) for path, fd in rawlist: if isfile_strict(path): ntuple = nt_openfile(path, fd) files.append(ntuple) return files
[ "Return", "files", "opened", "by", "process", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L224-L234
[ "def", "get_open_files", "(", "self", ")", ":", "if", "self", ".", "pid", "==", "0", ":", "return", "[", "]", "files", "=", "[", "]", "rawlist", "=", "_psutil_osx", ".", "get_process_open_files", "(", "self", ".", "pid", ")", "for", "path", ",", "fd", "in", "rawlist", ":", "if", "isfile_strict", "(", "path", ")", ":", "ntuple", "=", "nt_openfile", "(", "path", ",", "fd", ")", "files", ".", "append", "(", "ntuple", ")", "return", "files" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_connections
Return etwork connections opened by a process as a list of namedtuples.
environment/lib/python2.7/site-packages/psutil/_psosx.py
def get_connections(self, kind='inet'): """Return etwork connections opened by a process as a list of namedtuples. """ if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] ret = _psutil_osx.get_process_connections(self.pid, families, types) return [nt_connection(*conn) for conn in ret]
def get_connections(self, kind='inet'): """Return etwork connections opened by a process as a list of namedtuples. """ if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] ret = _psutil_osx.get_process_connections(self.pid, families, types) return [nt_connection(*conn) for conn in ret]
[ "Return", "etwork", "connections", "opened", "by", "a", "process", "as", "a", "list", "of", "namedtuples", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_psosx.py#L237-L246
[ "def", "get_connections", "(", "self", ",", "kind", "=", "'inet'", ")", ":", "if", "kind", "not", "in", "conn_tmap", ":", "raise", "ValueError", "(", "\"invalid %r kind argument; choose between %s\"", "%", "(", "kind", ",", "', '", ".", "join", "(", "[", "repr", "(", "x", ")", "for", "x", "in", "conn_tmap", "]", ")", ")", ")", "families", ",", "types", "=", "conn_tmap", "[", "kind", "]", "ret", "=", "_psutil_osx", ".", "get_process_connections", "(", "self", ".", "pid", ",", "families", ",", "types", ")", "return", "[", "nt_connection", "(", "*", "conn", ")", "for", "conn", "in", "ret", "]" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
user_has_group
Check if a user is in a certaing group. By default, the check is skipped for superusers.
django_baseline/__init__.py
def user_has_group(user, group, superuser_skip=True): """ Check if a user is in a certaing group. By default, the check is skipped for superusers. """ if user.is_superuser and superuser_skip: return True return user.groups.filter(name=group).exists()
def user_has_group(user, group, superuser_skip=True): """ Check if a user is in a certaing group. By default, the check is skipped for superusers. """ if user.is_superuser and superuser_skip: return True return user.groups.filter(name=group).exists()
[ "Check", "if", "a", "user", "is", "in", "a", "certaing", "group", ".", "By", "default", "the", "check", "is", "skipped", "for", "superusers", "." ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/__init__.py#L43-L52
[ "def", "user_has_group", "(", "user", ",", "group", ",", "superuser_skip", "=", "True", ")", ":", "if", "user", ".", "is_superuser", "and", "superuser_skip", ":", "return", "True", "return", "user", ".", "groups", ".", "filter", "(", "name", "=", "group", ")", ".", "exists", "(", ")" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
resolve_class
Load a class by a fully qualified class_path, eg. myapp.models.ModelName
django_baseline/__init__.py
def resolve_class(class_path): """ Load a class by a fully qualified class_path, eg. myapp.models.ModelName """ modulepath, classname = class_path.rsplit('.', 1) module = __import__(modulepath, fromlist=[classname]) return getattr(module, classname)
def resolve_class(class_path): """ Load a class by a fully qualified class_path, eg. myapp.models.ModelName """ modulepath, classname = class_path.rsplit('.', 1) module = __import__(modulepath, fromlist=[classname]) return getattr(module, classname)
[ "Load", "a", "class", "by", "a", "fully", "qualified", "class_path", "eg", ".", "myapp", ".", "models", ".", "ModelName" ]
theduke/django-baseline
python
https://github.com/theduke/django-baseline/blob/7be8b956e53c70b35f34e1783a8fe8f716955afb/django_baseline/__init__.py#L55-L63
[ "def", "resolve_class", "(", "class_path", ")", ":", "modulepath", ",", "classname", "=", "class_path", ".", "rsplit", "(", "'.'", ",", "1", ")", "module", "=", "__import__", "(", "modulepath", ",", "fromlist", "=", "[", "classname", "]", ")", "return", "getattr", "(", "module", ",", "classname", ")" ]
7be8b956e53c70b35f34e1783a8fe8f716955afb
test
usage_percent
Calculate percentage usage of 'used' against 'total'.
environment/lib/python2.7/site-packages/psutil/_common.py
def usage_percent(used, total, _round=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (used / total) * 100 except ZeroDivisionError: ret = 0 if _round is not None: return round(ret, _round) else: return ret
def usage_percent(used, total, _round=None): """Calculate percentage usage of 'used' against 'total'.""" try: ret = (used / total) * 100 except ZeroDivisionError: ret = 0 if _round is not None: return round(ret, _round) else: return ret
[ "Calculate", "percentage", "usage", "of", "used", "against", "total", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_common.py#L22-L31
[ "def", "usage_percent", "(", "used", ",", "total", ",", "_round", "=", "None", ")", ":", "try", ":", "ret", "=", "(", "used", "/", "total", ")", "*", "100", "except", "ZeroDivisionError", ":", "ret", "=", "0", "if", "_round", "is", "not", "None", ":", "return", "round", "(", "ret", ",", "_round", ")", "else", ":", "return", "ret" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
memoize
A simple memoize decorator for functions.
environment/lib/python2.7/site-packages/psutil/_common.py
def memoize(f): """A simple memoize decorator for functions.""" cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return memf
def memoize(f): """A simple memoize decorator for functions.""" cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return memf
[ "A", "simple", "memoize", "decorator", "for", "functions", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_common.py#L65-L72
[ "def", "memoize", "(", "f", ")", ":", "cache", "=", "{", "}", "def", "memf", "(", "*", "x", ")", ":", "if", "x", "not", "in", "cache", ":", "cache", "[", "x", "]", "=", "f", "(", "*", "x", ")", "return", "cache", "[", "x", "]", "return", "memf" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
deprecated
A decorator which can be used to mark functions as deprecated.
environment/lib/python2.7/site-packages/psutil/_common.py
def deprecated(replacement=None): """A decorator which can be used to mark functions as deprecated.""" def outer(fun): msg = "psutil.%s is deprecated" % fun.__name__ if replacement is not None: msg += "; use %s instead" % replacement if fun.__doc__ is None: fun.__doc__ = msg @wraps(fun) def inner(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return fun(*args, **kwargs) return inner return outer
def deprecated(replacement=None): """A decorator which can be used to mark functions as deprecated.""" def outer(fun): msg = "psutil.%s is deprecated" % fun.__name__ if replacement is not None: msg += "; use %s instead" % replacement if fun.__doc__ is None: fun.__doc__ = msg @wraps(fun) def inner(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning, stacklevel=2) return fun(*args, **kwargs) return inner return outer
[ "A", "decorator", "which", "can", "be", "used", "to", "mark", "functions", "as", "deprecated", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_common.py#L88-L103
[ "def", "deprecated", "(", "replacement", "=", "None", ")", ":", "def", "outer", "(", "fun", ")", ":", "msg", "=", "\"psutil.%s is deprecated\"", "%", "fun", ".", "__name__", "if", "replacement", "is", "not", "None", ":", "msg", "+=", "\"; use %s instead\"", "%", "replacement", "if", "fun", ".", "__doc__", "is", "None", ":", "fun", ".", "__doc__", "=", "msg", "@", "wraps", "(", "fun", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "msg", ",", "category", "=", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "return", "fun", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "inner", "return", "outer" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
isfile_strict
Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html
environment/lib/python2.7/site-packages/psutil/_common.py
def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except OSError: err = sys.exc_info()[1] if err.errno in (errno.EPERM, errno.EACCES): raise return False else: return stat.S_ISREG(st.st_mode)
def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except OSError: err = sys.exc_info()[1] if err.errno in (errno.EPERM, errno.EACCES): raise return False else: return stat.S_ISREG(st.st_mode)
[ "Same", "as", "os", ".", "path", ".", "isfile", "()", "but", "does", "not", "swallow", "EACCES", "/", "EPERM", "exceptions", "see", ":", "http", ":", "//", "mail", ".", "python", ".", "org", "/", "pipermail", "/", "python", "-", "dev", "/", "2012", "-", "June", "/", "120787", ".", "html" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/_common.py#L106-L119
[ "def", "isfile_strict", "(", "path", ")", ":", "try", ":", "st", "=", "os", ".", "stat", "(", "path", ")", "except", "OSError", ":", "err", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "if", "err", ".", "errno", "in", "(", "errno", ".", "EPERM", ",", "errno", ".", "EACCES", ")", ":", "raise", "return", "False", "else", ":", "return", "stat", ".", "S_ISREG", "(", "st", ".", "st_mode", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
git_push
Pushes specified directory to git remote :param git_message: commit message :param git_repository: repository address :param git_branch: git branch :param locale_root: path to locale root folder containing directories with languages :return: tuple stdout, stderr of completed command
c3po/mod/communicator.py
def git_push(git_message=None, git_repository=None, git_branch=None, locale_root=None): """ Pushes specified directory to git remote :param git_message: commit message :param git_repository: repository address :param git_branch: git branch :param locale_root: path to locale root folder containing directories with languages :return: tuple stdout, stderr of completed command """ if git_message is None: git_message = settings.GIT_MESSAGE if git_repository is None: git_repository = settings.GIT_REPOSITORY if git_branch is None: git_branch = settings.GIT_BRANCH if locale_root is None: locale_root = settings.LOCALE_ROOT try: subprocess.check_call(['git', 'checkout', git_branch]) except subprocess.CalledProcessError: try: subprocess.check_call(['git', 'checkout', '-b', git_branch]) except subprocess.CalledProcessError as e: raise PODocsError(e) try: subprocess.check_call(['git', 'ls-remote', git_repository]) except subprocess.CalledProcessError: try: subprocess.check_call(['git', 'remote', 'add', 'po_translator', git_repository]) except subprocess.CalledProcessError as e: raise PODocsError(e) commands = 'git add ' + locale_root + \ ' && git commit -m "' + git_message + '"' + \ ' && git push po_translator ' + git_branch + ':' + git_branch proc = Popen(commands, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = proc.communicate() return stdout, stderr
def git_push(git_message=None, git_repository=None, git_branch=None, locale_root=None): """ Pushes specified directory to git remote :param git_message: commit message :param git_repository: repository address :param git_branch: git branch :param locale_root: path to locale root folder containing directories with languages :return: tuple stdout, stderr of completed command """ if git_message is None: git_message = settings.GIT_MESSAGE if git_repository is None: git_repository = settings.GIT_REPOSITORY if git_branch is None: git_branch = settings.GIT_BRANCH if locale_root is None: locale_root = settings.LOCALE_ROOT try: subprocess.check_call(['git', 'checkout', git_branch]) except subprocess.CalledProcessError: try: subprocess.check_call(['git', 'checkout', '-b', git_branch]) except subprocess.CalledProcessError as e: raise PODocsError(e) try: subprocess.check_call(['git', 'ls-remote', git_repository]) except subprocess.CalledProcessError: try: subprocess.check_call(['git', 'remote', 'add', 'po_translator', git_repository]) except subprocess.CalledProcessError as e: raise PODocsError(e) commands = 'git add ' + locale_root + \ ' && git commit -m "' + git_message + '"' + \ ' && git push po_translator ' + git_branch + ':' + git_branch proc = Popen(commands, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = proc.communicate() return stdout, stderr
[ "Pushes", "specified", "directory", "to", "git", "remote", ":", "param", "git_message", ":", "commit", "message", ":", "param", "git_repository", ":", "repository", "address", ":", "param", "git_branch", ":", "git", "branch", ":", "param", "locale_root", ":", "path", "to", "locale", "root", "folder", "containing", "directories", "with", "languages", ":", "return", ":", "tuple", "stdout", "stderr", "of", "completed", "command" ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L275-L318
[ "def", "git_push", "(", "git_message", "=", "None", ",", "git_repository", "=", "None", ",", "git_branch", "=", "None", ",", "locale_root", "=", "None", ")", ":", "if", "git_message", "is", "None", ":", "git_message", "=", "settings", ".", "GIT_MESSAGE", "if", "git_repository", "is", "None", ":", "git_repository", "=", "settings", ".", "GIT_REPOSITORY", "if", "git_branch", "is", "None", ":", "git_branch", "=", "settings", ".", "GIT_BRANCH", "if", "locale_root", "is", "None", ":", "locale_root", "=", "settings", ".", "LOCALE_ROOT", "try", ":", "subprocess", ".", "check_call", "(", "[", "'git'", ",", "'checkout'", ",", "git_branch", "]", ")", "except", "subprocess", ".", "CalledProcessError", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "'git'", ",", "'checkout'", ",", "'-b'", ",", "git_branch", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "raise", "PODocsError", "(", "e", ")", "try", ":", "subprocess", ".", "check_call", "(", "[", "'git'", ",", "'ls-remote'", ",", "git_repository", "]", ")", "except", "subprocess", ".", "CalledProcessError", ":", "try", ":", "subprocess", ".", "check_call", "(", "[", "'git'", ",", "'remote'", ",", "'add'", ",", "'po_translator'", ",", "git_repository", "]", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "raise", "PODocsError", "(", "e", ")", "commands", "=", "'git add '", "+", "locale_root", "+", "' && git commit -m \"'", "+", "git_message", "+", "'\"'", "+", "' && git push po_translator '", "+", "git_branch", "+", "':'", "+", "git_branch", "proc", "=", "Popen", "(", "commands", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "stdout", ",", "stderr", "=", "proc", ".", "communicate", "(", ")", "return", "stdout", ",", "stderr" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
git_checkout
Checkouts branch to last commit :param git_branch: branch to checkout :param locale_root: locale folder path :return: tuple stdout, stderr of completed command
c3po/mod/communicator.py
def git_checkout(git_branch=None, locale_root=None): """ Checkouts branch to last commit :param git_branch: branch to checkout :param locale_root: locale folder path :return: tuple stdout, stderr of completed command """ if git_branch is None: git_branch = settings.GIT_BRANCH if locale_root is None: locale_root = settings.LOCALE_ROOT proc = Popen('git checkout ' + git_branch + ' -- ' + locale_root, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = proc.communicate() return stdout, stderr
def git_checkout(git_branch=None, locale_root=None): """ Checkouts branch to last commit :param git_branch: branch to checkout :param locale_root: locale folder path :return: tuple stdout, stderr of completed command """ if git_branch is None: git_branch = settings.GIT_BRANCH if locale_root is None: locale_root = settings.LOCALE_ROOT proc = Popen('git checkout ' + git_branch + ' -- ' + locale_root, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = proc.communicate() return stdout, stderr
[ "Checkouts", "branch", "to", "last", "commit", ":", "param", "git_branch", ":", "branch", "to", "checkout", ":", "param", "locale_root", ":", "locale", "folder", "path", ":", "return", ":", "tuple", "stdout", "stderr", "of", "completed", "command" ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L321-L337
[ "def", "git_checkout", "(", "git_branch", "=", "None", ",", "locale_root", "=", "None", ")", ":", "if", "git_branch", "is", "None", ":", "git_branch", "=", "settings", ".", "GIT_BRANCH", "if", "locale_root", "is", "None", ":", "locale_root", "=", "settings", ".", "LOCALE_ROOT", "proc", "=", "Popen", "(", "'git checkout '", "+", "git_branch", "+", "' -- '", "+", "locale_root", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ")", "stdout", ",", "stderr", "=", "proc", ".", "communicate", "(", ")", "return", "stdout", ",", "stderr" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator._login
Login into Google Docs with user authentication info.
c3po/mod/communicator.py
def _login(self): """ Login into Google Docs with user authentication info. """ try: self.gd_client = gdata.docs.client.DocsClient() self.gd_client.ClientLogin(self.email, self.password, self.source) except RequestError as e: raise PODocsError(e)
def _login(self): """ Login into Google Docs with user authentication info. """ try: self.gd_client = gdata.docs.client.DocsClient() self.gd_client.ClientLogin(self.email, self.password, self.source) except RequestError as e: raise PODocsError(e)
[ "Login", "into", "Google", "Docs", "with", "user", "authentication", "info", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L85-L93
[ "def", "_login", "(", "self", ")", ":", "try", ":", "self", ".", "gd_client", "=", "gdata", ".", "docs", ".", "client", ".", "DocsClient", "(", ")", "self", ".", "gd_client", ".", "ClientLogin", "(", "self", ".", "email", ",", "self", ".", "password", ",", "self", ".", "source", ")", "except", "RequestError", "as", "e", ":", "raise", "PODocsError", "(", "e", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator._get_gdocs_key
Parse GDocs key from Spreadsheet url.
c3po/mod/communicator.py
def _get_gdocs_key(self): """ Parse GDocs key from Spreadsheet url. """ try: args = urlparse.parse_qs(urlparse.urlparse(self.url).query) self.key = args['key'][0] except KeyError as e: raise PODocsError(e)
def _get_gdocs_key(self): """ Parse GDocs key from Spreadsheet url. """ try: args = urlparse.parse_qs(urlparse.urlparse(self.url).query) self.key = args['key'][0] except KeyError as e: raise PODocsError(e)
[ "Parse", "GDocs", "key", "from", "Spreadsheet", "url", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L95-L103
[ "def", "_get_gdocs_key", "(", "self", ")", ":", "try", ":", "args", "=", "urlparse", ".", "parse_qs", "(", "urlparse", ".", "urlparse", "(", "self", ".", "url", ")", ".", "query", ")", "self", ".", "key", "=", "args", "[", "'key'", "]", "[", "0", "]", "except", "KeyError", "as", "e", ":", "raise", "PODocsError", "(", "e", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator._ensure_temp_path_exists
Make sure temp directory exists and create one if it does not.
c3po/mod/communicator.py
def _ensure_temp_path_exists(self): """ Make sure temp directory exists and create one if it does not. """ try: if not os.path.exists(self.temp_path): os.mkdir(self.temp_path) except OSError as e: raise PODocsError(e)
def _ensure_temp_path_exists(self): """ Make sure temp directory exists and create one if it does not. """ try: if not os.path.exists(self.temp_path): os.mkdir(self.temp_path) except OSError as e: raise PODocsError(e)
[ "Make", "sure", "temp", "directory", "exists", "and", "create", "one", "if", "it", "does", "not", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L105-L113
[ "def", "_ensure_temp_path_exists", "(", "self", ")", ":", "try", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "temp_path", ")", ":", "os", ".", "mkdir", "(", "self", ".", "temp_path", ")", "except", "OSError", "as", "e", ":", "raise", "PODocsError", "(", "e", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator._clear_temp
Clear temp directory from created csv and ods files during communicator operations.
c3po/mod/communicator.py
def _clear_temp(self): """ Clear temp directory from created csv and ods files during communicator operations. """ temp_files = [LOCAL_ODS, GDOCS_TRANS_CSV, GDOCS_META_CSV, LOCAL_TRANS_CSV, LOCAL_META_CSV] for temp_file in temp_files: file_path = os.path.join(self.temp_path, temp_file) if os.path.exists(file_path): os.remove(file_path)
def _clear_temp(self): """ Clear temp directory from created csv and ods files during communicator operations. """ temp_files = [LOCAL_ODS, GDOCS_TRANS_CSV, GDOCS_META_CSV, LOCAL_TRANS_CSV, LOCAL_META_CSV] for temp_file in temp_files: file_path = os.path.join(self.temp_path, temp_file) if os.path.exists(file_path): os.remove(file_path)
[ "Clear", "temp", "directory", "from", "created", "csv", "and", "ods", "files", "during", "communicator", "operations", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L115-L125
[ "def", "_clear_temp", "(", "self", ")", ":", "temp_files", "=", "[", "LOCAL_ODS", ",", "GDOCS_TRANS_CSV", ",", "GDOCS_META_CSV", ",", "LOCAL_TRANS_CSV", ",", "LOCAL_META_CSV", "]", "for", "temp_file", "in", "temp_files", ":", "file_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "temp_file", ")", "if", "os", ".", "path", ".", "exists", "(", "file_path", ")", ":", "os", ".", "remove", "(", "file_path", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator._download_csv_from_gdocs
Download csv from GDoc. :return: returns resource if worksheets are present :except: raises PODocsError with info if communication with GDocs lead to any errors
c3po/mod/communicator.py
def _download_csv_from_gdocs(self, trans_csv_path, meta_csv_path): """ Download csv from GDoc. :return: returns resource if worksheets are present :except: raises PODocsError with info if communication with GDocs lead to any errors """ try: entry = self.gd_client.GetResourceById(self.key) self.gd_client.DownloadResource( entry, trans_csv_path, extra_params={'gid': 0, 'exportFormat': 'csv'} ) self.gd_client.DownloadResource( entry, meta_csv_path, extra_params={'gid': 1, 'exportFormat': 'csv'} ) except (RequestError, IOError) as e: raise PODocsError(e) return entry
def _download_csv_from_gdocs(self, trans_csv_path, meta_csv_path): """ Download csv from GDoc. :return: returns resource if worksheets are present :except: raises PODocsError with info if communication with GDocs lead to any errors """ try: entry = self.gd_client.GetResourceById(self.key) self.gd_client.DownloadResource( entry, trans_csv_path, extra_params={'gid': 0, 'exportFormat': 'csv'} ) self.gd_client.DownloadResource( entry, meta_csv_path, extra_params={'gid': 1, 'exportFormat': 'csv'} ) except (RequestError, IOError) as e: raise PODocsError(e) return entry
[ "Download", "csv", "from", "GDoc", ".", ":", "return", ":", "returns", "resource", "if", "worksheets", "are", "present", ":", "except", ":", "raises", "PODocsError", "with", "info", "if", "communication", "with", "GDocs", "lead", "to", "any", "errors" ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L127-L146
[ "def", "_download_csv_from_gdocs", "(", "self", ",", "trans_csv_path", ",", "meta_csv_path", ")", ":", "try", ":", "entry", "=", "self", ".", "gd_client", ".", "GetResourceById", "(", "self", ".", "key", ")", "self", ".", "gd_client", ".", "DownloadResource", "(", "entry", ",", "trans_csv_path", ",", "extra_params", "=", "{", "'gid'", ":", "0", ",", "'exportFormat'", ":", "'csv'", "}", ")", "self", ".", "gd_client", ".", "DownloadResource", "(", "entry", ",", "meta_csv_path", ",", "extra_params", "=", "{", "'gid'", ":", "1", ",", "'exportFormat'", ":", "'csv'", "}", ")", "except", "(", "RequestError", ",", "IOError", ")", "as", "e", ":", "raise", "PODocsError", "(", "e", ")", "return", "entry" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator._upload_file_to_gdoc
Uploads file to GDocs spreadsheet. Content type can be provided as argument, default is ods.
c3po/mod/communicator.py
def _upload_file_to_gdoc( self, file_path, content_type='application/x-vnd.oasis.opendocument.spreadsheet'): """ Uploads file to GDocs spreadsheet. Content type can be provided as argument, default is ods. """ try: entry = self.gd_client.GetResourceById(self.key) media = gdata.data.MediaSource( file_path=file_path, content_type=content_type) self.gd_client.UpdateResource( entry, media=media, update_metadata=True) except (RequestError, IOError) as e: raise PODocsError(e)
def _upload_file_to_gdoc( self, file_path, content_type='application/x-vnd.oasis.opendocument.spreadsheet'): """ Uploads file to GDocs spreadsheet. Content type can be provided as argument, default is ods. """ try: entry = self.gd_client.GetResourceById(self.key) media = gdata.data.MediaSource( file_path=file_path, content_type=content_type) self.gd_client.UpdateResource( entry, media=media, update_metadata=True) except (RequestError, IOError) as e: raise PODocsError(e)
[ "Uploads", "file", "to", "GDocs", "spreadsheet", ".", "Content", "type", "can", "be", "provided", "as", "argument", "default", "is", "ods", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L148-L162
[ "def", "_upload_file_to_gdoc", "(", "self", ",", "file_path", ",", "content_type", "=", "'application/x-vnd.oasis.opendocument.spreadsheet'", ")", ":", "try", ":", "entry", "=", "self", ".", "gd_client", ".", "GetResourceById", "(", "self", ".", "key", ")", "media", "=", "gdata", ".", "data", ".", "MediaSource", "(", "file_path", "=", "file_path", ",", "content_type", "=", "content_type", ")", "self", ".", "gd_client", ".", "UpdateResource", "(", "entry", ",", "media", "=", "media", ",", "update_metadata", "=", "True", ")", "except", "(", "RequestError", ",", "IOError", ")", "as", "e", ":", "raise", "PODocsError", "(", "e", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator._merge_local_and_gdoc
Download csv from GDoc. :return: returns resource if worksheets are present :except: raises PODocsError with info if communication with GDocs lead to any errors
c3po/mod/communicator.py
def _merge_local_and_gdoc(self, entry, local_trans_csv, local_meta_csv, gdocs_trans_csv, gdocs_meta_csv): """ Download csv from GDoc. :return: returns resource if worksheets are present :except: raises PODocsError with info if communication with GDocs lead to any errors """ try: new_translations = po_to_csv_merge( self.languages, self.locale_root, self.po_files_path, local_trans_csv, local_meta_csv, gdocs_trans_csv, gdocs_meta_csv) if new_translations: local_ods = os.path.join(self.temp_path, LOCAL_ODS) csv_to_ods(local_trans_csv, local_meta_csv, local_ods) media = gdata.data.MediaSource( file_path=local_ods, content_type= 'application/x-vnd.oasis.opendocument.spreadsheet' ) self.gd_client.UpdateResource(entry, media=media, update_metadata=True) except (IOError, OSError, RequestError) as e: raise PODocsError(e)
def _merge_local_and_gdoc(self, entry, local_trans_csv, local_meta_csv, gdocs_trans_csv, gdocs_meta_csv): """ Download csv from GDoc. :return: returns resource if worksheets are present :except: raises PODocsError with info if communication with GDocs lead to any errors """ try: new_translations = po_to_csv_merge( self.languages, self.locale_root, self.po_files_path, local_trans_csv, local_meta_csv, gdocs_trans_csv, gdocs_meta_csv) if new_translations: local_ods = os.path.join(self.temp_path, LOCAL_ODS) csv_to_ods(local_trans_csv, local_meta_csv, local_ods) media = gdata.data.MediaSource( file_path=local_ods, content_type= 'application/x-vnd.oasis.opendocument.spreadsheet' ) self.gd_client.UpdateResource(entry, media=media, update_metadata=True) except (IOError, OSError, RequestError) as e: raise PODocsError(e)
[ "Download", "csv", "from", "GDoc", ".", ":", "return", ":", "returns", "resource", "if", "worksheets", "are", "present", ":", "except", ":", "raises", "PODocsError", "with", "info", "if", "communication", "with", "GDocs", "lead", "to", "any", "errors" ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L164-L187
[ "def", "_merge_local_and_gdoc", "(", "self", ",", "entry", ",", "local_trans_csv", ",", "local_meta_csv", ",", "gdocs_trans_csv", ",", "gdocs_meta_csv", ")", ":", "try", ":", "new_translations", "=", "po_to_csv_merge", "(", "self", ".", "languages", ",", "self", ".", "locale_root", ",", "self", ".", "po_files_path", ",", "local_trans_csv", ",", "local_meta_csv", ",", "gdocs_trans_csv", ",", "gdocs_meta_csv", ")", "if", "new_translations", ":", "local_ods", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "LOCAL_ODS", ")", "csv_to_ods", "(", "local_trans_csv", ",", "local_meta_csv", ",", "local_ods", ")", "media", "=", "gdata", ".", "data", ".", "MediaSource", "(", "file_path", "=", "local_ods", ",", "content_type", "=", "'application/x-vnd.oasis.opendocument.spreadsheet'", ")", "self", ".", "gd_client", ".", "UpdateResource", "(", "entry", ",", "media", "=", "media", ",", "update_metadata", "=", "True", ")", "except", "(", "IOError", ",", "OSError", ",", "RequestError", ")", "as", "e", ":", "raise", "PODocsError", "(", "e", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator.synchronize
Synchronize local po files with translations on GDocs Spreadsheet. Downloads two csv files, merges them and converts into po files structure. If new msgids appeared in po files, this method creates new ods with appended content and sends it to GDocs.
c3po/mod/communicator.py
def synchronize(self): """ Synchronize local po files with translations on GDocs Spreadsheet. Downloads two csv files, merges them and converts into po files structure. If new msgids appeared in po files, this method creates new ods with appended content and sends it to GDocs. """ gdocs_trans_csv = os.path.join(self.temp_path, GDOCS_TRANS_CSV) gdocs_meta_csv = os.path.join(self.temp_path, GDOCS_META_CSV) local_trans_csv = os.path.join(self.temp_path, LOCAL_TRANS_CSV) local_meta_csv = os.path.join(self.temp_path, LOCAL_META_CSV) try: entry = self._download_csv_from_gdocs(gdocs_trans_csv, gdocs_meta_csv) except PODocsError as e: if 'Sheet 1 not found' in str(e) \ or 'Conversion failed unexpectedly' in str(e): self.upload() else: raise PODocsError(e) else: self._merge_local_and_gdoc(entry, local_trans_csv, local_meta_csv, gdocs_trans_csv, gdocs_meta_csv) try: csv_to_po(local_trans_csv, local_meta_csv, self.locale_root, self.po_files_path, self.header) except IOError as e: raise PODocsError(e) self._clear_temp()
def synchronize(self): """ Synchronize local po files with translations on GDocs Spreadsheet. Downloads two csv files, merges them and converts into po files structure. If new msgids appeared in po files, this method creates new ods with appended content and sends it to GDocs. """ gdocs_trans_csv = os.path.join(self.temp_path, GDOCS_TRANS_CSV) gdocs_meta_csv = os.path.join(self.temp_path, GDOCS_META_CSV) local_trans_csv = os.path.join(self.temp_path, LOCAL_TRANS_CSV) local_meta_csv = os.path.join(self.temp_path, LOCAL_META_CSV) try: entry = self._download_csv_from_gdocs(gdocs_trans_csv, gdocs_meta_csv) except PODocsError as e: if 'Sheet 1 not found' in str(e) \ or 'Conversion failed unexpectedly' in str(e): self.upload() else: raise PODocsError(e) else: self._merge_local_and_gdoc(entry, local_trans_csv, local_meta_csv, gdocs_trans_csv, gdocs_meta_csv) try: csv_to_po(local_trans_csv, local_meta_csv, self.locale_root, self.po_files_path, self.header) except IOError as e: raise PODocsError(e) self._clear_temp()
[ "Synchronize", "local", "po", "files", "with", "translations", "on", "GDocs", "Spreadsheet", ".", "Downloads", "two", "csv", "files", "merges", "them", "and", "converts", "into", "po", "files", "structure", ".", "If", "new", "msgids", "appeared", "in", "po", "files", "this", "method", "creates", "new", "ods", "with", "appended", "content", "and", "sends", "it", "to", "GDocs", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L189-L220
[ "def", "synchronize", "(", "self", ")", ":", "gdocs_trans_csv", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "GDOCS_TRANS_CSV", ")", "gdocs_meta_csv", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "GDOCS_META_CSV", ")", "local_trans_csv", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "LOCAL_TRANS_CSV", ")", "local_meta_csv", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "LOCAL_META_CSV", ")", "try", ":", "entry", "=", "self", ".", "_download_csv_from_gdocs", "(", "gdocs_trans_csv", ",", "gdocs_meta_csv", ")", "except", "PODocsError", "as", "e", ":", "if", "'Sheet 1 not found'", "in", "str", "(", "e", ")", "or", "'Conversion failed unexpectedly'", "in", "str", "(", "e", ")", ":", "self", ".", "upload", "(", ")", "else", ":", "raise", "PODocsError", "(", "e", ")", "else", ":", "self", ".", "_merge_local_and_gdoc", "(", "entry", ",", "local_trans_csv", ",", "local_meta_csv", ",", "gdocs_trans_csv", ",", "gdocs_meta_csv", ")", "try", ":", "csv_to_po", "(", "local_trans_csv", ",", "local_meta_csv", ",", "self", ".", "locale_root", ",", "self", ".", "po_files_path", ",", "self", ".", "header", ")", "except", "IOError", "as", "e", ":", "raise", "PODocsError", "(", "e", ")", "self", ".", "_clear_temp", "(", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator.download
Download csv files from GDocs and convert them into po files structure.
c3po/mod/communicator.py
def download(self): """ Download csv files from GDocs and convert them into po files structure. """ trans_csv_path = os.path.realpath( os.path.join(self.temp_path, GDOCS_TRANS_CSV)) meta_csv_path = os.path.realpath( os.path.join(self.temp_path, GDOCS_META_CSV)) self._download_csv_from_gdocs(trans_csv_path, meta_csv_path) try: csv_to_po(trans_csv_path, meta_csv_path, self.locale_root, self.po_files_path, header=self.header) except IOError as e: raise PODocsError(e) self._clear_temp()
def download(self): """ Download csv files from GDocs and convert them into po files structure. """ trans_csv_path = os.path.realpath( os.path.join(self.temp_path, GDOCS_TRANS_CSV)) meta_csv_path = os.path.realpath( os.path.join(self.temp_path, GDOCS_META_CSV)) self._download_csv_from_gdocs(trans_csv_path, meta_csv_path) try: csv_to_po(trans_csv_path, meta_csv_path, self.locale_root, self.po_files_path, header=self.header) except IOError as e: raise PODocsError(e) self._clear_temp()
[ "Download", "csv", "files", "from", "GDocs", "and", "convert", "them", "into", "po", "files", "structure", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L222-L239
[ "def", "download", "(", "self", ")", ":", "trans_csv_path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "GDOCS_TRANS_CSV", ")", ")", "meta_csv_path", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "GDOCS_META_CSV", ")", ")", "self", ".", "_download_csv_from_gdocs", "(", "trans_csv_path", ",", "meta_csv_path", ")", "try", ":", "csv_to_po", "(", "trans_csv_path", ",", "meta_csv_path", ",", "self", ".", "locale_root", ",", "self", ".", "po_files_path", ",", "header", "=", "self", ".", "header", ")", "except", "IOError", "as", "e", ":", "raise", "PODocsError", "(", "e", ")", "self", ".", "_clear_temp", "(", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator.upload
Upload all po files to GDocs ignoring conflicts. This method looks for all msgids in po_files and sends them as ods to GDocs Spreadsheet.
c3po/mod/communicator.py
def upload(self): """ Upload all po files to GDocs ignoring conflicts. This method looks for all msgids in po_files and sends them as ods to GDocs Spreadsheet. """ local_ods_path = os.path.join(self.temp_path, LOCAL_ODS) try: po_to_ods(self.languages, self.locale_root, self.po_files_path, local_ods_path) except (IOError, OSError) as e: raise PODocsError(e) self._upload_file_to_gdoc(local_ods_path) self._clear_temp()
def upload(self): """ Upload all po files to GDocs ignoring conflicts. This method looks for all msgids in po_files and sends them as ods to GDocs Spreadsheet. """ local_ods_path = os.path.join(self.temp_path, LOCAL_ODS) try: po_to_ods(self.languages, self.locale_root, self.po_files_path, local_ods_path) except (IOError, OSError) as e: raise PODocsError(e) self._upload_file_to_gdoc(local_ods_path) self._clear_temp()
[ "Upload", "all", "po", "files", "to", "GDocs", "ignoring", "conflicts", ".", "This", "method", "looks", "for", "all", "msgids", "in", "po_files", "and", "sends", "them", "as", "ods", "to", "GDocs", "Spreadsheet", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L241-L256
[ "def", "upload", "(", "self", ")", ":", "local_ods_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "LOCAL_ODS", ")", "try", ":", "po_to_ods", "(", "self", ".", "languages", ",", "self", ".", "locale_root", ",", "self", ".", "po_files_path", ",", "local_ods_path", ")", "except", "(", "IOError", ",", "OSError", ")", "as", "e", ":", "raise", "PODocsError", "(", "e", ")", "self", ".", "_upload_file_to_gdoc", "(", "local_ods_path", ")", "self", ".", "_clear_temp", "(", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
Communicator.clear
Clear GDoc Spreadsheet by sending empty csv file.
c3po/mod/communicator.py
def clear(self): """ Clear GDoc Spreadsheet by sending empty csv file. """ empty_file_path = os.path.join(self.temp_path, 'empty.csv') try: empty_file = open(empty_file_path, 'w') empty_file.write(',') empty_file.close() except IOError as e: raise PODocsError(e) self._upload_file_to_gdoc(empty_file_path, content_type='text/csv') os.remove(empty_file_path)
def clear(self): """ Clear GDoc Spreadsheet by sending empty csv file. """ empty_file_path = os.path.join(self.temp_path, 'empty.csv') try: empty_file = open(empty_file_path, 'w') empty_file.write(',') empty_file.close() except IOError as e: raise PODocsError(e) self._upload_file_to_gdoc(empty_file_path, content_type='text/csv') os.remove(empty_file_path)
[ "Clear", "GDoc", "Spreadsheet", "by", "sending", "empty", "csv", "file", "." ]
VorskiImagineering/C3PO
python
https://github.com/VorskiImagineering/C3PO/blob/e3e35835e5ac24158848afed4f905ca44ac3ae00/c3po/mod/communicator.py#L258-L272
[ "def", "clear", "(", "self", ")", ":", "empty_file_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "temp_path", ",", "'empty.csv'", ")", "try", ":", "empty_file", "=", "open", "(", "empty_file_path", ",", "'w'", ")", "empty_file", ".", "write", "(", "','", ")", "empty_file", ".", "close", "(", ")", "except", "IOError", "as", "e", ":", "raise", "PODocsError", "(", "e", ")", "self", ".", "_upload_file_to_gdoc", "(", "empty_file_path", ",", "content_type", "=", "'text/csv'", ")", "os", ".", "remove", "(", "empty_file_path", ")" ]
e3e35835e5ac24158848afed4f905ca44ac3ae00
test
InternalIPKernel.new_qt_console
start a new qtconsole connected to our kernel
environment/share/doc/ipython/examples/lib/internal_ipkernel.py
def new_qt_console(self, evt=None): """start a new qtconsole connected to our kernel""" return connect_qtconsole(self.ipkernel.connection_file, profile=self.ipkernel.profile)
def new_qt_console(self, evt=None): """start a new qtconsole connected to our kernel""" return connect_qtconsole(self.ipkernel.connection_file, profile=self.ipkernel.profile)
[ "start", "a", "new", "qtconsole", "connected", "to", "our", "kernel" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/share/doc/ipython/examples/lib/internal_ipkernel.py#L50-L52
[ "def", "new_qt_console", "(", "self", ",", "evt", "=", "None", ")", ":", "return", "connect_qtconsole", "(", "self", ".", "ipkernel", ".", "connection_file", ",", "profile", "=", "self", ".", "ipkernel", ".", "profile", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
check_url_accessibility
Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py
def check_url_accessibility(url, timeout=10): ''' Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError ''' if(url=='localhost'): url = 'http://127.0.0.1' try: req = urllib2.urlopen(url, timeout=timeout) if (req.getcode()==200): return True except Exception: pass fail("URL '%s' is not accessible from this machine" % url)
def check_url_accessibility(url, timeout=10): ''' Check whether the URL accessible and returns HTTP 200 OK or not if not raises ValidationError ''' if(url=='localhost'): url = 'http://127.0.0.1' try: req = urllib2.urlopen(url, timeout=timeout) if (req.getcode()==200): return True except Exception: pass fail("URL '%s' is not accessible from this machine" % url)
[ "Check", "whether", "the", "URL", "accessible", "and", "returns", "HTTP", "200", "OK", "or", "not", "if", "not", "raises", "ValidationError" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py#L5-L18
[ "def", "check_url_accessibility", "(", "url", ",", "timeout", "=", "10", ")", ":", "if", "(", "url", "==", "'localhost'", ")", ":", "url", "=", "'http://127.0.0.1'", "try", ":", "req", "=", "urllib2", ".", "urlopen", "(", "url", ",", "timeout", "=", "timeout", ")", "if", "(", "req", ".", "getcode", "(", ")", "==", "200", ")", ":", "return", "True", "except", "Exception", ":", "pass", "fail", "(", "\"URL '%s' is not accessible from this machine\"", "%", "url", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
url_has_contents
Check whether the HTML page contains the content or not and return boolean
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py
def url_has_contents(url, contents, case_sensitive=False, timeout=10): ''' Check whether the HTML page contains the content or not and return boolean ''' try: req = urllib2.urlopen(url, timeout=timeout) except Exception, _: False else: rep = req.read() if (not case_sensitive and rep.lower().find(contents.lower()) >= 0) or (case_sensitive and rep.find(contents) >= 0): return True else: return False
def url_has_contents(url, contents, case_sensitive=False, timeout=10): ''' Check whether the HTML page contains the content or not and return boolean ''' try: req = urllib2.urlopen(url, timeout=timeout) except Exception, _: False else: rep = req.read() if (not case_sensitive and rep.lower().find(contents.lower()) >= 0) or (case_sensitive and rep.find(contents) >= 0): return True else: return False
[ "Check", "whether", "the", "HTML", "page", "contains", "the", "content", "or", "not", "and", "return", "boolean" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py#L20-L33
[ "def", "url_has_contents", "(", "url", ",", "contents", ",", "case_sensitive", "=", "False", ",", "timeout", "=", "10", ")", ":", "try", ":", "req", "=", "urllib2", ".", "urlopen", "(", "url", ",", "timeout", "=", "timeout", ")", "except", "Exception", ",", "_", ":", "False", "else", ":", "rep", "=", "req", ".", "read", "(", ")", "if", "(", "not", "case_sensitive", "and", "rep", ".", "lower", "(", ")", ".", "find", "(", "contents", ".", "lower", "(", ")", ")", ">=", "0", ")", "or", "(", "case_sensitive", "and", "rep", ".", "find", "(", "contents", ")", ">=", "0", ")", ":", "return", "True", "else", ":", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_response_code
Visit the URL and return the HTTP response code in 'int'
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py
def get_response_code(url, timeout=10): ''' Visit the URL and return the HTTP response code in 'int' ''' try: req = urllib2.urlopen(url, timeout=timeout) except HTTPError, e: return e.getcode() except Exception, _: fail("Couldn't reach the URL '%s'" % url) else: return req.getcode()
def get_response_code(url, timeout=10): ''' Visit the URL and return the HTTP response code in 'int' ''' try: req = urllib2.urlopen(url, timeout=timeout) except HTTPError, e: return e.getcode() except Exception, _: fail("Couldn't reach the URL '%s'" % url) else: return req.getcode()
[ "Visit", "the", "URL", "and", "return", "the", "HTTP", "response", "code", "in", "int" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py#L35-L46
[ "def", "get_response_code", "(", "url", ",", "timeout", "=", "10", ")", ":", "try", ":", "req", "=", "urllib2", ".", "urlopen", "(", "url", ",", "timeout", "=", "timeout", ")", "except", "HTTPError", ",", "e", ":", "return", "e", ".", "getcode", "(", ")", "except", "Exception", ",", "_", ":", "fail", "(", "\"Couldn't reach the URL '%s'\"", "%", "url", ")", "else", ":", "return", "req", ".", "getcode", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
compare_content_type
Compare the content type header of url param with content_type param and returns boolean @param url -> string e.g. http://127.0.0.1/index @param content_type -> string e.g. text/html
environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py
def compare_content_type(url, content_type): ''' Compare the content type header of url param with content_type param and returns boolean @param url -> string e.g. http://127.0.0.1/index @param content_type -> string e.g. text/html ''' try: response = urllib2.urlopen(url) except: return False return response.headers.type == content_type
def compare_content_type(url, content_type): ''' Compare the content type header of url param with content_type param and returns boolean @param url -> string e.g. http://127.0.0.1/index @param content_type -> string e.g. text/html ''' try: response = urllib2.urlopen(url) except: return False return response.headers.type == content_type
[ "Compare", "the", "content", "type", "header", "of", "url", "param", "with", "content_type", "param", "and", "returns", "boolean" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/gurumate-2.8.6-py2.7.egg/gurumate/web.py#L57-L68
[ "def", "compare_content_type", "(", "url", ",", "content_type", ")", ":", "try", ":", "response", "=", "urllib2", ".", "urlopen", "(", "url", ")", "except", ":", "return", "False", "return", "response", ".", "headers", ".", "type", "==", "content_type" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e