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 'break'
|
'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 mode) or (mode == COMPLETE_FILES))):
self._remove_autocomplete_window()
mode = COMPLETE_FILES
while (i and (curline[(i - 1)] in FILENAME_CHARS)):
i -= 1
comp_start = curline[i:j]
j = i
while (i and (curline[(i - 1)] in (FILENAME_CHARS + SEPS))):
i -= 1
comp_what = curline[i:j]
elif (hp.is_in_code() and ((not mode) or (mode == COMPLETE_ATTRIBUTES))):
self._remove_autocomplete_window()
mode = COMPLETE_ATTRIBUTES
while (i and (curline[(i - 1)] in ID_CHARS)):
i -= 1
comp_start = curline[i:j]
if (i and (curline[(i - 1)] == '.')):
hp.set_index(('insert-%dc' % (len(curline) - (i - 1))))
comp_what = hp.get_expression()
if ((not comp_what) or ((not evalfuncs) and (comp_what.find('(') != (-1)))):
return
else:
comp_what = ''
else:
return
if (complete and (not comp_what) and (not comp_start)):
return
comp_lists = self.fetch_completions(comp_what, mode)
if (not comp_lists[0]):
return
self.autocompletewindow = self._make_autocomplete_window()
self.autocompletewindow.show_window(comp_lists, ('insert-%dc' % len(comp_start)), complete, mode, userWantsWin)
return True
|
'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.
The subprocess environment is that of the most recently run script. If
two unrelated modules are being edited some calltips in the current
module may be inoperative if the module was not the last to 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__.__dict__.copy()
namespace.update(__main__.__builtins__.__dict__)
bigl = eval('dir()', namespace)
bigl.sort()
if ('__all__' in bigl):
smalll = eval('__all__', namespace)
smalll.sort()
else:
smalll = [s for s in bigl if (s[:1] != '_')]
else:
try:
entity = self.get_entity(what)
bigl = dir(entity)
bigl.sort()
if ('__all__' in bigl):
smalll = entity.__all__
smalll.sort()
else:
smalll = [s for s in bigl if (s[:1] != '_')]
except:
return ([], [])
elif (mode == COMPLETE_FILES):
if (what == ''):
what = '.'
try:
expandedpath = os.path.expanduser(what)
bigl = os.listdir(expandedpath)
bigl.sort()
smalll = [s for s in bigl if (s[:1] != '.')]
except OSError:
return ([], [])
if (not smalll):
smalll = bigl
return (smalll, bigl)
|
'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: ', client_address
print >>erf, 'Request: ', repr(request)
traceback.print_exc(file=erf)
print >>erf, '\n*** Unrecoverable, server exiting!'
print >>erf, ('-' * 40)
os._exit(0)
|
'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 are used for tasks (which may block or hang) to be
processed in a different thread. These requests are fed into
request_queue by self.localcall(). Responses to queued requests are
taken from response_queue and sent across the link with the associated
sequence numbers. Messages in the queues are (sequence_number,
request/response) tuples and code using this module removing messages
from the request_queue is responsible for returning the correct
sequence number in the response_queue.
pollresponse() will loop until a response message with the myseq
sequence number is received, and will save other responses in
self.responses and notify the owning thread.'
| 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 (message is None):
return None
except EOFError:
self.handle_EOF()
return None
except AttributeError:
return None
(seq, resq) = message
how = resq[0]
self.debug(('pollresponse:%d:myseq:%s' % (seq, myseq)))
if (how in ('CALL', 'QUEUE')):
self.debug(('pollresponse:%d:localcall:call:' % seq))
response = self.localcall(seq, resq)
self.debug(('pollresponse:%d:localcall:response:%s' % (seq, response)))
if (how == 'CALL'):
self.putmessage((seq, response))
elif (how == 'QUEUE'):
pass
continue
elif (seq == myseq):
return resq
else:
cv = self.cvars.get(seq, None)
if (cv is not None):
cv.acquire()
self.responses[seq] = resq
cv.notify()
cv.release()
continue
|
'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()
self.protocol('WM_DELETE_WINDOW', self.Ok)
self.parent = parent
self.textView.focus_set()
self.bind('<Return>', self.Ok)
self.bind('<Escape>', self.Ok)
self.textView.insert(0.0, text)
self.textView.config(state=DISABLED)
self.wait_window()
|
'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 (indent, text, opener)
|
'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')):
lastindent += 1
if (opener and (linenum < new_topvisible) and (indent >= stopindent)):
lines.append((linenum, indent, text, opener))
if (lastindent <= stopindent):
break
lines.reverse()
return (lines, lastindent)
|
'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.info[(-1)]
elif (self.topvisible > new_topvisible):
stopindent = (self.info[(-1)][1] + 1)
while (self.info[(-1)][0] >= new_topvisible):
stopindent = self.info[(-1)][1]
del self.info[(-1)]
(lines, lastindent) = self.get_context(new_topvisible, (self.info[(-1)][0] + 1), stopindent)
self.info.extend(lines)
self.topvisible = new_topvisible
context_strings = ([''] * max(0, (self.context_depth - len(self.info))))
context_strings += [x[2] for x in self.info[(- self.context_depth):]]
self.label['text'] = '\n'.join(context_strings)
|
'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)
if (first == last):
return self.completions[first]
first_comp = self.completions[first]
last_comp = self.completions[last]
min_len = min(len(first_comp), len(last_comp))
i = len(s)
while ((i < min_len) and (first_comp[i] == last_comp[i])):
i += 1
return first_comp[:i]
|
'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 (lts[i] == selstart[i])):
i += 1
newstart = selstart[:i]
self._change_start(newstart)
if (self.completions[cursel][:len(self.start)] == self.start):
self.listbox.configure(selectbackground=self.origselbackground, selectforeground=self.origselforeground)
else:
self.listbox.configure(selectbackground=self.listbox.cget('bg'), selectforeground=self.listbox.cget('fg'))
if self.morecompletions:
self.completions = self.morecompletions
self.morecompletions = None
self.listbox.delete(0, END)
for item in self.completions:
self.listbox.insert(END, item)
self.listbox.select_set(self._binary_search(self.start))
self._selection_changed()
|
'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_search(completed)
if ((self.completions[i] == completed) and ((i == (len(self.completions) - 1)) or (self.completions[(i + 1)][:len(completed)] != completed))):
return
self.userwantswindow = userWantsWin
self.lasttypedstart = self.start
self.autocompletewindow = acw = Toplevel(self.widget)
acw.wm_geometry('+10000+10000')
acw.wm_overrideredirect(1)
try:
acw.tk.call('::tk::unsupported::MacWindowStyle', 'style', acw._w, 'help', 'noActivates')
except TclError:
pass
self.scrollbar = scrollbar = Scrollbar(acw, orient=VERTICAL)
self.listbox = listbox = Listbox(acw, yscrollcommand=scrollbar.set, exportselection=False, bg='white')
for item in self.completions:
listbox.insert(END, item)
self.origselforeground = listbox.cget('selectforeground')
self.origselbackground = listbox.cget('selectbackground')
scrollbar.config(command=listbox.yview)
scrollbar.pack(side=RIGHT, fill=Y)
listbox.pack(side=LEFT, fill=BOTH, expand=True)
self.listbox.select_set(self._binary_search(self.start))
self._selection_changed()
self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event)
for seq in HIDE_SEQUENCES:
self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq)
self.keypressid = self.widget.bind(KEYPRESS_VIRTUAL_EVENT_NAME, self.keypress_event)
for seq in KEYPRESS_SEQUENCES:
self.widget.event_add(KEYPRESS_VIRTUAL_EVENT_NAME, seq)
self.keyreleaseid = self.widget.bind(KEYRELEASE_VIRTUAL_EVENT_NAME, self.keyrelease_event)
self.widget.event_add(KEYRELEASE_VIRTUAL_EVENT_NAME, KEYRELEASE_SEQUENCE)
self.listupdateid = listbox.bind(LISTUPDATE_SEQUENCE, self.listselect_event)
self.winconfigid = acw.bind(WINCONFIG_SEQUENCE, self.winconfig_event)
self.doubleclickid = listbox.bind(DOUBLECLICK_SEQUENCE, self.doubleclick_event)
|
'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:
return filename.decode('iso8859-1')
|
'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[edge_index])
except TclError:
pass
return move_at_edge
|
'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(foreground=normal_colors['foreground'], background=normal_colors['background'], insertbackground=cursor_color, selectforeground=select_colors['foreground'], selectbackground=select_colors['background'])
|
'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:
for (event, keylist) in xkeydefs.items():
self.text.event_delete(event, *keylist)
|
'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 menu in self.Bindings.menudefs:
menuEventDict[menu[0]] = {}
for item in menu[1]:
if item:
menuEventDict[menu[0]][prepstr(item[0])[1]] = item[1]
for menubarItem in self.menudict.keys():
menu = self.menudict[menubarItem]
end = (menu.index(END) + 1)
for index in range(0, end):
if (menu.type(index) == 'command'):
accel = menu.entrycget(index, 'accelerator')
if accel:
itemName = menu.entrycget(index, 'label')
event = ''
if (menubarItem in menuEventDict):
if (itemName in menuEventDict[menubarItem]):
event = menuEventDict[menubarItem][itemName]
if event:
accel = get_accelerator(keydefs, event)
menu.entryconfig(index, accelerator=accel)
|
'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()
for entry in help_list:
cmd = self.__extra_help_callback(entry[1])
helpmenu.add_command(label=entry[0], command=cmd)
self.menudict['help'] = helpmenu
|
'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.showerror(title='Document Start Failure', message=str(why), parent=self.text)
else:
webbrowser.open(helpfile)
return display_extra_help
|
'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_file in rf_list):
rf_list.remove(new_file)
rf_list.insert(0, new_file)
bad_paths = []
for path in rf_list:
if (('\x00' in path) or (not os.path.exists(path[0:(-1)]))):
bad_paths.append(path)
rf_list = [path for path in rf_list if (path not in bad_paths)]
ulchars = '1234567890ABCDEFGHIJK'
rf_list = rf_list[0:len(ulchars)]
rf_file = open(self.recent_files_path, 'w')
try:
rf_file.writelines(rf_list)
finally:
rf_file.close()
for instance in self.top.instance_dict.keys():
menu = instance.recent_files_menu
menu.delete(1, END)
for (i, file_name) in enumerate(rf_list):
file_name = file_name.rstrip()
ufile_name = self._filename_to_unicode(file_name)
callback = instance.__recent_file_callback(file_name)
menu.add_command(label=((ulchars[i] + ' ') + ufile_name), command=callback, underline=0)
|
'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
for entry in entrylist:
if (not entry):
menu.add_separator()
else:
(label, eventname) = entry
checkbutton = (label[:1] == '!')
if checkbutton:
label = label[1:]
(underline, label) = prepstr(label)
accelerator = get_accelerator(keydefs, eventname)
def command(text=text, eventname=eventname):
text.event_generate(eventname)
if checkbutton:
var = self.get_var_obj(eventname, BooleanVar)
menu.add_checkbutton(label=label, underline=underline, command=command, accelerator=accelerator, variable=var)
else:
menu.add_command(label=label, underline=underline, command=command, accelerator=accelerator)
|
'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])) + '\n')
for macro in self.macros.keys():
rep = (((rep + 'macdef ') + macro) + '\n')
for line in self.macros[macro]:
rep = (rep + line)
rep = (rep + '\n')
return rep
|
'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 % {'stmt': stmt, 'setup': '_setup()'})
ns['_setup'] = setup
else:
raise ValueError('setup is neither a string nor callable')
self.src = src
code = compile(src, dummy_src_name, 'exec')
exec code in globals(), ns
self.inner = ns['inner']
elif hasattr(stmt, '__call__'):
self.src = None
if isinstance(setup, basestring):
_setup = setup
def setup():
exec _setup in globals(), ns
elif (not hasattr(setup, '__call__')):
raise ValueError('setup is neither a string nor callable')
self.inner = _template_func(setup, stmt)
else:
raise ValueError('stmt is neither a string nor callable')
|
'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 the traceback is
sent; it defaults to sys.stderr.'
| 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 statement, the setup statement and
the timer function to be used are passed to the constructor.'
| 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 and standard deviation
from the result vector and report these. However, this is not
very useful. In a typical case, the lowest value gives a
lower bound for how fast your machine can run the given code
snippet; higher values in the result vector are typically not
caused by variability in Python\'s speed, but by other
processes interfering with your timing accuracy. So the min()
of the result is probably the only number you should be
interested in. After that, you should look at the entire
vector and apply common sense rather than statistics.'
| 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
Decimal(\'314\')
>>> Decimal(\' 3.14 \n\') # leading and trailing whitespace okay
Decimal(\'3.14\')'
| 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))
if (m.group('sign') == '-'):
self._sign = 1
else:
self._sign = 0
intpart = m.group('int')
if (intpart is not None):
fracpart = (m.group('frac') or '')
exp = int((m.group('exp') or '0'))
self._int = str(int((intpart + fracpart)))
self._exp = (exp - len(fracpart))
self._is_special = False
else:
diag = m.group('diag')
if (diag is not None):
self._int = str(int((diag or '0'))).lstrip('0')
if m.group('signal'):
self._exp = 'N'
else:
self._exp = 'n'
else:
self._int = '0'
self._exp = 'F'
self._is_special = True
return self
if isinstance(value, (int, long)):
if (value >= 0):
self._sign = 0
else:
self._sign = 1
self._exp = 0
self._int = str(abs(value))
self._is_special = False
return self
if isinstance(value, Decimal):
self._exp = value._exp
self._sign = value._sign
self._int = value._int
self._is_special = value._is_special
return self
if isinstance(value, _WorkRep):
self._sign = value.sign
self._int = str(value.int)
self._exp = int(value.exp)
self._is_special = False
return self
if isinstance(value, (list, tuple)):
if (len(value) != 3):
raise ValueError('Invalid tuple size in creation of Decimal from list or tuple. The list or tuple should have exactly three elements.')
if (not (isinstance(value[0], (int, long)) and (value[0] in (0, 1)))):
raise ValueError('Invalid sign. The first value in the tuple should be an integer; either 0 for a positive number or 1 for a negative number.')
self._sign = value[0]
if (value[2] == 'F'):
self._int = '0'
self._exp = value[2]
self._is_special = True
else:
digits = []
for digit in value[1]:
if (isinstance(digit, (int, long)) and (0 <= digit <= 9)):
if (digits or (digit != 0)):
digits.append(digit)
else:
raise ValueError('The second value in the tuple must be composed of integers in the range 0 through 9.')
if (value[2] in ('n', 'N')):
self._int = ''.join(map(str, digits))
self._exp = value[2]
self._is_special = True
elif isinstance(value[2], (int, long)):
self._int = ''.join(map(str, (digits or [0])))
self._exp = value[2]
self._is_special = False
else:
raise ValueError("The third value in the tuple must be an integer, or one of the strings 'F', 'n', 'N'.")
return self
if isinstance(value, float):
value = Decimal.from_float(value)
self._exp = value._exp
self._sign = value._sign
self._int = value._int
self._is_special = value._is_special
return self
raise TypeError(('Cannot convert %r to Decimal' % 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.1000000000000000055511151231257827021181583404541015625.
>>> Decimal.from_float(0.1)
Decimal(\'0.1000000000000000055511151231257827021181583404541015625\')
>>> Decimal.from_float(float(\'nan\'))
Decimal(\'NaN\')
>>> Decimal.from_float(float(\'inf\'))
Decimal(\'Infinity\')
>>> Decimal.from_float(-float(\'inf\'))
Decimal(\'-Infinity\')
>>> Decimal.from_float(-0.0)
Decimal(\'-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((n * (5 ** k))), (- k))
if (cls is Decimal):
return result
else:
return cls(result)
|
'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(InvalidOperation, 'sNaN', self)
if (other_is_nan == 2):
return context._raise_error(InvalidOperation, 'sNaN', other)
if self_is_nan:
return self._fix_nan(context)
return other._fix_nan(context)
return 0
|
'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, 'comparison involving sNaN', other)
elif self.is_qnan():
return context._raise_error(InvalidOperation, 'comparison involving NaN', self)
elif other.is_qnan():
return context._raise_error(InvalidOperation, 'comparison involving NaN', other)
return 0
|
'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):
return 0
else:
return (- ((-1) ** other._sign))
if (not other):
return ((-1) ** self._sign)
if (other._sign < self._sign):
return (-1)
if (self._sign < other._sign):
return 1
self_adjusted = self.adjusted()
other_adjusted = other.adjusted()
if (self_adjusted == other_adjusted):
self_padded = (self._int + ('0' * (self._exp - other._exp)))
other_padded = (other._int + ('0' * (other._exp - self._exp)))
if (self_padded == other_padded):
return 0
elif (self_padded < other_padded):
return (- ((-1) ** self._sign))
else:
return ((-1) ** self._sign)
elif (self_adjusted > other_adjusted):
return ((-1) ** self._sign)
else:
return (- ((-1) ** self._sign))
|
'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 (Decimal.from_float(self_as_float) == self):
return hash(self_as_float)
if self._isinteger():
op = _WorkRep(self.to_integral_value())
return hash(((((-1) ** op.sign) * op.int) * pow(10, op.exp, ((2 ** 64) - 1))))
return hash((self._sign, (self._exp + len(self._int)), self._int.rstrip('0')))
|
'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))
if ((self._exp <= 0) and (leftdigits > (-6))):
dotplace = leftdigits
elif (not eng):
dotplace = 1
elif (self._int == '0'):
dotplace = (((leftdigits + 1) % 3) - 1)
else:
dotplace = (((leftdigits - 1) % 3) + 1)
if (dotplace <= 0):
intpart = '0'
fracpart = (('.' + ('0' * (- dotplace))) + self._int)
elif (dotplace >= len(self._int)):
intpart = (self._int + ('0' * (dotplace - len(self._int))))
fracpart = ''
else:
intpart = self._int[:dotplace]
fracpart = ('.' + self._int[dotplace:])
if (leftdigits == dotplace):
exp = ''
else:
if (context is None):
context = getcontext()
exp = (['e', 'E'][context.capitals] + ('%+d' % (leftdigits - dotplace)))
return (((sign + intpart) + fracpart) + exp)
|
'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(context)
|
'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(context)
|
'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():
if ((self._sign != other._sign) and other._isinfinity()):
return context._raise_error(InvalidOperation, '-INF + INF')
return Decimal(self)
if other._isinfinity():
return Decimal(other)
exp = min(self._exp, other._exp)
negativezero = 0
if ((context.rounding == ROUND_FLOOR) and (self._sign != other._sign)):
negativezero = 1
if ((not self) and (not other)):
sign = min(self._sign, other._sign)
if negativezero:
sign = 1
ans = _dec_from_triple(sign, '0', exp)
ans = ans._fix(context)
return ans
if (not self):
exp = max(exp, ((other._exp - context.prec) - 1))
ans = other._rescale(exp, context.rounding)
ans = ans._fix(context)
return ans
if (not other):
exp = max(exp, ((self._exp - context.prec) - 1))
ans = self._rescale(exp, context.rounding)
ans = ans._fix(context)
return ans
op1 = _WorkRep(self)
op2 = _WorkRep(other)
(op1, op2) = _normalize(op1, op2, context.prec)
result = _WorkRep()
if (op1.sign != op2.sign):
if (op1.int == op2.int):
ans = _dec_from_triple(negativezero, '0', exp)
ans = ans._fix(context)
return ans
if (op1.int < op2.int):
(op1, op2) = (op2, op1)
if (op1.sign == 1):
result.sign = 1
(op1.sign, op2.sign) = (op2.sign, op1.sign)
else:
result.sign = 0
elif (op1.sign == 1):
result.sign = 1
(op1.sign, op2.sign) = (0, 0)
else:
result.sign = 0
if (op2.sign == 0):
result.int = (op1.int + op2.int)
else:
result.int = (op1.int - op2.int)
result.exp = op1.exp
ans = Decimal(result)
ans = ans._fix(context)
return ans
|
'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 ans
if self._isinfinity():
if (not other):
return context._raise_error(InvalidOperation, '(+-)INF * 0')
return _SignedInfinity[resultsign]
if other._isinfinity():
if (not self):
return context._raise_error(InvalidOperation, '0 * (+-)INF')
return _SignedInfinity[resultsign]
resultexp = (self._exp + other._exp)
if ((not self) or (not other)):
ans = _dec_from_triple(resultsign, '0', resultexp)
ans = ans._fix(context)
return ans
if (self._int == '1'):
ans = _dec_from_triple(resultsign, other._int, resultexp)
ans = ans._fix(context)
return ans
if (other._int == '1'):
ans = _dec_from_triple(resultsign, self._int, resultexp)
ans = ans._fix(context)
return ans
op1 = _WorkRep(self)
op2 = _WorkRep(other)
ans = _dec_from_triple(resultsign, str((op1.int * op2.int)), resultexp)
ans = ans._fix(context)
return ans
|
'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:
return ans
if (self._isinfinity() and other._isinfinity()):
return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
if self._isinfinity():
return _SignedInfinity[sign]
if other._isinfinity():
context._raise_error(Clamped, 'Division by infinity')
return _dec_from_triple(sign, '0', context.Etiny())
if (not other):
if (not self):
return context._raise_error(DivisionUndefined, '0 / 0')
return context._raise_error(DivisionByZero, 'x / 0', sign)
if (not self):
exp = (self._exp - other._exp)
coeff = 0
else:
shift = (((len(other._int) - len(self._int)) + context.prec) + 1)
exp = ((self._exp - other._exp) - shift)
op1 = _WorkRep(self)
op2 = _WorkRep(other)
if (shift >= 0):
(coeff, remainder) = divmod((op1.int * (10 ** shift)), op2.int)
else:
(coeff, remainder) = divmod(op1.int, (op2.int * (10 ** (- shift))))
if remainder:
if ((coeff % 5) == 0):
coeff += 1
else:
ideal_exp = (self._exp - other._exp)
while ((exp < ideal_exp) and ((coeff % 10) == 0)):
coeff //= 10
exp += 1
ans = _dec_from_triple(sign, str(coeff), exp)
return ans._fix(context)
|
'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), self._rescale(ideal_exp, context.rounding))
if (expdiff <= context.prec):
op1 = _WorkRep(self)
op2 = _WorkRep(other)
if (op1.exp >= op2.exp):
op1.int *= (10 ** (op1.exp - op2.exp))
else:
op2.int *= (10 ** (op2.exp - op1.exp))
(q, r) = divmod(op1.int, op2.int)
if (q < (10 ** context.prec)):
return (_dec_from_triple(sign, str(q), 0), _dec_from_triple(self._sign, str(r), ideal_exp))
ans = context._raise_error(DivisionImpossible, 'quotient too large in //, % or divmod')
return (ans, ans)
|
'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():
ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
return (ans, ans)
else:
return (_SignedInfinity[sign], context._raise_error(InvalidOperation, 'INF % x'))
if (not other):
if (not self):
ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
return (ans, ans)
else:
return (context._raise_error(DivisionByZero, 'x // 0', sign), context._raise_error(InvalidOperation, 'x % 0'))
(quotient, remainder) = self._divide(other, context)
remainder = remainder._fix(context)
return (quotient, remainder)
|
'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')
elif (not other):
if self:
return context._raise_error(InvalidOperation, 'x % 0')
else:
return context._raise_error(DivisionUndefined, '0 % 0')
remainder = self._divide(other, context)[1]
remainder = remainder._fix(context)
return remainder
|
'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):
if self:
return context._raise_error(InvalidOperation, 'remainder_near(x, 0)')
else:
return context._raise_error(DivisionUndefined, 'remainder_near(0, 0)')
if other._isinfinity():
ans = Decimal(self)
return ans._fix(context)
ideal_exponent = min(self._exp, other._exp)
if (not self):
ans = _dec_from_triple(self._sign, '0', ideal_exponent)
return ans._fix(context)
expdiff = (self.adjusted() - other.adjusted())
if (expdiff >= (context.prec + 1)):
return context._raise_error(DivisionImpossible)
if (expdiff <= (-2)):
ans = self._rescale(ideal_exponent, context.rounding)
return ans._fix(context)
op1 = _WorkRep(self)
op2 = _WorkRep(other)
if (op1.exp >= op2.exp):
op1.int *= (10 ** (op1.exp - op2.exp))
else:
op2.int *= (10 ** (op2.exp - op1.exp))
(q, r) = divmod(op1.int, op2.int)
if (((2 * r) + (q & 1)) > op2.int):
r -= op2.int
q += 1
if (q >= (10 ** context.prec)):
return context._raise_error(DivisionImpossible)
sign = self._sign
if (r < 0):
sign = (1 - sign)
r = (- r)
ans = _dec_from_triple(sign, str(r), ideal_exponent)
return ans._fix(context)
|
'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(InvalidOperation, 'INF // INF')
else:
return _SignedInfinity[(self._sign ^ other._sign)]
if (not other):
if self:
return context._raise_error(DivisionByZero, 'x // 0', (self._sign ^ other._sign))
else:
return context._raise_error(DivisionUndefined, '0 // 0')
return self._divide(other, context)[0]
|
'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(self._int)) * (10 ** self._exp))
else:
return (s * int((self._int[:self._exp] or '0')))
|
'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)
if (new_exp != self._exp):
context._raise_error(Clamped)
return _dec_from_triple(self._sign, '0', new_exp)
else:
return Decimal(self)
exp_min = ((len(self._int) + self._exp) - context.prec)
if (exp_min > Etop):
ans = context._raise_error(Overflow, 'above Emax', self._sign)
context._raise_error(Inexact)
context._raise_error(Rounded)
return ans
self_is_subnormal = (exp_min < Etiny)
if self_is_subnormal:
exp_min = Etiny
if (self._exp < exp_min):
digits = ((len(self._int) + self._exp) - exp_min)
if (digits < 0):
self = _dec_from_triple(self._sign, '1', (exp_min - 1))
digits = 0
rounding_method = self._pick_rounding_function[context.rounding]
changed = rounding_method(self, digits)
coeff = (self._int[:digits] or '0')
if (changed > 0):
coeff = str((int(coeff) + 1))
if (len(coeff) > context.prec):
coeff = coeff[:(-1)]
exp_min += 1
if (exp_min > Etop):
ans = context._raise_error(Overflow, 'above Emax', self._sign)
else:
ans = _dec_from_triple(self._sign, coeff, exp_min)
if (changed and self_is_subnormal):
context._raise_error(Underflow)
if self_is_subnormal:
context._raise_error(Subnormal)
if changed:
context._raise_error(Inexact)
context._raise_error(Rounded)
if (not ans):
context._raise_error(Clamped)
return ans
if self_is_subnormal:
context._raise_error(Subnormal)
if ((context._clamp == 1) and (self._exp > Etop)):
context._raise_error(Clamped)
self_padded = (self._int + ('0' * (self._exp - Etop)))
return _dec_from_triple(self._sign, self_padded, Etop)
return Decimal(self)
|
'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 context._raise_error(InvalidOperation, 'sNaN', other)
if (self._exp == 'n'):
product = self
elif (other._exp == 'n'):
product = other
elif (self._exp == 'F'):
if (not other):
return context._raise_error(InvalidOperation, 'INF * 0 in fma')
product = _SignedInfinity[(self._sign ^ other._sign)]
elif (other._exp == 'F'):
if (not self):
return context._raise_error(InvalidOperation, '0 * INF in fma')
product = _SignedInfinity[(self._sign ^ other._sign)]
else:
product = _dec_from_triple((self._sign ^ other._sign), str((int(self._int) * int(other._int))), (self._exp + other._exp))
third = _convert_other(third, raiseit=True)
return product.__add__(third, context)
|
'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):
if (self_is_nan == 2):
return context._raise_error(InvalidOperation, 'sNaN', self)
if (other_is_nan == 2):
return context._raise_error(InvalidOperation, 'sNaN', other)
if (modulo_is_nan == 2):
return context._raise_error(InvalidOperation, 'sNaN', modulo)
if self_is_nan:
return self._fix_nan(context)
if other_is_nan:
return other._fix_nan(context)
return modulo._fix_nan(context)
if (not (self._isinteger() and other._isinteger() and modulo._isinteger())):
return context._raise_error(InvalidOperation, 'pow() 3rd argument not allowed unless all arguments are integers')
if (other < 0):
return context._raise_error(InvalidOperation, 'pow() 2nd argument cannot be negative when 3rd argument specified')
if (not modulo):
return context._raise_error(InvalidOperation, 'pow() 3rd argument cannot be 0')
if (modulo.adjusted() >= context.prec):
return context._raise_error(InvalidOperation, 'insufficient precision: pow() 3rd argument must not have more than precision digits')
if ((not other) and (not self)):
return context._raise_error(InvalidOperation, 'at least one of pow() 1st argument and 2nd argument must be nonzero ;0**0 is not defined')
if other._iseven():
sign = 0
else:
sign = self._sign
modulo = abs(int(modulo))
base = _WorkRep(self.to_integral_value())
exponent = _WorkRep(other.to_integral_value())
base = (((base.int % modulo) * pow(10, base.exp, modulo)) % modulo)
for i in xrange(exponent.exp):
base = pow(base, 10, modulo)
base = pow(base, exponent.int, modulo)
return _dec_from_triple(sign, str(base), 0)
|
'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: self and other must both be nonspecial; self must
be positive and not numerically equal to 1; other must be
nonzero. For efficiency, other._exp should not be too large,
so that 10**abs(other._exp) is a feasible calculation.'
| 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
ye += 1
if (ye < 0):
return None
exponent = (xe * (10 ** ye))
if (y.sign == 1):
exponent = (- exponent)
if (other._isinteger() and (other._sign == 0)):
ideal_exponent = (self._exp * int(other))
zeros = min((exponent - ideal_exponent), (p - 1))
else:
zeros = 0
return _dec_from_triple(0, ('1' + ('0' * zeros)), (exponent - zeros))
if (y.sign == 1):
last_digit = (xc % 10)
if (last_digit in (2, 4, 6, 8)):
if ((xc & (- xc)) != xc):
return None
e = (_nbits(xc) - 1)
if (ye >= 0):
y_as_int = (yc * (10 ** ye))
e = (e * y_as_int)
xe = (xe * y_as_int)
else:
ten_pow = (10 ** (- ye))
(e, remainder) = divmod((e * yc), ten_pow)
if remainder:
return None
(xe, remainder) = divmod((xe * yc), ten_pow)
if remainder:
return None
if ((e * 65) >= (p * 93)):
return None
xc = (5 ** e)
elif (last_digit == 5):
e = ((_nbits(xc) * 28) // 65)
(xc, remainder) = divmod((5 ** e), xc)
if remainder:
return None
while ((xc % 5) == 0):
xc //= 5
e -= 1
if (ye >= 0):
y_as_integer = (yc * (10 ** ye))
e = (e * y_as_integer)
xe = (xe * y_as_integer)
else:
ten_pow = (10 ** (- ye))
(e, remainder) = divmod((e * yc), ten_pow)
if remainder:
return None
(xe, remainder) = divmod((xe * yc), ten_pow)
if remainder:
return None
if ((e * 3) >= (p * 10)):
return None
xc = (2 ** e)
else:
return None
if (xc >= (10 ** p)):
return None
xe = ((- e) - xe)
return _dec_from_triple(0, str(xc), xe)
if (ye >= 0):
(m, n) = ((yc * (10 ** ye)), 1)
else:
if ((xe != 0) and (len(str(abs((yc * xe)))) <= (- ye))):
return None
xc_bits = _nbits(xc)
if ((xc != 1) and (len(str((abs(yc) * xc_bits))) <= (- ye))):
return None
(m, n) = (yc, (10 ** (- ye)))
while ((m % 2) == (n % 2) == 0):
m //= 2
n //= 2
while ((m % 5) == (n % 5) == 0):
m //= 5
n //= 5
if (n > 1):
if ((xc != 1) and (xc_bits <= n)):
return None
(xe, rem) = divmod(xe, n)
if (rem != 0):
return None
a = (1L << (- ((- _nbits(xc)) // n)))
while True:
(q, r) = divmod(xc, (a ** (n - 1)))
if (a <= q):
break
else:
a = (((a * (n - 1)) + q) // n)
if (not ((a == q) and (r == 0))):
return None
xc = a
if ((xc > 1) and (m > ((p * 100) // _log10_lb(xc)))):
return None
xc = (xc ** m)
xe *= m
if (xc > (10 ** p)):
return None
str_xc = str(xc)
if (other._isinteger() and (other._sign == 0)):
ideal_exponent = (self._exp * int(other))
zeros = min((xe - ideal_exponent), (p - len(str_xc)))
else:
zeros = 0
return _dec_from_triple(0, (str_xc + ('0' * zeros)), (xe - zeros))
|
'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 nonzero
- modulo must be nonzero and must have at most p digits,
where p is the context precision.
If any of these restrictions is violated the InvalidOperation
flag is raised.
The result of pow(self, other, modulo) is identical to the
result that would be obtained by computing (self**other) %
modulo with unbounded precision, but is computed more
efficiently. It is always exact.'
| 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 other):
if (not self):
return context._raise_error(InvalidOperation, '0 ** 0')
else:
return _One
result_sign = 0
if (self._sign == 1):
if other._isinteger():
if (not other._iseven()):
result_sign = 1
elif self:
return context._raise_error(InvalidOperation, 'x ** y with x negative and y not an integer')
self = self.copy_negate()
if (not self):
if (other._sign == 0):
return _dec_from_triple(result_sign, '0', 0)
else:
return _SignedInfinity[result_sign]
if self._isinfinity():
if (other._sign == 0):
return _SignedInfinity[result_sign]
else:
return _dec_from_triple(result_sign, '0', 0)
if (self == _One):
if other._isinteger():
if (other._sign == 1):
multiplier = 0
elif (other > context.prec):
multiplier = context.prec
else:
multiplier = int(other)
exp = (self._exp * multiplier)
if (exp < (1 - context.prec)):
exp = (1 - context.prec)
context._raise_error(Rounded)
else:
context._raise_error(Inexact)
context._raise_error(Rounded)
exp = (1 - context.prec)
return _dec_from_triple(result_sign, ('1' + ('0' * (- exp))), exp)
self_adj = self.adjusted()
if other._isinfinity():
if ((other._sign == 0) == (self_adj < 0)):
return _dec_from_triple(result_sign, '0', 0)
else:
return _SignedInfinity[result_sign]
ans = None
exact = False
bound = (self._log10_exp_bound() + other.adjusted())
if ((self_adj >= 0) == (other._sign == 0)):
if (bound >= len(str(context.Emax))):
ans = _dec_from_triple(result_sign, '1', (context.Emax + 1))
else:
Etiny = context.Etiny()
if (bound >= len(str((- Etiny)))):
ans = _dec_from_triple(result_sign, '1', (Etiny - 1))
if (ans is None):
ans = self._power_exact(other, (context.prec + 1))
if (ans is not None):
if (result_sign == 1):
ans = _dec_from_triple(1, ans._int, ans._exp)
exact = True
if (ans is None):
p = context.prec
x = _WorkRep(self)
(xc, xe) = (x.int, x.exp)
y = _WorkRep(other)
(yc, ye) = (y.int, y.exp)
if (y.sign == 1):
yc = (- yc)
extra = 3
while True:
(coeff, exp) = _dpower(xc, xe, yc, ye, (p + extra))
if (coeff % (5 * (10 ** ((len(str(coeff)) - p) - 1)))):
break
extra += 3
ans = _dec_from_triple(result_sign, str(coeff), exp)
if (exact and (not other._isinteger())):
if (len(ans._int) <= context.prec):
expdiff = ((context.prec + 1) - len(ans._int))
ans = _dec_from_triple(ans._sign, (ans._int + ('0' * expdiff)), (ans._exp - expdiff))
newcontext = context.copy()
newcontext.clear_flags()
for exception in _signals:
newcontext.traps[exception] = 0
ans = ans._fix(newcontext)
newcontext._raise_error(Inexact)
if newcontext.flags[Subnormal]:
newcontext._raise_error(Underflow)
if newcontext.flags[Overflow]:
context._raise_error(Overflow, 'above Emax', ans._sign)
for exception in (Underflow, Subnormal, Inexact, Rounded, Clamped):
if newcontext.flags[exception]:
context._raise_error(exception)
else:
ans = ans._fix(context)
return ans
|
'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_max = [context.Emax, context.Etop()][context._clamp]
end = len(dup._int)
exp = dup._exp
while ((dup._int[(end - 1)] == '0') and (exp < exp_max)):
exp += 1
end -= 1
return _dec_from_triple(dup._sign, dup._int[:end], 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._isinfinity() or self._isinfinity()):
if (exp._isinfinity() and self._isinfinity()):
return Decimal(self)
return context._raise_error(InvalidOperation, 'quantize with one INF')
if (not watchexp):
ans = self._rescale(exp._exp, rounding)
if (ans._exp > self._exp):
context._raise_error(Rounded)
if (ans != self):
context._raise_error(Inexact)
return ans
if (not (context.Etiny() <= exp._exp <= context.Emax)):
return context._raise_error(InvalidOperation, 'target exponent out of bounds in quantize')
if (not self):
ans = _dec_from_triple(self._sign, '0', exp._exp)
return ans._fix(context)
self_adjusted = self.adjusted()
if (self_adjusted > context.Emax):
return context._raise_error(InvalidOperation, 'exponent of quantize result too large for current context')
if (((self_adjusted - exp._exp) + 1) > context.prec):
return context._raise_error(InvalidOperation, 'quantize result has too many digits for current context')
ans = self._rescale(exp._exp, rounding)
if (ans.adjusted() > context.Emax):
return context._raise_error(InvalidOperation, 'exponent of quantize result too large for current context')
if (len(ans._int) > context.prec):
return context._raise_error(InvalidOperation, 'quantize result has too many digits for current context')
if (ans and (ans.adjusted() < context.Emin)):
context._raise_error(Subnormal)
if (ans._exp > self._exp):
if (ans != self):
context._raise_error(Inexact)
context._raise_error(Rounded)
ans = ans._fix(context)
return ans
|
'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):
self = _dec_from_triple(self._sign, '1', (exp - 1))
digits = 0
this_function = self._pick_rounding_function[rounding]
changed = this_function(self, digits)
coeff = (self._int[:digits] or '0')
if (changed == 1):
coeff = str((int(coeff) + 1))
return _dec_from_triple(self._sign, coeff, exp)
|
'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(((ans.adjusted() + 1) - places), rounding)
return ans
|
'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()
if (rounding is None):
rounding = context.rounding
ans = self._rescale(0, rounding)
if (ans != self):
context._raise_error(Inexact)
context._raise_error(Rounded)
return ans
|
'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)
else:
return self._rescale(0, rounding)
|
'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, '0', (self._exp // 2))
return ans._fix(context)
if (self._sign == 1):
return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
prec = (context.prec + 1)
op = _WorkRep(self)
e = (op.exp >> 1)
if (op.exp & 1):
c = (op.int * 10)
l = ((len(self._int) >> 1) + 1)
else:
c = op.int
l = ((len(self._int) + 1) >> 1)
shift = (prec - l)
if (shift >= 0):
c *= (100 ** shift)
exact = True
else:
(c, remainder) = divmod(c, (100 ** (- shift)))
exact = (not remainder)
e -= shift
n = (10 ** prec)
while True:
q = (c // n)
if (n <= q):
break
else:
n = ((n + q) >> 1)
exact = (exact and ((n * n) == c))
if exact:
if (shift >= 0):
n //= (10 ** shift)
else:
n *= (10 ** (- shift))
e += shift
elif ((n % 5) == 0):
n += 1
ans = _dec_from_triple(0, str(n), e)
context = context._shallow_copy()
rounding = context._set_rounding(ROUND_HALF_EVEN)
ans = ans._fix(context)
context.rounding = rounding
return ans
|
'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)
if ((sn == 1) and (on == 0)):
return other._fix(context)
return self._check_nans(other, context)
c = self._cmp(other)
if (c == 0):
c = self.compare_total(other)
if (c == (-1)):
ans = other
else:
ans = self
return ans._fix(context)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.