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
Pdb.print_list_lines
The printing (as opposed to the parsing part of a 'list' command.
environment/lib/python2.7/site-packages/IPython/core/debugger.py
def print_list_lines(self, filename, first, last): """The printing (as opposed to the parsing part of a 'list' command.""" try: Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) src = [] for lineno in range(first, last+1): line = linecache.getline(filename, lineno) if not line: break if lineno == self.curframe.f_lineno: line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) else: line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) src.append(line) self.lineno = lineno print >>io.stdout, ''.join(src) except KeyboardInterrupt: pass
def print_list_lines(self, filename, first, last): """The printing (as opposed to the parsing part of a 'list' command.""" try: Colors = self.color_scheme_table.active_colors ColorsNormal = Colors.Normal tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) src = [] for lineno in range(first, last+1): line = linecache.getline(filename, lineno) if not line: break if lineno == self.curframe.f_lineno: line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) else: line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) src.append(line) self.lineno = lineno print >>io.stdout, ''.join(src) except KeyboardInterrupt: pass
[ "The", "printing", "(", "as", "opposed", "to", "the", "parsing", "part", "of", "a", "list", "command", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/debugger.py#L415-L440
[ "def", "print_list_lines", "(", "self", ",", "filename", ",", "first", ",", "last", ")", ":", "try", ":", "Colors", "=", "self", ".", "color_scheme_table", ".", "active_colors", "ColorsNormal", "=", "Colors", ".", "Normal", "tpl_line", "=", "'%%s%s%%s %s%%s'", "%", "(", "Colors", ".", "lineno", ",", "ColorsNormal", ")", "tpl_line_em", "=", "'%%s%s%%s %s%%s%s'", "%", "(", "Colors", ".", "linenoEm", ",", "Colors", ".", "line", ",", "ColorsNormal", ")", "src", "=", "[", "]", "for", "lineno", "in", "range", "(", "first", ",", "last", "+", "1", ")", ":", "line", "=", "linecache", ".", "getline", "(", "filename", ",", "lineno", ")", "if", "not", "line", ":", "break", "if", "lineno", "==", "self", ".", "curframe", ".", "f_lineno", ":", "line", "=", "self", ".", "__format_line", "(", "tpl_line_em", ",", "filename", ",", "lineno", ",", "line", ",", "arrow", "=", "True", ")", "else", ":", "line", "=", "self", ".", "__format_line", "(", "tpl_line", ",", "filename", ",", "lineno", ",", "line", ",", "arrow", "=", "False", ")", "src", ".", "append", "(", "line", ")", "self", ".", "lineno", "=", "lineno", "print", ">>", "io", ".", "stdout", ",", "''", ".", "join", "(", "src", ")", "except", "KeyboardInterrupt", ":", "pass" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Pdb.do_pdef
The debugger interface to magic_pdef
environment/lib/python2.7/site-packages/IPython/core/debugger.py
def do_pdef(self, arg): """The debugger interface to magic_pdef""" namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
def do_pdef(self, arg): """The debugger interface to magic_pdef""" namespaces = [('Locals', self.curframe.f_locals), ('Globals', self.curframe.f_globals)] self.shell.find_line_magic('pdef')(arg, namespaces=namespaces)
[ "The", "debugger", "interface", "to", "magic_pdef" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/debugger.py#L476-L480
[ "def", "do_pdef", "(", "self", ",", "arg", ")", ":", "namespaces", "=", "[", "(", "'Locals'", ",", "self", ".", "curframe", ".", "f_locals", ")", ",", "(", "'Globals'", ",", "self", ".", "curframe", ".", "f_globals", ")", "]", "self", ".", "shell", ".", "find_line_magic", "(", "'pdef'", ")", "(", "arg", ",", "namespaces", "=", "namespaces", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Pdb.checkline
Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive.
environment/lib/python2.7/site-packages/IPython/core/debugger.py
def checkline(self, filename, lineno): """Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive. """ ####################################################################### # XXX Hack! Use python-2.5 compatible code for this call, because with # all of our changes, we've drifted from the pdb api in 2.6. For now, # changing: # #line = linecache.getline(filename, lineno, self.curframe.f_globals) # to: # line = linecache.getline(filename, lineno) # # does the trick. But in reality, we need to fix this by reconciling # our updates with the new Pdb APIs in Python 2.6. # # End hack. The rest of this method is copied verbatim from 2.6 pdb.py ####################################################################### if not line: print >>self.stdout, 'End of file' return 0 line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): print >>self.stdout, '*** Blank or comment' return 0 return lineno
def checkline(self, filename, lineno): """Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive. """ ####################################################################### # XXX Hack! Use python-2.5 compatible code for this call, because with # all of our changes, we've drifted from the pdb api in 2.6. For now, # changing: # #line = linecache.getline(filename, lineno, self.curframe.f_globals) # to: # line = linecache.getline(filename, lineno) # # does the trick. But in reality, we need to fix this by reconciling # our updates with the new Pdb APIs in Python 2.6. # # End hack. The rest of this method is copied verbatim from 2.6 pdb.py ####################################################################### if not line: print >>self.stdout, 'End of file' return 0 line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): print >>self.stdout, '*** Blank or comment' return 0 return lineno
[ "Check", "whether", "specified", "line", "seems", "to", "be", "executable", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/debugger.py#L495-L526
[ "def", "checkline", "(", "self", ",", "filename", ",", "lineno", ")", ":", "#######################################################################", "# XXX Hack! Use python-2.5 compatible code for this call, because with", "# all of our changes, we've drifted from the pdb api in 2.6. For now,", "# changing:", "#", "#line = linecache.getline(filename, lineno, self.curframe.f_globals)", "# to:", "#", "line", "=", "linecache", ".", "getline", "(", "filename", ",", "lineno", ")", "#", "# does the trick. But in reality, we need to fix this by reconciling", "# our updates with the new Pdb APIs in Python 2.6.", "#", "# End hack. The rest of this method is copied verbatim from 2.6 pdb.py", "#######################################################################", "if", "not", "line", ":", "print", ">>", "self", ".", "stdout", ",", "'End of file'", "return", "0", "line", "=", "line", ".", "strip", "(", ")", "# Don't allow setting breakpoint at a blank line", "if", "(", "not", "line", "or", "(", "line", "[", "0", "]", "==", "'#'", ")", "or", "(", "line", "[", ":", "3", "]", "==", "'\"\"\"'", ")", "or", "line", "[", ":", "3", "]", "==", "\"'''\"", ")", ":", "print", ">>", "self", ".", "stdout", ",", "'*** Blank or comment'", "return", "0", "return", "lineno" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
conversion_factor
Generates a multiplying factor used to convert two currencies
forex/models.py
def conversion_factor(from_symbol, to_symbol, date): """ Generates a multiplying factor used to convert two currencies """ from_currency = Currency.objects.get(symbol=from_symbol) try: from_currency_price = CurrencyPrice.objects.get(currency=from_currency, date=date).mid_price except CurrencyPrice.DoesNotExist: print "Cannot fetch prices for %s on %s" % (str(from_currency), str(date)) return None to_currency = Currency.objects.get(symbol=to_symbol) try: to_currency_price = CurrencyPrice.objects.get(currency=to_currency, date=date).mid_price except CurrencyPrice.DoesNotExist: print "Cannot fetch prices for %s on %s" % (str(to_currency), str(date)) return None return to_currency_price / from_currency_price
def conversion_factor(from_symbol, to_symbol, date): """ Generates a multiplying factor used to convert two currencies """ from_currency = Currency.objects.get(symbol=from_symbol) try: from_currency_price = CurrencyPrice.objects.get(currency=from_currency, date=date).mid_price except CurrencyPrice.DoesNotExist: print "Cannot fetch prices for %s on %s" % (str(from_currency), str(date)) return None to_currency = Currency.objects.get(symbol=to_symbol) try: to_currency_price = CurrencyPrice.objects.get(currency=to_currency, date=date).mid_price except CurrencyPrice.DoesNotExist: print "Cannot fetch prices for %s on %s" % (str(to_currency), str(date)) return None return to_currency_price / from_currency_price
[ "Generates", "a", "multiplying", "factor", "used", "to", "convert", "two", "currencies" ]
Valuehorizon/valuehorizon-forex
python
https://github.com/Valuehorizon/valuehorizon-forex/blob/e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8/forex/models.py#L210-L229
[ "def", "conversion_factor", "(", "from_symbol", ",", "to_symbol", ",", "date", ")", ":", "from_currency", "=", "Currency", ".", "objects", ".", "get", "(", "symbol", "=", "from_symbol", ")", "try", ":", "from_currency_price", "=", "CurrencyPrice", ".", "objects", ".", "get", "(", "currency", "=", "from_currency", ",", "date", "=", "date", ")", ".", "mid_price", "except", "CurrencyPrice", ".", "DoesNotExist", ":", "print", "\"Cannot fetch prices for %s on %s\"", "%", "(", "str", "(", "from_currency", ")", ",", "str", "(", "date", ")", ")", "return", "None", "to_currency", "=", "Currency", ".", "objects", ".", "get", "(", "symbol", "=", "to_symbol", ")", "try", ":", "to_currency_price", "=", "CurrencyPrice", ".", "objects", ".", "get", "(", "currency", "=", "to_currency", ",", "date", "=", "date", ")", ".", "mid_price", "except", "CurrencyPrice", ".", "DoesNotExist", ":", "print", "\"Cannot fetch prices for %s on %s\"", "%", "(", "str", "(", "to_currency", ")", ",", "str", "(", "date", ")", ")", "return", "None", "return", "to_currency_price", "/", "from_currency_price" ]
e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8
test
convert_currency
Converts an amount of money from one currency to another on a specified date.
forex/models.py
def convert_currency(from_symbol, to_symbol, value, date): """ Converts an amount of money from one currency to another on a specified date. """ if from_symbol == to_symbol: return value factor = conversion_factor(from_symbol, to_symbol, date) if type(value) == float: output = value * float(factor) elif type(value) == Decimal: output = Decimal(format(value * factor, '.%sf' % str(PRICE_PRECISION))) elif type(value) in [np.float16, np.float32, np.float64, np.float128, np.float]: output = float(value) * float(factor) else: output = None return output
def convert_currency(from_symbol, to_symbol, value, date): """ Converts an amount of money from one currency to another on a specified date. """ if from_symbol == to_symbol: return value factor = conversion_factor(from_symbol, to_symbol, date) if type(value) == float: output = value * float(factor) elif type(value) == Decimal: output = Decimal(format(value * factor, '.%sf' % str(PRICE_PRECISION))) elif type(value) in [np.float16, np.float32, np.float64, np.float128, np.float]: output = float(value) * float(factor) else: output = None return output
[ "Converts", "an", "amount", "of", "money", "from", "one", "currency", "to", "another", "on", "a", "specified", "date", "." ]
Valuehorizon/valuehorizon-forex
python
https://github.com/Valuehorizon/valuehorizon-forex/blob/e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8/forex/models.py#L232-L250
[ "def", "convert_currency", "(", "from_symbol", ",", "to_symbol", ",", "value", ",", "date", ")", ":", "if", "from_symbol", "==", "to_symbol", ":", "return", "value", "factor", "=", "conversion_factor", "(", "from_symbol", ",", "to_symbol", ",", "date", ")", "if", "type", "(", "value", ")", "==", "float", ":", "output", "=", "value", "*", "float", "(", "factor", ")", "elif", "type", "(", "value", ")", "==", "Decimal", ":", "output", "=", "Decimal", "(", "format", "(", "value", "*", "factor", ",", "'.%sf'", "%", "str", "(", "PRICE_PRECISION", ")", ")", ")", "elif", "type", "(", "value", ")", "in", "[", "np", ".", "float16", ",", "np", ".", "float32", ",", "np", ".", "float64", ",", "np", ".", "float128", ",", "np", ".", "float", "]", ":", "output", "=", "float", "(", "value", ")", "*", "float", "(", "factor", ")", "else", ":", "output", "=", "None", "return", "output" ]
e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8
test
Currency.compute_return
Compute the return of the currency between two dates
forex/models.py
def compute_return(self, start_date, end_date, rate="MID"): """ Compute the return of the currency between two dates """ if rate not in ["MID", "ASK", "BID"]: raise ValueError("Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'" % str(rate)) if end_date <= start_date: raise ValueError("End date must be on or after start date") df = self.generate_dataframe(start_date=start_date, end_date=end_date) start_price = df.ix[start_date][rate] end_price = df.ix[end_date][rate] currency_return = (end_price / start_price) - 1.0 return currency_return
def compute_return(self, start_date, end_date, rate="MID"): """ Compute the return of the currency between two dates """ if rate not in ["MID", "ASK", "BID"]: raise ValueError("Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'" % str(rate)) if end_date <= start_date: raise ValueError("End date must be on or after start date") df = self.generate_dataframe(start_date=start_date, end_date=end_date) start_price = df.ix[start_date][rate] end_price = df.ix[end_date][rate] currency_return = (end_price / start_price) - 1.0 return currency_return
[ "Compute", "the", "return", "of", "the", "currency", "between", "two", "dates" ]
Valuehorizon/valuehorizon-forex
python
https://github.com/Valuehorizon/valuehorizon-forex/blob/e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8/forex/models.py#L59-L75
[ "def", "compute_return", "(", "self", ",", "start_date", ",", "end_date", ",", "rate", "=", "\"MID\"", ")", ":", "if", "rate", "not", "in", "[", "\"MID\"", ",", "\"ASK\"", ",", "\"BID\"", "]", ":", "raise", "ValueError", "(", "\"Unknown rate type (%s)- must be 'MID', 'ASK' or 'BID'\"", "%", "str", "(", "rate", ")", ")", "if", "end_date", "<=", "start_date", ":", "raise", "ValueError", "(", "\"End date must be on or after start date\"", ")", "df", "=", "self", ".", "generate_dataframe", "(", "start_date", "=", "start_date", ",", "end_date", "=", "end_date", ")", "start_price", "=", "df", ".", "ix", "[", "start_date", "]", "[", "rate", "]", "end_price", "=", "df", ".", "ix", "[", "end_date", "]", "[", "rate", "]", "currency_return", "=", "(", "end_price", "/", "start_price", ")", "-", "1.0", "return", "currency_return" ]
e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8
test
CurrencyPriceManager.generate_dataframe
Generate a dataframe consisting of the currency prices (specified by symbols) from the start to end date
forex/models.py
def generate_dataframe(self, symbols=None, date_index=None, price_type="mid"): """ Generate a dataframe consisting of the currency prices (specified by symbols) from the start to end date """ # Set defaults if necessary if symbols is None: symbols = list(Currency.objects.all().values_list('symbol', flat=True)) try: start_date = date_index[0] end_date = date_index[-1] except: start_date = DATEFRAME_START_DATE end_date = date.today() date_index = date_range(start_date, end_date) currency_price_data = CurrencyPrice.objects.filter(currency__symbol__in=symbols, date__gte=date_index[0], date__lte=date_index[-1]).values_list('date', 'currency__symbol', 'ask_price', 'bid_price') try: forex_data_array = np.core.records.fromrecords(currency_price_data, names=['date', 'symbol', 'ask_price', 'bid_price']) except IndexError: forex_data_array = np.core.records.fromrecords([(date(1900, 1, 1), "", 0, 0)], names=['date', 'symbol', 'ask_price', 'bid_price']) df = DataFrame.from_records(forex_data_array, index='date') df['date'] = df.index if price_type == "mid": df['price'] = (df['ask_price'] + df['bid_price']) / 2 elif price_type == "ask": df['price'] = df['ask_price'] elif price_type == "bid": df['price'] = df['bid_price'] else: raise ValueError("Incorrect price_type (%s) must be on of 'ask', 'bid' or 'mid'" % str(price_type)) df = df.pivot(index='date', columns='symbol', values='price') df = df.reindex(date_index) df = df.fillna(method="ffill") unlisted_symbols = list(set(symbols) - set(df.columns)) for unlisted_symbol in unlisted_symbols: df[unlisted_symbol] = np.nan df = df[symbols] return df
def generate_dataframe(self, symbols=None, date_index=None, price_type="mid"): """ Generate a dataframe consisting of the currency prices (specified by symbols) from the start to end date """ # Set defaults if necessary if symbols is None: symbols = list(Currency.objects.all().values_list('symbol', flat=True)) try: start_date = date_index[0] end_date = date_index[-1] except: start_date = DATEFRAME_START_DATE end_date = date.today() date_index = date_range(start_date, end_date) currency_price_data = CurrencyPrice.objects.filter(currency__symbol__in=symbols, date__gte=date_index[0], date__lte=date_index[-1]).values_list('date', 'currency__symbol', 'ask_price', 'bid_price') try: forex_data_array = np.core.records.fromrecords(currency_price_data, names=['date', 'symbol', 'ask_price', 'bid_price']) except IndexError: forex_data_array = np.core.records.fromrecords([(date(1900, 1, 1), "", 0, 0)], names=['date', 'symbol', 'ask_price', 'bid_price']) df = DataFrame.from_records(forex_data_array, index='date') df['date'] = df.index if price_type == "mid": df['price'] = (df['ask_price'] + df['bid_price']) / 2 elif price_type == "ask": df['price'] = df['ask_price'] elif price_type == "bid": df['price'] = df['bid_price'] else: raise ValueError("Incorrect price_type (%s) must be on of 'ask', 'bid' or 'mid'" % str(price_type)) df = df.pivot(index='date', columns='symbol', values='price') df = df.reindex(date_index) df = df.fillna(method="ffill") unlisted_symbols = list(set(symbols) - set(df.columns)) for unlisted_symbol in unlisted_symbols: df[unlisted_symbol] = np.nan df = df[symbols] return df
[ "Generate", "a", "dataframe", "consisting", "of", "the", "currency", "prices", "(", "specified", "by", "symbols", ")", "from", "the", "start", "to", "end", "date" ]
Valuehorizon/valuehorizon-forex
python
https://github.com/Valuehorizon/valuehorizon-forex/blob/e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8/forex/models.py#L81-L125
[ "def", "generate_dataframe", "(", "self", ",", "symbols", "=", "None", ",", "date_index", "=", "None", ",", "price_type", "=", "\"mid\"", ")", ":", "# Set defaults if necessary", "if", "symbols", "is", "None", ":", "symbols", "=", "list", "(", "Currency", ".", "objects", ".", "all", "(", ")", ".", "values_list", "(", "'symbol'", ",", "flat", "=", "True", ")", ")", "try", ":", "start_date", "=", "date_index", "[", "0", "]", "end_date", "=", "date_index", "[", "-", "1", "]", "except", ":", "start_date", "=", "DATEFRAME_START_DATE", "end_date", "=", "date", ".", "today", "(", ")", "date_index", "=", "date_range", "(", "start_date", ",", "end_date", ")", "currency_price_data", "=", "CurrencyPrice", ".", "objects", ".", "filter", "(", "currency__symbol__in", "=", "symbols", ",", "date__gte", "=", "date_index", "[", "0", "]", ",", "date__lte", "=", "date_index", "[", "-", "1", "]", ")", ".", "values_list", "(", "'date'", ",", "'currency__symbol'", ",", "'ask_price'", ",", "'bid_price'", ")", "try", ":", "forex_data_array", "=", "np", ".", "core", ".", "records", ".", "fromrecords", "(", "currency_price_data", ",", "names", "=", "[", "'date'", ",", "'symbol'", ",", "'ask_price'", ",", "'bid_price'", "]", ")", "except", "IndexError", ":", "forex_data_array", "=", "np", ".", "core", ".", "records", ".", "fromrecords", "(", "[", "(", "date", "(", "1900", ",", "1", ",", "1", ")", ",", "\"\"", ",", "0", ",", "0", ")", "]", ",", "names", "=", "[", "'date'", ",", "'symbol'", ",", "'ask_price'", ",", "'bid_price'", "]", ")", "df", "=", "DataFrame", ".", "from_records", "(", "forex_data_array", ",", "index", "=", "'date'", ")", "df", "[", "'date'", "]", "=", "df", ".", "index", "if", "price_type", "==", "\"mid\"", ":", "df", "[", "'price'", "]", "=", "(", "df", "[", "'ask_price'", "]", "+", "df", "[", "'bid_price'", "]", ")", "/", "2", "elif", "price_type", "==", "\"ask\"", ":", "df", "[", "'price'", "]", "=", "df", "[", "'ask_price'", "]", "elif", "price_type", "==", "\"bid\"", ":", "df", "[", "'price'", "]", "=", "df", "[", "'bid_price'", "]", "else", ":", "raise", "ValueError", "(", "\"Incorrect price_type (%s) must be on of 'ask', 'bid' or 'mid'\"", "%", "str", "(", "price_type", ")", ")", "df", "=", "df", ".", "pivot", "(", "index", "=", "'date'", ",", "columns", "=", "'symbol'", ",", "values", "=", "'price'", ")", "df", "=", "df", ".", "reindex", "(", "date_index", ")", "df", "=", "df", ".", "fillna", "(", "method", "=", "\"ffill\"", ")", "unlisted_symbols", "=", "list", "(", "set", "(", "symbols", ")", "-", "set", "(", "df", ".", "columns", ")", ")", "for", "unlisted_symbol", "in", "unlisted_symbols", ":", "df", "[", "unlisted_symbol", "]", "=", "np", ".", "nan", "df", "=", "df", "[", "symbols", "]", "return", "df" ]
e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8
test
CurrencyPrice.save
Sanitation checks
forex/models.py
def save(self, *args, **kwargs): """ Sanitation checks """ if self.ask_price < 0: raise ValidationError("Ask price must be greater than zero") if self.bid_price < 0: raise ValidationError("Bid price must be greater than zero") if self.ask_price < self.bid_price: raise ValidationError("Ask price must be at least Bid price") super(CurrencyPrice, self).save(*args, **kwargs)
def save(self, *args, **kwargs): """ Sanitation checks """ if self.ask_price < 0: raise ValidationError("Ask price must be greater than zero") if self.bid_price < 0: raise ValidationError("Bid price must be greater than zero") if self.ask_price < self.bid_price: raise ValidationError("Ask price must be at least Bid price") super(CurrencyPrice, self).save(*args, **kwargs)
[ "Sanitation", "checks" ]
Valuehorizon/valuehorizon-forex
python
https://github.com/Valuehorizon/valuehorizon-forex/blob/e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8/forex/models.py#L160-L171
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "ask_price", "<", "0", ":", "raise", "ValidationError", "(", "\"Ask price must be greater than zero\"", ")", "if", "self", ".", "bid_price", "<", "0", ":", "raise", "ValidationError", "(", "\"Bid price must be greater than zero\"", ")", "if", "self", ".", "ask_price", "<", "self", ".", "bid_price", ":", "raise", "ValidationError", "(", "\"Ask price must be at least Bid price\"", ")", "super", "(", "CurrencyPrice", ",", "self", ")", ".", "save", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
e921379ae6c9d07ddad87a1fd3b5bb8fdfc74cb8
test
get_stream_enc
Return the given stream's encoding or a default. There are cases where sys.std* might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. `default' is None if not provided.
environment/lib/python2.7/site-packages/IPython/utils/encoding.py
def get_stream_enc(stream, default=None): """Return the given stream's encoding or a default. There are cases where sys.std* might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. `default' is None if not provided. """ if not hasattr(stream, 'encoding') or not stream.encoding: return default else: return stream.encoding
def get_stream_enc(stream, default=None): """Return the given stream's encoding or a default. There are cases where sys.std* might not actually be a stream, so check for the encoding attribute prior to returning it, and return a default if it doesn't exist or evaluates as False. `default' is None if not provided. """ if not hasattr(stream, 'encoding') or not stream.encoding: return default else: return stream.encoding
[ "Return", "the", "given", "stream", "s", "encoding", "or", "a", "default", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/encoding.py#L20-L31
[ "def", "get_stream_enc", "(", "stream", ",", "default", "=", "None", ")", ":", "if", "not", "hasattr", "(", "stream", ",", "'encoding'", ")", "or", "not", "stream", ".", "encoding", ":", "return", "default", "else", ":", "return", "stream", ".", "encoding" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
getdefaultencoding
Return IPython's guess for the default encoding for bytes as text. Asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Fall back on locale.getpreferredencoding() which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually ASCII.
environment/lib/python2.7/site-packages/IPython/utils/encoding.py
def getdefaultencoding(): """Return IPython's guess for the default encoding for bytes as text. Asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Fall back on locale.getpreferredencoding() which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually ASCII. """ enc = get_stream_enc(sys.stdin) if not enc or enc=='ascii': try: # There are reports of getpreferredencoding raising errors # in some cases, which may well be fixed, but let's be conservative here. enc = locale.getpreferredencoding() except Exception: pass return enc or sys.getdefaultencoding()
def getdefaultencoding(): """Return IPython's guess for the default encoding for bytes as text. Asks for stdin.encoding first, to match the calling Terminal, but that is often None for subprocesses. Fall back on locale.getpreferredencoding() which should be a sensible platform default (that respects LANG environment), and finally to sys.getdefaultencoding() which is the most conservative option, and usually ASCII. """ enc = get_stream_enc(sys.stdin) if not enc or enc=='ascii': try: # There are reports of getpreferredencoding raising errors # in some cases, which may well be fixed, but let's be conservative here. enc = locale.getpreferredencoding() except Exception: pass return enc or sys.getdefaultencoding()
[ "Return", "IPython", "s", "guess", "for", "the", "default", "encoding", "for", "bytes", "as", "text", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/encoding.py#L37-L54
[ "def", "getdefaultencoding", "(", ")", ":", "enc", "=", "get_stream_enc", "(", "sys", ".", "stdin", ")", "if", "not", "enc", "or", "enc", "==", "'ascii'", ":", "try", ":", "# There are reports of getpreferredencoding raising errors", "# in some cases, which may well be fixed, but let's be conservative here.", "enc", "=", "locale", ".", "getpreferredencoding", "(", ")", "except", "Exception", ":", "pass", "return", "enc", "or", "sys", ".", "getdefaultencoding", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
get_userpass_value
Gets the username / password from config. Uses the following rules: 1. If it is specified on the cli (`cli_value`), use that. 2. If `config[key]` is specified, use that. 3. Otherwise prompt using `prompt_strategy`. :param cli_value: The value supplied from the command line or `None`. :type cli_value: unicode or `None` :param config: Config dictionary :type config: dict :param key: Key to find the config value. :type key: unicode :prompt_strategy: Argumentless function to return fallback value. :type prompt_strategy: function :returns: The value for the username / password :rtype: unicode
virtualEnvironment/lib/python2.7/site-packages/twine/utils.py
def get_userpass_value(cli_value, config, key, prompt_strategy): """Gets the username / password from config. Uses the following rules: 1. If it is specified on the cli (`cli_value`), use that. 2. If `config[key]` is specified, use that. 3. Otherwise prompt using `prompt_strategy`. :param cli_value: The value supplied from the command line or `None`. :type cli_value: unicode or `None` :param config: Config dictionary :type config: dict :param key: Key to find the config value. :type key: unicode :prompt_strategy: Argumentless function to return fallback value. :type prompt_strategy: function :returns: The value for the username / password :rtype: unicode """ if cli_value is not None: return cli_value elif config.get(key): return config[key] else: return prompt_strategy()
def get_userpass_value(cli_value, config, key, prompt_strategy): """Gets the username / password from config. Uses the following rules: 1. If it is specified on the cli (`cli_value`), use that. 2. If `config[key]` is specified, use that. 3. Otherwise prompt using `prompt_strategy`. :param cli_value: The value supplied from the command line or `None`. :type cli_value: unicode or `None` :param config: Config dictionary :type config: dict :param key: Key to find the config value. :type key: unicode :prompt_strategy: Argumentless function to return fallback value. :type prompt_strategy: function :returns: The value for the username / password :rtype: unicode """ if cli_value is not None: return cli_value elif config.get(key): return config[key] else: return prompt_strategy()
[ "Gets", "the", "username", "/", "password", "from", "config", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/twine/utils.py#L89-L114
[ "def", "get_userpass_value", "(", "cli_value", ",", "config", ",", "key", ",", "prompt_strategy", ")", ":", "if", "cli_value", "is", "not", "None", ":", "return", "cli_value", "elif", "config", ".", "get", "(", "key", ")", ":", "return", "config", "[", "key", "]", "else", ":", "return", "prompt_strategy", "(", ")" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
KernelApp.load_connection_file
load ip/port/hmac config from JSON connection file
environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py
def load_connection_file(self): """load ip/port/hmac config from JSON connection file""" try: fname = filefind(self.connection_file, ['.', self.profile_dir.security_dir]) except IOError: self.log.debug("Connection file not found: %s", self.connection_file) # This means I own it, so I will clean it up: atexit.register(self.cleanup_connection_file) return self.log.debug(u"Loading connection file %s", fname) with open(fname) as f: s = f.read() cfg = json.loads(s) if self.ip == LOCALHOST and 'ip' in cfg: # not overridden by config or cl_args self.ip = cfg['ip'] for channel in ('hb', 'shell', 'iopub', 'stdin'): name = channel + '_port' if getattr(self, name) == 0 and name in cfg: # not overridden by config or cl_args setattr(self, name, cfg[name]) if 'key' in cfg: self.config.Session.key = str_to_bytes(cfg['key'])
def load_connection_file(self): """load ip/port/hmac config from JSON connection file""" try: fname = filefind(self.connection_file, ['.', self.profile_dir.security_dir]) except IOError: self.log.debug("Connection file not found: %s", self.connection_file) # This means I own it, so I will clean it up: atexit.register(self.cleanup_connection_file) return self.log.debug(u"Loading connection file %s", fname) with open(fname) as f: s = f.read() cfg = json.loads(s) if self.ip == LOCALHOST and 'ip' in cfg: # not overridden by config or cl_args self.ip = cfg['ip'] for channel in ('hb', 'shell', 'iopub', 'stdin'): name = channel + '_port' if getattr(self, name) == 0 and name in cfg: # not overridden by config or cl_args setattr(self, name, cfg[name]) if 'key' in cfg: self.config.Session.key = str_to_bytes(cfg['key'])
[ "load", "ip", "/", "port", "/", "hmac", "config", "from", "JSON", "connection", "file" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L164-L186
[ "def", "load_connection_file", "(", "self", ")", ":", "try", ":", "fname", "=", "filefind", "(", "self", ".", "connection_file", ",", "[", "'.'", ",", "self", ".", "profile_dir", ".", "security_dir", "]", ")", "except", "IOError", ":", "self", ".", "log", ".", "debug", "(", "\"Connection file not found: %s\"", ",", "self", ".", "connection_file", ")", "# This means I own it, so I will clean it up:", "atexit", ".", "register", "(", "self", ".", "cleanup_connection_file", ")", "return", "self", ".", "log", ".", "debug", "(", "u\"Loading connection file %s\"", ",", "fname", ")", "with", "open", "(", "fname", ")", "as", "f", ":", "s", "=", "f", ".", "read", "(", ")", "cfg", "=", "json", ".", "loads", "(", "s", ")", "if", "self", ".", "ip", "==", "LOCALHOST", "and", "'ip'", "in", "cfg", ":", "# not overridden by config or cl_args", "self", ".", "ip", "=", "cfg", "[", "'ip'", "]", "for", "channel", "in", "(", "'hb'", ",", "'shell'", ",", "'iopub'", ",", "'stdin'", ")", ":", "name", "=", "channel", "+", "'_port'", "if", "getattr", "(", "self", ",", "name", ")", "==", "0", "and", "name", "in", "cfg", ":", "# not overridden by config or cl_args", "setattr", "(", "self", ",", "name", ",", "cfg", "[", "name", "]", ")", "if", "'key'", "in", "cfg", ":", "self", ".", "config", ".", "Session", ".", "key", "=", "str_to_bytes", "(", "cfg", "[", "'key'", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KernelApp.write_connection_file
write connection info to JSON file
environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py
def write_connection_file(self): """write connection info to JSON file""" if os.path.basename(self.connection_file) == self.connection_file: cf = os.path.join(self.profile_dir.security_dir, self.connection_file) else: cf = self.connection_file write_connection_file(cf, ip=self.ip, key=self.session.key, shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port, iopub_port=self.iopub_port) self._full_connection_file = cf
def write_connection_file(self): """write connection info to JSON file""" if os.path.basename(self.connection_file) == self.connection_file: cf = os.path.join(self.profile_dir.security_dir, self.connection_file) else: cf = self.connection_file write_connection_file(cf, ip=self.ip, key=self.session.key, shell_port=self.shell_port, stdin_port=self.stdin_port, hb_port=self.hb_port, iopub_port=self.iopub_port) self._full_connection_file = cf
[ "write", "connection", "info", "to", "JSON", "file" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L188-L198
[ "def", "write_connection_file", "(", "self", ")", ":", "if", "os", ".", "path", ".", "basename", "(", "self", ".", "connection_file", ")", "==", "self", ".", "connection_file", ":", "cf", "=", "os", ".", "path", ".", "join", "(", "self", ".", "profile_dir", ".", "security_dir", ",", "self", ".", "connection_file", ")", "else", ":", "cf", "=", "self", ".", "connection_file", "write_connection_file", "(", "cf", ",", "ip", "=", "self", ".", "ip", ",", "key", "=", "self", ".", "session", ".", "key", ",", "shell_port", "=", "self", ".", "shell_port", ",", "stdin_port", "=", "self", ".", "stdin_port", ",", "hb_port", "=", "self", ".", "hb_port", ",", "iopub_port", "=", "self", ".", "iopub_port", ")", "self", ".", "_full_connection_file", "=", "cf" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KernelApp.init_heartbeat
start the heart beating
environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py
def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.ip, self.hb_port)) self.hb_port = self.heartbeat.port self.log.debug("Heartbeat REP Channel on port: %i"%self.hb_port) self.heartbeat.start() # Helper to make it easier to connect to an existing kernel. # set log-level to critical, to make sure it is output self.log.critical("To connect another client to this kernel, use:")
def init_heartbeat(self): """start the heart beating""" # heartbeat doesn't share context, because it mustn't be blocked # by the GIL, which is accessed by libzmq when freeing zero-copy messages hb_ctx = zmq.Context() self.heartbeat = Heartbeat(hb_ctx, (self.ip, self.hb_port)) self.hb_port = self.heartbeat.port self.log.debug("Heartbeat REP Channel on port: %i"%self.hb_port) self.heartbeat.start() # Helper to make it easier to connect to an existing kernel. # set log-level to critical, to make sure it is output self.log.critical("To connect another client to this kernel, use:")
[ "start", "the", "heart", "beating" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L236-L248
[ "def", "init_heartbeat", "(", "self", ")", ":", "# heartbeat doesn't share context, because it mustn't be blocked", "# by the GIL, which is accessed by libzmq when freeing zero-copy messages", "hb_ctx", "=", "zmq", ".", "Context", "(", ")", "self", ".", "heartbeat", "=", "Heartbeat", "(", "hb_ctx", ",", "(", "self", ".", "ip", ",", "self", ".", "hb_port", ")", ")", "self", ".", "hb_port", "=", "self", ".", "heartbeat", ".", "port", "self", ".", "log", ".", "debug", "(", "\"Heartbeat REP Channel on port: %i\"", "%", "self", ".", "hb_port", ")", "self", ".", "heartbeat", ".", "start", "(", ")", "# Helper to make it easier to connect to an existing kernel.", "# set log-level to critical, to make sure it is output", "self", ".", "log", ".", "critical", "(", "\"To connect another client to this kernel, use:\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KernelApp.log_connection_info
display connection info, and store ports
environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py
def log_connection_info(self): """display connection info, and store ports""" basename = os.path.basename(self.connection_file) if basename == self.connection_file or \ os.path.dirname(self.connection_file) == self.profile_dir.security_dir: # use shortname tail = basename if self.profile != 'default': tail += " --profile %s" % self.profile else: tail = self.connection_file self.log.critical("--existing %s", tail) self.ports = dict(shell=self.shell_port, iopub=self.iopub_port, stdin=self.stdin_port, hb=self.hb_port)
def log_connection_info(self): """display connection info, and store ports""" basename = os.path.basename(self.connection_file) if basename == self.connection_file or \ os.path.dirname(self.connection_file) == self.profile_dir.security_dir: # use shortname tail = basename if self.profile != 'default': tail += " --profile %s" % self.profile else: tail = self.connection_file self.log.critical("--existing %s", tail) self.ports = dict(shell=self.shell_port, iopub=self.iopub_port, stdin=self.stdin_port, hb=self.hb_port)
[ "display", "connection", "info", "and", "store", "ports" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L250-L265
[ "def", "log_connection_info", "(", "self", ")", ":", "basename", "=", "os", ".", "path", ".", "basename", "(", "self", ".", "connection_file", ")", "if", "basename", "==", "self", ".", "connection_file", "or", "os", ".", "path", ".", "dirname", "(", "self", ".", "connection_file", ")", "==", "self", ".", "profile_dir", ".", "security_dir", ":", "# use shortname", "tail", "=", "basename", "if", "self", ".", "profile", "!=", "'default'", ":", "tail", "+=", "\" --profile %s\"", "%", "self", ".", "profile", "else", ":", "tail", "=", "self", ".", "connection_file", "self", ".", "log", ".", "critical", "(", "\"--existing %s\"", ",", "tail", ")", "self", ".", "ports", "=", "dict", "(", "shell", "=", "self", ".", "shell_port", ",", "iopub", "=", "self", ".", "iopub_port", ",", "stdin", "=", "self", ".", "stdin_port", ",", "hb", "=", "self", ".", "hb_port", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KernelApp.init_session
create our session object
environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py
def init_session(self): """create our session object""" default_secure(self.config) self.session = Session(config=self.config, username=u'kernel')
def init_session(self): """create our session object""" default_secure(self.config) self.session = Session(config=self.config, username=u'kernel')
[ "create", "our", "session", "object" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L267-L270
[ "def", "init_session", "(", "self", ")", ":", "default_secure", "(", "self", ".", "config", ")", "self", ".", "session", "=", "Session", "(", "config", "=", "self", ".", "config", ",", "username", "=", "u'kernel'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KernelApp.init_blackhole
redirects stdout/stderr to devnull if necessary
environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py
def init_blackhole(self): """redirects stdout/stderr to devnull if necessary""" if self.no_stdout or self.no_stderr: blackhole = open(os.devnull, 'w') if self.no_stdout: sys.stdout = sys.__stdout__ = blackhole if self.no_stderr: sys.stderr = sys.__stderr__ = blackhole
def init_blackhole(self): """redirects stdout/stderr to devnull if necessary""" if self.no_stdout or self.no_stderr: blackhole = open(os.devnull, 'w') if self.no_stdout: sys.stdout = sys.__stdout__ = blackhole if self.no_stderr: sys.stderr = sys.__stderr__ = blackhole
[ "redirects", "stdout", "/", "stderr", "to", "devnull", "if", "necessary" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L272-L279
[ "def", "init_blackhole", "(", "self", ")", ":", "if", "self", ".", "no_stdout", "or", "self", ".", "no_stderr", ":", "blackhole", "=", "open", "(", "os", ".", "devnull", ",", "'w'", ")", "if", "self", ".", "no_stdout", ":", "sys", ".", "stdout", "=", "sys", ".", "__stdout__", "=", "blackhole", "if", "self", ".", "no_stderr", ":", "sys", ".", "stderr", "=", "sys", ".", "__stderr__", "=", "blackhole" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KernelApp.init_io
Redirect input streams and set a display hook.
environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py
def init_io(self): """Redirect input streams and set a display hook.""" if self.outstream_class: outstream_factory = import_item(str(self.outstream_class)) sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout') sys.stderr = outstream_factory(self.session, self.iopub_socket, u'stderr') if self.displayhook_class: displayhook_factory = import_item(str(self.displayhook_class)) sys.displayhook = displayhook_factory(self.session, self.iopub_socket)
def init_io(self): """Redirect input streams and set a display hook.""" if self.outstream_class: outstream_factory = import_item(str(self.outstream_class)) sys.stdout = outstream_factory(self.session, self.iopub_socket, u'stdout') sys.stderr = outstream_factory(self.session, self.iopub_socket, u'stderr') if self.displayhook_class: displayhook_factory = import_item(str(self.displayhook_class)) sys.displayhook = displayhook_factory(self.session, self.iopub_socket)
[ "Redirect", "input", "streams", "and", "set", "a", "display", "hook", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L281-L289
[ "def", "init_io", "(", "self", ")", ":", "if", "self", ".", "outstream_class", ":", "outstream_factory", "=", "import_item", "(", "str", "(", "self", ".", "outstream_class", ")", ")", "sys", ".", "stdout", "=", "outstream_factory", "(", "self", ".", "session", ",", "self", ".", "iopub_socket", ",", "u'stdout'", ")", "sys", ".", "stderr", "=", "outstream_factory", "(", "self", ".", "session", ",", "self", ".", "iopub_socket", ",", "u'stderr'", ")", "if", "self", ".", "displayhook_class", ":", "displayhook_factory", "=", "import_item", "(", "str", "(", "self", ".", "displayhook_class", ")", ")", "sys", ".", "displayhook", "=", "displayhook_factory", "(", "self", ".", "session", ",", "self", ".", "iopub_socket", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
KernelApp.init_kernel
Create the Kernel object itself
environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py
def init_kernel(self): """Create the Kernel object itself""" kernel_factory = import_item(str(self.kernel_class)) self.kernel = kernel_factory(config=self.config, session=self.session, shell_socket=self.shell_socket, iopub_socket=self.iopub_socket, stdin_socket=self.stdin_socket, log=self.log ) self.kernel.record_ports(self.ports)
def init_kernel(self): """Create the Kernel object itself""" kernel_factory = import_item(str(self.kernel_class)) self.kernel = kernel_factory(config=self.config, session=self.session, shell_socket=self.shell_socket, iopub_socket=self.iopub_socket, stdin_socket=self.stdin_socket, log=self.log ) self.kernel.record_ports(self.ports)
[ "Create", "the", "Kernel", "object", "itself" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/zmq/kernelapp.py#L294-L303
[ "def", "init_kernel", "(", "self", ")", ":", "kernel_factory", "=", "import_item", "(", "str", "(", "self", ".", "kernel_class", ")", ")", "self", ".", "kernel", "=", "kernel_factory", "(", "config", "=", "self", ".", "config", ",", "session", "=", "self", ".", "session", ",", "shell_socket", "=", "self", ".", "shell_socket", ",", "iopub_socket", "=", "self", ".", "iopub_socket", ",", "stdin_socket", "=", "self", ".", "stdin_socket", ",", "log", "=", "self", ".", "log", ")", "self", ".", "kernel", ".", "record_ports", "(", "self", ".", "ports", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EngineFactory.init_connector
construct connection function, which handles tunnels.
environment/lib/python2.7/site-packages/IPython/parallel/engine/engine.py
def init_connector(self): """construct connection function, which handles tunnels.""" self.using_ssh = bool(self.sshkey or self.sshserver) if self.sshkey and not self.sshserver: # We are using ssh directly to the controller, tunneling localhost to localhost self.sshserver = self.url.split('://')[1].split(':')[0] if self.using_ssh: if tunnel.try_passwordless_ssh(self.sshserver, self.sshkey, self.paramiko): password=False else: password = getpass("SSH Password for %s: "%self.sshserver) else: password = False def connect(s, url): url = disambiguate_url(url, self.location) if self.using_ssh: self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver)) return tunnel.tunnel_connection(s, url, self.sshserver, keyfile=self.sshkey, paramiko=self.paramiko, password=password, ) else: return s.connect(url) def maybe_tunnel(url): """like connect, but don't complete the connection (for use by heartbeat)""" url = disambiguate_url(url, self.location) if self.using_ssh: self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver)) url,tunnelobj = tunnel.open_tunnel(url, self.sshserver, keyfile=self.sshkey, paramiko=self.paramiko, password=password, ) return url return connect, maybe_tunnel
def init_connector(self): """construct connection function, which handles tunnels.""" self.using_ssh = bool(self.sshkey or self.sshserver) if self.sshkey and not self.sshserver: # We are using ssh directly to the controller, tunneling localhost to localhost self.sshserver = self.url.split('://')[1].split(':')[0] if self.using_ssh: if tunnel.try_passwordless_ssh(self.sshserver, self.sshkey, self.paramiko): password=False else: password = getpass("SSH Password for %s: "%self.sshserver) else: password = False def connect(s, url): url = disambiguate_url(url, self.location) if self.using_ssh: self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver)) return tunnel.tunnel_connection(s, url, self.sshserver, keyfile=self.sshkey, paramiko=self.paramiko, password=password, ) else: return s.connect(url) def maybe_tunnel(url): """like connect, but don't complete the connection (for use by heartbeat)""" url = disambiguate_url(url, self.location) if self.using_ssh: self.log.debug("Tunneling connection to %s via %s"%(url, self.sshserver)) url,tunnelobj = tunnel.open_tunnel(url, self.sshserver, keyfile=self.sshkey, paramiko=self.paramiko, password=password, ) return url return connect, maybe_tunnel
[ "construct", "connection", "function", "which", "handles", "tunnels", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/engine/engine.py#L80-L117
[ "def", "init_connector", "(", "self", ")", ":", "self", ".", "using_ssh", "=", "bool", "(", "self", ".", "sshkey", "or", "self", ".", "sshserver", ")", "if", "self", ".", "sshkey", "and", "not", "self", ".", "sshserver", ":", "# We are using ssh directly to the controller, tunneling localhost to localhost", "self", ".", "sshserver", "=", "self", ".", "url", ".", "split", "(", "'://'", ")", "[", "1", "]", ".", "split", "(", "':'", ")", "[", "0", "]", "if", "self", ".", "using_ssh", ":", "if", "tunnel", ".", "try_passwordless_ssh", "(", "self", ".", "sshserver", ",", "self", ".", "sshkey", ",", "self", ".", "paramiko", ")", ":", "password", "=", "False", "else", ":", "password", "=", "getpass", "(", "\"SSH Password for %s: \"", "%", "self", ".", "sshserver", ")", "else", ":", "password", "=", "False", "def", "connect", "(", "s", ",", "url", ")", ":", "url", "=", "disambiguate_url", "(", "url", ",", "self", ".", "location", ")", "if", "self", ".", "using_ssh", ":", "self", ".", "log", ".", "debug", "(", "\"Tunneling connection to %s via %s\"", "%", "(", "url", ",", "self", ".", "sshserver", ")", ")", "return", "tunnel", ".", "tunnel_connection", "(", "s", ",", "url", ",", "self", ".", "sshserver", ",", "keyfile", "=", "self", ".", "sshkey", ",", "paramiko", "=", "self", ".", "paramiko", ",", "password", "=", "password", ",", ")", "else", ":", "return", "s", ".", "connect", "(", "url", ")", "def", "maybe_tunnel", "(", "url", ")", ":", "\"\"\"like connect, but don't complete the connection (for use by heartbeat)\"\"\"", "url", "=", "disambiguate_url", "(", "url", ",", "self", ".", "location", ")", "if", "self", ".", "using_ssh", ":", "self", ".", "log", ".", "debug", "(", "\"Tunneling connection to %s via %s\"", "%", "(", "url", ",", "self", ".", "sshserver", ")", ")", "url", ",", "tunnelobj", "=", "tunnel", ".", "open_tunnel", "(", "url", ",", "self", ".", "sshserver", ",", "keyfile", "=", "self", ".", "sshkey", ",", "paramiko", "=", "self", ".", "paramiko", ",", "password", "=", "password", ",", ")", "return", "url", "return", "connect", ",", "maybe_tunnel" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EngineFactory.register
send the registration_request
environment/lib/python2.7/site-packages/IPython/parallel/engine/engine.py
def register(self): """send the registration_request""" self.log.info("Registering with controller at %s"%self.url) ctx = self.context connect,maybe_tunnel = self.init_connector() reg = ctx.socket(zmq.DEALER) reg.setsockopt(zmq.IDENTITY, self.bident) connect(reg, self.url) self.registrar = zmqstream.ZMQStream(reg, self.loop) content = dict(queue=self.ident, heartbeat=self.ident, control=self.ident) self.registrar.on_recv(lambda msg: self.complete_registration(msg, connect, maybe_tunnel)) # print (self.session.key) self.session.send(self.registrar, "registration_request",content=content)
def register(self): """send the registration_request""" self.log.info("Registering with controller at %s"%self.url) ctx = self.context connect,maybe_tunnel = self.init_connector() reg = ctx.socket(zmq.DEALER) reg.setsockopt(zmq.IDENTITY, self.bident) connect(reg, self.url) self.registrar = zmqstream.ZMQStream(reg, self.loop) content = dict(queue=self.ident, heartbeat=self.ident, control=self.ident) self.registrar.on_recv(lambda msg: self.complete_registration(msg, connect, maybe_tunnel)) # print (self.session.key) self.session.send(self.registrar, "registration_request",content=content)
[ "send", "the", "registration_request" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/engine/engine.py#L119-L134
[ "def", "register", "(", "self", ")", ":", "self", ".", "log", ".", "info", "(", "\"Registering with controller at %s\"", "%", "self", ".", "url", ")", "ctx", "=", "self", ".", "context", "connect", ",", "maybe_tunnel", "=", "self", ".", "init_connector", "(", ")", "reg", "=", "ctx", ".", "socket", "(", "zmq", ".", "DEALER", ")", "reg", ".", "setsockopt", "(", "zmq", ".", "IDENTITY", ",", "self", ".", "bident", ")", "connect", "(", "reg", ",", "self", ".", "url", ")", "self", ".", "registrar", "=", "zmqstream", ".", "ZMQStream", "(", "reg", ",", "self", ".", "loop", ")", "content", "=", "dict", "(", "queue", "=", "self", ".", "ident", ",", "heartbeat", "=", "self", ".", "ident", ",", "control", "=", "self", ".", "ident", ")", "self", ".", "registrar", ".", "on_recv", "(", "lambda", "msg", ":", "self", ".", "complete_registration", "(", "msg", ",", "connect", ",", "maybe_tunnel", ")", ")", "# print (self.session.key)", "self", ".", "session", ".", "send", "(", "self", ".", "registrar", ",", "\"registration_request\"", ",", "content", "=", "content", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
html_to_text
Converts html content to plain text
toolware/utils/convert.py
def html_to_text(content): """ Converts html content to plain text """ text = None h2t = html2text.HTML2Text() h2t.ignore_links = False text = h2t.handle(content) return text
def html_to_text(content): """ Converts html content to plain text """ text = None h2t = html2text.HTML2Text() h2t.ignore_links = False text = h2t.handle(content) return text
[ "Converts", "html", "content", "to", "plain", "text" ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/convert.py#L5-L11
[ "def", "html_to_text", "(", "content", ")", ":", "text", "=", "None", "h2t", "=", "html2text", ".", "HTML2Text", "(", ")", "h2t", ".", "ignore_links", "=", "False", "text", "=", "h2t", ".", "handle", "(", "content", ")", "return", "text" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
md_to_text
Converts markdown content to text
toolware/utils/convert.py
def md_to_text(content): """ Converts markdown content to text """ text = None html = markdown.markdown(content) if html: text = html_to_text(content) return text
def md_to_text(content): """ Converts markdown content to text """ text = None html = markdown.markdown(content) if html: text = html_to_text(content) return text
[ "Converts", "markdown", "content", "to", "text" ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/convert.py#L20-L26
[ "def", "md_to_text", "(", "content", ")", ":", "text", "=", "None", "html", "=", "markdown", ".", "markdown", "(", "content", ")", "if", "html", ":", "text", "=", "html_to_text", "(", "content", ")", "return", "text" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
parts_to_uri
Converts uri parts to valid uri. Example: /memebers, ['profile', 'view'] => /memembers/profile/view
toolware/utils/convert.py
def parts_to_uri(base_uri, uri_parts): """ Converts uri parts to valid uri. Example: /memebers, ['profile', 'view'] => /memembers/profile/view """ uri = "/".join(map(lambda x: str(x).rstrip('/'), [base_uri] + uri_parts)) return uri
def parts_to_uri(base_uri, uri_parts): """ Converts uri parts to valid uri. Example: /memebers, ['profile', 'view'] => /memembers/profile/view """ uri = "/".join(map(lambda x: str(x).rstrip('/'), [base_uri] + uri_parts)) return uri
[ "Converts", "uri", "parts", "to", "valid", "uri", ".", "Example", ":", "/", "memebers", "[", "profile", "view", "]", "=", ">", "/", "memembers", "/", "profile", "/", "view" ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/convert.py#L29-L35
[ "def", "parts_to_uri", "(", "base_uri", ",", "uri_parts", ")", ":", "uri", "=", "\"/\"", ".", "join", "(", "map", "(", "lambda", "x", ":", "str", "(", "x", ")", ".", "rstrip", "(", "'/'", ")", ",", "[", "base_uri", "]", "+", "uri_parts", ")", ")", "return", "uri" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
domain_to_fqdn
returns a fully qualified app domain name
toolware/utils/convert.py
def domain_to_fqdn(domain, proto=None): """ returns a fully qualified app domain name """ from .generic import get_site_proto proto = proto or get_site_proto() fdqn = '{proto}://{domain}'.format(proto=proto, domain=domain) return fdqn
def domain_to_fqdn(domain, proto=None): """ returns a fully qualified app domain name """ from .generic import get_site_proto proto = proto or get_site_proto() fdqn = '{proto}://{domain}'.format(proto=proto, domain=domain) return fdqn
[ "returns", "a", "fully", "qualified", "app", "domain", "name" ]
un33k/django-toolware
python
https://github.com/un33k/django-toolware/blob/973f3e003dc38b812897dab88455bee37dcaf931/toolware/utils/convert.py#L38-L43
[ "def", "domain_to_fqdn", "(", "domain", ",", "proto", "=", "None", ")", ":", "from", ".", "generic", "import", "get_site_proto", "proto", "=", "proto", "or", "get_site_proto", "(", ")", "fdqn", "=", "'{proto}://{domain}'", ".", "format", "(", "proto", "=", "proto", ",", "domain", "=", "domain", ")", "return", "fdqn" ]
973f3e003dc38b812897dab88455bee37dcaf931
test
NoseExclude.options
Define the command line options for the plugin.
environment/lib/python2.7/site-packages/nose_exclude.py
def options(self, parser, env=os.environ): """Define the command line options for the plugin.""" super(NoseExclude, self).options(parser, env) env_dirs = [] if 'NOSE_EXCLUDE_DIRS' in env: exclude_dirs = env.get('NOSE_EXCLUDE_DIRS','') env_dirs.extend(exclude_dirs.split(';')) parser.add_option( "--exclude-dir", action="append", dest="exclude_dirs", default=env_dirs, help="Directory to exclude from test discovery. \ Path can be relative to current working directory \ or an absolute path. May be specified multiple \ times. [NOSE_EXCLUDE_DIRS]") parser.add_option( "--exclude-dir-file", type="string", dest="exclude_dir_file", default=env.get('NOSE_EXCLUDE_DIRS_FILE', False), help="A file containing a list of directories to exclude \ from test discovery. Paths can be relative to current \ working directory or an absolute path. \ [NOSE_EXCLUDE_DIRS_FILE]")
def options(self, parser, env=os.environ): """Define the command line options for the plugin.""" super(NoseExclude, self).options(parser, env) env_dirs = [] if 'NOSE_EXCLUDE_DIRS' in env: exclude_dirs = env.get('NOSE_EXCLUDE_DIRS','') env_dirs.extend(exclude_dirs.split(';')) parser.add_option( "--exclude-dir", action="append", dest="exclude_dirs", default=env_dirs, help="Directory to exclude from test discovery. \ Path can be relative to current working directory \ or an absolute path. May be specified multiple \ times. [NOSE_EXCLUDE_DIRS]") parser.add_option( "--exclude-dir-file", type="string", dest="exclude_dir_file", default=env.get('NOSE_EXCLUDE_DIRS_FILE', False), help="A file containing a list of directories to exclude \ from test discovery. Paths can be relative to current \ working directory or an absolute path. \ [NOSE_EXCLUDE_DIRS_FILE]")
[ "Define", "the", "command", "line", "options", "for", "the", "plugin", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose_exclude.py#L9-L32
[ "def", "options", "(", "self", ",", "parser", ",", "env", "=", "os", ".", "environ", ")", ":", "super", "(", "NoseExclude", ",", "self", ")", ".", "options", "(", "parser", ",", "env", ")", "env_dirs", "=", "[", "]", "if", "'NOSE_EXCLUDE_DIRS'", "in", "env", ":", "exclude_dirs", "=", "env", ".", "get", "(", "'NOSE_EXCLUDE_DIRS'", ",", "''", ")", "env_dirs", ".", "extend", "(", "exclude_dirs", ".", "split", "(", "';'", ")", ")", "parser", ".", "add_option", "(", "\"--exclude-dir\"", ",", "action", "=", "\"append\"", ",", "dest", "=", "\"exclude_dirs\"", ",", "default", "=", "env_dirs", ",", "help", "=", "\"Directory to exclude from test discovery. \\\n Path can be relative to current working directory \\\n or an absolute path. May be specified multiple \\\n times. [NOSE_EXCLUDE_DIRS]\"", ")", "parser", ".", "add_option", "(", "\"--exclude-dir-file\"", ",", "type", "=", "\"string\"", ",", "dest", "=", "\"exclude_dir_file\"", ",", "default", "=", "env", ".", "get", "(", "'NOSE_EXCLUDE_DIRS_FILE'", ",", "False", ")", ",", "help", "=", "\"A file containing a list of directories to exclude \\\n from test discovery. Paths can be relative to current \\\n working directory or an absolute path. \\\n [NOSE_EXCLUDE_DIRS_FILE]\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
NoseExclude.configure
Configure plugin based on command line options
environment/lib/python2.7/site-packages/nose_exclude.py
def configure(self, options, conf): """Configure plugin based on command line options""" super(NoseExclude, self).configure(options, conf) self.exclude_dirs = {} # preload directories from file if options.exclude_dir_file: if not options.exclude_dirs: options.exclude_dirs = [] new_dirs = self._load_from_file(options.exclude_dir_file) options.exclude_dirs.extend(new_dirs) if not options.exclude_dirs: self.enabled = False return self.enabled = True root = os.getcwd() log.debug('cwd: %s' % root) # Normalize excluded directory names for lookup for exclude_param in options.exclude_dirs: # when using setup.cfg, you can specify only one 'exclude-dir' # separated by some character (new line is good enough) for d in exclude_param.split('\n'): d = d.strip() abs_d = self._force_to_abspath(d) if abs_d: self.exclude_dirs[abs_d] = True exclude_str = "excluding dirs: %s" % ",".join(self.exclude_dirs.keys()) log.debug(exclude_str)
def configure(self, options, conf): """Configure plugin based on command line options""" super(NoseExclude, self).configure(options, conf) self.exclude_dirs = {} # preload directories from file if options.exclude_dir_file: if not options.exclude_dirs: options.exclude_dirs = [] new_dirs = self._load_from_file(options.exclude_dir_file) options.exclude_dirs.extend(new_dirs) if not options.exclude_dirs: self.enabled = False return self.enabled = True root = os.getcwd() log.debug('cwd: %s' % root) # Normalize excluded directory names for lookup for exclude_param in options.exclude_dirs: # when using setup.cfg, you can specify only one 'exclude-dir' # separated by some character (new line is good enough) for d in exclude_param.split('\n'): d = d.strip() abs_d = self._force_to_abspath(d) if abs_d: self.exclude_dirs[abs_d] = True exclude_str = "excluding dirs: %s" % ",".join(self.exclude_dirs.keys()) log.debug(exclude_str)
[ "Configure", "plugin", "based", "on", "command", "line", "options" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose_exclude.py#L52-L85
[ "def", "configure", "(", "self", ",", "options", ",", "conf", ")", ":", "super", "(", "NoseExclude", ",", "self", ")", ".", "configure", "(", "options", ",", "conf", ")", "self", ".", "exclude_dirs", "=", "{", "}", "# preload directories from file", "if", "options", ".", "exclude_dir_file", ":", "if", "not", "options", ".", "exclude_dirs", ":", "options", ".", "exclude_dirs", "=", "[", "]", "new_dirs", "=", "self", ".", "_load_from_file", "(", "options", ".", "exclude_dir_file", ")", "options", ".", "exclude_dirs", ".", "extend", "(", "new_dirs", ")", "if", "not", "options", ".", "exclude_dirs", ":", "self", ".", "enabled", "=", "False", "return", "self", ".", "enabled", "=", "True", "root", "=", "os", ".", "getcwd", "(", ")", "log", ".", "debug", "(", "'cwd: %s'", "%", "root", ")", "# Normalize excluded directory names for lookup", "for", "exclude_param", "in", "options", ".", "exclude_dirs", ":", "# when using setup.cfg, you can specify only one 'exclude-dir'", "# separated by some character (new line is good enough)", "for", "d", "in", "exclude_param", ".", "split", "(", "'\\n'", ")", ":", "d", "=", "d", ".", "strip", "(", ")", "abs_d", "=", "self", ".", "_force_to_abspath", "(", "d", ")", "if", "abs_d", ":", "self", ".", "exclude_dirs", "[", "abs_d", "]", "=", "True", "exclude_str", "=", "\"excluding dirs: %s\"", "%", "\",\"", ".", "join", "(", "self", ".", "exclude_dirs", ".", "keys", "(", ")", ")", "log", ".", "debug", "(", "exclude_str", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
NoseExclude.wantDirectory
Check if directory is eligible for test discovery
environment/lib/python2.7/site-packages/nose_exclude.py
def wantDirectory(self, dirname): """Check if directory is eligible for test discovery""" if dirname in self.exclude_dirs: log.debug("excluded: %s" % dirname) return False else: return None
def wantDirectory(self, dirname): """Check if directory is eligible for test discovery""" if dirname in self.exclude_dirs: log.debug("excluded: %s" % dirname) return False else: return None
[ "Check", "if", "directory", "is", "eligible", "for", "test", "discovery" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose_exclude.py#L87-L93
[ "def", "wantDirectory", "(", "self", ",", "dirname", ")", ":", "if", "dirname", "in", "self", ".", "exclude_dirs", ":", "log", ".", "debug", "(", "\"excluded: %s\"", "%", "dirname", ")", "return", "False", "else", ":", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
build_ext.links_to_dynamic
Return true if 'ext' links to a dynamic lib in the same package
environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/build_ext.py
def links_to_dynamic(self, ext): """Return true if 'ext' links to a dynamic lib in the same package""" # XXX this should check to ensure the lib is actually being built # XXX as dynamic, and not just using a locally-found version or a # XXX static-compiled version libnames = dict.fromkeys([lib._full_name for lib in self.shlibs]) pkg = '.'.join(ext._full_name.split('.')[:-1]+['']) for libname in ext.libraries: if pkg+libname in libnames: return True return False
def links_to_dynamic(self, ext): """Return true if 'ext' links to a dynamic lib in the same package""" # XXX this should check to ensure the lib is actually being built # XXX as dynamic, and not just using a locally-found version or a # XXX static-compiled version libnames = dict.fromkeys([lib._full_name for lib in self.shlibs]) pkg = '.'.join(ext._full_name.split('.')[:-1]+['']) for libname in ext.libraries: if pkg+libname in libnames: return True return False
[ "Return", "true", "if", "ext", "links", "to", "a", "dynamic", "lib", "in", "the", "same", "package" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/distribute-0.6.31-py2.7.egg/setuptools/command/build_ext.py#L190-L199
[ "def", "links_to_dynamic", "(", "self", ",", "ext", ")", ":", "# XXX this should check to ensure the lib is actually being built", "# XXX as dynamic, and not just using a locally-found version or a", "# XXX static-compiled version", "libnames", "=", "dict", ".", "fromkeys", "(", "[", "lib", ".", "_full_name", "for", "lib", "in", "self", ".", "shlibs", "]", ")", "pkg", "=", "'.'", ".", "join", "(", "ext", ".", "_full_name", ".", "split", "(", "'.'", ")", "[", ":", "-", "1", "]", "+", "[", "''", "]", ")", "for", "libname", "in", "ext", ".", "libraries", ":", "if", "pkg", "+", "libname", "in", "libnames", ":", "return", "True", "return", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
call_each
call each func from func list. return the last func value or None if func list is empty.
jasily/collection/funcs.py
def call_each(funcs: list, *args, **kwargs): ''' call each func from func list. return the last func value or None if func list is empty. ''' ret = None for func in funcs: ret = func(*args, **kwargs) return ret
def call_each(funcs: list, *args, **kwargs): ''' call each func from func list. return the last func value or None if func list is empty. ''' ret = None for func in funcs: ret = func(*args, **kwargs) return ret
[ "call", "each", "func", "from", "func", "list", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/collection/funcs.py#L10-L19
[ "def", "call_each", "(", "funcs", ":", "list", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "None", "for", "func", "in", "funcs", ":", "ret", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "ret" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
call_each_reversed
call each func from reversed func list. return the last func value or None if func list is empty.
jasily/collection/funcs.py
def call_each_reversed(funcs: list, *args, **kwargs): ''' call each func from reversed func list. return the last func value or None if func list is empty. ''' ret = None for func in reversed(funcs): ret = func(*args, **kwargs) return ret
def call_each_reversed(funcs: list, *args, **kwargs): ''' call each func from reversed func list. return the last func value or None if func list is empty. ''' ret = None for func in reversed(funcs): ret = func(*args, **kwargs) return ret
[ "call", "each", "func", "from", "reversed", "func", "list", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/collection/funcs.py#L21-L30
[ "def", "call_each_reversed", "(", "funcs", ":", "list", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "None", "for", "func", "in", "reversed", "(", "funcs", ")", ":", "ret", "=", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "ret" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
CallableList.append_func
append func with given arguments and keywords.
jasily/collection/funcs.py
def append_func(self, func, *args, **kwargs): ''' append func with given arguments and keywords. ''' wraped_func = partial(func, *args, **kwargs) self.append(wraped_func)
def append_func(self, func, *args, **kwargs): ''' append func with given arguments and keywords. ''' wraped_func = partial(func, *args, **kwargs) self.append(wraped_func)
[ "append", "func", "with", "given", "arguments", "and", "keywords", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/collection/funcs.py#L41-L46
[ "def", "append_func", "(", "self", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "wraped_func", "=", "partial", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "append", "(", "wraped_func", ")" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
CallableList.insert_func
insert func with given arguments and keywords.
jasily/collection/funcs.py
def insert_func(self, index, func, *args, **kwargs): ''' insert func with given arguments and keywords. ''' wraped_func = partial(func, *args, **kwargs) self.insert(index, wraped_func)
def insert_func(self, index, func, *args, **kwargs): ''' insert func with given arguments and keywords. ''' wraped_func = partial(func, *args, **kwargs) self.insert(index, wraped_func)
[ "insert", "func", "with", "given", "arguments", "and", "keywords", "." ]
Jasily/jasily-python
python
https://github.com/Jasily/jasily-python/blob/1c821a120ebbbbc3c5761f5f1e8a73588059242a/jasily/collection/funcs.py#L48-L53
[ "def", "insert_func", "(", "self", ",", "index", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "wraped_func", "=", "partial", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "insert", "(", "index", ",", "wraped_func", ")" ]
1c821a120ebbbbc3c5761f5f1e8a73588059242a
test
PrettyHelpFormatter.format_usage
ensure there is only one newline between usage and the first heading if there is no description
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/baseparser.py
def format_usage(self, usage): """ ensure there is only one newline between usage and the first heading if there is no description """ msg = 'Usage: %s' % usage if self.parser.description: msg += '\n' return msg
def format_usage(self, usage): """ ensure there is only one newline between usage and the first heading if there is no description """ msg = 'Usage: %s' % usage if self.parser.description: msg += '\n' return msg
[ "ensure", "there", "is", "only", "one", "newline", "between", "usage", "and", "the", "first", "heading", "if", "there", "is", "no", "description" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/baseparser.py#L53-L61
[ "def", "format_usage", "(", "self", ",", "usage", ")", ":", "msg", "=", "'Usage: %s'", "%", "usage", "if", "self", ".", "parser", ".", "description", ":", "msg", "+=", "'\\n'", "return", "msg" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseParallelApplication.initialize
initialize the app
environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py
def initialize(self, argv=None): """initialize the app""" super(BaseParallelApplication, self).initialize(argv) self.to_work_dir() self.reinit_logging()
def initialize(self, argv=None): """initialize the app""" super(BaseParallelApplication, self).initialize(argv) self.to_work_dir() self.reinit_logging()
[ "initialize", "the", "app" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py#L153-L157
[ "def", "initialize", "(", "self", ",", "argv", "=", "None", ")", ":", "super", "(", "BaseParallelApplication", ",", "self", ")", ".", "initialize", "(", "argv", ")", "self", ".", "to_work_dir", "(", ")", "self", ".", "reinit_logging", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseParallelApplication.write_pid_file
Create a .pid file in the pid_dir with my pid. This must be called after pre_construct, which sets `self.pid_dir`. This raises :exc:`PIDFileError` if the pid file exists already.
environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py
def write_pid_file(self, overwrite=False): """Create a .pid file in the pid_dir with my pid. This must be called after pre_construct, which sets `self.pid_dir`. This raises :exc:`PIDFileError` if the pid file exists already. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if os.path.isfile(pid_file): pid = self.get_pid_from_file() if not overwrite: raise PIDFileError( 'The pid file [%s] already exists. \nThis could mean that this ' 'server is already running with [pid=%s].' % (pid_file, pid) ) with open(pid_file, 'w') as f: self.log.info("Creating pid file: %s" % pid_file) f.write(repr(os.getpid())+'\n')
def write_pid_file(self, overwrite=False): """Create a .pid file in the pid_dir with my pid. This must be called after pre_construct, which sets `self.pid_dir`. This raises :exc:`PIDFileError` if the pid file exists already. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if os.path.isfile(pid_file): pid = self.get_pid_from_file() if not overwrite: raise PIDFileError( 'The pid file [%s] already exists. \nThis could mean that this ' 'server is already running with [pid=%s].' % (pid_file, pid) ) with open(pid_file, 'w') as f: self.log.info("Creating pid file: %s" % pid_file) f.write(repr(os.getpid())+'\n')
[ "Create", "a", ".", "pid", "file", "in", "the", "pid_dir", "with", "my", "pid", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py#L202-L218
[ "def", "write_pid_file", "(", "self", ",", "overwrite", "=", "False", ")", ":", "pid_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "profile_dir", ".", "pid_dir", ",", "self", ".", "name", "+", "u'.pid'", ")", "if", "os", ".", "path", ".", "isfile", "(", "pid_file", ")", ":", "pid", "=", "self", ".", "get_pid_from_file", "(", ")", "if", "not", "overwrite", ":", "raise", "PIDFileError", "(", "'The pid file [%s] already exists. \\nThis could mean that this '", "'server is already running with [pid=%s].'", "%", "(", "pid_file", ",", "pid", ")", ")", "with", "open", "(", "pid_file", ",", "'w'", ")", "as", "f", ":", "self", ".", "log", ".", "info", "(", "\"Creating pid file: %s\"", "%", "pid_file", ")", "f", ".", "write", "(", "repr", "(", "os", ".", "getpid", "(", ")", ")", "+", "'\\n'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseParallelApplication.remove_pid_file
Remove the pid file. This should be called at shutdown by registering a callback with :func:`reactor.addSystemEventTrigger`. This needs to return ``None``.
environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py
def remove_pid_file(self): """Remove the pid file. This should be called at shutdown by registering a callback with :func:`reactor.addSystemEventTrigger`. This needs to return ``None``. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if os.path.isfile(pid_file): try: self.log.info("Removing pid file: %s" % pid_file) os.remove(pid_file) except: self.log.warn("Error removing the pid file: %s" % pid_file)
def remove_pid_file(self): """Remove the pid file. This should be called at shutdown by registering a callback with :func:`reactor.addSystemEventTrigger`. This needs to return ``None``. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if os.path.isfile(pid_file): try: self.log.info("Removing pid file: %s" % pid_file) os.remove(pid_file) except: self.log.warn("Error removing the pid file: %s" % pid_file)
[ "Remove", "the", "pid", "file", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py#L220-L233
[ "def", "remove_pid_file", "(", "self", ")", ":", "pid_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "profile_dir", ".", "pid_dir", ",", "self", ".", "name", "+", "u'.pid'", ")", "if", "os", ".", "path", ".", "isfile", "(", "pid_file", ")", ":", "try", ":", "self", ".", "log", ".", "info", "(", "\"Removing pid file: %s\"", "%", "pid_file", ")", "os", ".", "remove", "(", "pid_file", ")", "except", ":", "self", ".", "log", ".", "warn", "(", "\"Error removing the pid file: %s\"", "%", "pid_file", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BaseParallelApplication.get_pid_from_file
Get the pid from the pid file. If the pid file doesn't exist a :exc:`PIDFileError` is raised.
environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py
def get_pid_from_file(self): """Get the pid from the pid file. If the pid file doesn't exist a :exc:`PIDFileError` is raised. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if os.path.isfile(pid_file): with open(pid_file, 'r') as f: s = f.read().strip() try: pid = int(s) except: raise PIDFileError("invalid pid file: %s (contents: %r)"%(pid_file, s)) return pid else: raise PIDFileError('pid file not found: %s' % pid_file)
def get_pid_from_file(self): """Get the pid from the pid file. If the pid file doesn't exist a :exc:`PIDFileError` is raised. """ pid_file = os.path.join(self.profile_dir.pid_dir, self.name + u'.pid') if os.path.isfile(pid_file): with open(pid_file, 'r') as f: s = f.read().strip() try: pid = int(s) except: raise PIDFileError("invalid pid file: %s (contents: %r)"%(pid_file, s)) return pid else: raise PIDFileError('pid file not found: %s' % pid_file)
[ "Get", "the", "pid", "from", "the", "pid", "file", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/parallel/apps/baseapp.py#L235-L250
[ "def", "get_pid_from_file", "(", "self", ")", ":", "pid_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "profile_dir", ".", "pid_dir", ",", "self", ".", "name", "+", "u'.pid'", ")", "if", "os", ".", "path", ".", "isfile", "(", "pid_file", ")", ":", "with", "open", "(", "pid_file", ",", "'r'", ")", "as", "f", ":", "s", "=", "f", ".", "read", "(", ")", ".", "strip", "(", ")", "try", ":", "pid", "=", "int", "(", "s", ")", "except", ":", "raise", "PIDFileError", "(", "\"invalid pid file: %s (contents: %r)\"", "%", "(", "pid_file", ",", "s", ")", ")", "return", "pid", "else", ":", "raise", "PIDFileError", "(", "'pid file not found: %s'", "%", "pid_file", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
construct_parser
Construct an argument parser using the function decorations.
environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py
def construct_parser(magic_func): """ Construct an argument parser using the function decorations. """ kwds = getattr(magic_func, 'argcmd_kwds', {}) if 'description' not in kwds: kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArgumentParser(arg_name, **kwds) # Reverse the list of decorators in order to apply them in the # order in which they appear in the source. group = None for deco in magic_func.decorators[::-1]: result = deco.add_to_parser(parser, group) if result is not None: group = result # Replace the starting 'usage: ' with IPython's %. help_text = parser.format_help() if help_text.startswith('usage: '): help_text = help_text.replace('usage: ', '%', 1) else: help_text = '%' + help_text # Replace the magic function's docstring with the full help text. magic_func.__doc__ = help_text return parser
def construct_parser(magic_func): """ Construct an argument parser using the function decorations. """ kwds = getattr(magic_func, 'argcmd_kwds', {}) if 'description' not in kwds: kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArgumentParser(arg_name, **kwds) # Reverse the list of decorators in order to apply them in the # order in which they appear in the source. group = None for deco in magic_func.decorators[::-1]: result = deco.add_to_parser(parser, group) if result is not None: group = result # Replace the starting 'usage: ' with IPython's %. help_text = parser.format_help() if help_text.startswith('usage: '): help_text = help_text.replace('usage: ', '%', 1) else: help_text = '%' + help_text # Replace the magic function's docstring with the full help text. magic_func.__doc__ = help_text return parser
[ "Construct", "an", "argument", "parser", "using", "the", "function", "decorations", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py#L95-L121
[ "def", "construct_parser", "(", "magic_func", ")", ":", "kwds", "=", "getattr", "(", "magic_func", ",", "'argcmd_kwds'", ",", "{", "}", ")", "if", "'description'", "not", "in", "kwds", ":", "kwds", "[", "'description'", "]", "=", "getattr", "(", "magic_func", ",", "'__doc__'", ",", "None", ")", "arg_name", "=", "real_name", "(", "magic_func", ")", "parser", "=", "MagicArgumentParser", "(", "arg_name", ",", "*", "*", "kwds", ")", "# Reverse the list of decorators in order to apply them in the", "# order in which they appear in the source.", "group", "=", "None", "for", "deco", "in", "magic_func", ".", "decorators", "[", ":", ":", "-", "1", "]", ":", "result", "=", "deco", ".", "add_to_parser", "(", "parser", ",", "group", ")", "if", "result", "is", "not", "None", ":", "group", "=", "result", "# Replace the starting 'usage: ' with IPython's %.", "help_text", "=", "parser", ".", "format_help", "(", ")", "if", "help_text", ".", "startswith", "(", "'usage: '", ")", ":", "help_text", "=", "help_text", ".", "replace", "(", "'usage: '", ",", "'%'", ",", "1", ")", "else", ":", "help_text", "=", "'%'", "+", "help_text", "# Replace the magic function's docstring with the full help text.", "magic_func", ".", "__doc__", "=", "help_text", "return", "parser" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
real_name
Find the real name of the magic.
environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py
def real_name(magic_func): """ Find the real name of the magic. """ magic_name = magic_func.__name__ if magic_name.startswith('magic_'): magic_name = magic_name[len('magic_'):] return getattr(magic_func, 'argcmd_name', magic_name)
def real_name(magic_func): """ Find the real name of the magic. """ magic_name = magic_func.__name__ if magic_name.startswith('magic_'): magic_name = magic_name[len('magic_'):] return getattr(magic_func, 'argcmd_name', magic_name)
[ "Find", "the", "real", "name", "of", "the", "magic", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py#L130-L136
[ "def", "real_name", "(", "magic_func", ")", ":", "magic_name", "=", "magic_func", ".", "__name__", "if", "magic_name", ".", "startswith", "(", "'magic_'", ")", ":", "magic_name", "=", "magic_name", "[", "len", "(", "'magic_'", ")", ":", "]", "return", "getattr", "(", "magic_func", ",", "'argcmd_name'", ",", "magic_name", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
argument.add_to_parser
Add this object's information to the parser.
environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py
def add_to_parser(self, parser, group): """ Add this object's information to the parser. """ if group is not None: parser = group parser.add_argument(*self.args, **self.kwds) return None
def add_to_parser(self, parser, group): """ Add this object's information to the parser. """ if group is not None: parser = group parser.add_argument(*self.args, **self.kwds) return None
[ "Add", "this", "object", "s", "information", "to", "the", "parser", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py#L185-L191
[ "def", "add_to_parser", "(", "self", ",", "parser", ",", "group", ")", ":", "if", "group", "is", "not", "None", ":", "parser", "=", "group", "parser", ".", "add_argument", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwds", ")", "return", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
argument_group.add_to_parser
Add this object's information to the parser.
environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py
def add_to_parser(self, parser, group): """ Add this object's information to the parser. """ return parser.add_argument_group(*self.args, **self.kwds)
def add_to_parser(self, parser, group): """ Add this object's information to the parser. """ return parser.add_argument_group(*self.args, **self.kwds)
[ "Add", "this", "object", "s", "information", "to", "the", "parser", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/core/magic_arguments.py#L203-L206
[ "def", "add_to_parser", "(", "self", ",", "parser", ",", "group", ")", ":", "return", "parser", ".", "add_argument_group", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwds", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendHighlighter.highlightBlock
Highlight a block of text. Reimplemented to highlight selectively.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def highlightBlock(self, string): """ Highlight a block of text. Reimplemented to highlight selectively. """ if not self.highlighting_on: return # The input to this function is a unicode string that may contain # paragraph break characters, non-breaking spaces, etc. Here we acquire # the string as plain text so we can compare it. current_block = self.currentBlock() string = self._frontend._get_block_plain_text(current_block) # Decide whether to check for the regular or continuation prompt. if current_block.contains(self._frontend._prompt_pos): prompt = self._frontend._prompt else: prompt = self._frontend._continuation_prompt # Only highlight if we can identify a prompt, but make sure not to # highlight the prompt. if string.startswith(prompt): self._current_offset = len(prompt) string = string[len(prompt):] super(FrontendHighlighter, self).highlightBlock(string)
def highlightBlock(self, string): """ Highlight a block of text. Reimplemented to highlight selectively. """ if not self.highlighting_on: return # The input to this function is a unicode string that may contain # paragraph break characters, non-breaking spaces, etc. Here we acquire # the string as plain text so we can compare it. current_block = self.currentBlock() string = self._frontend._get_block_plain_text(current_block) # Decide whether to check for the regular or continuation prompt. if current_block.contains(self._frontend._prompt_pos): prompt = self._frontend._prompt else: prompt = self._frontend._continuation_prompt # Only highlight if we can identify a prompt, but make sure not to # highlight the prompt. if string.startswith(prompt): self._current_offset = len(prompt) string = string[len(prompt):] super(FrontendHighlighter, self).highlightBlock(string)
[ "Highlight", "a", "block", "of", "text", ".", "Reimplemented", "to", "highlight", "selectively", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L36-L59
[ "def", "highlightBlock", "(", "self", ",", "string", ")", ":", "if", "not", "self", ".", "highlighting_on", ":", "return", "# The input to this function is a unicode string that may contain", "# paragraph break characters, non-breaking spaces, etc. Here we acquire", "# the string as plain text so we can compare it.", "current_block", "=", "self", ".", "currentBlock", "(", ")", "string", "=", "self", ".", "_frontend", ".", "_get_block_plain_text", "(", "current_block", ")", "# Decide whether to check for the regular or continuation prompt.", "if", "current_block", ".", "contains", "(", "self", ".", "_frontend", ".", "_prompt_pos", ")", ":", "prompt", "=", "self", ".", "_frontend", ".", "_prompt", "else", ":", "prompt", "=", "self", ".", "_frontend", ".", "_continuation_prompt", "# Only highlight if we can identify a prompt, but make sure not to", "# highlight the prompt.", "if", "string", ".", "startswith", "(", "prompt", ")", ":", "self", ".", "_current_offset", "=", "len", "(", "prompt", ")", "string", "=", "string", "[", "len", "(", "prompt", ")", ":", "]", "super", "(", "FrontendHighlighter", ",", "self", ")", ".", "highlightBlock", "(", "string", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendHighlighter.rehighlightBlock
Reimplemented to temporarily enable highlighting if disabled.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def rehighlightBlock(self, block): """ Reimplemented to temporarily enable highlighting if disabled. """ old = self.highlighting_on self.highlighting_on = True super(FrontendHighlighter, self).rehighlightBlock(block) self.highlighting_on = old
def rehighlightBlock(self, block): """ Reimplemented to temporarily enable highlighting if disabled. """ old = self.highlighting_on self.highlighting_on = True super(FrontendHighlighter, self).rehighlightBlock(block) self.highlighting_on = old
[ "Reimplemented", "to", "temporarily", "enable", "highlighting", "if", "disabled", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L61-L67
[ "def", "rehighlightBlock", "(", "self", ",", "block", ")", ":", "old", "=", "self", ".", "highlighting_on", "self", ".", "highlighting_on", "=", "True", "super", "(", "FrontendHighlighter", ",", "self", ")", ".", "rehighlightBlock", "(", "block", ")", "self", ".", "highlighting_on", "=", "old" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendHighlighter.setFormat
Reimplemented to highlight selectively.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def setFormat(self, start, count, format): """ Reimplemented to highlight selectively. """ start += self._current_offset super(FrontendHighlighter, self).setFormat(start, count, format)
def setFormat(self, start, count, format): """ Reimplemented to highlight selectively. """ start += self._current_offset super(FrontendHighlighter, self).setFormat(start, count, format)
[ "Reimplemented", "to", "highlight", "selectively", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L69-L73
[ "def", "setFormat", "(", "self", ",", "start", ",", "count", ",", "format", ")", ":", "start", "+=", "self", ".", "_current_offset", "super", "(", "FrontendHighlighter", ",", "self", ")", ".", "setFormat", "(", "start", ",", "count", ",", "format", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget.copy
Copy the currently selected text to the clipboard, removing prompts.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def copy(self): """ Copy the currently selected text to the clipboard, removing prompts. """ if self._page_control is not None and self._page_control.hasFocus(): self._page_control.copy() elif self._control.hasFocus(): text = self._control.textCursor().selection().toPlainText() if text: lines = map(self._transform_prompt, text.splitlines()) text = '\n'.join(lines) QtGui.QApplication.clipboard().setText(text) else: self.log.debug("frontend widget : unknown copy target")
def copy(self): """ Copy the currently selected text to the clipboard, removing prompts. """ if self._page_control is not None and self._page_control.hasFocus(): self._page_control.copy() elif self._control.hasFocus(): text = self._control.textCursor().selection().toPlainText() if text: lines = map(self._transform_prompt, text.splitlines()) text = '\n'.join(lines) QtGui.QApplication.clipboard().setText(text) else: self.log.debug("frontend widget : unknown copy target")
[ "Copy", "the", "currently", "selected", "text", "to", "the", "clipboard", "removing", "prompts", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L181-L193
[ "def", "copy", "(", "self", ")", ":", "if", "self", ".", "_page_control", "is", "not", "None", "and", "self", ".", "_page_control", ".", "hasFocus", "(", ")", ":", "self", ".", "_page_control", ".", "copy", "(", ")", "elif", "self", ".", "_control", ".", "hasFocus", "(", ")", ":", "text", "=", "self", ".", "_control", ".", "textCursor", "(", ")", ".", "selection", "(", ")", ".", "toPlainText", "(", ")", "if", "text", ":", "lines", "=", "map", "(", "self", ".", "_transform_prompt", ",", "text", ".", "splitlines", "(", ")", ")", "text", "=", "'\\n'", ".", "join", "(", "lines", ")", "QtGui", ".", "QApplication", ".", "clipboard", "(", ")", ".", "setText", "(", "text", ")", "else", ":", "self", ".", "log", ".", "debug", "(", "\"frontend widget : unknown copy target\"", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._is_complete
Returns whether 'source' can be completely processed and a new prompt created. When triggered by an Enter/Return key press, 'interactive' is True; otherwise, it is False.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _is_complete(self, source, interactive): """ Returns whether 'source' can be completely processed and a new prompt created. When triggered by an Enter/Return key press, 'interactive' is True; otherwise, it is False. """ complete = self._input_splitter.push(source) if interactive: complete = not self._input_splitter.push_accepts_more() return complete
def _is_complete(self, source, interactive): """ Returns whether 'source' can be completely processed and a new prompt created. When triggered by an Enter/Return key press, 'interactive' is True; otherwise, it is False. """ complete = self._input_splitter.push(source) if interactive: complete = not self._input_splitter.push_accepts_more() return complete
[ "Returns", "whether", "source", "can", "be", "completely", "processed", "and", "a", "new", "prompt", "created", ".", "When", "triggered", "by", "an", "Enter", "/", "Return", "key", "press", "interactive", "is", "True", ";", "otherwise", "it", "is", "False", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L199-L207
[ "def", "_is_complete", "(", "self", ",", "source", ",", "interactive", ")", ":", "complete", "=", "self", ".", "_input_splitter", ".", "push", "(", "source", ")", "if", "interactive", ":", "complete", "=", "not", "self", ".", "_input_splitter", ".", "push_accepts_more", "(", ")", "return", "complete" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._execute
Execute 'source'. If 'hidden', do not show any output. See parent class :meth:`execute` docstring for full details.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _execute(self, source, hidden): """ Execute 'source'. If 'hidden', do not show any output. See parent class :meth:`execute` docstring for full details. """ msg_id = self.kernel_manager.shell_channel.execute(source, hidden) self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'user') self._hidden = hidden if not hidden: self.executing.emit(source)
def _execute(self, source, hidden): """ Execute 'source'. If 'hidden', do not show any output. See parent class :meth:`execute` docstring for full details. """ msg_id = self.kernel_manager.shell_channel.execute(source, hidden) self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'user') self._hidden = hidden if not hidden: self.executing.emit(source)
[ "Execute", "source", ".", "If", "hidden", "do", "not", "show", "any", "output", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L209-L218
[ "def", "_execute", "(", "self", ",", "source", ",", "hidden", ")", ":", "msg_id", "=", "self", ".", "kernel_manager", ".", "shell_channel", ".", "execute", "(", "source", ",", "hidden", ")", "self", ".", "_request_info", "[", "'execute'", "]", "[", "msg_id", "]", "=", "self", ".", "_ExecutionRequest", "(", "msg_id", ",", "'user'", ")", "self", ".", "_hidden", "=", "hidden", "if", "not", "hidden", ":", "self", ".", "executing", ".", "emit", "(", "source", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._prompt_finished_hook
Called immediately after a prompt is finished, i.e. when some input will be processed and a new prompt displayed.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _prompt_finished_hook(self): """ Called immediately after a prompt is finished, i.e. when some input will be processed and a new prompt displayed. """ # Flush all state from the input splitter so the next round of # reading input starts with a clean buffer. self._input_splitter.reset() if not self._reading: self._highlighter.highlighting_on = False
def _prompt_finished_hook(self): """ Called immediately after a prompt is finished, i.e. when some input will be processed and a new prompt displayed. """ # Flush all state from the input splitter so the next round of # reading input starts with a clean buffer. self._input_splitter.reset() if not self._reading: self._highlighter.highlighting_on = False
[ "Called", "immediately", "after", "a", "prompt", "is", "finished", "i", ".", "e", ".", "when", "some", "input", "will", "be", "processed", "and", "a", "new", "prompt", "displayed", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L226-L235
[ "def", "_prompt_finished_hook", "(", "self", ")", ":", "# Flush all state from the input splitter so the next round of", "# reading input starts with a clean buffer.", "self", ".", "_input_splitter", ".", "reset", "(", ")", "if", "not", "self", ".", "_reading", ":", "self", ".", "_highlighter", ".", "highlighting_on", "=", "False" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._tab_pressed
Called when the tab key is pressed. Returns whether to continue processing the event.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _tab_pressed(self): """ Called when the tab key is pressed. Returns whether to continue processing the event. """ # Perform tab completion if: # 1) The cursor is in the input buffer. # 2) There is a non-whitespace character before the cursor. text = self._get_input_buffer_cursor_line() if text is None: return False complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) if complete: self._complete() return not complete
def _tab_pressed(self): """ Called when the tab key is pressed. Returns whether to continue processing the event. """ # Perform tab completion if: # 1) The cursor is in the input buffer. # 2) There is a non-whitespace character before the cursor. text = self._get_input_buffer_cursor_line() if text is None: return False complete = bool(text[:self._get_input_buffer_cursor_column()].strip()) if complete: self._complete() return not complete
[ "Called", "when", "the", "tab", "key", "is", "pressed", ".", "Returns", "whether", "to", "continue", "processing", "the", "event", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L237-L250
[ "def", "_tab_pressed", "(", "self", ")", ":", "# Perform tab completion if:", "# 1) The cursor is in the input buffer.", "# 2) There is a non-whitespace character before the cursor.", "text", "=", "self", ".", "_get_input_buffer_cursor_line", "(", ")", "if", "text", "is", "None", ":", "return", "False", "complete", "=", "bool", "(", "text", "[", ":", "self", ".", "_get_input_buffer_cursor_column", "(", ")", "]", ".", "strip", "(", ")", ")", "if", "complete", ":", "self", ".", "_complete", "(", ")", "return", "not", "complete" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._context_menu_make
Reimplemented to add an action for raw copy.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _context_menu_make(self, pos): """ Reimplemented to add an action for raw copy. """ menu = super(FrontendWidget, self)._context_menu_make(pos) for before_action in menu.actions(): if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ QtGui.QKeySequence.ExactMatch: menu.insertAction(before_action, self._copy_raw_action) break return menu
def _context_menu_make(self, pos): """ Reimplemented to add an action for raw copy. """ menu = super(FrontendWidget, self)._context_menu_make(pos) for before_action in menu.actions(): if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \ QtGui.QKeySequence.ExactMatch: menu.insertAction(before_action, self._copy_raw_action) break return menu
[ "Reimplemented", "to", "add", "an", "action", "for", "raw", "copy", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L256-L265
[ "def", "_context_menu_make", "(", "self", ",", "pos", ")", ":", "menu", "=", "super", "(", "FrontendWidget", ",", "self", ")", ".", "_context_menu_make", "(", "pos", ")", "for", "before_action", "in", "menu", ".", "actions", "(", ")", ":", "if", "before_action", ".", "shortcut", "(", ")", ".", "matches", "(", "QtGui", ".", "QKeySequence", ".", "Paste", ")", "==", "QtGui", ".", "QKeySequence", ".", "ExactMatch", ":", "menu", ".", "insertAction", "(", "before_action", ",", "self", ".", "_copy_raw_action", ")", "break", "return", "menu" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._event_filter_console_keypress
Reimplemented for execution interruption and smart backspace.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _event_filter_console_keypress(self, event): """ Reimplemented for execution interruption and smart backspace. """ key = event.key() if self._control_key_down(event.modifiers(), include_command=False): if key == QtCore.Qt.Key_C and self._executing: self.request_interrupt_kernel() return True elif key == QtCore.Qt.Key_Period: self.request_restart_kernel() return True elif not event.modifiers() & QtCore.Qt.AltModifier: # Smart backspace: remove four characters in one backspace if: # 1) everything left of the cursor is whitespace # 2) the four characters immediately left of the cursor are spaces if key == QtCore.Qt.Key_Backspace: col = self._get_input_buffer_cursor_column() cursor = self._control.textCursor() if col > 3 and not cursor.hasSelection(): text = self._get_input_buffer_cursor_line()[:col] if text.endswith(' ') and not text.strip(): cursor.movePosition(QtGui.QTextCursor.Left, QtGui.QTextCursor.KeepAnchor, 4) cursor.removeSelectedText() return True return super(FrontendWidget, self)._event_filter_console_keypress(event)
def _event_filter_console_keypress(self, event): """ Reimplemented for execution interruption and smart backspace. """ key = event.key() if self._control_key_down(event.modifiers(), include_command=False): if key == QtCore.Qt.Key_C and self._executing: self.request_interrupt_kernel() return True elif key == QtCore.Qt.Key_Period: self.request_restart_kernel() return True elif not event.modifiers() & QtCore.Qt.AltModifier: # Smart backspace: remove four characters in one backspace if: # 1) everything left of the cursor is whitespace # 2) the four characters immediately left of the cursor are spaces if key == QtCore.Qt.Key_Backspace: col = self._get_input_buffer_cursor_column() cursor = self._control.textCursor() if col > 3 and not cursor.hasSelection(): text = self._get_input_buffer_cursor_line()[:col] if text.endswith(' ') and not text.strip(): cursor.movePosition(QtGui.QTextCursor.Left, QtGui.QTextCursor.KeepAnchor, 4) cursor.removeSelectedText() return True return super(FrontendWidget, self)._event_filter_console_keypress(event)
[ "Reimplemented", "for", "execution", "interruption", "and", "smart", "backspace", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L275-L305
[ "def", "_event_filter_console_keypress", "(", "self", ",", "event", ")", ":", "key", "=", "event", ".", "key", "(", ")", "if", "self", ".", "_control_key_down", "(", "event", ".", "modifiers", "(", ")", ",", "include_command", "=", "False", ")", ":", "if", "key", "==", "QtCore", ".", "Qt", ".", "Key_C", "and", "self", ".", "_executing", ":", "self", ".", "request_interrupt_kernel", "(", ")", "return", "True", "elif", "key", "==", "QtCore", ".", "Qt", ".", "Key_Period", ":", "self", ".", "request_restart_kernel", "(", ")", "return", "True", "elif", "not", "event", ".", "modifiers", "(", ")", "&", "QtCore", ".", "Qt", ".", "AltModifier", ":", "# Smart backspace: remove four characters in one backspace if:", "# 1) everything left of the cursor is whitespace", "# 2) the four characters immediately left of the cursor are spaces", "if", "key", "==", "QtCore", ".", "Qt", ".", "Key_Backspace", ":", "col", "=", "self", ".", "_get_input_buffer_cursor_column", "(", ")", "cursor", "=", "self", ".", "_control", ".", "textCursor", "(", ")", "if", "col", ">", "3", "and", "not", "cursor", ".", "hasSelection", "(", ")", ":", "text", "=", "self", ".", "_get_input_buffer_cursor_line", "(", ")", "[", ":", "col", "]", "if", "text", ".", "endswith", "(", "' '", ")", "and", "not", "text", ".", "strip", "(", ")", ":", "cursor", ".", "movePosition", "(", "QtGui", ".", "QTextCursor", ".", "Left", ",", "QtGui", ".", "QTextCursor", ".", "KeepAnchor", ",", "4", ")", "cursor", ".", "removeSelectedText", "(", ")", "return", "True", "return", "super", "(", "FrontendWidget", ",", "self", ")", ".", "_event_filter_console_keypress", "(", "event", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._insert_continuation_prompt
Reimplemented for auto-indentation.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _insert_continuation_prompt(self, cursor): """ Reimplemented for auto-indentation. """ super(FrontendWidget, self)._insert_continuation_prompt(cursor) cursor.insertText(' ' * self._input_splitter.indent_spaces)
def _insert_continuation_prompt(self, cursor): """ Reimplemented for auto-indentation. """ super(FrontendWidget, self)._insert_continuation_prompt(cursor) cursor.insertText(' ' * self._input_splitter.indent_spaces)
[ "Reimplemented", "for", "auto", "-", "indentation", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L307-L311
[ "def", "_insert_continuation_prompt", "(", "self", ",", "cursor", ")", ":", "super", "(", "FrontendWidget", ",", "self", ")", ".", "_insert_continuation_prompt", "(", "cursor", ")", "cursor", ".", "insertText", "(", "' '", "*", "self", ".", "_input_splitter", ".", "indent_spaces", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_complete_reply
Handle replies for tab completion.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_complete_reply(self, rep): """ Handle replies for tab completion. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): text = '.'.join(self._get_context()) cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) self._complete_with_items(cursor, rep['content']['matches'])
def _handle_complete_reply(self, rep): """ Handle replies for tab completion. """ self.log.debug("complete: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('complete') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): text = '.'.join(self._get_context()) cursor.movePosition(QtGui.QTextCursor.Left, n=len(text)) self._complete_with_items(cursor, rep['content']['matches'])
[ "Handle", "replies", "for", "tab", "completion", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L317-L327
[ "def", "_handle_complete_reply", "(", "self", ",", "rep", ")", ":", "self", ".", "log", ".", "debug", "(", "\"complete: %s\"", ",", "rep", ".", "get", "(", "'content'", ",", "''", ")", ")", "cursor", "=", "self", ".", "_get_cursor", "(", ")", "info", "=", "self", ".", "_request_info", ".", "get", "(", "'complete'", ")", "if", "info", "and", "info", ".", "id", "==", "rep", "[", "'parent_header'", "]", "[", "'msg_id'", "]", "and", "info", ".", "pos", "==", "cursor", ".", "position", "(", ")", ":", "text", "=", "'.'", ".", "join", "(", "self", ".", "_get_context", "(", ")", ")", "cursor", ".", "movePosition", "(", "QtGui", ".", "QTextCursor", ".", "Left", ",", "n", "=", "len", "(", "text", ")", ")", "self", ".", "_complete_with_items", "(", "cursor", ",", "rep", "[", "'content'", "]", "[", "'matches'", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._silent_exec_callback
Silently execute `expr` in the kernel and call `callback` with reply the `expr` is evaluated silently in the kernel (without) output in the frontend. Call `callback` with the `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument Parameters ---------- expr : string valid string to be executed by the kernel. callback : function function accepting one argument, as a string. The string will be the `repr` of the result of evaluating `expr` The `callback` is called with the `repr()` of the result of `expr` as first argument. To get the object, do `eval()` on the passed value. See Also -------- _handle_exec_callback : private method, deal with calling callback with reply
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _silent_exec_callback(self, expr, callback): """Silently execute `expr` in the kernel and call `callback` with reply the `expr` is evaluated silently in the kernel (without) output in the frontend. Call `callback` with the `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument Parameters ---------- expr : string valid string to be executed by the kernel. callback : function function accepting one argument, as a string. The string will be the `repr` of the result of evaluating `expr` The `callback` is called with the `repr()` of the result of `expr` as first argument. To get the object, do `eval()` on the passed value. See Also -------- _handle_exec_callback : private method, deal with calling callback with reply """ # generate uuid, which would be used as an indication of whether or # not the unique request originated from here (can use msg id ?) local_uuid = str(uuid.uuid1()) msg_id = self.kernel_manager.shell_channel.execute('', silent=True, user_expressions={ local_uuid:expr }) self._callback_dict[local_uuid] = callback self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_callback')
def _silent_exec_callback(self, expr, callback): """Silently execute `expr` in the kernel and call `callback` with reply the `expr` is evaluated silently in the kernel (without) output in the frontend. Call `callback` with the `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument Parameters ---------- expr : string valid string to be executed by the kernel. callback : function function accepting one argument, as a string. The string will be the `repr` of the result of evaluating `expr` The `callback` is called with the `repr()` of the result of `expr` as first argument. To get the object, do `eval()` on the passed value. See Also -------- _handle_exec_callback : private method, deal with calling callback with reply """ # generate uuid, which would be used as an indication of whether or # not the unique request originated from here (can use msg id ?) local_uuid = str(uuid.uuid1()) msg_id = self.kernel_manager.shell_channel.execute('', silent=True, user_expressions={ local_uuid:expr }) self._callback_dict[local_uuid] = callback self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_callback')
[ "Silently", "execute", "expr", "in", "the", "kernel", "and", "call", "callback", "with", "reply" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L329-L359
[ "def", "_silent_exec_callback", "(", "self", ",", "expr", ",", "callback", ")", ":", "# generate uuid, which would be used as an indication of whether or", "# not the unique request originated from here (can use msg id ?)", "local_uuid", "=", "str", "(", "uuid", ".", "uuid1", "(", ")", ")", "msg_id", "=", "self", ".", "kernel_manager", ".", "shell_channel", ".", "execute", "(", "''", ",", "silent", "=", "True", ",", "user_expressions", "=", "{", "local_uuid", ":", "expr", "}", ")", "self", ".", "_callback_dict", "[", "local_uuid", "]", "=", "callback", "self", ".", "_request_info", "[", "'execute'", "]", "[", "msg_id", "]", "=", "self", ".", "_ExecutionRequest", "(", "msg_id", ",", "'silent_exec_callback'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_exec_callback
Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback`` Parameters ---------- msg : raw message send by the kernel containing an `user_expressions` and having a 'silent_exec_callback' kind. Notes ----- This function will look for a `callback` associated with the corresponding message id. Association has been made by `_silent_exec_callback`. `callback` is then called with the `repr()` of the value of corresponding `user_expressions` as argument. `callback` is then removed from the known list so that any message coming again with the same id won't trigger it.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_exec_callback(self, msg): """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback`` Parameters ---------- msg : raw message send by the kernel containing an `user_expressions` and having a 'silent_exec_callback' kind. Notes ----- This function will look for a `callback` associated with the corresponding message id. Association has been made by `_silent_exec_callback`. `callback` is then called with the `repr()` of the value of corresponding `user_expressions` as argument. `callback` is then removed from the known list so that any message coming again with the same id won't trigger it. """ user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._callback_dict: self._callback_dict.pop(expression)(user_exp[expression])
def _handle_exec_callback(self, msg): """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback`` Parameters ---------- msg : raw message send by the kernel containing an `user_expressions` and having a 'silent_exec_callback' kind. Notes ----- This function will look for a `callback` associated with the corresponding message id. Association has been made by `_silent_exec_callback`. `callback` is then called with the `repr()` of the value of corresponding `user_expressions` as argument. `callback` is then removed from the known list so that any message coming again with the same id won't trigger it. """ user_exp = msg['content'].get('user_expressions') if not user_exp: return for expression in user_exp: if expression in self._callback_dict: self._callback_dict.pop(expression)(user_exp[expression])
[ "Execute", "callback", "corresponding", "to", "msg", "reply", "after", "_silent_exec_callback" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L361-L385
[ "def", "_handle_exec_callback", "(", "self", ",", "msg", ")", ":", "user_exp", "=", "msg", "[", "'content'", "]", ".", "get", "(", "'user_expressions'", ")", "if", "not", "user_exp", ":", "return", "for", "expression", "in", "user_exp", ":", "if", "expression", "in", "self", ".", "_callback_dict", ":", "self", ".", "_callback_dict", ".", "pop", "(", "expression", ")", "(", "user_exp", "[", "expression", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_execute_reply
Handles replies for code execution.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_execute_reply(self, msg): """ Handles replies for code execution. """ self.log.debug("execute: %s", msg.get('content', '')) msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) # unset reading flag, because if execute finished, raw_input can't # still be pending. self._reading = False if info and info.kind == 'user' and not self._hidden: # Make sure that all output from the SUB channel has been processed # before writing a new prompt. self.kernel_manager.sub_channel.flush() # Reset the ANSI style information to prevent bad text in stdout # from messing up our colors. We're not a true terminal so we're # allowed to do this. if self.ansi_codes: self._ansi_processor.reset_sgr() content = msg['content'] status = content['status'] if status == 'ok': self._process_execute_ok(msg) elif status == 'error': self._process_execute_error(msg) elif status == 'aborted': self._process_execute_abort(msg) self._show_interpreter_prompt_for_reply(msg) self.executed.emit(msg) self._request_info['execute'].pop(msg_id) elif info and info.kind == 'silent_exec_callback' and not self._hidden: self._handle_exec_callback(msg) self._request_info['execute'].pop(msg_id) else: super(FrontendWidget, self)._handle_execute_reply(msg)
def _handle_execute_reply(self, msg): """ Handles replies for code execution. """ self.log.debug("execute: %s", msg.get('content', '')) msg_id = msg['parent_header']['msg_id'] info = self._request_info['execute'].get(msg_id) # unset reading flag, because if execute finished, raw_input can't # still be pending. self._reading = False if info and info.kind == 'user' and not self._hidden: # Make sure that all output from the SUB channel has been processed # before writing a new prompt. self.kernel_manager.sub_channel.flush() # Reset the ANSI style information to prevent bad text in stdout # from messing up our colors. We're not a true terminal so we're # allowed to do this. if self.ansi_codes: self._ansi_processor.reset_sgr() content = msg['content'] status = content['status'] if status == 'ok': self._process_execute_ok(msg) elif status == 'error': self._process_execute_error(msg) elif status == 'aborted': self._process_execute_abort(msg) self._show_interpreter_prompt_for_reply(msg) self.executed.emit(msg) self._request_info['execute'].pop(msg_id) elif info and info.kind == 'silent_exec_callback' and not self._hidden: self._handle_exec_callback(msg) self._request_info['execute'].pop(msg_id) else: super(FrontendWidget, self)._handle_execute_reply(msg)
[ "Handles", "replies", "for", "code", "execution", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L387-L423
[ "def", "_handle_execute_reply", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"execute: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "msg_id", "=", "msg", "[", "'parent_header'", "]", "[", "'msg_id'", "]", "info", "=", "self", ".", "_request_info", "[", "'execute'", "]", ".", "get", "(", "msg_id", ")", "# unset reading flag, because if execute finished, raw_input can't", "# still be pending.", "self", ".", "_reading", "=", "False", "if", "info", "and", "info", ".", "kind", "==", "'user'", "and", "not", "self", ".", "_hidden", ":", "# Make sure that all output from the SUB channel has been processed", "# before writing a new prompt.", "self", ".", "kernel_manager", ".", "sub_channel", ".", "flush", "(", ")", "# Reset the ANSI style information to prevent bad text in stdout", "# from messing up our colors. We're not a true terminal so we're", "# allowed to do this.", "if", "self", ".", "ansi_codes", ":", "self", ".", "_ansi_processor", ".", "reset_sgr", "(", ")", "content", "=", "msg", "[", "'content'", "]", "status", "=", "content", "[", "'status'", "]", "if", "status", "==", "'ok'", ":", "self", ".", "_process_execute_ok", "(", "msg", ")", "elif", "status", "==", "'error'", ":", "self", ".", "_process_execute_error", "(", "msg", ")", "elif", "status", "==", "'aborted'", ":", "self", ".", "_process_execute_abort", "(", "msg", ")", "self", ".", "_show_interpreter_prompt_for_reply", "(", "msg", ")", "self", ".", "executed", ".", "emit", "(", "msg", ")", "self", ".", "_request_info", "[", "'execute'", "]", ".", "pop", "(", "msg_id", ")", "elif", "info", "and", "info", ".", "kind", "==", "'silent_exec_callback'", "and", "not", "self", ".", "_hidden", ":", "self", ".", "_handle_exec_callback", "(", "msg", ")", "self", ".", "_request_info", "[", "'execute'", "]", ".", "pop", "(", "msg_id", ")", "else", ":", "super", "(", "FrontendWidget", ",", "self", ")", ".", "_handle_execute_reply", "(", "msg", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_input_request
Handle requests for raw_input.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_input_request(self, msg): """ Handle requests for raw_input. """ self.log.debug("input: %s", msg.get('content', '')) if self._hidden: raise RuntimeError('Request for raw input during hidden execution.') # Make sure that all output from the SUB channel has been processed # before entering readline mode. self.kernel_manager.sub_channel.flush() def callback(line): self.kernel_manager.stdin_channel.input(line) if self._reading: self.log.debug("Got second input request, assuming first was interrupted.") self._reading = False self._readline(msg['content']['prompt'], callback=callback)
def _handle_input_request(self, msg): """ Handle requests for raw_input. """ self.log.debug("input: %s", msg.get('content', '')) if self._hidden: raise RuntimeError('Request for raw input during hidden execution.') # Make sure that all output from the SUB channel has been processed # before entering readline mode. self.kernel_manager.sub_channel.flush() def callback(line): self.kernel_manager.stdin_channel.input(line) if self._reading: self.log.debug("Got second input request, assuming first was interrupted.") self._reading = False self._readline(msg['content']['prompt'], callback=callback)
[ "Handle", "requests", "for", "raw_input", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L425-L441
[ "def", "_handle_input_request", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"input: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "if", "self", ".", "_hidden", ":", "raise", "RuntimeError", "(", "'Request for raw input during hidden execution.'", ")", "# Make sure that all output from the SUB channel has been processed", "# before entering readline mode.", "self", ".", "kernel_manager", ".", "sub_channel", ".", "flush", "(", ")", "def", "callback", "(", "line", ")", ":", "self", ".", "kernel_manager", ".", "stdin_channel", ".", "input", "(", "line", ")", "if", "self", ".", "_reading", ":", "self", ".", "log", ".", "debug", "(", "\"Got second input request, assuming first was interrupted.\"", ")", "self", ".", "_reading", "=", "False", "self", ".", "_readline", "(", "msg", "[", "'content'", "]", "[", "'prompt'", "]", ",", "callback", "=", "callback", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_kernel_died
Handle the kernel's death by asking if the user wants to restart.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_kernel_died(self, since_last_heartbeat): """ Handle the kernel's death by asking if the user wants to restart. """ self.log.debug("kernel died: %s", since_last_heartbeat) if self.custom_restart: self.custom_restart_kernel_died.emit(since_last_heartbeat) else: message = 'The kernel heartbeat has been inactive for %.2f ' \ 'seconds. Do you want to restart the kernel? You may ' \ 'first want to check the network connection.' % \ since_last_heartbeat self.restart_kernel(message, now=True)
def _handle_kernel_died(self, since_last_heartbeat): """ Handle the kernel's death by asking if the user wants to restart. """ self.log.debug("kernel died: %s", since_last_heartbeat) if self.custom_restart: self.custom_restart_kernel_died.emit(since_last_heartbeat) else: message = 'The kernel heartbeat has been inactive for %.2f ' \ 'seconds. Do you want to restart the kernel? You may ' \ 'first want to check the network connection.' % \ since_last_heartbeat self.restart_kernel(message, now=True)
[ "Handle", "the", "kernel", "s", "death", "by", "asking", "if", "the", "user", "wants", "to", "restart", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L443-L454
[ "def", "_handle_kernel_died", "(", "self", ",", "since_last_heartbeat", ")", ":", "self", ".", "log", ".", "debug", "(", "\"kernel died: %s\"", ",", "since_last_heartbeat", ")", "if", "self", ".", "custom_restart", ":", "self", ".", "custom_restart_kernel_died", ".", "emit", "(", "since_last_heartbeat", ")", "else", ":", "message", "=", "'The kernel heartbeat has been inactive for %.2f '", "'seconds. Do you want to restart the kernel? You may '", "'first want to check the network connection.'", "%", "since_last_heartbeat", "self", ".", "restart_kernel", "(", "message", ",", "now", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_object_info_reply
Handle replies for call tips.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_object_info_reply(self, rep): """ Handle replies for call tips. """ self.log.debug("oinfo: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('call_tip') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): # Get the information for a call tip. For now we format the call # line as string, later we can pass False to format_call and # syntax-highlight it ourselves for nicer formatting in the # calltip. content = rep['content'] # if this is from pykernel, 'docstring' will be the only key if content.get('ismagic', False): # Don't generate a call-tip for magics. Ideally, we should # generate a tooltip, but not on ( like we do for actual # callables. call_info, doc = None, None else: call_info, doc = call_tip(content, format_call=True) if call_info or doc: self._call_tip_widget.show_call_info(call_info, doc)
def _handle_object_info_reply(self, rep): """ Handle replies for call tips. """ self.log.debug("oinfo: %s", rep.get('content', '')) cursor = self._get_cursor() info = self._request_info.get('call_tip') if info and info.id == rep['parent_header']['msg_id'] and \ info.pos == cursor.position(): # Get the information for a call tip. For now we format the call # line as string, later we can pass False to format_call and # syntax-highlight it ourselves for nicer formatting in the # calltip. content = rep['content'] # if this is from pykernel, 'docstring' will be the only key if content.get('ismagic', False): # Don't generate a call-tip for magics. Ideally, we should # generate a tooltip, but not on ( like we do for actual # callables. call_info, doc = None, None else: call_info, doc = call_tip(content, format_call=True) if call_info or doc: self._call_tip_widget.show_call_info(call_info, doc)
[ "Handle", "replies", "for", "call", "tips", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L456-L478
[ "def", "_handle_object_info_reply", "(", "self", ",", "rep", ")", ":", "self", ".", "log", ".", "debug", "(", "\"oinfo: %s\"", ",", "rep", ".", "get", "(", "'content'", ",", "''", ")", ")", "cursor", "=", "self", ".", "_get_cursor", "(", ")", "info", "=", "self", ".", "_request_info", ".", "get", "(", "'call_tip'", ")", "if", "info", "and", "info", ".", "id", "==", "rep", "[", "'parent_header'", "]", "[", "'msg_id'", "]", "and", "info", ".", "pos", "==", "cursor", ".", "position", "(", ")", ":", "# Get the information for a call tip. For now we format the call", "# line as string, later we can pass False to format_call and", "# syntax-highlight it ourselves for nicer formatting in the", "# calltip.", "content", "=", "rep", "[", "'content'", "]", "# if this is from pykernel, 'docstring' will be the only key", "if", "content", ".", "get", "(", "'ismagic'", ",", "False", ")", ":", "# Don't generate a call-tip for magics. Ideally, we should", "# generate a tooltip, but not on ( like we do for actual", "# callables.", "call_info", ",", "doc", "=", "None", ",", "None", "else", ":", "call_info", ",", "doc", "=", "call_tip", "(", "content", ",", "format_call", "=", "True", ")", "if", "call_info", "or", "doc", ":", "self", ".", "_call_tip_widget", ".", "show_call_info", "(", "call_info", ",", "doc", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_pyout
Handle display hook output.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_pyout(self, msg): """ Handle display hook output. """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): text = msg['content']['data'] self._append_plain_text(text + '\n', before_prompt=True)
def _handle_pyout(self, msg): """ Handle display hook output. """ self.log.debug("pyout: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): text = msg['content']['data'] self._append_plain_text(text + '\n', before_prompt=True)
[ "Handle", "display", "hook", "output", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L480-L486
[ "def", "_handle_pyout", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"pyout: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "if", "not", "self", ".", "_hidden", "and", "self", ".", "_is_from_this_session", "(", "msg", ")", ":", "text", "=", "msg", "[", "'content'", "]", "[", "'data'", "]", "self", ".", "_append_plain_text", "(", "text", "+", "'\\n'", ",", "before_prompt", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_stream
Handle stdout, stderr, and stdin.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_stream(self, msg): """ Handle stdout, stderr, and stdin. """ self.log.debug("stream: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): # Most consoles treat tabs as being 8 space characters. Convert tabs # to spaces so that output looks as expected regardless of this # widget's tab width. text = msg['content']['data'].expandtabs(8) self._append_plain_text(text, before_prompt=True) self._control.moveCursor(QtGui.QTextCursor.End)
def _handle_stream(self, msg): """ Handle stdout, stderr, and stdin. """ self.log.debug("stream: %s", msg.get('content', '')) if not self._hidden and self._is_from_this_session(msg): # Most consoles treat tabs as being 8 space characters. Convert tabs # to spaces so that output looks as expected regardless of this # widget's tab width. text = msg['content']['data'].expandtabs(8) self._append_plain_text(text, before_prompt=True) self._control.moveCursor(QtGui.QTextCursor.End)
[ "Handle", "stdout", "stderr", "and", "stdin", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L488-L499
[ "def", "_handle_stream", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"stream: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "if", "not", "self", ".", "_hidden", "and", "self", ".", "_is_from_this_session", "(", "msg", ")", ":", "# Most consoles treat tabs as being 8 space characters. Convert tabs", "# to spaces so that output looks as expected regardless of this", "# widget's tab width.", "text", "=", "msg", "[", "'content'", "]", "[", "'data'", "]", ".", "expandtabs", "(", "8", ")", "self", ".", "_append_plain_text", "(", "text", ",", "before_prompt", "=", "True", ")", "self", ".", "_control", ".", "moveCursor", "(", "QtGui", ".", "QTextCursor", ".", "End", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._handle_shutdown_reply
Handle shutdown signal, only if from other console.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _handle_shutdown_reply(self, msg): """ Handle shutdown signal, only if from other console. """ self.log.debug("shutdown: %s", msg.get('content', '')) if not self._hidden and not self._is_from_this_session(msg): if self._local_kernel: if not msg['content']['restart']: self.exit_requested.emit(self) else: # we just got notified of a restart! time.sleep(0.25) # wait 1/4 sec to reset # lest the request for a new prompt # goes to the old kernel self.reset() else: # remote kernel, prompt on Kernel shutdown/reset title = self.window().windowTitle() if not msg['content']['restart']: reply = QtGui.QMessageBox.question(self, title, "Kernel has been shutdown permanently. " "Close the Console?", QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.exit_requested.emit(self) else: # XXX: remove message box in favor of using the # clear_on_kernel_restart setting? reply = QtGui.QMessageBox.question(self, title, "Kernel has been reset. Clear the Console?", QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: time.sleep(0.25) # wait 1/4 sec to reset # lest the request for a new prompt # goes to the old kernel self.reset()
def _handle_shutdown_reply(self, msg): """ Handle shutdown signal, only if from other console. """ self.log.debug("shutdown: %s", msg.get('content', '')) if not self._hidden and not self._is_from_this_session(msg): if self._local_kernel: if not msg['content']['restart']: self.exit_requested.emit(self) else: # we just got notified of a restart! time.sleep(0.25) # wait 1/4 sec to reset # lest the request for a new prompt # goes to the old kernel self.reset() else: # remote kernel, prompt on Kernel shutdown/reset title = self.window().windowTitle() if not msg['content']['restart']: reply = QtGui.QMessageBox.question(self, title, "Kernel has been shutdown permanently. " "Close the Console?", QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: self.exit_requested.emit(self) else: # XXX: remove message box in favor of using the # clear_on_kernel_restart setting? reply = QtGui.QMessageBox.question(self, title, "Kernel has been reset. Clear the Console?", QtGui.QMessageBox.Yes,QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: time.sleep(0.25) # wait 1/4 sec to reset # lest the request for a new prompt # goes to the old kernel self.reset()
[ "Handle", "shutdown", "signal", "only", "if", "from", "other", "console", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L501-L534
[ "def", "_handle_shutdown_reply", "(", "self", ",", "msg", ")", ":", "self", ".", "log", ".", "debug", "(", "\"shutdown: %s\"", ",", "msg", ".", "get", "(", "'content'", ",", "''", ")", ")", "if", "not", "self", ".", "_hidden", "and", "not", "self", ".", "_is_from_this_session", "(", "msg", ")", ":", "if", "self", ".", "_local_kernel", ":", "if", "not", "msg", "[", "'content'", "]", "[", "'restart'", "]", ":", "self", ".", "exit_requested", ".", "emit", "(", "self", ")", "else", ":", "# we just got notified of a restart!", "time", ".", "sleep", "(", "0.25", ")", "# wait 1/4 sec to reset", "# lest the request for a new prompt", "# goes to the old kernel", "self", ".", "reset", "(", ")", "else", ":", "# remote kernel, prompt on Kernel shutdown/reset", "title", "=", "self", ".", "window", "(", ")", ".", "windowTitle", "(", ")", "if", "not", "msg", "[", "'content'", "]", "[", "'restart'", "]", ":", "reply", "=", "QtGui", ".", "QMessageBox", ".", "question", "(", "self", ",", "title", ",", "\"Kernel has been shutdown permanently. \"", "\"Close the Console?\"", ",", "QtGui", ".", "QMessageBox", ".", "Yes", ",", "QtGui", ".", "QMessageBox", ".", "No", ")", "if", "reply", "==", "QtGui", ".", "QMessageBox", ".", "Yes", ":", "self", ".", "exit_requested", ".", "emit", "(", "self", ")", "else", ":", "# XXX: remove message box in favor of using the", "# clear_on_kernel_restart setting?", "reply", "=", "QtGui", ".", "QMessageBox", ".", "question", "(", "self", ",", "title", ",", "\"Kernel has been reset. Clear the Console?\"", ",", "QtGui", ".", "QMessageBox", ".", "Yes", ",", "QtGui", ".", "QMessageBox", ".", "No", ")", "if", "reply", "==", "QtGui", ".", "QMessageBox", ".", "Yes", ":", "time", ".", "sleep", "(", "0.25", ")", "# wait 1/4 sec to reset", "# lest the request for a new prompt", "# goes to the old kernel", "self", ".", "reset", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget.execute_file
Attempts to execute file with 'path'. If 'hidden', no output is shown.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def execute_file(self, path, hidden=False): """ Attempts to execute file with 'path'. If 'hidden', no output is shown. """ self.execute('execfile(%r)' % path, hidden=hidden)
def execute_file(self, path, hidden=False): """ Attempts to execute file with 'path'. If 'hidden', no output is shown. """ self.execute('execfile(%r)' % path, hidden=hidden)
[ "Attempts", "to", "execute", "file", "with", "path", ".", "If", "hidden", "no", "output", "is", "shown", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L552-L556
[ "def", "execute_file", "(", "self", ",", "path", ",", "hidden", "=", "False", ")", ":", "self", ".", "execute", "(", "'execfile(%r)'", "%", "path", ",", "hidden", "=", "hidden", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget.interrupt_kernel
Attempts to interrupt the running kernel. Also unsets _reading flag, to avoid runtime errors if raw_input is called again.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def interrupt_kernel(self): """ Attempts to interrupt the running kernel. Also unsets _reading flag, to avoid runtime errors if raw_input is called again. """ if self.custom_interrupt: self._reading = False self.custom_interrupt_requested.emit() elif self.kernel_manager.has_kernel: self._reading = False self.kernel_manager.interrupt_kernel() else: self._append_plain_text('Kernel process is either remote or ' 'unspecified. Cannot interrupt.\n')
def interrupt_kernel(self): """ Attempts to interrupt the running kernel. Also unsets _reading flag, to avoid runtime errors if raw_input is called again. """ if self.custom_interrupt: self._reading = False self.custom_interrupt_requested.emit() elif self.kernel_manager.has_kernel: self._reading = False self.kernel_manager.interrupt_kernel() else: self._append_plain_text('Kernel process is either remote or ' 'unspecified. Cannot interrupt.\n')
[ "Attempts", "to", "interrupt", "the", "running", "kernel", ".", "Also", "unsets", "_reading", "flag", "to", "avoid", "runtime", "errors", "if", "raw_input", "is", "called", "again", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L558-L572
[ "def", "interrupt_kernel", "(", "self", ")", ":", "if", "self", ".", "custom_interrupt", ":", "self", ".", "_reading", "=", "False", "self", ".", "custom_interrupt_requested", ".", "emit", "(", ")", "elif", "self", ".", "kernel_manager", ".", "has_kernel", ":", "self", ".", "_reading", "=", "False", "self", ".", "kernel_manager", ".", "interrupt_kernel", "(", ")", "else", ":", "self", ".", "_append_plain_text", "(", "'Kernel process is either remote or '", "'unspecified. Cannot interrupt.\\n'", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget.reset
Resets the widget to its initial state if ``clear`` parameter or ``clear_on_kernel_restart`` configuration setting is True, otherwise prints a visual indication of the fact that the kernel restarted, but does not clear the traces from previous usage of the kernel before it was restarted. With ``clear=True``, it is similar to ``%clear``, but also re-writes the banner and aborts execution if necessary.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def reset(self, clear=False): """ Resets the widget to its initial state if ``clear`` parameter or ``clear_on_kernel_restart`` configuration setting is True, otherwise prints a visual indication of the fact that the kernel restarted, but does not clear the traces from previous usage of the kernel before it was restarted. With ``clear=True``, it is similar to ``%clear``, but also re-writes the banner and aborts execution if necessary. """ if self._executing: self._executing = False self._request_info['execute'] = {} self._reading = False self._highlighter.highlighting_on = False if self.clear_on_kernel_restart or clear: self._control.clear() self._append_plain_text(self.banner) else: self._append_plain_text("# restarting kernel...") self._append_html("<hr><br>") # XXX: Reprinting the full banner may be too much, but once #1680 is # addressed, that will mitigate it. #self._append_plain_text(self.banner) # update output marker for stdout/stderr, so that startup # messages appear after banner: self._append_before_prompt_pos = self._get_cursor().position() self._show_interpreter_prompt()
def reset(self, clear=False): """ Resets the widget to its initial state if ``clear`` parameter or ``clear_on_kernel_restart`` configuration setting is True, otherwise prints a visual indication of the fact that the kernel restarted, but does not clear the traces from previous usage of the kernel before it was restarted. With ``clear=True``, it is similar to ``%clear``, but also re-writes the banner and aborts execution if necessary. """ if self._executing: self._executing = False self._request_info['execute'] = {} self._reading = False self._highlighter.highlighting_on = False if self.clear_on_kernel_restart or clear: self._control.clear() self._append_plain_text(self.banner) else: self._append_plain_text("# restarting kernel...") self._append_html("<hr><br>") # XXX: Reprinting the full banner may be too much, but once #1680 is # addressed, that will mitigate it. #self._append_plain_text(self.banner) # update output marker for stdout/stderr, so that startup # messages appear after banner: self._append_before_prompt_pos = self._get_cursor().position() self._show_interpreter_prompt()
[ "Resets", "the", "widget", "to", "its", "initial", "state", "if", "clear", "parameter", "or", "clear_on_kernel_restart", "configuration", "setting", "is", "True", "otherwise", "prints", "a", "visual", "indication", "of", "the", "fact", "that", "the", "kernel", "restarted", "but", "does", "not", "clear", "the", "traces", "from", "previous", "usage", "of", "the", "kernel", "before", "it", "was", "restarted", ".", "With", "clear", "=", "True", "it", "is", "similar", "to", "%clear", "but", "also", "re", "-", "writes", "the", "banner", "and", "aborts", "execution", "if", "necessary", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L574-L600
[ "def", "reset", "(", "self", ",", "clear", "=", "False", ")", ":", "if", "self", ".", "_executing", ":", "self", ".", "_executing", "=", "False", "self", ".", "_request_info", "[", "'execute'", "]", "=", "{", "}", "self", ".", "_reading", "=", "False", "self", ".", "_highlighter", ".", "highlighting_on", "=", "False", "if", "self", ".", "clear_on_kernel_restart", "or", "clear", ":", "self", ".", "_control", ".", "clear", "(", ")", "self", ".", "_append_plain_text", "(", "self", ".", "banner", ")", "else", ":", "self", ".", "_append_plain_text", "(", "\"# restarting kernel...\"", ")", "self", ".", "_append_html", "(", "\"<hr><br>\"", ")", "# XXX: Reprinting the full banner may be too much, but once #1680 is", "# addressed, that will mitigate it.", "#self._append_plain_text(self.banner)", "# update output marker for stdout/stderr, so that startup", "# messages appear after banner:", "self", ".", "_append_before_prompt_pos", "=", "self", ".", "_get_cursor", "(", ")", ".", "position", "(", ")", "self", ".", "_show_interpreter_prompt", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget.restart_kernel
Attempts to restart the running kernel.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def restart_kernel(self, message, now=False): """ Attempts to restart the running kernel. """ # FIXME: now should be configurable via a checkbox in the dialog. Right # now at least the heartbeat path sets it to True and the manual restart # to False. But those should just be the pre-selected states of a # checkbox that the user could override if so desired. But I don't know # enough Qt to go implementing the checkbox now. if self.custom_restart: self.custom_restart_requested.emit() elif self.kernel_manager.has_kernel: # Pause the heart beat channel to prevent further warnings. self.kernel_manager.hb_channel.pause() # Prompt the user to restart the kernel. Un-pause the heartbeat if # they decline. (If they accept, the heartbeat will be un-paused # automatically when the kernel is restarted.) if self.confirm_restart: buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No result = QtGui.QMessageBox.question(self, 'Restart kernel?', message, buttons) do_restart = result == QtGui.QMessageBox.Yes else: # confirm_restart is False, so we don't need to ask user # anything, just do the restart do_restart = True if do_restart: try: self.kernel_manager.restart_kernel(now=now) except RuntimeError: self._append_plain_text('Kernel started externally. ' 'Cannot restart.\n', before_prompt=True ) else: self.reset() else: self.kernel_manager.hb_channel.unpause() else: self._append_plain_text('Kernel process is either remote or ' 'unspecified. Cannot restart.\n', before_prompt=True )
def restart_kernel(self, message, now=False): """ Attempts to restart the running kernel. """ # FIXME: now should be configurable via a checkbox in the dialog. Right # now at least the heartbeat path sets it to True and the manual restart # to False. But those should just be the pre-selected states of a # checkbox that the user could override if so desired. But I don't know # enough Qt to go implementing the checkbox now. if self.custom_restart: self.custom_restart_requested.emit() elif self.kernel_manager.has_kernel: # Pause the heart beat channel to prevent further warnings. self.kernel_manager.hb_channel.pause() # Prompt the user to restart the kernel. Un-pause the heartbeat if # they decline. (If they accept, the heartbeat will be un-paused # automatically when the kernel is restarted.) if self.confirm_restart: buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No result = QtGui.QMessageBox.question(self, 'Restart kernel?', message, buttons) do_restart = result == QtGui.QMessageBox.Yes else: # confirm_restart is False, so we don't need to ask user # anything, just do the restart do_restart = True if do_restart: try: self.kernel_manager.restart_kernel(now=now) except RuntimeError: self._append_plain_text('Kernel started externally. ' 'Cannot restart.\n', before_prompt=True ) else: self.reset() else: self.kernel_manager.hb_channel.unpause() else: self._append_plain_text('Kernel process is either remote or ' 'unspecified. Cannot restart.\n', before_prompt=True )
[ "Attempts", "to", "restart", "the", "running", "kernel", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L602-L647
[ "def", "restart_kernel", "(", "self", ",", "message", ",", "now", "=", "False", ")", ":", "# FIXME: now should be configurable via a checkbox in the dialog. Right", "# now at least the heartbeat path sets it to True and the manual restart", "# to False. But those should just be the pre-selected states of a", "# checkbox that the user could override if so desired. But I don't know", "# enough Qt to go implementing the checkbox now.", "if", "self", ".", "custom_restart", ":", "self", ".", "custom_restart_requested", ".", "emit", "(", ")", "elif", "self", ".", "kernel_manager", ".", "has_kernel", ":", "# Pause the heart beat channel to prevent further warnings.", "self", ".", "kernel_manager", ".", "hb_channel", ".", "pause", "(", ")", "# Prompt the user to restart the kernel. Un-pause the heartbeat if", "# they decline. (If they accept, the heartbeat will be un-paused", "# automatically when the kernel is restarted.)", "if", "self", ".", "confirm_restart", ":", "buttons", "=", "QtGui", ".", "QMessageBox", ".", "Yes", "|", "QtGui", ".", "QMessageBox", ".", "No", "result", "=", "QtGui", ".", "QMessageBox", ".", "question", "(", "self", ",", "'Restart kernel?'", ",", "message", ",", "buttons", ")", "do_restart", "=", "result", "==", "QtGui", ".", "QMessageBox", ".", "Yes", "else", ":", "# confirm_restart is False, so we don't need to ask user", "# anything, just do the restart", "do_restart", "=", "True", "if", "do_restart", ":", "try", ":", "self", ".", "kernel_manager", ".", "restart_kernel", "(", "now", "=", "now", ")", "except", "RuntimeError", ":", "self", ".", "_append_plain_text", "(", "'Kernel started externally. '", "'Cannot restart.\\n'", ",", "before_prompt", "=", "True", ")", "else", ":", "self", ".", "reset", "(", ")", "else", ":", "self", ".", "kernel_manager", ".", "hb_channel", ".", "unpause", "(", ")", "else", ":", "self", ".", "_append_plain_text", "(", "'Kernel process is either remote or '", "'unspecified. Cannot restart.\\n'", ",", "before_prompt", "=", "True", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._call_tip
Shows a call tip, if appropriate, at the current cursor location.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _call_tip(self): """ Shows a call tip, if appropriate, at the current cursor location. """ # Decide if it makes sense to show a call tip if not self.enable_calltips: return False cursor = self._get_cursor() cursor.movePosition(QtGui.QTextCursor.Left) if cursor.document().characterAt(cursor.position()) != '(': return False context = self._get_context(cursor) if not context: return False # Send the metadata request to the kernel name = '.'.join(context) msg_id = self.kernel_manager.shell_channel.object_info(name) pos = self._get_cursor().position() self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) return True
def _call_tip(self): """ Shows a call tip, if appropriate, at the current cursor location. """ # Decide if it makes sense to show a call tip if not self.enable_calltips: return False cursor = self._get_cursor() cursor.movePosition(QtGui.QTextCursor.Left) if cursor.document().characterAt(cursor.position()) != '(': return False context = self._get_context(cursor) if not context: return False # Send the metadata request to the kernel name = '.'.join(context) msg_id = self.kernel_manager.shell_channel.object_info(name) pos = self._get_cursor().position() self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos) return True
[ "Shows", "a", "call", "tip", "if", "appropriate", "at", "the", "current", "cursor", "location", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L653-L672
[ "def", "_call_tip", "(", "self", ")", ":", "# Decide if it makes sense to show a call tip", "if", "not", "self", ".", "enable_calltips", ":", "return", "False", "cursor", "=", "self", ".", "_get_cursor", "(", ")", "cursor", ".", "movePosition", "(", "QtGui", ".", "QTextCursor", ".", "Left", ")", "if", "cursor", ".", "document", "(", ")", ".", "characterAt", "(", "cursor", ".", "position", "(", ")", ")", "!=", "'('", ":", "return", "False", "context", "=", "self", ".", "_get_context", "(", "cursor", ")", "if", "not", "context", ":", "return", "False", "# Send the metadata request to the kernel", "name", "=", "'.'", ".", "join", "(", "context", ")", "msg_id", "=", "self", ".", "kernel_manager", ".", "shell_channel", ".", "object_info", "(", "name", ")", "pos", "=", "self", ".", "_get_cursor", "(", ")", ".", "position", "(", ")", "self", ".", "_request_info", "[", "'call_tip'", "]", "=", "self", ".", "_CallTipRequest", "(", "msg_id", ",", "pos", ")", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._complete
Performs completion at the current cursor location.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _complete(self): """ Performs completion at the current cursor location. """ context = self._get_context() if context: # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( '.'.join(context), # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info
def _complete(self): """ Performs completion at the current cursor location. """ context = self._get_context() if context: # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( '.'.join(context), # text self._get_input_buffer_cursor_line(), # line self._get_input_buffer_cursor_column(), # cursor_pos self.input_buffer) # block pos = self._get_cursor().position() info = self._CompletionRequest(msg_id, pos) self._request_info['complete'] = info
[ "Performs", "completion", "at", "the", "current", "cursor", "location", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L674-L687
[ "def", "_complete", "(", "self", ")", ":", "context", "=", "self", ".", "_get_context", "(", ")", "if", "context", ":", "# Send the completion request to the kernel", "msg_id", "=", "self", ".", "kernel_manager", ".", "shell_channel", ".", "complete", "(", "'.'", ".", "join", "(", "context", ")", ",", "# text", "self", ".", "_get_input_buffer_cursor_line", "(", ")", ",", "# line", "self", ".", "_get_input_buffer_cursor_column", "(", ")", ",", "# cursor_pos", "self", ".", "input_buffer", ")", "# block", "pos", "=", "self", ".", "_get_cursor", "(", ")", ".", "position", "(", ")", "info", "=", "self", ".", "_CompletionRequest", "(", "msg_id", ",", "pos", ")", "self", ".", "_request_info", "[", "'complete'", "]", "=", "info" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._get_context
Gets the context for the specified cursor (or the current cursor if none is specified).
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _get_context(self, cursor=None): """ Gets the context for the specified cursor (or the current cursor if none is specified). """ if cursor is None: cursor = self._get_cursor() cursor.movePosition(QtGui.QTextCursor.StartOfBlock, QtGui.QTextCursor.KeepAnchor) text = cursor.selection().toPlainText() return self._completion_lexer.get_context(text)
def _get_context(self, cursor=None): """ Gets the context for the specified cursor (or the current cursor if none is specified). """ if cursor is None: cursor = self._get_cursor() cursor.movePosition(QtGui.QTextCursor.StartOfBlock, QtGui.QTextCursor.KeepAnchor) text = cursor.selection().toPlainText() return self._completion_lexer.get_context(text)
[ "Gets", "the", "context", "for", "the", "specified", "cursor", "(", "or", "the", "current", "cursor", "if", "none", "is", "specified", ")", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L689-L698
[ "def", "_get_context", "(", "self", ",", "cursor", "=", "None", ")", ":", "if", "cursor", "is", "None", ":", "cursor", "=", "self", ".", "_get_cursor", "(", ")", "cursor", ".", "movePosition", "(", "QtGui", ".", "QTextCursor", ".", "StartOfBlock", ",", "QtGui", ".", "QTextCursor", ".", "KeepAnchor", ")", "text", "=", "cursor", ".", "selection", "(", ")", ".", "toPlainText", "(", ")", "return", "self", ".", "_completion_lexer", ".", "get_context", "(", "text", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._process_execute_error
Process a reply for an execution request that resulted in an error.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _process_execute_error(self, msg): """ Process a reply for an execution request that resulted in an error. """ content = msg['content'] # If a SystemExit is passed along, this means exit() was called - also # all the ipython %exit magic syntax of '-k' to be used to keep # the kernel running if content['ename']=='SystemExit': keepkernel = content['evalue']=='-k' or content['evalue']=='True' self._keep_kernel_on_exit = keepkernel self.exit_requested.emit(self) else: traceback = ''.join(content['traceback']) self._append_plain_text(traceback)
def _process_execute_error(self, msg): """ Process a reply for an execution request that resulted in an error. """ content = msg['content'] # If a SystemExit is passed along, this means exit() was called - also # all the ipython %exit magic syntax of '-k' to be used to keep # the kernel running if content['ename']=='SystemExit': keepkernel = content['evalue']=='-k' or content['evalue']=='True' self._keep_kernel_on_exit = keepkernel self.exit_requested.emit(self) else: traceback = ''.join(content['traceback']) self._append_plain_text(traceback)
[ "Process", "a", "reply", "for", "an", "execution", "request", "that", "resulted", "in", "an", "error", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L705-L718
[ "def", "_process_execute_error", "(", "self", ",", "msg", ")", ":", "content", "=", "msg", "[", "'content'", "]", "# If a SystemExit is passed along, this means exit() was called - also", "# all the ipython %exit magic syntax of '-k' to be used to keep", "# the kernel running", "if", "content", "[", "'ename'", "]", "==", "'SystemExit'", ":", "keepkernel", "=", "content", "[", "'evalue'", "]", "==", "'-k'", "or", "content", "[", "'evalue'", "]", "==", "'True'", "self", ".", "_keep_kernel_on_exit", "=", "keepkernel", "self", ".", "exit_requested", ".", "emit", "(", "self", ")", "else", ":", "traceback", "=", "''", ".", "join", "(", "content", "[", "'traceback'", "]", ")", "self", ".", "_append_plain_text", "(", "traceback", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._process_execute_ok
Process a reply for a successful execution request.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _process_execute_ok(self, msg): """ Process a reply for a successful execution request. """ payload = msg['content']['payload'] for item in payload: if not self._process_execute_payload(item): warning = 'Warning: received unknown payload of type %s' print(warning % repr(item['source']))
def _process_execute_ok(self, msg): """ Process a reply for a successful execution request. """ payload = msg['content']['payload'] for item in payload: if not self._process_execute_payload(item): warning = 'Warning: received unknown payload of type %s' print(warning % repr(item['source']))
[ "Process", "a", "reply", "for", "a", "successful", "execution", "request", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L720-L727
[ "def", "_process_execute_ok", "(", "self", ",", "msg", ")", ":", "payload", "=", "msg", "[", "'content'", "]", "[", "'payload'", "]", "for", "item", "in", "payload", ":", "if", "not", "self", ".", "_process_execute_payload", "(", "item", ")", ":", "warning", "=", "'Warning: received unknown payload of type %s'", "print", "(", "warning", "%", "repr", "(", "item", "[", "'source'", "]", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
FrontendWidget._document_contents_change
Called whenever the document's content changes. Display a call tip if appropriate.
environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py
def _document_contents_change(self, position, removed, added): """ Called whenever the document's content changes. Display a call tip if appropriate. """ # Calculate where the cursor should be *after* the change: position += added document = self._control.document() if position == self._get_cursor().position(): self._call_tip()
def _document_contents_change(self, position, removed, added): """ Called whenever the document's content changes. Display a call tip if appropriate. """ # Calculate where the cursor should be *after* the change: position += added document = self._control.document() if position == self._get_cursor().position(): self._call_tip()
[ "Called", "whenever", "the", "document", "s", "content", "changes", ".", "Display", "a", "call", "tip", "if", "appropriate", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/frontend/qt/console/frontend_widget.py#L749-L758
[ "def", "_document_contents_change", "(", "self", ",", "position", ",", "removed", ",", "added", ")", ":", "# Calculate where the cursor should be *after* the change:", "position", "+=", "added", "document", "=", "self", ".", "_control", ".", "document", "(", ")", "if", "position", "==", "self", ".", "_get_cursor", "(", ")", ".", "position", "(", ")", ":", "self", ".", "_call_tip", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PluginProxy.addPlugin
Add plugin to my list of plugins to call, if it has the attribute I'm bound to.
environment/lib/python2.7/site-packages/nose/plugins/manager.py
def addPlugin(self, plugin, call): """Add plugin to my list of plugins to call, if it has the attribute I'm bound to. """ meth = getattr(plugin, call, None) if meth is not None: if call == 'loadTestsFromModule' and \ len(inspect.getargspec(meth)[0]) == 2: orig_meth = meth meth = lambda module, path, **kwargs: orig_meth(module) self.plugins.append((plugin, meth))
def addPlugin(self, plugin, call): """Add plugin to my list of plugins to call, if it has the attribute I'm bound to. """ meth = getattr(plugin, call, None) if meth is not None: if call == 'loadTestsFromModule' and \ len(inspect.getargspec(meth)[0]) == 2: orig_meth = meth meth = lambda module, path, **kwargs: orig_meth(module) self.plugins.append((plugin, meth))
[ "Add", "plugin", "to", "my", "list", "of", "plugins", "to", "call", "if", "it", "has", "the", "attribute", "I", "m", "bound", "to", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L101-L111
[ "def", "addPlugin", "(", "self", ",", "plugin", ",", "call", ")", ":", "meth", "=", "getattr", "(", "plugin", ",", "call", ",", "None", ")", "if", "meth", "is", "not", "None", ":", "if", "call", "==", "'loadTestsFromModule'", "and", "len", "(", "inspect", ".", "getargspec", "(", "meth", ")", "[", "0", "]", ")", "==", "2", ":", "orig_meth", "=", "meth", "meth", "=", "lambda", "module", ",", "path", ",", "*", "*", "kwargs", ":", "orig_meth", "(", "module", ")", "self", ".", "plugins", ".", "append", "(", "(", "plugin", ",", "meth", ")", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PluginProxy.chain
Call plugins in a chain, where the result of each plugin call is sent to the next plugin as input. The final output result is returned.
environment/lib/python2.7/site-packages/nose/plugins/manager.py
def chain(self, *arg, **kw): """Call plugins in a chain, where the result of each plugin call is sent to the next plugin as input. The final output result is returned. """ result = None # extract the static arguments (if any) from arg so they can # be passed to each plugin call in the chain static = [a for (static, a) in zip(getattr(self.method, 'static_args', []), arg) if static] for p, meth in self.plugins: result = meth(*arg, **kw) arg = static[:] arg.append(result) return result
def chain(self, *arg, **kw): """Call plugins in a chain, where the result of each plugin call is sent to the next plugin as input. The final output result is returned. """ result = None # extract the static arguments (if any) from arg so they can # be passed to each plugin call in the chain static = [a for (static, a) in zip(getattr(self.method, 'static_args', []), arg) if static] for p, meth in self.plugins: result = meth(*arg, **kw) arg = static[:] arg.append(result) return result
[ "Call", "plugins", "in", "a", "chain", "where", "the", "result", "of", "each", "plugin", "call", "is", "sent", "to", "the", "next", "plugin", "as", "input", ".", "The", "final", "output", "result", "is", "returned", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L130-L144
[ "def", "chain", "(", "self", ",", "*", "arg", ",", "*", "*", "kw", ")", ":", "result", "=", "None", "# extract the static arguments (if any) from arg so they can", "# be passed to each plugin call in the chain", "static", "=", "[", "a", "for", "(", "static", ",", "a", ")", "in", "zip", "(", "getattr", "(", "self", ".", "method", ",", "'static_args'", ",", "[", "]", ")", ",", "arg", ")", "if", "static", "]", "for", "p", ",", "meth", "in", "self", ".", "plugins", ":", "result", "=", "meth", "(", "*", "arg", ",", "*", "*", "kw", ")", "arg", "=", "static", "[", ":", "]", "arg", ".", "append", "(", "result", ")", "return", "result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PluginProxy.generate
Call all plugins, yielding each item in each non-None result.
environment/lib/python2.7/site-packages/nose/plugins/manager.py
def generate(self, *arg, **kw): """Call all plugins, yielding each item in each non-None result. """ for p, meth in self.plugins: result = None try: result = meth(*arg, **kw) if result is not None: for r in result: yield r except (KeyboardInterrupt, SystemExit): raise except: exc = sys.exc_info() yield Failure(*exc) continue
def generate(self, *arg, **kw): """Call all plugins, yielding each item in each non-None result. """ for p, meth in self.plugins: result = None try: result = meth(*arg, **kw) if result is not None: for r in result: yield r except (KeyboardInterrupt, SystemExit): raise except: exc = sys.exc_info() yield Failure(*exc) continue
[ "Call", "all", "plugins", "yielding", "each", "item", "in", "each", "non", "-", "None", "result", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L146-L161
[ "def", "generate", "(", "self", ",", "*", "arg", ",", "*", "*", "kw", ")", ":", "for", "p", ",", "meth", "in", "self", ".", "plugins", ":", "result", "=", "None", "try", ":", "result", "=", "meth", "(", "*", "arg", ",", "*", "*", "kw", ")", "if", "result", "is", "not", "None", ":", "for", "r", "in", "result", ":", "yield", "r", "except", "(", "KeyboardInterrupt", ",", "SystemExit", ")", ":", "raise", "except", ":", "exc", "=", "sys", ".", "exc_info", "(", ")", "yield", "Failure", "(", "*", "exc", ")", "continue" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PluginProxy.simple
Call all plugins, returning the first non-None result.
environment/lib/python2.7/site-packages/nose/plugins/manager.py
def simple(self, *arg, **kw): """Call all plugins, returning the first non-None result. """ for p, meth in self.plugins: result = meth(*arg, **kw) if result is not None: return result
def simple(self, *arg, **kw): """Call all plugins, returning the first non-None result. """ for p, meth in self.plugins: result = meth(*arg, **kw) if result is not None: return result
[ "Call", "all", "plugins", "returning", "the", "first", "non", "-", "None", "result", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L163-L169
[ "def", "simple", "(", "self", ",", "*", "arg", ",", "*", "*", "kw", ")", ":", "for", "p", ",", "meth", "in", "self", ".", "plugins", ":", "result", "=", "meth", "(", "*", "arg", ",", "*", "*", "kw", ")", "if", "result", "is", "not", "None", ":", "return", "result" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PluginManager.addPlugins
extraplugins are maintained in a separate list and re-added by loadPlugins() to prevent their being overwritten by plugins added by a subclass of PluginManager
environment/lib/python2.7/site-packages/nose/plugins/manager.py
def addPlugins(self, plugins=(), extraplugins=()): """extraplugins are maintained in a separate list and re-added by loadPlugins() to prevent their being overwritten by plugins added by a subclass of PluginManager """ self._extraplugins = extraplugins for plug in iterchain(plugins, extraplugins): self.addPlugin(plug)
def addPlugins(self, plugins=(), extraplugins=()): """extraplugins are maintained in a separate list and re-added by loadPlugins() to prevent their being overwritten by plugins added by a subclass of PluginManager """ self._extraplugins = extraplugins for plug in iterchain(plugins, extraplugins): self.addPlugin(plug)
[ "extraplugins", "are", "maintained", "in", "a", "separate", "list", "and", "re", "-", "added", "by", "loadPlugins", "()", "to", "prevent", "their", "being", "overwritten", "by", "plugins", "added", "by", "a", "subclass", "of", "PluginManager" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L267-L274
[ "def", "addPlugins", "(", "self", ",", "plugins", "=", "(", ")", ",", "extraplugins", "=", "(", ")", ")", ":", "self", ".", "_extraplugins", "=", "extraplugins", "for", "plug", "in", "iterchain", "(", "plugins", ",", "extraplugins", ")", ":", "self", ".", "addPlugin", "(", "plug", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
PluginManager.configure
Configure the set of plugins with the given options and config instance. After configuration, disabled plugins are removed from the plugins list.
environment/lib/python2.7/site-packages/nose/plugins/manager.py
def configure(self, options, config): """Configure the set of plugins with the given options and config instance. After configuration, disabled plugins are removed from the plugins list. """ log.debug("Configuring plugins") self.config = config cfg = PluginProxy('configure', self._plugins) cfg(options, config) enabled = [plug for plug in self._plugins if plug.enabled] self.plugins = enabled self.sort() log.debug("Plugins enabled: %s", enabled)
def configure(self, options, config): """Configure the set of plugins with the given options and config instance. After configuration, disabled plugins are removed from the plugins list. """ log.debug("Configuring plugins") self.config = config cfg = PluginProxy('configure', self._plugins) cfg(options, config) enabled = [plug for plug in self._plugins if plug.enabled] self.plugins = enabled self.sort() log.debug("Plugins enabled: %s", enabled)
[ "Configure", "the", "set", "of", "plugins", "with", "the", "given", "options", "and", "config", "instance", ".", "After", "configuration", "disabled", "plugins", "are", "removed", "from", "the", "plugins", "list", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L276-L288
[ "def", "configure", "(", "self", ",", "options", ",", "config", ")", ":", "log", ".", "debug", "(", "\"Configuring plugins\"", ")", "self", ".", "config", "=", "config", "cfg", "=", "PluginProxy", "(", "'configure'", ",", "self", ".", "_plugins", ")", "cfg", "(", "options", ",", "config", ")", "enabled", "=", "[", "plug", "for", "plug", "in", "self", ".", "_plugins", "if", "plug", ".", "enabled", "]", "self", ".", "plugins", "=", "enabled", "self", ".", "sort", "(", ")", "log", ".", "debug", "(", "\"Plugins enabled: %s\"", ",", "enabled", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
EntryPointPluginManager.loadPlugins
Load plugins by iterating the `nose.plugins` entry point.
environment/lib/python2.7/site-packages/nose/plugins/manager.py
def loadPlugins(self): """Load plugins by iterating the `nose.plugins` entry point. """ from pkg_resources import iter_entry_points loaded = {} for entry_point, adapt in self.entry_points: for ep in iter_entry_points(entry_point): if ep.name in loaded: continue loaded[ep.name] = True log.debug('%s load plugin %s', self.__class__.__name__, ep) try: plugcls = ep.load() except KeyboardInterrupt: raise except Exception, e: # never want a plugin load to kill the test run # but we can't log here because the logger is not yet # configured warn("Unable to load plugin %s: %s" % (ep, e), RuntimeWarning) continue if adapt: plug = adapt(plugcls()) else: plug = plugcls() self.addPlugin(plug) super(EntryPointPluginManager, self).loadPlugins()
def loadPlugins(self): """Load plugins by iterating the `nose.plugins` entry point. """ from pkg_resources import iter_entry_points loaded = {} for entry_point, adapt in self.entry_points: for ep in iter_entry_points(entry_point): if ep.name in loaded: continue loaded[ep.name] = True log.debug('%s load plugin %s', self.__class__.__name__, ep) try: plugcls = ep.load() except KeyboardInterrupt: raise except Exception, e: # never want a plugin load to kill the test run # but we can't log here because the logger is not yet # configured warn("Unable to load plugin %s: %s" % (ep, e), RuntimeWarning) continue if adapt: plug = adapt(plugcls()) else: plug = plugcls() self.addPlugin(plug) super(EntryPointPluginManager, self).loadPlugins()
[ "Load", "plugins", "by", "iterating", "the", "nose", ".", "plugins", "entry", "point", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L375-L402
[ "def", "loadPlugins", "(", "self", ")", ":", "from", "pkg_resources", "import", "iter_entry_points", "loaded", "=", "{", "}", "for", "entry_point", ",", "adapt", "in", "self", ".", "entry_points", ":", "for", "ep", "in", "iter_entry_points", "(", "entry_point", ")", ":", "if", "ep", ".", "name", "in", "loaded", ":", "continue", "loaded", "[", "ep", ".", "name", "]", "=", "True", "log", ".", "debug", "(", "'%s load plugin %s'", ",", "self", ".", "__class__", ".", "__name__", ",", "ep", ")", "try", ":", "plugcls", "=", "ep", ".", "load", "(", ")", "except", "KeyboardInterrupt", ":", "raise", "except", "Exception", ",", "e", ":", "# never want a plugin load to kill the test run", "# but we can't log here because the logger is not yet", "# configured", "warn", "(", "\"Unable to load plugin %s: %s\"", "%", "(", "ep", ",", "e", ")", ",", "RuntimeWarning", ")", "continue", "if", "adapt", ":", "plug", "=", "adapt", "(", "plugcls", "(", ")", ")", "else", ":", "plug", "=", "plugcls", "(", ")", "self", ".", "addPlugin", "(", "plug", ")", "super", "(", "EntryPointPluginManager", ",", "self", ")", ".", "loadPlugins", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
BuiltinPluginManager.loadPlugins
Load plugins in nose.plugins.builtin
environment/lib/python2.7/site-packages/nose/plugins/manager.py
def loadPlugins(self): """Load plugins in nose.plugins.builtin """ from nose.plugins import builtin for plug in builtin.plugins: self.addPlugin(plug()) super(BuiltinPluginManager, self).loadPlugins()
def loadPlugins(self): """Load plugins in nose.plugins.builtin """ from nose.plugins import builtin for plug in builtin.plugins: self.addPlugin(plug()) super(BuiltinPluginManager, self).loadPlugins()
[ "Load", "plugins", "in", "nose", ".", "plugins", ".", "builtin" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/nose/plugins/manager.py#L409-L415
[ "def", "loadPlugins", "(", "self", ")", ":", "from", "nose", ".", "plugins", "import", "builtin", "for", "plug", "in", "builtin", ".", "plugins", ":", "self", ".", "addPlugin", "(", "plug", "(", ")", ")", "super", "(", "BuiltinPluginManager", ",", "self", ")", ".", "loadPlugins", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
latex_to_png
Render a LaTeX string to PNG. Parameters ---------- s : str The raw string containing valid inline LaTeX. encode : bool, optional Should the PNG data bebase64 encoded to make it JSON'able. backend : {mpl, dvipng} Backend for producing PNG data. None is returned when the backend cannot be used.
environment/lib/python2.7/site-packages/IPython/lib/latextools.py
def latex_to_png(s, encode=False, backend='mpl'): """Render a LaTeX string to PNG. Parameters ---------- s : str The raw string containing valid inline LaTeX. encode : bool, optional Should the PNG data bebase64 encoded to make it JSON'able. backend : {mpl, dvipng} Backend for producing PNG data. None is returned when the backend cannot be used. """ if backend == 'mpl': f = latex_to_png_mpl elif backend == 'dvipng': f = latex_to_png_dvipng else: raise ValueError('No such backend {0}'.format(backend)) bin_data = f(s) if encode and bin_data: bin_data = encodestring(bin_data) return bin_data
def latex_to_png(s, encode=False, backend='mpl'): """Render a LaTeX string to PNG. Parameters ---------- s : str The raw string containing valid inline LaTeX. encode : bool, optional Should the PNG data bebase64 encoded to make it JSON'able. backend : {mpl, dvipng} Backend for producing PNG data. None is returned when the backend cannot be used. """ if backend == 'mpl': f = latex_to_png_mpl elif backend == 'dvipng': f = latex_to_png_dvipng else: raise ValueError('No such backend {0}'.format(backend)) bin_data = f(s) if encode and bin_data: bin_data = encodestring(bin_data) return bin_data
[ "Render", "a", "LaTeX", "string", "to", "PNG", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/latextools.py#L34-L58
[ "def", "latex_to_png", "(", "s", ",", "encode", "=", "False", ",", "backend", "=", "'mpl'", ")", ":", "if", "backend", "==", "'mpl'", ":", "f", "=", "latex_to_png_mpl", "elif", "backend", "==", "'dvipng'", ":", "f", "=", "latex_to_png_dvipng", "else", ":", "raise", "ValueError", "(", "'No such backend {0}'", ".", "format", "(", "backend", ")", ")", "bin_data", "=", "f", "(", "s", ")", "if", "encode", "and", "bin_data", ":", "bin_data", "=", "encodestring", "(", "bin_data", ")", "return", "bin_data" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
latex_to_html
Render LaTeX to HTML with embedded PNG data using data URIs. Parameters ---------- s : str The raw string containing valid inline LateX. alt : str The alt text to use for the HTML.
environment/lib/python2.7/site-packages/IPython/lib/latextools.py
def latex_to_html(s, alt='image'): """Render LaTeX to HTML with embedded PNG data using data URIs. Parameters ---------- s : str The raw string containing valid inline LateX. alt : str The alt text to use for the HTML. """ base64_data = latex_to_png(s, encode=True) if base64_data: return _data_uri_template_png % (base64_data, alt)
def latex_to_html(s, alt='image'): """Render LaTeX to HTML with embedded PNG data using data URIs. Parameters ---------- s : str The raw string containing valid inline LateX. alt : str The alt text to use for the HTML. """ base64_data = latex_to_png(s, encode=True) if base64_data: return _data_uri_template_png % (base64_data, alt)
[ "Render", "LaTeX", "to", "HTML", "with", "embedded", "PNG", "data", "using", "data", "URIs", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/latextools.py#L121-L133
[ "def", "latex_to_html", "(", "s", ",", "alt", "=", "'image'", ")", ":", "base64_data", "=", "latex_to_png", "(", "s", ",", "encode", "=", "True", ")", "if", "base64_data", ":", "return", "_data_uri_template_png", "%", "(", "base64_data", ",", "alt", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
math_to_image
Given a math expression, renders it in a closely-clipped bounding box to an image file. *s* A math expression. The math portion should be enclosed in dollar signs. *filename_or_obj* A filepath or writable file-like object to write the image data to. *prop* If provided, a FontProperties() object describing the size and style of the text. *dpi* Override the output dpi, otherwise use the default associated with the output format. *format* The output format, eg. 'svg', 'pdf', 'ps' or 'png'. If not provided, will be deduced from the filename.
environment/lib/python2.7/site-packages/IPython/lib/latextools.py
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None): """ Given a math expression, renders it in a closely-clipped bounding box to an image file. *s* A math expression. The math portion should be enclosed in dollar signs. *filename_or_obj* A filepath or writable file-like object to write the image data to. *prop* If provided, a FontProperties() object describing the size and style of the text. *dpi* Override the output dpi, otherwise use the default associated with the output format. *format* The output format, eg. 'svg', 'pdf', 'ps' or 'png'. If not provided, will be deduced from the filename. """ from matplotlib import figure # backend_agg supports all of the core output formats from matplotlib.backends import backend_agg from matplotlib.font_manager import FontProperties from matplotlib.mathtext import MathTextParser if prop is None: prop = FontProperties() parser = MathTextParser('path') width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(figsize=(width / 72.0, height / 72.0)) fig.text(0, depth/height, s, fontproperties=prop) backend_agg.FigureCanvasAgg(fig) fig.savefig(filename_or_obj, dpi=dpi, format=format) return depth
def math_to_image(s, filename_or_obj, prop=None, dpi=None, format=None): """ Given a math expression, renders it in a closely-clipped bounding box to an image file. *s* A math expression. The math portion should be enclosed in dollar signs. *filename_or_obj* A filepath or writable file-like object to write the image data to. *prop* If provided, a FontProperties() object describing the size and style of the text. *dpi* Override the output dpi, otherwise use the default associated with the output format. *format* The output format, eg. 'svg', 'pdf', 'ps' or 'png'. If not provided, will be deduced from the filename. """ from matplotlib import figure # backend_agg supports all of the core output formats from matplotlib.backends import backend_agg from matplotlib.font_manager import FontProperties from matplotlib.mathtext import MathTextParser if prop is None: prop = FontProperties() parser = MathTextParser('path') width, height, depth, _, _ = parser.parse(s, dpi=72, prop=prop) fig = figure.Figure(figsize=(width / 72.0, height / 72.0)) fig.text(0, depth/height, s, fontproperties=prop) backend_agg.FigureCanvasAgg(fig) fig.savefig(filename_or_obj, dpi=dpi, format=format) return depth
[ "Given", "a", "math", "expression", "renders", "it", "in", "a", "closely", "-", "clipped", "bounding", "box", "to", "an", "image", "file", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/lib/latextools.py#L138-L180
[ "def", "math_to_image", "(", "s", ",", "filename_or_obj", ",", "prop", "=", "None", ",", "dpi", "=", "None", ",", "format", "=", "None", ")", ":", "from", "matplotlib", "import", "figure", "# backend_agg supports all of the core output formats", "from", "matplotlib", ".", "backends", "import", "backend_agg", "from", "matplotlib", ".", "font_manager", "import", "FontProperties", "from", "matplotlib", ".", "mathtext", "import", "MathTextParser", "if", "prop", "is", "None", ":", "prop", "=", "FontProperties", "(", ")", "parser", "=", "MathTextParser", "(", "'path'", ")", "width", ",", "height", ",", "depth", ",", "_", ",", "_", "=", "parser", ".", "parse", "(", "s", ",", "dpi", "=", "72", ",", "prop", "=", "prop", ")", "fig", "=", "figure", ".", "Figure", "(", "figsize", "=", "(", "width", "/", "72.0", ",", "height", "/", "72.0", ")", ")", "fig", ".", "text", "(", "0", ",", "depth", "/", "height", ",", "s", ",", "fontproperties", "=", "prop", ")", "backend_agg", ".", "FigureCanvasAgg", "(", "fig", ")", "fig", ".", "savefig", "(", "filename_or_obj", ",", "dpi", "=", "dpi", ",", "format", "=", "format", ")", "return", "depth" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
WheelBuilder.build
Build wheels.
virtualEnvironment/lib/python2.7/site-packages/pip/wheel.py
def build(self): """Build wheels.""" # unpack and constructs req set self.requirement_set.prepare_files(self.finder) reqset = self.requirement_set.requirements.values() buildset = [] for req in reqset: if req.is_wheel: logger.info( 'Skipping %s, due to already being wheel.', req.name, ) elif req.editable: logger.info( 'Skipping %s, due to being editable', req.name, ) else: buildset.append(req) if not buildset: return True # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join([req.name for req in buildset]), ) with indent_log(): build_success, build_failure = [], [] for req in buildset: if self._build_one(req): build_success.append(req) else: build_failure.append(req) # notify success/failure if build_success: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_success]), ) if build_failure: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failure]), ) # Return True if all builds were successful return len(build_failure) == 0
def build(self): """Build wheels.""" # unpack and constructs req set self.requirement_set.prepare_files(self.finder) reqset = self.requirement_set.requirements.values() buildset = [] for req in reqset: if req.is_wheel: logger.info( 'Skipping %s, due to already being wheel.', req.name, ) elif req.editable: logger.info( 'Skipping %s, due to being editable', req.name, ) else: buildset.append(req) if not buildset: return True # Build the wheels. logger.info( 'Building wheels for collected packages: %s', ', '.join([req.name for req in buildset]), ) with indent_log(): build_success, build_failure = [], [] for req in buildset: if self._build_one(req): build_success.append(req) else: build_failure.append(req) # notify success/failure if build_success: logger.info( 'Successfully built %s', ' '.join([req.name for req in build_success]), ) if build_failure: logger.info( 'Failed to build %s', ' '.join([req.name for req in build_failure]), ) # Return True if all builds were successful return len(build_failure) == 0
[ "Build", "wheels", "." ]
tnkteja/myhelp
python
https://github.com/tnkteja/myhelp/blob/fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb/virtualEnvironment/lib/python2.7/site-packages/pip/wheel.py#L572-L621
[ "def", "build", "(", "self", ")", ":", "# unpack and constructs req set", "self", ".", "requirement_set", ".", "prepare_files", "(", "self", ".", "finder", ")", "reqset", "=", "self", ".", "requirement_set", ".", "requirements", ".", "values", "(", ")", "buildset", "=", "[", "]", "for", "req", "in", "reqset", ":", "if", "req", ".", "is_wheel", ":", "logger", ".", "info", "(", "'Skipping %s, due to already being wheel.'", ",", "req", ".", "name", ",", ")", "elif", "req", ".", "editable", ":", "logger", ".", "info", "(", "'Skipping %s, due to being editable'", ",", "req", ".", "name", ",", ")", "else", ":", "buildset", ".", "append", "(", "req", ")", "if", "not", "buildset", ":", "return", "True", "# Build the wheels.", "logger", ".", "info", "(", "'Building wheels for collected packages: %s'", ",", "', '", ".", "join", "(", "[", "req", ".", "name", "for", "req", "in", "buildset", "]", ")", ",", ")", "with", "indent_log", "(", ")", ":", "build_success", ",", "build_failure", "=", "[", "]", ",", "[", "]", "for", "req", "in", "buildset", ":", "if", "self", ".", "_build_one", "(", "req", ")", ":", "build_success", ".", "append", "(", "req", ")", "else", ":", "build_failure", ".", "append", "(", "req", ")", "# notify success/failure", "if", "build_success", ":", "logger", ".", "info", "(", "'Successfully built %s'", ",", "' '", ".", "join", "(", "[", "req", ".", "name", "for", "req", "in", "build_success", "]", ")", ",", ")", "if", "build_failure", ":", "logger", ".", "info", "(", "'Failed to build %s'", ",", "' '", ".", "join", "(", "[", "req", ".", "name", "for", "req", "in", "build_failure", "]", ")", ",", ")", "# Return True if all builds were successful", "return", "len", "(", "build_failure", ")", "==", "0" ]
fb3a4809d448ad14d5b2e6ddf2e7e89ad52b71cb
test
parse_editable
Parses svn+http://blahblah@rev#egg=Foobar into a requirement (Foobar) and a URL
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py
def parse_editable(editable_req, default_vcs=None): """Parses svn+http://blahblah@rev#egg=Foobar into a requirement (Foobar) and a URL""" url = editable_req extras = None # If a file path is specified with extras, strip off the extras. m = re.match(r'^(.+)(\[[^\]]+\])$', url) if m: url_no_extras = m.group(1) extras = m.group(2) else: url_no_extras = url if os.path.isdir(url_no_extras): if not os.path.exists(os.path.join(url_no_extras, 'setup.py')): raise InstallationError("Directory %r is not installable. File 'setup.py' not found.", url_no_extras) # Treating it as code that has already been checked out url_no_extras = path_to_url(url_no_extras) if url_no_extras.lower().startswith('file:'): if extras: return None, url_no_extras, pkg_resources.Requirement.parse('__placeholder__' + extras).extras else: return None, url_no_extras, None for version_control in vcs: if url.lower().startswith('%s:' % version_control): url = '%s+%s' % (version_control, url) if '+' not in url: if default_vcs: url = default_vcs + '+' + url else: raise InstallationError( '--editable=%s should be formatted with svn+URL, git+URL, hg+URL or bzr+URL' % editable_req) vc_type = url.split('+', 1)[0].lower() if not vcs.get_backend(vc_type): error_message = 'For --editable=%s only ' % editable_req + \ ', '.join([backend.name + '+URL' for backend in vcs.backends]) + \ ' is currently supported' raise InstallationError(error_message) match = re.search(r'(?:#|#.*?&)egg=([^&]*)', editable_req) if (not match or not match.group(1)) and vcs.get_backend(vc_type): parts = [p for p in editable_req.split('#', 1)[0].split('/') if p] if parts[-2] in ('tags', 'branches', 'tag', 'branch'): req = parts[-3] elif parts[-1] == 'trunk': req = parts[-2] else: raise InstallationError( '--editable=%s is not the right format; it must have #egg=Package' % editable_req) else: req = match.group(1) ## FIXME: use package_to_requirement? match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req) if match: # Strip off -dev, -0.2, etc. req = match.group(1) return req, url, None
def parse_editable(editable_req, default_vcs=None): """Parses svn+http://blahblah@rev#egg=Foobar into a requirement (Foobar) and a URL""" url = editable_req extras = None # If a file path is specified with extras, strip off the extras. m = re.match(r'^(.+)(\[[^\]]+\])$', url) if m: url_no_extras = m.group(1) extras = m.group(2) else: url_no_extras = url if os.path.isdir(url_no_extras): if not os.path.exists(os.path.join(url_no_extras, 'setup.py')): raise InstallationError("Directory %r is not installable. File 'setup.py' not found.", url_no_extras) # Treating it as code that has already been checked out url_no_extras = path_to_url(url_no_extras) if url_no_extras.lower().startswith('file:'): if extras: return None, url_no_extras, pkg_resources.Requirement.parse('__placeholder__' + extras).extras else: return None, url_no_extras, None for version_control in vcs: if url.lower().startswith('%s:' % version_control): url = '%s+%s' % (version_control, url) if '+' not in url: if default_vcs: url = default_vcs + '+' + url else: raise InstallationError( '--editable=%s should be formatted with svn+URL, git+URL, hg+URL or bzr+URL' % editable_req) vc_type = url.split('+', 1)[0].lower() if not vcs.get_backend(vc_type): error_message = 'For --editable=%s only ' % editable_req + \ ', '.join([backend.name + '+URL' for backend in vcs.backends]) + \ ' is currently supported' raise InstallationError(error_message) match = re.search(r'(?:#|#.*?&)egg=([^&]*)', editable_req) if (not match or not match.group(1)) and vcs.get_backend(vc_type): parts = [p for p in editable_req.split('#', 1)[0].split('/') if p] if parts[-2] in ('tags', 'branches', 'tag', 'branch'): req = parts[-3] elif parts[-1] == 'trunk': req = parts[-2] else: raise InstallationError( '--editable=%s is not the right format; it must have #egg=Package' % editable_req) else: req = match.group(1) ## FIXME: use package_to_requirement? match = re.search(r'^(.*?)(?:-dev|-\d.*)$', req) if match: # Strip off -dev, -0.2, etc. req = match.group(1) return req, url, None
[ "Parses", "svn", "+", "http", ":", "//", "blahblah" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py#L1334-L1394
[ "def", "parse_editable", "(", "editable_req", ",", "default_vcs", "=", "None", ")", ":", "url", "=", "editable_req", "extras", "=", "None", "# If a file path is specified with extras, strip off the extras.", "m", "=", "re", ".", "match", "(", "r'^(.+)(\\[[^\\]]+\\])$'", ",", "url", ")", "if", "m", ":", "url_no_extras", "=", "m", ".", "group", "(", "1", ")", "extras", "=", "m", ".", "group", "(", "2", ")", "else", ":", "url_no_extras", "=", "url", "if", "os", ".", "path", ".", "isdir", "(", "url_no_extras", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "os", ".", "path", ".", "join", "(", "url_no_extras", ",", "'setup.py'", ")", ")", ":", "raise", "InstallationError", "(", "\"Directory %r is not installable. File 'setup.py' not found.\"", ",", "url_no_extras", ")", "# Treating it as code that has already been checked out", "url_no_extras", "=", "path_to_url", "(", "url_no_extras", ")", "if", "url_no_extras", ".", "lower", "(", ")", ".", "startswith", "(", "'file:'", ")", ":", "if", "extras", ":", "return", "None", ",", "url_no_extras", ",", "pkg_resources", ".", "Requirement", ".", "parse", "(", "'__placeholder__'", "+", "extras", ")", ".", "extras", "else", ":", "return", "None", ",", "url_no_extras", ",", "None", "for", "version_control", "in", "vcs", ":", "if", "url", ".", "lower", "(", ")", ".", "startswith", "(", "'%s:'", "%", "version_control", ")", ":", "url", "=", "'%s+%s'", "%", "(", "version_control", ",", "url", ")", "if", "'+'", "not", "in", "url", ":", "if", "default_vcs", ":", "url", "=", "default_vcs", "+", "'+'", "+", "url", "else", ":", "raise", "InstallationError", "(", "'--editable=%s should be formatted with svn+URL, git+URL, hg+URL or bzr+URL'", "%", "editable_req", ")", "vc_type", "=", "url", ".", "split", "(", "'+'", ",", "1", ")", "[", "0", "]", ".", "lower", "(", ")", "if", "not", "vcs", ".", "get_backend", "(", "vc_type", ")", ":", "error_message", "=", "'For --editable=%s only '", "%", "editable_req", "+", "', '", ".", "join", "(", "[", "backend", ".", "name", "+", "'+URL'", "for", "backend", "in", "vcs", ".", "backends", "]", ")", "+", "' is currently supported'", "raise", "InstallationError", "(", "error_message", ")", "match", "=", "re", ".", "search", "(", "r'(?:#|#.*?&)egg=([^&]*)'", ",", "editable_req", ")", "if", "(", "not", "match", "or", "not", "match", ".", "group", "(", "1", ")", ")", "and", "vcs", ".", "get_backend", "(", "vc_type", ")", ":", "parts", "=", "[", "p", "for", "p", "in", "editable_req", ".", "split", "(", "'#'", ",", "1", ")", "[", "0", "]", ".", "split", "(", "'/'", ")", "if", "p", "]", "if", "parts", "[", "-", "2", "]", "in", "(", "'tags'", ",", "'branches'", ",", "'tag'", ",", "'branch'", ")", ":", "req", "=", "parts", "[", "-", "3", "]", "elif", "parts", "[", "-", "1", "]", "==", "'trunk'", ":", "req", "=", "parts", "[", "-", "2", "]", "else", ":", "raise", "InstallationError", "(", "'--editable=%s is not the right format; it must have #egg=Package'", "%", "editable_req", ")", "else", ":", "req", "=", "match", ".", "group", "(", "1", ")", "## FIXME: use package_to_requirement?", "match", "=", "re", ".", "search", "(", "r'^(.*?)(?:-dev|-\\d.*)$'", ",", "req", ")", "if", "match", ":", "# Strip off -dev, -0.2, etc.", "req", "=", "match", ".", "group", "(", "1", ")", "return", "req", ",", "url", ",", "None" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InstallRequirement.uninstall
Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv is linked to global site-packages.
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py
def uninstall(self, auto_confirm=False): """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv is linked to global site-packages. """ if not self.check_if_exists(): raise UninstallationError("Cannot uninstall requirement %s, not installed" % (self.name,)) dist = self.satisfied_by or self.conflicts_with paths_to_remove = UninstallPathSet(dist) pip_egg_info_path = os.path.join(dist.location, dist.egg_name()) + '.egg-info' # workaround for http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=618367 debian_egg_info_path = pip_egg_info_path.replace( '-py%s' % pkg_resources.PY_MAJOR, '') easy_install_egg = dist.egg_name() + '.egg' develop_egg_link = egg_link_path(dist) pip_egg_info_exists = os.path.exists(pip_egg_info_path) debian_egg_info_exists = os.path.exists(debian_egg_info_path) if pip_egg_info_exists or debian_egg_info_exists: # package installed by pip if pip_egg_info_exists: egg_info_path = pip_egg_info_path else: egg_info_path = debian_egg_info_path paths_to_remove.add(egg_info_path) if dist.has_metadata('installed-files.txt'): for installed_file in dist.get_metadata('installed-files.txt').splitlines(): path = os.path.normpath(os.path.join(egg_info_path, installed_file)) paths_to_remove.add(path) #FIXME: need a test for this elif block #occurs with --single-version-externally-managed/--record outside of pip elif dist.has_metadata('top_level.txt'): if dist.has_metadata('namespace_packages.txt'): namespaces = dist.get_metadata('namespace_packages.txt') else: namespaces = [] for top_level_pkg in [p for p in dist.get_metadata('top_level.txt').splitlines() if p and p not in namespaces]: path = os.path.join(dist.location, top_level_pkg) paths_to_remove.add(path) paths_to_remove.add(path + '.py') paths_to_remove.add(path + '.pyc') elif dist.location.endswith(easy_install_egg): # package installed by easy_install paths_to_remove.add(dist.location) easy_install_pth = os.path.join(os.path.dirname(dist.location), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg) elif develop_egg_link: # develop egg fh = open(develop_egg_link, 'r') link_pointer = os.path.normcase(fh.readline().strip()) fh.close() assert (link_pointer == dist.location), 'Egg-link %s does not match installed location of %s (at %s)' % (link_pointer, self.name, dist.location) paths_to_remove.add(develop_egg_link) easy_install_pth = os.path.join(os.path.dirname(develop_egg_link), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, dist.location) # find distutils scripts= scripts if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'): for script in dist.metadata_listdir('scripts'): paths_to_remove.add(os.path.join(bin_py, script)) if sys.platform == 'win32': paths_to_remove.add(os.path.join(bin_py, script) + '.bat') # find console_scripts if dist.has_metadata('entry_points.txt'): config = ConfigParser.SafeConfigParser() config.readfp(FakeFile(dist.get_metadata_lines('entry_points.txt'))) if config.has_section('console_scripts'): for name, value in config.items('console_scripts'): paths_to_remove.add(os.path.join(bin_py, name)) if sys.platform == 'win32': paths_to_remove.add(os.path.join(bin_py, name) + '.exe') paths_to_remove.add(os.path.join(bin_py, name) + '.exe.manifest') paths_to_remove.add(os.path.join(bin_py, name) + '-script.py') paths_to_remove.remove(auto_confirm) self.uninstalled = paths_to_remove
def uninstall(self, auto_confirm=False): """ Uninstall the distribution currently satisfying this requirement. Prompts before removing or modifying files unless ``auto_confirm`` is True. Refuses to delete or modify files outside of ``sys.prefix`` - thus uninstallation within a virtual environment can only modify that virtual environment, even if the virtualenv is linked to global site-packages. """ if not self.check_if_exists(): raise UninstallationError("Cannot uninstall requirement %s, not installed" % (self.name,)) dist = self.satisfied_by or self.conflicts_with paths_to_remove = UninstallPathSet(dist) pip_egg_info_path = os.path.join(dist.location, dist.egg_name()) + '.egg-info' # workaround for http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=618367 debian_egg_info_path = pip_egg_info_path.replace( '-py%s' % pkg_resources.PY_MAJOR, '') easy_install_egg = dist.egg_name() + '.egg' develop_egg_link = egg_link_path(dist) pip_egg_info_exists = os.path.exists(pip_egg_info_path) debian_egg_info_exists = os.path.exists(debian_egg_info_path) if pip_egg_info_exists or debian_egg_info_exists: # package installed by pip if pip_egg_info_exists: egg_info_path = pip_egg_info_path else: egg_info_path = debian_egg_info_path paths_to_remove.add(egg_info_path) if dist.has_metadata('installed-files.txt'): for installed_file in dist.get_metadata('installed-files.txt').splitlines(): path = os.path.normpath(os.path.join(egg_info_path, installed_file)) paths_to_remove.add(path) #FIXME: need a test for this elif block #occurs with --single-version-externally-managed/--record outside of pip elif dist.has_metadata('top_level.txt'): if dist.has_metadata('namespace_packages.txt'): namespaces = dist.get_metadata('namespace_packages.txt') else: namespaces = [] for top_level_pkg in [p for p in dist.get_metadata('top_level.txt').splitlines() if p and p not in namespaces]: path = os.path.join(dist.location, top_level_pkg) paths_to_remove.add(path) paths_to_remove.add(path + '.py') paths_to_remove.add(path + '.pyc') elif dist.location.endswith(easy_install_egg): # package installed by easy_install paths_to_remove.add(dist.location) easy_install_pth = os.path.join(os.path.dirname(dist.location), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, './' + easy_install_egg) elif develop_egg_link: # develop egg fh = open(develop_egg_link, 'r') link_pointer = os.path.normcase(fh.readline().strip()) fh.close() assert (link_pointer == dist.location), 'Egg-link %s does not match installed location of %s (at %s)' % (link_pointer, self.name, dist.location) paths_to_remove.add(develop_egg_link) easy_install_pth = os.path.join(os.path.dirname(develop_egg_link), 'easy-install.pth') paths_to_remove.add_pth(easy_install_pth, dist.location) # find distutils scripts= scripts if dist.has_metadata('scripts') and dist.metadata_isdir('scripts'): for script in dist.metadata_listdir('scripts'): paths_to_remove.add(os.path.join(bin_py, script)) if sys.platform == 'win32': paths_to_remove.add(os.path.join(bin_py, script) + '.bat') # find console_scripts if dist.has_metadata('entry_points.txt'): config = ConfigParser.SafeConfigParser() config.readfp(FakeFile(dist.get_metadata_lines('entry_points.txt'))) if config.has_section('console_scripts'): for name, value in config.items('console_scripts'): paths_to_remove.add(os.path.join(bin_py, name)) if sys.platform == 'win32': paths_to_remove.add(os.path.join(bin_py, name) + '.exe') paths_to_remove.add(os.path.join(bin_py, name) + '.exe.manifest') paths_to_remove.add(os.path.join(bin_py, name) + '-script.py') paths_to_remove.remove(auto_confirm) self.uninstalled = paths_to_remove
[ "Uninstall", "the", "distribution", "currently", "satisfying", "this", "requirement", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py#L403-L496
[ "def", "uninstall", "(", "self", ",", "auto_confirm", "=", "False", ")", ":", "if", "not", "self", ".", "check_if_exists", "(", ")", ":", "raise", "UninstallationError", "(", "\"Cannot uninstall requirement %s, not installed\"", "%", "(", "self", ".", "name", ",", ")", ")", "dist", "=", "self", ".", "satisfied_by", "or", "self", ".", "conflicts_with", "paths_to_remove", "=", "UninstallPathSet", "(", "dist", ")", "pip_egg_info_path", "=", "os", ".", "path", ".", "join", "(", "dist", ".", "location", ",", "dist", ".", "egg_name", "(", ")", ")", "+", "'.egg-info'", "# workaround for http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=618367", "debian_egg_info_path", "=", "pip_egg_info_path", ".", "replace", "(", "'-py%s'", "%", "pkg_resources", ".", "PY_MAJOR", ",", "''", ")", "easy_install_egg", "=", "dist", ".", "egg_name", "(", ")", "+", "'.egg'", "develop_egg_link", "=", "egg_link_path", "(", "dist", ")", "pip_egg_info_exists", "=", "os", ".", "path", ".", "exists", "(", "pip_egg_info_path", ")", "debian_egg_info_exists", "=", "os", ".", "path", ".", "exists", "(", "debian_egg_info_path", ")", "if", "pip_egg_info_exists", "or", "debian_egg_info_exists", ":", "# package installed by pip", "if", "pip_egg_info_exists", ":", "egg_info_path", "=", "pip_egg_info_path", "else", ":", "egg_info_path", "=", "debian_egg_info_path", "paths_to_remove", ".", "add", "(", "egg_info_path", ")", "if", "dist", ".", "has_metadata", "(", "'installed-files.txt'", ")", ":", "for", "installed_file", "in", "dist", ".", "get_metadata", "(", "'installed-files.txt'", ")", ".", "splitlines", "(", ")", ":", "path", "=", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "egg_info_path", ",", "installed_file", ")", ")", "paths_to_remove", ".", "add", "(", "path", ")", "#FIXME: need a test for this elif block", "#occurs with --single-version-externally-managed/--record outside of pip", "elif", "dist", ".", "has_metadata", "(", "'top_level.txt'", ")", ":", "if", "dist", ".", "has_metadata", "(", "'namespace_packages.txt'", ")", ":", "namespaces", "=", "dist", ".", "get_metadata", "(", "'namespace_packages.txt'", ")", "else", ":", "namespaces", "=", "[", "]", "for", "top_level_pkg", "in", "[", "p", "for", "p", "in", "dist", ".", "get_metadata", "(", "'top_level.txt'", ")", ".", "splitlines", "(", ")", "if", "p", "and", "p", "not", "in", "namespaces", "]", ":", "path", "=", "os", ".", "path", ".", "join", "(", "dist", ".", "location", ",", "top_level_pkg", ")", "paths_to_remove", ".", "add", "(", "path", ")", "paths_to_remove", ".", "add", "(", "path", "+", "'.py'", ")", "paths_to_remove", ".", "add", "(", "path", "+", "'.pyc'", ")", "elif", "dist", ".", "location", ".", "endswith", "(", "easy_install_egg", ")", ":", "# package installed by easy_install", "paths_to_remove", ".", "add", "(", "dist", ".", "location", ")", "easy_install_pth", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "dist", ".", "location", ")", ",", "'easy-install.pth'", ")", "paths_to_remove", ".", "add_pth", "(", "easy_install_pth", ",", "'./'", "+", "easy_install_egg", ")", "elif", "develop_egg_link", ":", "# develop egg", "fh", "=", "open", "(", "develop_egg_link", ",", "'r'", ")", "link_pointer", "=", "os", ".", "path", ".", "normcase", "(", "fh", ".", "readline", "(", ")", ".", "strip", "(", ")", ")", "fh", ".", "close", "(", ")", "assert", "(", "link_pointer", "==", "dist", ".", "location", ")", ",", "'Egg-link %s does not match installed location of %s (at %s)'", "%", "(", "link_pointer", ",", "self", ".", "name", ",", "dist", ".", "location", ")", "paths_to_remove", ".", "add", "(", "develop_egg_link", ")", "easy_install_pth", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "develop_egg_link", ")", ",", "'easy-install.pth'", ")", "paths_to_remove", ".", "add_pth", "(", "easy_install_pth", ",", "dist", ".", "location", ")", "# find distutils scripts= scripts", "if", "dist", ".", "has_metadata", "(", "'scripts'", ")", "and", "dist", ".", "metadata_isdir", "(", "'scripts'", ")", ":", "for", "script", "in", "dist", ".", "metadata_listdir", "(", "'scripts'", ")", ":", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_py", ",", "script", ")", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_py", ",", "script", ")", "+", "'.bat'", ")", "# find console_scripts", "if", "dist", ".", "has_metadata", "(", "'entry_points.txt'", ")", ":", "config", "=", "ConfigParser", ".", "SafeConfigParser", "(", ")", "config", ".", "readfp", "(", "FakeFile", "(", "dist", ".", "get_metadata_lines", "(", "'entry_points.txt'", ")", ")", ")", "if", "config", ".", "has_section", "(", "'console_scripts'", ")", ":", "for", "name", ",", "value", "in", "config", ".", "items", "(", "'console_scripts'", ")", ":", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_py", ",", "name", ")", ")", "if", "sys", ".", "platform", "==", "'win32'", ":", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_py", ",", "name", ")", "+", "'.exe'", ")", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_py", ",", "name", ")", "+", "'.exe.manifest'", ")", "paths_to_remove", ".", "add", "(", "os", ".", "path", ".", "join", "(", "bin_py", ",", "name", ")", "+", "'-script.py'", ")", "paths_to_remove", ".", "remove", "(", "auto_confirm", ")", "self", ".", "uninstalled", "=", "paths_to_remove" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
InstallRequirement.check_if_exists
Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py
def check_if_exists(self): """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.""" if self.req is None: return False try: self.satisfied_by = pkg_resources.get_distribution(self.req) except pkg_resources.DistributionNotFound: return False except pkg_resources.VersionConflict: existing_dist = pkg_resources.get_distribution(self.req.project_name) if self.use_user_site: if dist_in_usersite(existing_dist): self.conflicts_with = existing_dist elif running_under_virtualenv() and dist_in_site_packages(existing_dist): raise InstallationError("Will not install to the user site because it will lack sys.path precedence to %s in %s" %(existing_dist.project_name, existing_dist.location)) else: self.conflicts_with = existing_dist return True
def check_if_exists(self): """Find an installed distribution that satisfies or conflicts with this requirement, and set self.satisfied_by or self.conflicts_with appropriately.""" if self.req is None: return False try: self.satisfied_by = pkg_resources.get_distribution(self.req) except pkg_resources.DistributionNotFound: return False except pkg_resources.VersionConflict: existing_dist = pkg_resources.get_distribution(self.req.project_name) if self.use_user_site: if dist_in_usersite(existing_dist): self.conflicts_with = existing_dist elif running_under_virtualenv() and dist_in_site_packages(existing_dist): raise InstallationError("Will not install to the user site because it will lack sys.path precedence to %s in %s" %(existing_dist.project_name, existing_dist.location)) else: self.conflicts_with = existing_dist return True
[ "Find", "an", "installed", "distribution", "that", "satisfies", "or", "conflicts", "with", "this", "requirement", "and", "set", "self", ".", "satisfied_by", "or", "self", ".", "conflicts_with", "appropriately", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py#L669-L689
[ "def", "check_if_exists", "(", "self", ")", ":", "if", "self", ".", "req", "is", "None", ":", "return", "False", "try", ":", "self", ".", "satisfied_by", "=", "pkg_resources", ".", "get_distribution", "(", "self", ".", "req", ")", "except", "pkg_resources", ".", "DistributionNotFound", ":", "return", "False", "except", "pkg_resources", ".", "VersionConflict", ":", "existing_dist", "=", "pkg_resources", ".", "get_distribution", "(", "self", ".", "req", ".", "project_name", ")", "if", "self", ".", "use_user_site", ":", "if", "dist_in_usersite", "(", "existing_dist", ")", ":", "self", ".", "conflicts_with", "=", "existing_dist", "elif", "running_under_virtualenv", "(", ")", "and", "dist_in_site_packages", "(", "existing_dist", ")", ":", "raise", "InstallationError", "(", "\"Will not install to the user site because it will lack sys.path precedence to %s in %s\"", "%", "(", "existing_dist", ".", "project_name", ",", "existing_dist", ".", "location", ")", ")", "else", ":", "self", ".", "conflicts_with", "=", "existing_dist", "return", "True" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RequirementSet.cleanup_files
Clean up files, remove builds.
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py
def cleanup_files(self, bundle=False): """Clean up files, remove builds.""" logger.notify('Cleaning up...') logger.indent += 2 for req in self.reqs_to_cleanup: req.remove_temporary_source() remove_dir = [] if self._pip_has_created_build_dir(): remove_dir.append(self.build_dir) # The source dir of a bundle can always be removed. # FIXME: not if it pre-existed the bundle! if bundle: remove_dir.append(self.src_dir) for dir in remove_dir: if os.path.exists(dir): logger.info('Removing temporary dir %s...' % dir) rmtree(dir) logger.indent -= 2
def cleanup_files(self, bundle=False): """Clean up files, remove builds.""" logger.notify('Cleaning up...') logger.indent += 2 for req in self.reqs_to_cleanup: req.remove_temporary_source() remove_dir = [] if self._pip_has_created_build_dir(): remove_dir.append(self.build_dir) # The source dir of a bundle can always be removed. # FIXME: not if it pre-existed the bundle! if bundle: remove_dir.append(self.src_dir) for dir in remove_dir: if os.path.exists(dir): logger.info('Removing temporary dir %s...' % dir) rmtree(dir) logger.indent -= 2
[ "Clean", "up", "files", "remove", "builds", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py#L1095-L1116
[ "def", "cleanup_files", "(", "self", ",", "bundle", "=", "False", ")", ":", "logger", ".", "notify", "(", "'Cleaning up...'", ")", "logger", ".", "indent", "+=", "2", "for", "req", "in", "self", ".", "reqs_to_cleanup", ":", "req", ".", "remove_temporary_source", "(", ")", "remove_dir", "=", "[", "]", "if", "self", ".", "_pip_has_created_build_dir", "(", ")", ":", "remove_dir", ".", "append", "(", "self", ".", "build_dir", ")", "# The source dir of a bundle can always be removed.", "# FIXME: not if it pre-existed the bundle!", "if", "bundle", ":", "remove_dir", ".", "append", "(", "self", ".", "src_dir", ")", "for", "dir", "in", "remove_dir", ":", "if", "os", ".", "path", ".", "exists", "(", "dir", ")", ":", "logger", ".", "info", "(", "'Removing temporary dir %s...'", "%", "dir", ")", "rmtree", "(", "dir", ")", "logger", ".", "indent", "-=", "2" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
RequirementSet.install
Install everything in this set (after having downloaded and unpacked the packages)
environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py
def install(self, install_options, global_options=()): """Install everything in this set (after having downloaded and unpacked the packages)""" to_install = [r for r in self.requirements.values() if not r.satisfied_by] if to_install: logger.notify('Installing collected packages: %s' % ', '.join([req.name for req in to_install])) logger.indent += 2 try: for requirement in to_install: if requirement.conflicts_with: logger.notify('Found existing installation: %s' % requirement.conflicts_with) logger.indent += 2 try: requirement.uninstall(auto_confirm=True) finally: logger.indent -= 2 try: requirement.install(install_options, global_options) except: # if install did not succeed, rollback previous uninstall if requirement.conflicts_with and not requirement.install_succeeded: requirement.rollback_uninstall() raise else: if requirement.conflicts_with and requirement.install_succeeded: requirement.commit_uninstall() requirement.remove_temporary_source() finally: logger.indent -= 2 self.successfully_installed = to_install
def install(self, install_options, global_options=()): """Install everything in this set (after having downloaded and unpacked the packages)""" to_install = [r for r in self.requirements.values() if not r.satisfied_by] if to_install: logger.notify('Installing collected packages: %s' % ', '.join([req.name for req in to_install])) logger.indent += 2 try: for requirement in to_install: if requirement.conflicts_with: logger.notify('Found existing installation: %s' % requirement.conflicts_with) logger.indent += 2 try: requirement.uninstall(auto_confirm=True) finally: logger.indent -= 2 try: requirement.install(install_options, global_options) except: # if install did not succeed, rollback previous uninstall if requirement.conflicts_with and not requirement.install_succeeded: requirement.rollback_uninstall() raise else: if requirement.conflicts_with and requirement.install_succeeded: requirement.commit_uninstall() requirement.remove_temporary_source() finally: logger.indent -= 2 self.successfully_installed = to_install
[ "Install", "everything", "in", "this", "set", "(", "after", "having", "downloaded", "and", "unpacked", "the", "packages", ")" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/pip-1.2.1-py2.7.egg/pip/req.py#L1147-L1178
[ "def", "install", "(", "self", ",", "install_options", ",", "global_options", "=", "(", ")", ")", ":", "to_install", "=", "[", "r", "for", "r", "in", "self", ".", "requirements", ".", "values", "(", ")", "if", "not", "r", ".", "satisfied_by", "]", "if", "to_install", ":", "logger", ".", "notify", "(", "'Installing collected packages: %s'", "%", "', '", ".", "join", "(", "[", "req", ".", "name", "for", "req", "in", "to_install", "]", ")", ")", "logger", ".", "indent", "+=", "2", "try", ":", "for", "requirement", "in", "to_install", ":", "if", "requirement", ".", "conflicts_with", ":", "logger", ".", "notify", "(", "'Found existing installation: %s'", "%", "requirement", ".", "conflicts_with", ")", "logger", ".", "indent", "+=", "2", "try", ":", "requirement", ".", "uninstall", "(", "auto_confirm", "=", "True", ")", "finally", ":", "logger", ".", "indent", "-=", "2", "try", ":", "requirement", ".", "install", "(", "install_options", ",", "global_options", ")", "except", ":", "# if install did not succeed, rollback previous uninstall", "if", "requirement", ".", "conflicts_with", "and", "not", "requirement", ".", "install_succeeded", ":", "requirement", ".", "rollback_uninstall", "(", ")", "raise", "else", ":", "if", "requirement", ".", "conflicts_with", "and", "requirement", ".", "install_succeeded", ":", "requirement", ".", "commit_uninstall", "(", ")", "requirement", ".", "remove_temporary_source", "(", ")", "finally", ":", "logger", ".", "indent", "-=", "2", "self", ".", "successfully_installed", "=", "to_install" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
process_iter
Return a generator yielding a Process class instance for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. The sorting order in which processes are yielded is based on their PIDs.
environment/lib/python2.7/site-packages/psutil/__init__.py
def process_iter(): """Return a generator yielding a Process class instance for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. The sorting order in which processes are yielded is based on their PIDs. """ def add(pid): proc = Process(pid) _pmap[proc.pid] = proc return proc def remove(pid): _pmap.pop(pid, None) a = set(get_pid_list()) b = set(_pmap.keys()) new_pids = a - b gone_pids = b - a for pid in gone_pids: remove(pid) for pid, proc in sorted(list(_pmap.items()) + \ list(dict.fromkeys(new_pids).items())): try: if proc is None: # new process yield add(pid) else: # use is_running() to check whether PID has been reused by # another process in which case yield a new Process instance if proc.is_running(): yield proc else: yield add(pid) except NoSuchProcess: remove(pid) except AccessDenied: # Process creation time can't be determined hence there's # no way to tell whether the pid of the cached process # has been reused. Just return the cached version. yield proc
def process_iter(): """Return a generator yielding a Process class instance for all running processes on the local machine. Every new Process instance is only created once and then cached into an internal table which is updated every time this is used. The sorting order in which processes are yielded is based on their PIDs. """ def add(pid): proc = Process(pid) _pmap[proc.pid] = proc return proc def remove(pid): _pmap.pop(pid, None) a = set(get_pid_list()) b = set(_pmap.keys()) new_pids = a - b gone_pids = b - a for pid in gone_pids: remove(pid) for pid, proc in sorted(list(_pmap.items()) + \ list(dict.fromkeys(new_pids).items())): try: if proc is None: # new process yield add(pid) else: # use is_running() to check whether PID has been reused by # another process in which case yield a new Process instance if proc.is_running(): yield proc else: yield add(pid) except NoSuchProcess: remove(pid) except AccessDenied: # Process creation time can't be determined hence there's # no way to tell whether the pid of the cached process # has been reused. Just return the cached version. yield proc
[ "Return", "a", "generator", "yielding", "a", "Process", "class", "instance", "for", "all", "running", "processes", "on", "the", "local", "machine", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L792-L835
[ "def", "process_iter", "(", ")", ":", "def", "add", "(", "pid", ")", ":", "proc", "=", "Process", "(", "pid", ")", "_pmap", "[", "proc", ".", "pid", "]", "=", "proc", "return", "proc", "def", "remove", "(", "pid", ")", ":", "_pmap", ".", "pop", "(", "pid", ",", "None", ")", "a", "=", "set", "(", "get_pid_list", "(", ")", ")", "b", "=", "set", "(", "_pmap", ".", "keys", "(", ")", ")", "new_pids", "=", "a", "-", "b", "gone_pids", "=", "b", "-", "a", "for", "pid", "in", "gone_pids", ":", "remove", "(", "pid", ")", "for", "pid", ",", "proc", "in", "sorted", "(", "list", "(", "_pmap", ".", "items", "(", ")", ")", "+", "list", "(", "dict", ".", "fromkeys", "(", "new_pids", ")", ".", "items", "(", ")", ")", ")", ":", "try", ":", "if", "proc", "is", "None", ":", "# new process", "yield", "add", "(", "pid", ")", "else", ":", "# use is_running() to check whether PID has been reused by", "# another process in which case yield a new Process instance", "if", "proc", ".", "is_running", "(", ")", ":", "yield", "proc", "else", ":", "yield", "add", "(", "pid", ")", "except", "NoSuchProcess", ":", "remove", "(", "pid", ")", "except", "AccessDenied", ":", "# Process creation time can't be determined hence there's", "# no way to tell whether the pid of the cached process", "# has been reused. Just return the cached version.", "yield", "proc" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
cpu_percent
Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls.
environment/lib/python2.7/site-packages/psutil/__init__.py
def cpu_percent(interval=0.1, percpu=False): """Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. """ global _last_cpu_times global _last_per_cpu_times blocking = interval is not None and interval > 0.0 def calculate(t1, t2): t1_all = sum(t1) t1_busy = t1_all - t1.idle t2_all = sum(t2) t2_busy = t2_all - t2.idle # this usually indicates a float precision issue if t2_busy <= t1_busy: return 0.0 busy_delta = t2_busy - t1_busy all_delta = t2_all - t1_all busy_perc = (busy_delta / all_delta) * 100 return round(busy_perc, 1) # system-wide usage if not percpu: if blocking: t1 = cpu_times() time.sleep(interval) else: t1 = _last_cpu_times _last_cpu_times = cpu_times() return calculate(t1, _last_cpu_times) # per-cpu usage else: ret = [] if blocking: tot1 = cpu_times(percpu=True) time.sleep(interval) else: tot1 = _last_per_cpu_times _last_per_cpu_times = cpu_times(percpu=True) for t1, t2 in zip(tot1, _last_per_cpu_times): ret.append(calculate(t1, t2)) return ret
def cpu_percent(interval=0.1, percpu=False): """Return a float representing the current system-wide CPU utilization as a percentage. When interval is > 0.0 compares system CPU times elapsed before and after the interval (blocking). When interval is 0.0 or None compares system CPU times elapsed since last call or module import, returning immediately. In this case is recommended for accuracy that this function be called with at least 0.1 seconds between calls. When percpu is True returns a list of floats representing the utilization as a percentage for each CPU. First element of the list refers to first CPU, second element to second CPU and so on. The order of the list is consistent across calls. """ global _last_cpu_times global _last_per_cpu_times blocking = interval is not None and interval > 0.0 def calculate(t1, t2): t1_all = sum(t1) t1_busy = t1_all - t1.idle t2_all = sum(t2) t2_busy = t2_all - t2.idle # this usually indicates a float precision issue if t2_busy <= t1_busy: return 0.0 busy_delta = t2_busy - t1_busy all_delta = t2_all - t1_all busy_perc = (busy_delta / all_delta) * 100 return round(busy_perc, 1) # system-wide usage if not percpu: if blocking: t1 = cpu_times() time.sleep(interval) else: t1 = _last_cpu_times _last_cpu_times = cpu_times() return calculate(t1, _last_cpu_times) # per-cpu usage else: ret = [] if blocking: tot1 = cpu_times(percpu=True) time.sleep(interval) else: tot1 = _last_per_cpu_times _last_per_cpu_times = cpu_times(percpu=True) for t1, t2 in zip(tot1, _last_per_cpu_times): ret.append(calculate(t1, t2)) return ret
[ "Return", "a", "float", "representing", "the", "current", "system", "-", "wide", "CPU", "utilization", "as", "a", "percentage", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L868-L926
[ "def", "cpu_percent", "(", "interval", "=", "0.1", ",", "percpu", "=", "False", ")", ":", "global", "_last_cpu_times", "global", "_last_per_cpu_times", "blocking", "=", "interval", "is", "not", "None", "and", "interval", ">", "0.0", "def", "calculate", "(", "t1", ",", "t2", ")", ":", "t1_all", "=", "sum", "(", "t1", ")", "t1_busy", "=", "t1_all", "-", "t1", ".", "idle", "t2_all", "=", "sum", "(", "t2", ")", "t2_busy", "=", "t2_all", "-", "t2", ".", "idle", "# this usually indicates a float precision issue", "if", "t2_busy", "<=", "t1_busy", ":", "return", "0.0", "busy_delta", "=", "t2_busy", "-", "t1_busy", "all_delta", "=", "t2_all", "-", "t1_all", "busy_perc", "=", "(", "busy_delta", "/", "all_delta", ")", "*", "100", "return", "round", "(", "busy_perc", ",", "1", ")", "# system-wide usage", "if", "not", "percpu", ":", "if", "blocking", ":", "t1", "=", "cpu_times", "(", ")", "time", ".", "sleep", "(", "interval", ")", "else", ":", "t1", "=", "_last_cpu_times", "_last_cpu_times", "=", "cpu_times", "(", ")", "return", "calculate", "(", "t1", ",", "_last_cpu_times", ")", "# per-cpu usage", "else", ":", "ret", "=", "[", "]", "if", "blocking", ":", "tot1", "=", "cpu_times", "(", "percpu", "=", "True", ")", "time", ".", "sleep", "(", "interval", ")", "else", ":", "tot1", "=", "_last_per_cpu_times", "_last_per_cpu_times", "=", "cpu_times", "(", "percpu", "=", "True", ")", "for", "t1", ",", "t2", "in", "zip", "(", "tot1", ",", "_last_per_cpu_times", ")", ":", "ret", ".", "append", "(", "calculate", "(", "t1", ",", "t2", ")", ")", "return", "ret" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
disk_io_counters
Return system disk I/O statistics as a namedtuple including the following attributes: - read_count: number of reads - write_count: number of writes - read_bytes: number of bytes read - write_bytes: number of bytes written - read_time: time spent reading from disk (in milliseconds) - write_time: time spent writing to disk (in milliseconds) If perdisk is True return the same information for every physical disk installed on the system as a dictionary with partition names as the keys and the namedutuple described above as the values.
environment/lib/python2.7/site-packages/psutil/__init__.py
def disk_io_counters(perdisk=False): """Return system disk I/O statistics as a namedtuple including the following attributes: - read_count: number of reads - write_count: number of writes - read_bytes: number of bytes read - write_bytes: number of bytes written - read_time: time spent reading from disk (in milliseconds) - write_time: time spent writing to disk (in milliseconds) If perdisk is True return the same information for every physical disk installed on the system as a dictionary with partition names as the keys and the namedutuple described above as the values. """ rawdict = _psplatform.disk_io_counters() if not rawdict: raise RuntimeError("couldn't find any physical disk") if perdisk: for disk, fields in rawdict.items(): rawdict[disk] = _nt_disk_iostat(*fields) return rawdict else: return _nt_disk_iostat(*[sum(x) for x in zip(*rawdict.values())])
def disk_io_counters(perdisk=False): """Return system disk I/O statistics as a namedtuple including the following attributes: - read_count: number of reads - write_count: number of writes - read_bytes: number of bytes read - write_bytes: number of bytes written - read_time: time spent reading from disk (in milliseconds) - write_time: time spent writing to disk (in milliseconds) If perdisk is True return the same information for every physical disk installed on the system as a dictionary with partition names as the keys and the namedutuple described above as the values. """ rawdict = _psplatform.disk_io_counters() if not rawdict: raise RuntimeError("couldn't find any physical disk") if perdisk: for disk, fields in rawdict.items(): rawdict[disk] = _nt_disk_iostat(*fields) return rawdict else: return _nt_disk_iostat(*[sum(x) for x in zip(*rawdict.values())])
[ "Return", "system", "disk", "I", "/", "O", "statistics", "as", "a", "namedtuple", "including", "the", "following", "attributes", ":" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L1023-L1047
[ "def", "disk_io_counters", "(", "perdisk", "=", "False", ")", ":", "rawdict", "=", "_psplatform", ".", "disk_io_counters", "(", ")", "if", "not", "rawdict", ":", "raise", "RuntimeError", "(", "\"couldn't find any physical disk\"", ")", "if", "perdisk", ":", "for", "disk", ",", "fields", "in", "rawdict", ".", "items", "(", ")", ":", "rawdict", "[", "disk", "]", "=", "_nt_disk_iostat", "(", "*", "fields", ")", "return", "rawdict", "else", ":", "return", "_nt_disk_iostat", "(", "*", "[", "sum", "(", "x", ")", "for", "x", "in", "zip", "(", "*", "rawdict", ".", "values", "(", ")", ")", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
network_io_counters
Return network I/O statistics as a namedtuple including the following attributes: - bytes_sent: number of bytes sent - bytes_recv: number of bytes received - packets_sent: number of packets sent - packets_recv: number of packets received - errin: total number of errors while receiving - errout: total number of errors while sending - dropin: total number of incoming packets which were dropped - dropout: total number of outgoing packets which were dropped (always 0 on OSX and BSD) If pernic is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the namedtuple described above as the values.
environment/lib/python2.7/site-packages/psutil/__init__.py
def network_io_counters(pernic=False): """Return network I/O statistics as a namedtuple including the following attributes: - bytes_sent: number of bytes sent - bytes_recv: number of bytes received - packets_sent: number of packets sent - packets_recv: number of packets received - errin: total number of errors while receiving - errout: total number of errors while sending - dropin: total number of incoming packets which were dropped - dropout: total number of outgoing packets which were dropped (always 0 on OSX and BSD) If pernic is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the namedtuple described above as the values. """ rawdict = _psplatform.network_io_counters() if not rawdict: raise RuntimeError("couldn't find any network interface") if pernic: for nic, fields in rawdict.items(): rawdict[nic] = _nt_net_iostat(*fields) return rawdict else: return _nt_net_iostat(*[sum(x) for x in zip(*rawdict.values())])
def network_io_counters(pernic=False): """Return network I/O statistics as a namedtuple including the following attributes: - bytes_sent: number of bytes sent - bytes_recv: number of bytes received - packets_sent: number of packets sent - packets_recv: number of packets received - errin: total number of errors while receiving - errout: total number of errors while sending - dropin: total number of incoming packets which were dropped - dropout: total number of outgoing packets which were dropped (always 0 on OSX and BSD) If pernic is True return the same information for every network interface installed on the system as a dictionary with network interface names as the keys and the namedtuple described above as the values. """ rawdict = _psplatform.network_io_counters() if not rawdict: raise RuntimeError("couldn't find any network interface") if pernic: for nic, fields in rawdict.items(): rawdict[nic] = _nt_net_iostat(*fields) return rawdict else: return _nt_net_iostat(*[sum(x) for x in zip(*rawdict.values())])
[ "Return", "network", "I", "/", "O", "statistics", "as", "a", "namedtuple", "including", "the", "following", "attributes", ":" ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L1053-L1080
[ "def", "network_io_counters", "(", "pernic", "=", "False", ")", ":", "rawdict", "=", "_psplatform", ".", "network_io_counters", "(", ")", "if", "not", "rawdict", ":", "raise", "RuntimeError", "(", "\"couldn't find any network interface\"", ")", "if", "pernic", ":", "for", "nic", ",", "fields", "in", "rawdict", ".", "items", "(", ")", ":", "rawdict", "[", "nic", "]", "=", "_nt_net_iostat", "(", "*", "fields", ")", "return", "rawdict", "else", ":", "return", "_nt_net_iostat", "(", "*", "[", "sum", "(", "x", ")", "for", "x", "in", "zip", "(", "*", "rawdict", ".", "values", "(", ")", ")", "]", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
phymem_usage
Return the amount of total, used and free physical memory on the system in bytes plus the percentage usage. Deprecated by psutil.virtual_memory().
environment/lib/python2.7/site-packages/psutil/__init__.py
def phymem_usage(): """Return the amount of total, used and free physical memory on the system in bytes plus the percentage usage. Deprecated by psutil.virtual_memory(). """ mem = virtual_memory() return _nt_sysmeminfo(mem.total, mem.used, mem.free, mem.percent)
def phymem_usage(): """Return the amount of total, used and free physical memory on the system in bytes plus the percentage usage. Deprecated by psutil.virtual_memory(). """ mem = virtual_memory() return _nt_sysmeminfo(mem.total, mem.used, mem.free, mem.percent)
[ "Return", "the", "amount", "of", "total", "used", "and", "free", "physical", "memory", "on", "the", "system", "in", "bytes", "plus", "the", "percentage", "usage", ".", "Deprecated", "by", "psutil", ".", "virtual_memory", "()", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L1110-L1116
[ "def", "phymem_usage", "(", ")", ":", "mem", "=", "virtual_memory", "(", ")", "return", "_nt_sysmeminfo", "(", "mem", ".", "total", ",", "mem", ".", "used", ",", "mem", ".", "free", ",", "mem", ".", "percent", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.as_dict
Utility method returning process information as a hashable dictionary. If 'attrs' is specified it must be a list of strings reflecting available Process class's attribute names (e.g. ['get_cpu_times', 'name']) else all public (read only) attributes are assumed. 'ad_value' is the value which gets assigned to a dict key in case AccessDenied exception is raised when retrieving that particular process information.
environment/lib/python2.7/site-packages/psutil/__init__.py
def as_dict(self, attrs=[], ad_value=None): """Utility method returning process information as a hashable dictionary. If 'attrs' is specified it must be a list of strings reflecting available Process class's attribute names (e.g. ['get_cpu_times', 'name']) else all public (read only) attributes are assumed. 'ad_value' is the value which gets assigned to a dict key in case AccessDenied exception is raised when retrieving that particular process information. """ excluded_names = set(['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait', 'is_running', 'as_dict', 'parent', 'get_children', 'nice']) retdict = dict() for name in set(attrs or dir(self)): if name.startswith('_'): continue if name.startswith('set_'): continue if name in excluded_names: continue try: attr = getattr(self, name) if callable(attr): if name == 'get_cpu_percent': ret = attr(interval=0) else: ret = attr() else: ret = attr except AccessDenied: ret = ad_value except NotImplementedError: # in case of not implemented functionality (may happen # on old or exotic systems) we want to crash only if # the user explicitly asked for that particular attr if attrs: raise continue if name.startswith('get'): if name[3] == '_': name = name[4:] elif name == 'getcwd': name = 'cwd' retdict[name] = ret return retdict
def as_dict(self, attrs=[], ad_value=None): """Utility method returning process information as a hashable dictionary. If 'attrs' is specified it must be a list of strings reflecting available Process class's attribute names (e.g. ['get_cpu_times', 'name']) else all public (read only) attributes are assumed. 'ad_value' is the value which gets assigned to a dict key in case AccessDenied exception is raised when retrieving that particular process information. """ excluded_names = set(['send_signal', 'suspend', 'resume', 'terminate', 'kill', 'wait', 'is_running', 'as_dict', 'parent', 'get_children', 'nice']) retdict = dict() for name in set(attrs or dir(self)): if name.startswith('_'): continue if name.startswith('set_'): continue if name in excluded_names: continue try: attr = getattr(self, name) if callable(attr): if name == 'get_cpu_percent': ret = attr(interval=0) else: ret = attr() else: ret = attr except AccessDenied: ret = ad_value except NotImplementedError: # in case of not implemented functionality (may happen # on old or exotic systems) we want to crash only if # the user explicitly asked for that particular attr if attrs: raise continue if name.startswith('get'): if name[3] == '_': name = name[4:] elif name == 'getcwd': name = 'cwd' retdict[name] = ret return retdict
[ "Utility", "method", "returning", "process", "information", "as", "a", "hashable", "dictionary", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L138-L185
[ "def", "as_dict", "(", "self", ",", "attrs", "=", "[", "]", ",", "ad_value", "=", "None", ")", ":", "excluded_names", "=", "set", "(", "[", "'send_signal'", ",", "'suspend'", ",", "'resume'", ",", "'terminate'", ",", "'kill'", ",", "'wait'", ",", "'is_running'", ",", "'as_dict'", ",", "'parent'", ",", "'get_children'", ",", "'nice'", "]", ")", "retdict", "=", "dict", "(", ")", "for", "name", "in", "set", "(", "attrs", "or", "dir", "(", "self", ")", ")", ":", "if", "name", ".", "startswith", "(", "'_'", ")", ":", "continue", "if", "name", ".", "startswith", "(", "'set_'", ")", ":", "continue", "if", "name", "in", "excluded_names", ":", "continue", "try", ":", "attr", "=", "getattr", "(", "self", ",", "name", ")", "if", "callable", "(", "attr", ")", ":", "if", "name", "==", "'get_cpu_percent'", ":", "ret", "=", "attr", "(", "interval", "=", "0", ")", "else", ":", "ret", "=", "attr", "(", ")", "else", ":", "ret", "=", "attr", "except", "AccessDenied", ":", "ret", "=", "ad_value", "except", "NotImplementedError", ":", "# in case of not implemented functionality (may happen", "# on old or exotic systems) we want to crash only if", "# the user explicitly asked for that particular attr", "if", "attrs", ":", "raise", "continue", "if", "name", ".", "startswith", "(", "'get'", ")", ":", "if", "name", "[", "3", "]", "==", "'_'", ":", "name", "=", "name", "[", "4", ":", "]", "elif", "name", "==", "'getcwd'", ":", "name", "=", "'cwd'", "retdict", "[", "name", "]", "=", "ret", "return", "retdict" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.name
The process name.
environment/lib/python2.7/site-packages/psutil/__init__.py
def name(self): """The process name.""" name = self._platform_impl.get_process_name() if os.name == 'posix': # On UNIX the name gets truncated to the first 15 characters. # If it matches the first part of the cmdline we return that # one instead because it's usually more explicative. # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon". try: cmdline = self.cmdline except AccessDenied: pass else: if cmdline: extended_name = os.path.basename(cmdline[0]) if extended_name.startswith(name): name = extended_name # XXX - perhaps needs refactoring self._platform_impl._process_name = name return name
def name(self): """The process name.""" name = self._platform_impl.get_process_name() if os.name == 'posix': # On UNIX the name gets truncated to the first 15 characters. # If it matches the first part of the cmdline we return that # one instead because it's usually more explicative. # Examples are "gnome-keyring-d" vs. "gnome-keyring-daemon". try: cmdline = self.cmdline except AccessDenied: pass else: if cmdline: extended_name = os.path.basename(cmdline[0]) if extended_name.startswith(name): name = extended_name # XXX - perhaps needs refactoring self._platform_impl._process_name = name return name
[ "The", "process", "name", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L210-L229
[ "def", "name", "(", "self", ")", ":", "name", "=", "self", ".", "_platform_impl", ".", "get_process_name", "(", ")", "if", "os", ".", "name", "==", "'posix'", ":", "# On UNIX the name gets truncated to the first 15 characters.", "# If it matches the first part of the cmdline we return that", "# one instead because it's usually more explicative.", "# Examples are \"gnome-keyring-d\" vs. \"gnome-keyring-daemon\".", "try", ":", "cmdline", "=", "self", ".", "cmdline", "except", "AccessDenied", ":", "pass", "else", ":", "if", "cmdline", ":", "extended_name", "=", "os", ".", "path", ".", "basename", "(", "cmdline", "[", "0", "]", ")", "if", "extended_name", ".", "startswith", "(", "name", ")", ":", "name", "=", "extended_name", "# XXX - perhaps needs refactoring", "self", ".", "_platform_impl", ".", "_process_name", "=", "name", "return", "name" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.exe
The process executable path. May also be an empty string.
environment/lib/python2.7/site-packages/psutil/__init__.py
def exe(self): """The process executable path. May also be an empty string.""" def guess_it(fallback): # try to guess exe from cmdline[0] in absence of a native # exe representation cmdline = self.cmdline if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'): exe = cmdline[0] # the possible exe rexe = os.path.realpath(exe) # ...in case it's a symlink if os.path.isabs(rexe) and os.path.isfile(rexe) \ and os.access(rexe, os.X_OK): return exe if isinstance(fallback, AccessDenied): raise fallback return fallback try: exe = self._platform_impl.get_process_exe() except AccessDenied: err = sys.exc_info()[1] return guess_it(fallback=err) else: if not exe: # underlying implementation can legitimately return an # empty string; if that's the case we don't want to # raise AD while guessing from the cmdline try: exe = guess_it(fallback=exe) except AccessDenied: pass return exe
def exe(self): """The process executable path. May also be an empty string.""" def guess_it(fallback): # try to guess exe from cmdline[0] in absence of a native # exe representation cmdline = self.cmdline if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'): exe = cmdline[0] # the possible exe rexe = os.path.realpath(exe) # ...in case it's a symlink if os.path.isabs(rexe) and os.path.isfile(rexe) \ and os.access(rexe, os.X_OK): return exe if isinstance(fallback, AccessDenied): raise fallback return fallback try: exe = self._platform_impl.get_process_exe() except AccessDenied: err = sys.exc_info()[1] return guess_it(fallback=err) else: if not exe: # underlying implementation can legitimately return an # empty string; if that's the case we don't want to # raise AD while guessing from the cmdline try: exe = guess_it(fallback=exe) except AccessDenied: pass return exe
[ "The", "process", "executable", "path", ".", "May", "also", "be", "an", "empty", "string", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L232-L262
[ "def", "exe", "(", "self", ")", ":", "def", "guess_it", "(", "fallback", ")", ":", "# try to guess exe from cmdline[0] in absence of a native", "# exe representation", "cmdline", "=", "self", ".", "cmdline", "if", "cmdline", "and", "hasattr", "(", "os", ",", "'access'", ")", "and", "hasattr", "(", "os", ",", "'X_OK'", ")", ":", "exe", "=", "cmdline", "[", "0", "]", "# the possible exe", "rexe", "=", "os", ".", "path", ".", "realpath", "(", "exe", ")", "# ...in case it's a symlink", "if", "os", ".", "path", ".", "isabs", "(", "rexe", ")", "and", "os", ".", "path", ".", "isfile", "(", "rexe", ")", "and", "os", ".", "access", "(", "rexe", ",", "os", ".", "X_OK", ")", ":", "return", "exe", "if", "isinstance", "(", "fallback", ",", "AccessDenied", ")", ":", "raise", "fallback", "return", "fallback", "try", ":", "exe", "=", "self", ".", "_platform_impl", ".", "get_process_exe", "(", ")", "except", "AccessDenied", ":", "err", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "return", "guess_it", "(", "fallback", "=", "err", ")", "else", ":", "if", "not", "exe", ":", "# underlying implementation can legitimately return an", "# empty string; if that's the case we don't want to", "# raise AD while guessing from the cmdline", "try", ":", "exe", "=", "guess_it", "(", "fallback", "=", "exe", ")", "except", "AccessDenied", ":", "pass", "return", "exe" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.username
The name of the user that owns the process. On UNIX this is calculated by using *real* process uid.
environment/lib/python2.7/site-packages/psutil/__init__.py
def username(self): """The name of the user that owns the process. On UNIX this is calculated by using *real* process uid. """ if os.name == 'posix': if pwd is None: # might happen if python was installed from sources raise ImportError("requires pwd module shipped with standard python") return pwd.getpwuid(self.uids.real).pw_name else: return self._platform_impl.get_process_username()
def username(self): """The name of the user that owns the process. On UNIX this is calculated by using *real* process uid. """ if os.name == 'posix': if pwd is None: # might happen if python was installed from sources raise ImportError("requires pwd module shipped with standard python") return pwd.getpwuid(self.uids.real).pw_name else: return self._platform_impl.get_process_username()
[ "The", "name", "of", "the", "user", "that", "owns", "the", "process", ".", "On", "UNIX", "this", "is", "calculated", "by", "using", "*", "real", "*", "process", "uid", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L298-L308
[ "def", "username", "(", "self", ")", ":", "if", "os", ".", "name", "==", "'posix'", ":", "if", "pwd", "is", "None", ":", "# might happen if python was installed from sources", "raise", "ImportError", "(", "\"requires pwd module shipped with standard python\"", ")", "return", "pwd", ".", "getpwuid", "(", "self", ".", "uids", ".", "real", ")", ".", "pw_name", "else", ":", "return", "self", ".", "_platform_impl", ".", "get_process_username", "(", ")" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e
test
Process.get_children
Return the children of this process as a list of Process objects. If recursive is True return all the parent descendants. Example (A == this process): A ─┐ β”‚ β”œβ”€ B (child) ─┐ β”‚ └─ X (grandchild) ─┐ β”‚ └─ Y (great grandchild) β”œβ”€ C (child) └─ D (child) >>> p.get_children() B, C, D >>> p.get_children(recursive=True) B, X, Y, C, D Note that in the example above if process X disappears process Y won't be returned either as the reference to process A is lost.
environment/lib/python2.7/site-packages/psutil/__init__.py
def get_children(self, recursive=False): """Return the children of this process as a list of Process objects. If recursive is True return all the parent descendants. Example (A == this process): A ─┐ β”‚ β”œβ”€ B (child) ─┐ β”‚ └─ X (grandchild) ─┐ β”‚ └─ Y (great grandchild) β”œβ”€ C (child) └─ D (child) >>> p.get_children() B, C, D >>> p.get_children(recursive=True) B, X, Y, C, D Note that in the example above if process X disappears process Y won't be returned either as the reference to process A is lost. """ if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) ret = [] if not recursive: for p in process_iter(): try: if p.ppid == self.pid: # if child happens to be older than its parent # (self) it means child's PID has been reused if self.create_time <= p.create_time: ret.append(p) except NoSuchProcess: pass else: # construct a dict where 'values' are all the processes # having 'key' as their parent table = defaultdict(list) for p in process_iter(): try: table[p.ppid].append(p) except NoSuchProcess: pass # At this point we have a mapping table where table[self.pid] # are the current process's children. # Below, we look for all descendants recursively, similarly # to a recursive function call. checkpids = [self.pid] for pid in checkpids: for child in table[pid]: try: # if child happens to be older than its parent # (self) it means child's PID has been reused intime = self.create_time <= child.create_time except NoSuchProcess: pass else: if intime: ret.append(child) if child.pid not in checkpids: checkpids.append(child.pid) return ret
def get_children(self, recursive=False): """Return the children of this process as a list of Process objects. If recursive is True return all the parent descendants. Example (A == this process): A ─┐ β”‚ β”œβ”€ B (child) ─┐ β”‚ └─ X (grandchild) ─┐ β”‚ └─ Y (great grandchild) β”œβ”€ C (child) └─ D (child) >>> p.get_children() B, C, D >>> p.get_children(recursive=True) B, X, Y, C, D Note that in the example above if process X disappears process Y won't be returned either as the reference to process A is lost. """ if not self.is_running(): name = self._platform_impl._process_name raise NoSuchProcess(self.pid, name) ret = [] if not recursive: for p in process_iter(): try: if p.ppid == self.pid: # if child happens to be older than its parent # (self) it means child's PID has been reused if self.create_time <= p.create_time: ret.append(p) except NoSuchProcess: pass else: # construct a dict where 'values' are all the processes # having 'key' as their parent table = defaultdict(list) for p in process_iter(): try: table[p.ppid].append(p) except NoSuchProcess: pass # At this point we have a mapping table where table[self.pid] # are the current process's children. # Below, we look for all descendants recursively, similarly # to a recursive function call. checkpids = [self.pid] for pid in checkpids: for child in table[pid]: try: # if child happens to be older than its parent # (self) it means child's PID has been reused intime = self.create_time <= child.create_time except NoSuchProcess: pass else: if intime: ret.append(child) if child.pid not in checkpids: checkpids.append(child.pid) return ret
[ "Return", "the", "children", "of", "this", "process", "as", "a", "list", "of", "Process", "objects", ".", "If", "recursive", "is", "True", "return", "all", "the", "parent", "descendants", "." ]
cloud9ers/gurumate
python
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/psutil/__init__.py#L402-L468
[ "def", "get_children", "(", "self", ",", "recursive", "=", "False", ")", ":", "if", "not", "self", ".", "is_running", "(", ")", ":", "name", "=", "self", ".", "_platform_impl", ".", "_process_name", "raise", "NoSuchProcess", "(", "self", ".", "pid", ",", "name", ")", "ret", "=", "[", "]", "if", "not", "recursive", ":", "for", "p", "in", "process_iter", "(", ")", ":", "try", ":", "if", "p", ".", "ppid", "==", "self", ".", "pid", ":", "# if child happens to be older than its parent", "# (self) it means child's PID has been reused", "if", "self", ".", "create_time", "<=", "p", ".", "create_time", ":", "ret", ".", "append", "(", "p", ")", "except", "NoSuchProcess", ":", "pass", "else", ":", "# construct a dict where 'values' are all the processes", "# having 'key' as their parent", "table", "=", "defaultdict", "(", "list", ")", "for", "p", "in", "process_iter", "(", ")", ":", "try", ":", "table", "[", "p", ".", "ppid", "]", ".", "append", "(", "p", ")", "except", "NoSuchProcess", ":", "pass", "# At this point we have a mapping table where table[self.pid]", "# are the current process's children.", "# Below, we look for all descendants recursively, similarly", "# to a recursive function call.", "checkpids", "=", "[", "self", ".", "pid", "]", "for", "pid", "in", "checkpids", ":", "for", "child", "in", "table", "[", "pid", "]", ":", "try", ":", "# if child happens to be older than its parent", "# (self) it means child's PID has been reused", "intime", "=", "self", ".", "create_time", "<=", "child", ".", "create_time", "except", "NoSuchProcess", ":", "pass", "else", ":", "if", "intime", ":", "ret", ".", "append", "(", "child", ")", "if", "child", ".", "pid", "not", "in", "checkpids", ":", "checkpids", ".", "append", "(", "child", ".", "pid", ")", "return", "ret" ]
075dc74d1ee62a8c6b7a8bf2b271364f01629d1e