desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Happens when it would be nice to open a completion list, but not
really necessary, for example after an dot, so function
calls won\'t be made.'
| def try_open_completions_event(self, event):
| lastchar = self.text.get('insert-1c')
if (lastchar == '.'):
self._open_completions_later(False, False, False, COMPLETE_ATTRIBUTES)
elif (lastchar in SEPS):
self._open_completions_later(False, False, False, COMPLETE_FILES)
|
'Happens when the user wants to complete his word, and if necessary,
open a completion list after that (if there is more than one
completion)'
| def autocomplete_event(self, event):
| if (hasattr(event, 'mc_state') and event.mc_state):
return
if (self.autocompletewindow and self.autocompletewindow.is_active()):
self.autocompletewindow.complete()
return 'break'
else:
opened = self.open_completions(False, True, True)
if opened:
return 'br... |
'Find the completions and create the AutoCompleteWindow.
Return True if successful (no syntax error or so found).
if complete is True, then if there\'s nothing to complete and no
start of completion, won\'t open completions and return False.
If mode is given, will open a completion list only in this mode.'
| def open_completions(self, evalfuncs, complete, userWantsWin, mode=None):
| if (self._delayed_completion_id is not None):
self.text.after_cancel(self._delayed_completion_id)
self._delayed_completion_id = None
hp = HyperParser(self.editwin, 'insert')
curline = self.text.get('insert linestart', 'insert')
i = j = len(curline)
if (hp.is_in_string() and ((not ... |
'Return a pair of lists of completions for something. The first list
is a sublist of the second. Both are sorted.
If there is a Python subprocess, get the comp. list there. Otherwise,
either fetch_completions() is running in the subprocess itself or it
was called in an IDLE EditorWindow before any script had been run.... | def fetch_completions(self, what, mode):
| try:
rpcclt = self.editwin.flist.pyshell.interp.rpcclt
except:
rpcclt = None
if rpcclt:
return rpcclt.remotecall('exec', 'get_the_completion_list', (what, mode), {})
else:
if (mode == COMPLETE_ATTRIBUTES):
if (what == ''):
namespace = __main__.... |
'Lookup name in a namespace spanning sys.modules and __main.dict__'
| def get_entity(self, name):
| namespace = sys.modules.copy()
namespace.update(__main__.__dict__)
return eval(name, namespace)
|
'Override TCPServer method, no bind() phase for connecting entity'
| def server_bind(self):
| pass
|
'Override TCPServer method, connect() instead of listen()
Due to the reversed connection, self.server_address is actually the
address of the Idle Client to which we are connecting.'
| def server_activate(self):
| self.socket.connect(self.server_address)
|
'Override TCPServer method, return already connected socket'
| def get_request(self):
| return (self.socket, self.server_address)
|
'Override TCPServer method
Error message goes to __stderr__. No error message if exiting
normally or socket raised EOF. Other exceptions not handled in
server code will cause os._exit.'
| def handle_error(self, request, client_address):
| try:
raise
except SystemExit:
raise
except:
erf = sys.__stderr__
print >>erf, ('\n' + ('-' * 40))
print >>erf, 'Unhandled server exception!'
print >>erf, ('Thread: %s' % threading.currentThread().getName())
print >>erf, 'Client Address: ... |
'override for specific exit action'
| def exithook(self):
| os._exit()
|
''
| def decode_interrupthook(self):
| raise EOFError
|
'Listen on socket until I/O not ready or EOF
pollresponse() will loop looking for seq number None, which
never comes, and exit on EOFError.'
| def mainloop(self):
| try:
self.getresponse(myseq=None, wait=0.05)
except EOFError:
self.debug('mainloop:return')
return
|
'Handle messages received on the socket.
Some messages received may be asynchronous \'call\' or \'queue\' requests,
and some may be responses for other threads.
\'call\' requests are passed to self.localcall() with the expectation of
immediate execution, during which time the socket is not serviced.
\'queue\' requests ... | def pollresponse(self, myseq, wait):
| while 1:
try:
qmsg = response_queue.get(0)
except Queue.Empty:
pass
else:
(seq, response) = qmsg
message = (seq, ('OK', response))
self.putmessage(message)
try:
message = self.pollmessage(wait)
if (me... |
'action taken upon link being closed by peer'
| def handle_EOF(self):
| self.EOFhook()
self.debug('handle_EOF')
for key in self.cvars:
cv = self.cvars[key]
cv.acquire()
self.responses[key] = ('EOF', None)
cv.notify()
cv.release()
self.exithook()
|
'Classes using rpc client/server can override to augment EOF action'
| def EOFhook(self):
| pass
|
'handle() method required by SocketServer'
| def handle(self):
| self.mainloop()
|
'Show the given text in a scrollable window with a \'close\' button'
| def __init__(self, parent, title, text):
| Toplevel.__init__(self, parent)
self.configure(borderwidth=5)
self.geometry(('=%dx%d+%d+%d' % (625, 500, (parent.winfo_rootx() + 10), (parent.winfo_rooty() + 10))))
self.bg = '#ffffff'
self.fg = '#000000'
self.CreateWidgets()
self.title(title)
self.transient(parent)
self.grab_set()
... |
'Get the line indent value, text, and any block start keyword
If the line does not start a block, the keyword value is False.
The indentation of empty lines (or comment lines) is INFINITY.'
| def get_line_info(self, linenum):
| text = self.text.get(('%d.0' % linenum), ('%d.end' % linenum))
(spaces, firstword) = getspacesfirstword(text)
opener = ((firstword in BLOCKOPENERS) and firstword)
if ((len(text) == len(spaces)) or (text[len(spaces)] == '#')):
indent = INFINITY
else:
indent = len(spaces)
return (i... |
'Get context lines, starting at new_topvisible and working backwards.
Stop when stopline or stopindent is reached. Return a tuple of context
data and the indent level at the top of the region inspected.'
| def get_context(self, new_topvisible, stopline=1, stopindent=0):
| assert (stopline > 0)
lines = []
lastindent = INFINITY
for linenum in xrange(new_topvisible, (stopline - 1), (-1)):
(indent, text, opener) = self.get_line_info(linenum)
if (indent < lastindent):
lastindent = indent
if (opener in ('else', 'elif')):
... |
'Update context information and lines visible in the context pane.'
| def update_code_context(self):
| new_topvisible = int(self.text.index('@0,0').split('.')[0])
if (self.topvisible == new_topvisible):
return
if (self.topvisible < new_topvisible):
(lines, lastindent) = self.get_context(new_topvisible, self.topvisible)
while (self.info[(-1)][1] >= lastindent):
del self.inf... |
'Find the first index in self.completions where completions[i] is
greater or equal to s, or the last index if there is no such
one.'
| def _binary_search(self, s):
| i = 0
j = len(self.completions)
while (j > i):
m = ((i + j) // 2)
if (self.completions[m] >= s):
j = m
else:
i = (m + 1)
return min(i, (len(self.completions) - 1))
|
'Assuming that s is the prefix of a string in self.completions,
return the longest string which is a prefix of all the strings which
s is a prefix of them. If s is not a prefix of a string, return s.'
| def _complete_string(self, s):
| first = self._binary_search(s)
if (self.completions[first][:len(s)] != s):
return s
i = (first + 1)
j = len(self.completions)
while (j > i):
m = ((i + j) // 2)
if (self.completions[m][:len(s)] != s):
j = m
else:
i = (m + 1)
last = (i - 1)
... |
'Should be called when the selection of the Listbox has changed.
Updates the Listbox display and calls _change_start.'
| def _selection_changed(self):
| cursel = int(self.listbox.curselection()[0])
self.listbox.see(cursel)
lts = self.lasttypedstart
selstart = self.completions[cursel]
if (self._binary_search(lts) == cursel):
newstart = lts
else:
min_len = min(len(lts), len(selstart))
i = 0
while ((i < min_len) and ... |
'Show the autocomplete list, bind events.
If complete is True, complete the text, and if there is exactly one
matching completion, don\'t open a list.'
| def show_window(self, comp_lists, index, complete, mode, userWantsWin):
| (self.completions, self.morecompletions) = comp_lists
self.mode = mode
self.startindex = self.widget.index(index)
self.start = self.widget.get(self.startindex, 'insert')
if complete:
completed = self._complete_string(self.start)
self._change_start(completed)
i = self._binary_... |
'convert filename to unicode in order to display it in Tk'
| def _filename_to_unicode(self, filename):
| if (isinstance(filename, unicode) or (not filename)):
return filename
else:
try:
return filename.decode(self.filesystemencoding)
except UnicodeDecodeError:
try:
return filename.decode(self.encoding)
except UnicodeDecodeError:
... |
'Cursor move begins at start or end of selection
When a left/right cursor key is pressed create and return to Tkinter a
function which causes a cursor move from the associated edge of the
selection.'
| def move_at_edge_if_selection(self, edge_index):
| self_text_index = self.text.index
self_text_mark_set = self.text.mark_set
edges_table = ('sel.first+1c', 'sel.last-1c')
def move_at_edge(event):
if ((event.state & 5) == 0):
try:
self_text_index('sel.first')
self_text_mark_set('insert', edges_table[edg... |
'Update the colour theme'
| def ResetColorizer(self):
| self._rmcolorizer()
self._addcolorizer()
theme = idleConf.GetOption('main', 'Theme', 'name')
normal_colors = idleConf.GetHighlight(theme, 'normal')
cursor_color = idleConf.GetHighlight(theme, 'cursor', fgBg='fg')
select_colors = idleConf.GetHighlight(theme, 'hilite')
self.text.config(foregro... |
'Update the text widgets\' font if it is changed'
| def ResetFont(self):
| fontWeight = 'normal'
if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'):
fontWeight = 'bold'
self.text.config(font=(idleConf.GetOption('main', 'EditorWindow', 'font'), idleConf.GetOption('main', 'EditorWindow', 'font-size'), fontWeight))
|
'Remove the keybindings before they are changed.'
| def RemoveKeybindings(self):
| self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
for (event, keylist) in keydefs.items():
self.text.event_delete(event, *keylist)
for extensionName in self.get_standard_extension_names():
xkeydefs = idleConf.GetExtensionBindings(extensionName)
if xkeydefs:
... |
'Update the keybindings after they are changed'
| def ApplyKeybindings(self):
| self.Bindings.default_keydefs = keydefs = idleConf.GetCurrentKeySet()
self.apply_bindings()
for extensionName in self.get_standard_extension_names():
xkeydefs = idleConf.GetExtensionBindings(extensionName)
if xkeydefs:
self.apply_bindings(xkeydefs)
menuEventDict = {}
for ... |
'Update the indentwidth if changed and not using tabs in this window'
| def set_notabs_indentwidth(self):
| if (not self.usetabs):
self.indentwidth = idleConf.GetOption('main', 'Indent', 'num-spaces', type='int')
|
'Update the additional help entries on the Help menu'
| def reset_help_menu_entries(self):
| help_list = idleConf.GetAllExtraHelpSourcesList()
helpmenu = self.menudict['help']
helpmenu_length = helpmenu.index(END)
if (helpmenu_length > self.base_helpmenu_length):
helpmenu.delete((self.base_helpmenu_length + 1), helpmenu_length)
if help_list:
helpmenu.add_separator()
... |
'Create a callback with the helpfile value frozen at definition time'
| def __extra_help_callback(self, helpfile):
| def display_extra_help(helpfile=helpfile):
if (not helpfile.startswith(('www', 'http'))):
helpfile = os.path.normpath(helpfile)
if (sys.platform[:3] == 'win'):
try:
os.startfile(helpfile)
except WindowsError as why:
tkMessageBox.sho... |
'Load and update the recent files list and menus'
| def update_recent_files_list(self, new_file=None):
| rf_list = []
if os.path.exists(self.recent_files_path):
rf_list_file = open(self.recent_files_path, 'r')
try:
rf_list = rf_list_file.readlines()
finally:
rf_list_file.close()
if new_file:
new_file = (os.path.abspath(new_file) + '\n')
if (new_fi... |
'Return (width, height, x, y)'
| def get_geometry(self):
| geom = self.top.wm_geometry()
m = re.match('(\\d+)x(\\d+)\\+(-?\\d+)\\+(-?\\d+)', geom)
tuple = map(int, m.groups())
return tuple
|
'Add appropriate entries to the menus and submenus
Menus that are absent or None in self.menudict are ignored.'
| def fill_menus(self, menudefs=None, keydefs=None):
| if (menudefs is None):
menudefs = self.Bindings.menudefs
if (keydefs is None):
keydefs = self.Bindings.default_keydefs
menudict = self.menudict
text = self.text
for (mname, entrylist) in menudefs:
menu = menudict.get(mname)
if (not menu):
continue
... |
'Return a (user, account, password) tuple for given host.'
| def authenticators(self, host):
| if (host in self.hosts):
return self.hosts[host]
elif ('default' in self.hosts):
return self.hosts['default']
else:
return None
|
'Dump the class data in the format of a .netrc file.'
| def __repr__(self):
| rep = ''
for host in self.hosts.keys():
attrs = self.hosts[host]
rep = (((((rep + 'machine ') + host) + '\n DCTB login ') + repr(attrs[0])) + '\n')
if attrs[1]:
rep = ((rep + 'account ') + repr(attrs[1]))
rep = (((rep + ' DCTB password ') + repr(attrs[2]))... |
'Constructor. See class doc string.'
| def __init__(self, stmt='pass', setup='pass', timer=default_timer):
| self.timer = timer
ns = {}
if isinstance(stmt, basestring):
stmt = reindent(stmt, 8)
if isinstance(setup, basestring):
setup = reindent(setup, 4)
src = (template % {'stmt': stmt, 'setup': setup})
elif hasattr(setup, '__call__'):
src = (template % {... |
'Helper to print a traceback from the timed code.
Typical use:
t = Timer(...) # outside the try/except
try:
t.timeit(...) # or t.repeat(...)
except:
t.print_exc()
The advantage over the standard traceback is that source lines
in the compiled template will be displayed.
The optional file argument directs where ... | def print_exc(self, file=None):
| import linecache, traceback
if (self.src is not None):
linecache.cache[dummy_src_name] = (len(self.src), None, self.src.split('\n'), dummy_src_name)
traceback.print_exc(file=file)
|
'Time \'number\' executions of the main statement.
To be precise, this executes the setup statement once, and
then returns the time it takes to execute the main statement
a number of times, as a float measured in seconds. The
argument is the number of times through the loop, defaulting
to one million. The main statem... | def timeit(self, number=default_number):
| if itertools:
it = itertools.repeat(None, number)
else:
it = ([None] * number)
gcold = gc.isenabled()
gc.disable()
timing = self.inner(it, self.timer)
if gcold:
gc.enable()
return timing
|
'Call timeit() a few times.
This is a convenience function that calls the timeit()
repeatedly, returning a list of results. The first argument
specifies how many times to call timeit(), defaulting to 3;
the second argument specifies the timer argument, defaulting
to one million.
Note: it\'s tempting to calculate mean ... | def repeat(self, repeat=default_repeat, number=default_number):
| r = []
for i in range(repeat):
t = self.timeit(number)
r.append(t)
return r
|
'Create a decimal point instance.
>>> Decimal(\'3.14\') # string input
Decimal(\'3.14\')
>>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Decimal(\'3.14\')
>>> Decimal(314) # int or long
Decimal(\'314\')
>>> Decimal(Decimal(314)) # another decimal instance
Decim... | def __new__(cls, value='0', context=None):
| self = object.__new__(cls)
if isinstance(value, basestring):
m = _parser(value.strip())
if (m is None):
if (context is None):
context = getcontext()
return context._raise_error(ConversionSyntax, ('Invalid literal for Decimal: %r' % value))
... |
'Converts a float to a decimal number, exactly.
Note that Decimal.from_float(0.1) is not the same as Decimal(\'0.1\').
Since 0.1 is not exactly representable in binary floating point, the
value is stored as the nearest representable value which is
0x1.999999999999ap-4. The exact equivalent of the value in decimal
is 0... | def from_float(cls, f):
| if isinstance(f, (int, long)):
return cls(f)
if (_math.isinf(f) or _math.isnan(f)):
return cls(repr(f))
if (_math.copysign(1.0, f) == 1.0):
sign = 0
else:
sign = 1
(n, d) = abs(f).as_integer_ratio()
k = (d.bit_length() - 1)
result = _dec_from_triple(sign, str(... |
'Returns whether the number is not actually one.
0 if a number
1 if NaN
2 if sNaN'
| def _isnan(self):
| if self._is_special:
exp = self._exp
if (exp == 'n'):
return 1
elif (exp == 'N'):
return 2
return 0
|
'Returns whether the number is infinite
0 if finite or not a number
1 if +INF
-1 if -INF'
| def _isinfinity(self):
| if (self._exp == 'F'):
if self._sign:
return (-1)
return 1
return 0
|
'Returns whether the number is not actually one.
if self, other are sNaN, signal
if self, other are NaN return nan
return 0
Done before operations.'
| def _check_nans(self, other=None, context=None):
| self_is_nan = self._isnan()
if (other is None):
other_is_nan = False
else:
other_is_nan = other._isnan()
if (self_is_nan or other_is_nan):
if (context is None):
context = getcontext()
if (self_is_nan == 2):
return context._raise_error(InvalidOperat... |
'Version of _check_nans used for the signaling comparisons
compare_signal, __le__, __lt__, __ge__, __gt__.
Signal InvalidOperation if either self or other is a (quiet
or signaling) NaN. Signaling NaNs take precedence over quiet
NaNs.
Return 0 if neither operand is a NaN.'
| def _compare_check_nans(self, other, context):
| if (context is None):
context = getcontext()
if (self._is_special or other._is_special):
if self.is_snan():
return context._raise_error(InvalidOperation, 'comparison involving sNaN', self)
elif other.is_snan():
return context._raise_error(InvalidOperation, '... |
'Return True if self is nonzero; otherwise return False.
NaNs and infinities are considered nonzero.'
| def __nonzero__(self):
| return (self._is_special or (self._int != '0'))
|
'Compare the two non-NaN decimal instances self and other.
Returns -1 if self < other, 0 if self == other and 1
if self > other. This routine is for internal use only.'
| def _cmp(self, other):
| if (self._is_special or other._is_special):
self_inf = self._isinfinity()
other_inf = other._isinfinity()
if (self_inf == other_inf):
return 0
elif (self_inf < other_inf):
return (-1)
else:
return 1
if (not self):
if (not other)... |
'Compares one to another.
-1 => a < b
0 => a = b
1 => a > b
NaN => one is NaN
Like __cmp__, but returns Decimal instances.'
| def compare(self, other, context=None):
| other = _convert_other(other, raiseit=True)
if (self._is_special or (other and other._is_special)):
ans = self._check_nans(other, context)
if ans:
return ans
return Decimal(self._cmp(other))
|
'x.__hash__() <==> hash(x)'
| def __hash__(self):
| if self._is_special:
if self.is_snan():
raise TypeError('Cannot hash a signaling NaN value.')
elif self.is_nan():
return 0
elif self._sign:
return (-271828)
else:
return 314159
self_as_float = float(self)
if (Deci... |
'Represents the number as a triple tuple.
To show the internals exactly as they are.'
| def as_tuple(self):
| return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
|
'Represents the number as an instance of Decimal.'
| def __repr__(self):
| return ("Decimal('%s')" % str(self))
|
'Return string representation of the number in scientific notation.
Captures all of the information in the underlying representation.'
| def __str__(self, eng=False, context=None):
| sign = ['', '-'][self._sign]
if self._is_special:
if (self._exp == 'F'):
return (sign + 'Infinity')
elif (self._exp == 'n'):
return ((sign + 'NaN') + self._int)
else:
return ((sign + 'sNaN') + self._int)
leftdigits = (self._exp + len(self._int))
... |
'Convert to engineering-type string.
Engineering notation has an exponent which is a multiple of 3, so there
are up to 3 digits left of the decimal place.
Same rules for when in exponential and when as a value as in __str__.'
| def to_eng_string(self, context=None):
| return self.__str__(eng=True, context=context)
|
'Returns a copy with the sign switched.
Rounds, if it has reason.'
| def __neg__(self, context=None):
| if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
if (context is None):
context = getcontext()
if ((not self) and (context.rounding != ROUND_FLOOR)):
ans = self.copy_abs()
else:
ans = self.copy_negate()
return ans._fix... |
'Returns a copy, unless it is a sNaN.
Rounds the number (if more then precision digits)'
| def __pos__(self, context=None):
| if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
if (context is None):
context = getcontext()
if ((not self) and (context.rounding != ROUND_FLOOR)):
ans = self.copy_abs()
else:
ans = Decimal(self)
return ans._fix(cont... |
'Returns the absolute value of self.
If the keyword argument \'round\' is false, do not round. The
expression self.__abs__(round=False) is equivalent to
self.copy_abs().'
| def __abs__(self, round=True, context=None):
| if (not round):
return self.copy_abs()
if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
if self._sign:
ans = self.__neg__(context=context)
else:
ans = self.__pos__(context=context)
return ans
|
'Returns self + other.
-INF + INF (or the reverse) cause InvalidOperation errors.'
| def __add__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
if (context is None):
context = getcontext()
if (self._is_special or other._is_special):
ans = self._check_nans(other, context)
if ans:
return ans
if self._isinfinity():
... |
'Return self - other'
| def __sub__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
if (self._is_special or other._is_special):
ans = self._check_nans(other, context=context)
if ans:
return ans
return self.__add__(other.copy_negate(), context=context)
|
'Return other - self'
| def __rsub__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
return other.__sub__(self, context=context)
|
'Return self * other.
(+-) INF * 0 (or its reverse) raise InvalidOperation.'
| def __mul__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
if (context is None):
context = getcontext()
resultsign = (self._sign ^ other._sign)
if (self._is_special or other._is_special):
ans = self._check_nans(other, context)
if ans:
return ... |
'Return self / other.'
| def __truediv__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return NotImplemented
if (context is None):
context = getcontext()
sign = (self._sign ^ other._sign)
if (self._is_special or other._is_special):
ans = self._check_nans(other, context)
if ans:
retu... |
'Return (self // other, self % other), to context.prec precision.
Assumes that neither self nor other is a NaN, that self is not
infinite and that other is nonzero.'
| def _divide(self, other, context):
| sign = (self._sign ^ other._sign)
if other._isinfinity():
ideal_exp = self._exp
else:
ideal_exp = min(self._exp, other._exp)
expdiff = (self.adjusted() - other.adjusted())
if ((not self) or other._isinfinity() or (expdiff <= (-2))):
return (_dec_from_triple(sign, '0', 0), sel... |
'Swaps self/other and returns __truediv__.'
| def __rtruediv__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
return other.__truediv__(self, context=context)
|
'Return (self // other, self % other)'
| def __divmod__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
if (context is None):
context = getcontext()
ans = self._check_nans(other, context)
if ans:
return (ans, ans)
sign = (self._sign ^ other._sign)
if self._isinfinity():
if other._isinfinity... |
'Swaps self/other and returns __divmod__.'
| def __rdivmod__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
return other.__divmod__(self, context=context)
|
'self % other'
| def __mod__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
if (context is None):
context = getcontext()
ans = self._check_nans(other, context)
if ans:
return ans
if self._isinfinity():
return context._raise_error(InvalidOperation, 'INF % x')
... |
'Swaps self/other and returns __mod__.'
| def __rmod__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
return other.__mod__(self, context=context)
|
'Remainder nearest to 0- abs(remainder-near) <= other/2'
| def remainder_near(self, other, context=None):
| if (context is None):
context = getcontext()
other = _convert_other(other, raiseit=True)
ans = self._check_nans(other, context)
if ans:
return ans
if self._isinfinity():
return context._raise_error(InvalidOperation, 'remainder_near(infinity, x)')
if (not other):
... |
'self // other'
| def __floordiv__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
if (context is None):
context = getcontext()
ans = self._check_nans(other, context)
if ans:
return ans
if self._isinfinity():
if other._isinfinity():
return context._raise_error(I... |
'Swaps self/other and returns __floordiv__.'
| def __rfloordiv__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
return other.__floordiv__(self, context=context)
|
'Float representation.'
| def __float__(self):
| return float(str(self))
|
'Converts self to an int, truncating if necessary.'
| def __int__(self):
| if self._is_special:
if self._isnan():
raise ValueError('Cannot convert NaN to integer')
elif self._isinfinity():
raise OverflowError('Cannot convert infinity to integer')
s = ((-1) ** self._sign)
if (self._exp >= 0):
return ((s * int(s... |
'Converts to a long.
Equivalent to long(int(self))'
| def __long__(self):
| return long(self.__int__())
|
'Decapitate the payload of a NaN to fit the context'
| def _fix_nan(self, context):
| payload = self._int
max_payload_len = (context.prec - context._clamp)
if (len(payload) > max_payload_len):
payload = payload[(len(payload) - max_payload_len):].lstrip('0')
return _dec_from_triple(self._sign, payload, self._exp, True)
return Decimal(self)
|
'Round if it is necessary to keep self within prec precision.
Rounds and fixes the exponent. Does not raise on a sNaN.
Arguments:
self - Decimal instance
context - context used.'
| def _fix(self, context):
| if self._is_special:
if self._isnan():
return self._fix_nan(context)
else:
return Decimal(self)
Etiny = context.Etiny()
Etop = context.Etop()
if (not self):
exp_max = [context.Emax, Etop][context._clamp]
new_exp = min(max(self._exp, Etiny), exp_max... |
'Also known as round-towards-0, truncate.'
| def _round_down(self, prec):
| if _all_zeros(self._int, prec):
return 0
else:
return (-1)
|
'Rounds away from 0.'
| def _round_up(self, prec):
| return (- self._round_down(prec))
|
'Rounds 5 up (away from 0)'
| def _round_half_up(self, prec):
| if (self._int[prec] in '56789'):
return 1
elif _all_zeros(self._int, prec):
return 0
else:
return (-1)
|
'Round 5 down'
| def _round_half_down(self, prec):
| if _exact_half(self._int, prec):
return (-1)
else:
return self._round_half_up(prec)
|
'Round 5 to even, rest to nearest.'
| def _round_half_even(self, prec):
| if (_exact_half(self._int, prec) and ((prec == 0) or (self._int[(prec - 1)] in '02468'))):
return (-1)
else:
return self._round_half_up(prec)
|
'Rounds up (not away from 0 if negative.)'
| def _round_ceiling(self, prec):
| if self._sign:
return self._round_down(prec)
else:
return (- self._round_down(prec))
|
'Rounds down (not towards 0 if negative)'
| def _round_floor(self, prec):
| if (not self._sign):
return self._round_down(prec)
else:
return (- self._round_down(prec))
|
'Round down unless digit prec-1 is 0 or 5.'
| def _round_05up(self, prec):
| if (prec and (self._int[(prec - 1)] not in '05')):
return self._round_down(prec)
else:
return (- self._round_down(prec))
|
'Fused multiply-add.
Returns self*other+third with no rounding of the intermediate
product self*other.
self and other are multiplied together, with no rounding of
the result. The third operand is then added to the result,
and a single final rounding is performed.'
| def fma(self, other, third, context=None):
| other = _convert_other(other, raiseit=True)
if (self._is_special or other._is_special):
if (context is None):
context = getcontext()
if (self._exp == 'N'):
return context._raise_error(InvalidOperation, 'sNaN', self)
if (other._exp == 'N'):
return conte... |
'Three argument version of __pow__'
| def _power_modulo(self, other, modulo, context=None):
| other = _convert_other(other, raiseit=True)
modulo = _convert_other(modulo, raiseit=True)
if (context is None):
context = getcontext()
self_is_nan = self._isnan()
other_is_nan = other._isnan()
modulo_is_nan = modulo._isnan()
if (self_is_nan or other_is_nan or modulo_is_nan):
... |
'Attempt to compute self**other exactly.
Given Decimals self and other and an integer p, attempt to
compute an exact result for the power self**other, with p
digits of precision. Return None if self**other is not
exactly representable in p digits.
Assumes that elimination of special cases has already been
performed: s... | def _power_exact(self, other, p):
| x = _WorkRep(self)
(xc, xe) = (x.int, x.exp)
while ((xc % 10) == 0):
xc //= 10
xe += 1
y = _WorkRep(other)
(yc, ye) = (y.int, y.exp)
while ((yc % 10) == 0):
yc //= 10
ye += 1
if (xc == 1):
xe *= yc
while ((xe % 10) == 0):
xe //= 10
... |
'Return self ** other [ % modulo].
With two arguments, compute self**other.
With three arguments, compute (self**other) % modulo. For the
three argument form, the following restrictions on the
arguments hold:
- all three arguments must be integral
- other must be nonnegative
- either self or other (or both) must be no... | def __pow__(self, other, modulo=None, context=None):
| if (modulo is not None):
return self._power_modulo(other, modulo, context)
other = _convert_other(other)
if (other is NotImplemented):
return other
if (context is None):
context = getcontext()
ans = self._check_nans(other, context)
if ans:
return ans
if (not o... |
'Swaps self/other and returns __pow__.'
| def __rpow__(self, other, context=None):
| other = _convert_other(other)
if (other is NotImplemented):
return other
return other.__pow__(self, context=context)
|
'Normalize- strip trailing 0s, change anything equal to 0 to 0e0'
| def normalize(self, context=None):
| if (context is None):
context = getcontext()
if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
dup = self._fix(context)
if dup._isinfinity():
return dup
if (not dup):
return _dec_from_triple(dup._sign, '0', 0)
exp_... |
'Quantize self so its exponent is the same as that of exp.
Similar to self._rescale(exp._exp) but with error checking.'
| def quantize(self, exp, rounding=None, context=None, watchexp=True):
| exp = _convert_other(exp, raiseit=True)
if (context is None):
context = getcontext()
if (rounding is None):
rounding = context.rounding
if (self._is_special or exp._is_special):
ans = self._check_nans(exp, context)
if ans:
return ans
if (exp._isinfinit... |
'Return True if self and other have the same exponent; otherwise
return False.
If either operand is a special value, the following rules are used:
* return True if both operands are infinities
* return True if both operands are NaNs
* otherwise, return False.'
| def same_quantum(self, other):
| other = _convert_other(other, raiseit=True)
if (self._is_special or other._is_special):
return ((self.is_nan() and other.is_nan()) or (self.is_infinite() and other.is_infinite()))
return (self._exp == other._exp)
|
'Rescale self so that the exponent is exp, either by padding with zeros
or by truncating digits, using the given rounding mode.
Specials are returned without change. This operation is
quiet: it raises no flags, and uses no information from the
context.
exp = exp to scale to (an integer)
rounding = rounding mode'
| def _rescale(self, exp, rounding):
| if self._is_special:
return Decimal(self)
if (not self):
return _dec_from_triple(self._sign, '0', exp)
if (self._exp >= exp):
return _dec_from_triple(self._sign, (self._int + ('0' * (self._exp - exp))), exp)
digits = ((len(self._int) + self._exp) - exp)
if (digits < 0):
... |
'Round a nonzero, nonspecial Decimal to a fixed number of
significant figures, using the given rounding mode.
Infinities, NaNs and zeros are returned unaltered.
This operation is quiet: it raises no flags, and uses no
information from the context.'
| def _round(self, places, rounding):
| if (places <= 0):
raise ValueError('argument should be at least 1 in _round')
if (self._is_special or (not self)):
return Decimal(self)
ans = self._rescale(((self.adjusted() + 1) - places), rounding)
if (ans.adjusted() != self.adjusted()):
ans = ans._rescale(... |
'Rounds to a nearby integer.
If no rounding mode is specified, take the rounding mode from
the context. This method raises the Rounded and Inexact flags
when appropriate.
See also: to_integral_value, which does exactly the same as
this method except that it doesn\'t raise Inexact or Rounded.'
| def to_integral_exact(self, rounding=None, context=None):
| if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
return Decimal(self)
if (self._exp >= 0):
return Decimal(self)
if (not self):
return _dec_from_triple(self._sign, '0', 0)
if (context is None):
context = getcontext... |
'Rounds to the nearest integer, without raising inexact, rounded.'
| def to_integral_value(self, rounding=None, context=None):
| if (context is None):
context = getcontext()
if (rounding is None):
rounding = context.rounding
if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
return Decimal(self)
if (self._exp >= 0):
return Decimal(self)
e... |
'Return the square root of self.'
| def sqrt(self, context=None):
| if (context is None):
context = getcontext()
if self._is_special:
ans = self._check_nans(context=context)
if ans:
return ans
if (self._isinfinity() and (self._sign == 0)):
return Decimal(self)
if (not self):
ans = _dec_from_triple(self._sign, '... |
'Returns the larger value.
Like max(self, other) except if one is not a number, returns
NaN (and signals if one is sNaN). Also rounds.'
| def max(self, other, context=None):
| other = _convert_other(other, raiseit=True)
if (context is None):
context = getcontext()
if (self._is_special or other._is_special):
sn = self._isnan()
on = other._isnan()
if (sn or on):
if ((on == 1) and (sn == 0)):
return self._fix(context)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.