[yt-svn] commit/yt: 2 new changesets
commits-noreply at bitbucket.org
commits-noreply at bitbucket.org
Fri Feb 28 03:42:03 PST 2014
2 new commits in yt:
https://bitbucket.org/yt_analysis/yt/commits/fa9e71887344/
Changeset: fa9e71887344
Branch: yt-3.0
User: ngoldbaum
Date: 2014-02-25 18:54:49
Summary: Backing out c62c3cf
Affected #: 1 file
diff -r be8f535106ec53b427d8fbf04353288a17408aac -r fa9e7188734481e9958debac3c74bd87412f5180 yt/extern/progressbar/progressbar.py
--- a/yt/extern/progressbar/progressbar.py
+++ b/yt/extern/progressbar/progressbar.py
@@ -410,9 +410,7 @@
from IPython.display import Javascript, display
# First delete the node that held the progress bar from the page
js = """var element = document.getElementById('%s');
- var parent = element.parentNode
- parent.removeChild(element);
- parent.parentElement.remove();""" % self.uuid
+ element.parentNode.removeChild(element);""" % self.uuid
display(Javascript(js))
# Then also remove its trace from the cell output (so it doesn't get
https://bitbucket.org/yt_analysis/yt/commits/b81922576046/
Changeset: b81922576046
Branch: yt-3.0
User: ngoldbaum
Date: 2014-02-25 18:56:11
Summary: Backing out 0405d6ef
Affected #: 6 files
diff -r fa9e7188734481e9958debac3c74bd87412f5180 -r b8192257604644d2bb7a3534100df39fee93b072 yt/extern/progressbar.py
--- /dev/null
+++ b/yt/extern/progressbar.py
@@ -0,0 +1,368 @@
+#!/usr/bin/python
+# -*- coding: iso-8859-1 -*-
+#
+# progressbar - Text progressbar library for python.
+# Copyright (c) 2005 Nilton Volpato
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library; if not, write to the Free Software
+# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+
+"""Text progressbar library for python.
+
+This library provides a text mode progressbar. This is tipically used
+to display the progress of a long running operation, providing a
+visual clue that processing is underway.
+
+The ProgressBar class manages the progress, and the format of the line
+is given by a number of widgets. A widget is an object that may
+display diferently depending on the state of the progress. There are
+three types of widget:
+- a string, which always shows itself;
+- a ProgressBarWidget, which may return a diferent value every time
+it's update method is called; and
+- a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it
+expands to fill the remaining width of the line.
+
+The progressbar module is very easy to use, yet very powerful. And
+automatically supports features like auto-resizing when available.
+"""
+
+__author__ = "Nilton Volpato"
+__author_email__ = "first-name dot last-name @ gmail.com"
+__date__ = "2006-05-07"
+__version__ = "2.2"
+
+# Changelog
+#
+# 2006-05-07: v2.2 fixed bug in windows
+# 2005-12-04: v2.1 autodetect terminal width, added start method
+# 2005-12-04: v2.0 everything is now a widget (wow!)
+# 2005-12-03: v1.0 rewrite using widgets
+# 2005-06-02: v0.5 rewrite
+# 2004-??-??: v0.1 first version
+
+
+import sys, time
+from array import array
+try:
+ from fcntl import ioctl
+ import termios
+except ImportError:
+ pass
+import signal
+
+class ProgressBarWidget(object):
+ """This is an element of ProgressBar formatting.
+
+ The ProgressBar object will call it's update value when an update
+ is needed. It's size may change between call, but the results will
+ not be good if the size changes drastically and repeatedly.
+ """
+ def update(self, pbar):
+ """Returns the string representing the widget.
+
+ The parameter pbar is a reference to the calling ProgressBar,
+ where one can access attributes of the class for knowing how
+ the update must be made.
+
+ At least this function must be overriden."""
+ pass
+
+class ProgressBarWidgetHFill(object):
+ """This is a variable width element of ProgressBar formatting.
+
+ The ProgressBar object will call it's update value, informing the
+ width this object must the made. This is like TeX \\hfill, it will
+ expand to fill the line. You can use more than one in the same
+ line, and they will all have the same width, and together will
+ fill the line.
+ """
+ def update(self, pbar, width):
+ """Returns the string representing the widget.
+
+ The parameter pbar is a reference to the calling ProgressBar,
+ where one can access attributes of the class for knowing how
+ the update must be made. The parameter width is the total
+ horizontal width the widget must have.
+
+ At least this function must be overriden."""
+ pass
+
+
+class ETA(ProgressBarWidget):
+ "Widget for the Estimated Time of Arrival"
+ def format_time(self, seconds):
+ return time.strftime('%H:%M:%S', time.gmtime(seconds))
+ def update(self, pbar):
+ if pbar.currval == 0:
+ return 'ETA: --:--:--'
+ elif pbar.finished:
+ return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
+ else:
+ elapsed = pbar.seconds_elapsed
+ eta = elapsed * pbar.maxval / pbar.currval - elapsed
+ return 'ETA: %s' % self.format_time(eta)
+
+class FileTransferSpeed(ProgressBarWidget):
+ "Widget for showing the transfer speed (useful for file transfers)."
+ def __init__(self):
+ self.fmt = '%6.2f %s'
+ self.units = ['B','K','M','G','T','P']
+ def update(self, pbar):
+ if pbar.seconds_elapsed < 2e-6:#== 0:
+ bps = 0.0
+ else:
+ bps = float(pbar.currval) / pbar.seconds_elapsed
+ spd = bps
+ for u in self.units:
+ if spd < 1000:
+ break
+ spd /= 1000
+ return self.fmt % (spd, u+'/s')
+
+class RotatingMarker(ProgressBarWidget):
+ "A rotating marker for filling the bar of progress."
+ def __init__(self, markers='|/-\\'):
+ self.markers = markers
+ self.curmark = -1
+ def update(self, pbar):
+ if pbar.finished:
+ return self.markers[0]
+ self.curmark = (self.curmark + 1)%len(self.markers)
+ return self.markers[self.curmark]
+
+class Percentage(ProgressBarWidget):
+ "Just the percentage done."
+ def update(self, pbar):
+ return '%3d%%' % pbar.percentage()
+
+class Bar(ProgressBarWidgetHFill):
+ "The bar of progress. It will strech to fill the line."
+ def __init__(self, marker='#', left='|', right='|'):
+ self.marker = marker
+ self.left = left
+ self.right = right
+ def _format_marker(self, pbar):
+ if isinstance(self.marker, (str, unicode)):
+ return self.marker
+ else:
+ return self.marker.update(pbar)
+ def update(self, pbar, width):
+ percent = pbar.percentage()
+ cwidth = width - len(self.left) - len(self.right)
+ marked_width = int(percent * cwidth / 100)
+ m = self._format_marker(pbar)
+ bar = (self.left + (m*marked_width).ljust(cwidth) + self.right)
+ return bar
+
+class ReverseBar(Bar):
+ "The reverse bar of progress, or bar of regress. :)"
+ def update(self, pbar, width):
+ percent = pbar.percentage()
+ cwidth = width - len(self.left) - len(self.right)
+ marked_width = int(percent * cwidth / 100)
+ m = self._format_marker(pbar)
+ bar = (self.left + (m*marked_width).rjust(cwidth) + self.right)
+ return bar
+
+default_widgets = [Percentage(), ' ', Bar()]
+class ProgressBar(object):
+ """This is the ProgressBar class, it updates and prints the bar.
+
+ The term_width parameter may be an integer. Or None, in which case
+ it will try to guess it, if it fails it will default to 80 columns.
+
+ The simple use is like this:
+ >>> pbar = ProgressBar().start()
+ >>> for i in xrange(100):
+ ... # do something
+ ... pbar.update(i+1)
+ ...
+ >>> pbar.finish()
+
+ But anything you want to do is possible (well, almost anything).
+ You can supply different widgets of any type in any order. And you
+ can even write your own widgets! There are many widgets already
+ shipped and you should experiment with them.
+
+ When implementing a widget update method you may access any
+ attribute or function of the ProgressBar object calling the
+ widget's update method. The most important attributes you would
+ like to access are:
+ - currval: current value of the progress, 0 <= currval <= maxval
+ - maxval: maximum (and final) value of the progress
+ - finished: True if the bar is have finished (reached 100%), False o/w
+ - start_time: first time update() method of ProgressBar was called
+ - seconds_elapsed: seconds elapsed since start_time
+ - percentage(): percentage of the progress (this is a method)
+ """
+ def __init__(self, maxval=100, widgets=default_widgets, term_width=None,
+ fd=sys.stderr):
+ assert maxval > 0
+ self.maxval = maxval
+ self.widgets = widgets
+ self.fd = fd
+ self.signal_set = False
+ if term_width is None:
+ try:
+ self.handle_resize(None,None)
+ signal.signal(signal.SIGWINCH, self.handle_resize)
+ self.signal_set = True
+ except:
+ self.term_width = 79
+ else:
+ self.term_width = term_width
+
+ self.currval = 0
+ self.finished = False
+ self.prev_percentage = -1
+ self.start_time = None
+ self.seconds_elapsed = 0
+
+ def handle_resize(self, signum, frame):
+ h,w=array('h', ioctl(self.fd,termios.TIOCGWINSZ,'\0'*8))[:2]
+ self.term_width = w
+
+ def percentage(self):
+ "Returns the percentage of the progress."
+ return self.currval*100.0 / self.maxval
+
+ def _format_widgets(self):
+ r = []
+ hfill_inds = []
+ num_hfill = 0
+ currwidth = 0
+ for i, w in enumerate(self.widgets):
+ if isinstance(w, ProgressBarWidgetHFill):
+ r.append(w)
+ hfill_inds.append(i)
+ num_hfill += 1
+ elif isinstance(w, (str, unicode)):
+ r.append(w)
+ currwidth += len(w)
+ else:
+ weval = w.update(self)
+ currwidth += len(weval)
+ r.append(weval)
+ for iw in hfill_inds:
+ r[iw] = r[iw].update(self, (self.term_width-currwidth)/num_hfill)
+ return r
+
+ def _format_line(self):
+ return ''.join(self._format_widgets()).ljust(self.term_width)
+
+ def _need_update(self):
+ return int(self.percentage()) != int(self.prev_percentage)
+
+ def update(self, value):
+ "Updates the progress bar to a new value."
+ assert 0 <= value <= self.maxval
+ self.currval = value
+ if not self._need_update() or self.finished:
+ return
+ if not self.start_time:
+ self.start_time = time.time()
+ self.seconds_elapsed = time.time() - self.start_time
+ self.prev_percentage = self.percentage()
+ if value != self.maxval:
+ self.fd.write(self._format_line() + '\r')
+ else:
+ self.finished = True
+ self.fd.write(self._format_line() + '\n')
+
+ def start(self):
+ """Start measuring time, and prints the bar at 0%.
+
+ It returns self so you can use it like this:
+ >>> pbar = ProgressBar().start()
+ >>> for i in xrange(100):
+ ... # do something
+ ... pbar.update(i+1)
+ ...
+ >>> pbar.finish()
+ """
+ self.update(0)
+ return self
+
+ def finish(self):
+ """Used to tell the progress is finished."""
+ self.update(self.maxval)
+ if self.signal_set:
+ signal.signal(signal.SIGWINCH, signal.SIG_DFL)
+
+
+
+
+
+
+if __name__=='__main__':
+ import os
+
+ def example1():
+ widgets = ['Test: ', Percentage(), ' ', Bar(marker=RotatingMarker()),
+ ' ', ETA(), ' ', FileTransferSpeed()]
+ pbar = ProgressBar(widgets=widgets, maxval=10000000).start()
+ for i in range(1000000):
+ # do something
+ pbar.update(10*i+1)
+ pbar.finish()
+ print
+
+ def example2():
+ class CrazyFileTransferSpeed(FileTransferSpeed):
+ "It's bigger between 45 and 80 percent"
+ def update(self, pbar):
+ if 45 < pbar.percentage() < 80:
+ return 'Bigger Now ' + FileTransferSpeed.update(self,pbar)
+ else:
+ return FileTransferSpeed.update(self,pbar)
+
+ widgets = [CrazyFileTransferSpeed(),' <<<', Bar(), '>>> ', Percentage(),' ', ETA()]
+ pbar = ProgressBar(widgets=widgets, maxval=10000000)
+ # maybe do something
+ pbar.start()
+ for i in range(2000000):
+ # do something
+ pbar.update(5*i+1)
+ pbar.finish()
+ print
+
+ def example3():
+ widgets = [Bar('>'), ' ', ETA(), ' ', ReverseBar('<')]
+ pbar = ProgressBar(widgets=widgets, maxval=10000000).start()
+ for i in range(1000000):
+ # do something
+ pbar.update(10*i+1)
+ pbar.finish()
+ print
+
+ def example4():
+ widgets = ['Test: ', Percentage(), ' ',
+ Bar(marker='0',left='[',right=']'),
+ ' ', ETA(), ' ', FileTransferSpeed()]
+ pbar = ProgressBar(widgets=widgets, maxval=500)
+ pbar.start()
+ for i in range(100,500+1,50):
+ time.sleep(0.2)
+ pbar.update(i)
+ pbar.finish()
+ print
+
+
+ example1()
+ example2()
+ example3()
+ example4()
+
diff -r fa9e7188734481e9958debac3c74bd87412f5180 -r b8192257604644d2bb7a3534100df39fee93b072 yt/extern/progressbar/__init__.py
--- a/yt/extern/progressbar/__init__.py
+++ /dev/null
@@ -1,49 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# progressbar - Text progress bar library for Python.
-# Copyright (c) 2005 Nilton Volpato
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
-"""Text progress bar library for Python.
-
-A text progress bar is typically used to display the progress of a long
-running operation, providing a visual cue that processing is underway.
-
-The ProgressBar class manages the current progress, and the format of the line
-is given by a number of widgets. A widget is an object that may display
-differently depending on the state of the progress bar. There are three types
-of widgets:
- - a string, which always shows itself
-
- - a ProgressBarWidget, which may return a different value every time its
- update method is called
-
- - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it
- expands to fill the remaining width of the line.
-
-The progressbar module is very easy to use, yet very powerful. It will also
-automatically enable features like auto-resizing when the system supports it.
-"""
-
-__author__ = 'Nilton Volpato'
-__author_email__ = 'first-name dot last-name @ gmail.com'
-__date__ = '2011-05-14'
-__version__ = '2.3'
-
-from compat import *
-from widgets import *
-from progressbar import *
diff -r fa9e7188734481e9958debac3c74bd87412f5180 -r b8192257604644d2bb7a3534100df39fee93b072 yt/extern/progressbar/compat.py
--- a/yt/extern/progressbar/compat.py
+++ /dev/null
@@ -1,45 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# progressbar - Text progress bar library for Python.
-# Copyright (c) 2005 Nilton Volpato
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
-"""Compatibility methods and classes for the progressbar module."""
-
-
-# Python 3.x (and backports) use a modified iterator syntax
-# This will allow 2.x to behave with 3.x iterators
-try:
- next
-except NameError:
- def next(iter):
- try:
- # Try new style iterators
- return iter.__next__()
- except AttributeError:
- # Fallback in case of a "native" iterator
- return iter.next()
-
-
-# Python < 2.5 does not have "any"
-try:
- any
-except NameError:
- def any(iterator):
- for item in iterator:
- if item: return True
- return False
diff -r fa9e7188734481e9958debac3c74bd87412f5180 -r b8192257604644d2bb7a3534100df39fee93b072 yt/extern/progressbar/progressbar.py
--- a/yt/extern/progressbar/progressbar.py
+++ /dev/null
@@ -1,424 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# progressbar - Text progress bar library for Python.
-# Copyright (c) 2005 Nilton Volpato
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
-"""Main ProgressBar class."""
-
-from __future__ import division
-
-import math
-import os
-import signal
-import sys
-import time
-import uuid
-
-try:
- from fcntl import ioctl
- from array import array
- import termios
-except ImportError:
- pass
-
-import widgets
-
-# Test to see if we are in an IPython session.
-ipython = None
-for key in ['KernelApp','IPKernelApp']:
- try:
- ipython = get_ipython().config[key]['parent_appname']
- except (NameError, KeyError):
- pass
-
-ipython_notebook_css = """
-td.pb_widget {
- width: auto;
-}
-td.pb_widget_fill {
- width: 100%;
-}
-table.pb {
- font-family: monospace;
- border: 0;
- margin: 0;
-}
-table.pb tr { border: 0; }
-table.pb td {
- white-space: nowrap;
- border: 0;
-}
-div.pb {
- border: 1px solid #ddd;
- border-radius: 3px;
-}
-div.pb_bar {
- height: 1.5em;
-}
-""".replace('\n', ' ')
-
-class UnknownLength: pass
-
-
-class ProgressBar(object):
- """The ProgressBar class which updates and prints the bar.
-
- A common way of using it is like:
- >>> pbar = ProgressBar().start()
- >>> for i in range(100):
- ... # do something
- ... pbar.update(i+1)
- ...
- >>> pbar.finish()
-
- You can also use a ProgressBar as an iterator:
- >>> progress = ProgressBar()
- >>> for i in progress(some_iterable):
- ... # do something
- ...
-
- Since the progress bar is incredibly customizable you can specify
- different widgets of any type in any order. You can even write your own
- widgets! However, since there are already a good number of widgets you
- should probably play around with them before moving on to create your own
- widgets.
-
- The term_width parameter represents the current terminal width. If the
- parameter is set to an integer then the progress bar will use that,
- otherwise it will attempt to determine the terminal width falling back to
- 80 columns if the width cannot be determined.
-
- When implementing a widget's update method you are passed a reference to
- the current progress bar. As a result, you have access to the
- ProgressBar's methods and attributes. Although there is nothing preventing
- you from changing the ProgressBar you should treat it as read only.
-
- Useful methods and attributes include (Public API):
- - currval: current progress (0 <= currval <= maxval)
- - maxval: maximum (and final) value
- - finished: True if the bar has finished (reached 100%)
- - start_time: the time when start() method of ProgressBar was called
- - seconds_elapsed: seconds elapsed since start_time and last call to
- update
- - percentage(): progress in percent [0..100]
- """
-
- __slots__ = ('currval', 'fd', 'finished', 'last_update_time',
- 'left_justify', 'maxval', 'next_update', 'num_intervals',
- 'poll', 'seconds_elapsed', 'signal_set', 'start_time',
- 'term_width', 'update_interval', 'widgets', '_time_sensitive',
- '__iterable', 'attr', 'html_written', 'uuid')
-
- _DEFAULT_MAXVAL = 100
- _DEFAULT_TERMSIZE = 80
- _DEFAULT_WIDGETS = [widgets.Percentage, widgets.Bar]
-
- def __init__(self, maxval=None, widgets=None, term_width=None, poll=1,
- left_justify=True, fd=sys.stdout, attr={}):
- """Initializes a progress bar with sane defaults."""
-
- # Don't share a reference with any other progress bars
- if widgets is None:
- widgets = [widget() for widget in self._DEFAULT_WIDGETS]
-
- self.maxval = maxval
- self.widgets = widgets
- self.fd = fd
- self.left_justify = left_justify
-
- self.signal_set = False
- if term_width is not None:
- self.term_width = term_width
- else:
- try:
- self._handle_resize()
- signal.signal(signal.SIGWINCH, self._handle_resize)
- self.signal_set = True
- except (SystemExit, KeyboardInterrupt): raise
- except:
- self.term_width = self._env_size()
-
- self.__iterable = None
- self._update_widgets()
- self.currval = 0
- self.finished = False
- self.last_update_time = None
- self.poll = poll
- self.seconds_elapsed = 0
- self.start_time = None
- self.update_interval = 1
- self.attr = attr
-
- # Set flag so we only write out the HTML once,
- # then update with javascript
- self.html_written = False
-
- self.uuid = str(uuid.uuid4())
-
- # Install our CSS if we are in an IPython notebook
- if ipython == 'ipython-notebook':
- from IPython.display import Javascript, display
- display(Javascript('//%s\n$("head").append("<style>%s</style>")' %
- (self.uuid,ipython_notebook_css)))
-
- # Also add a function that removes progressbar output from the cells
- js = '''
- // %s -- used to remove this code blob in the end
- IPython.OutputArea.prototype.cleanProgressBar = function(uuids) {
- // filter by uuid-strings
- var myfilter = function(output) {
- var nuids = uuids.length;
- for (var i=0; i<nuids; i++) {
- if (output.hasOwnProperty('html')) {
- if (output.html.indexOf(uuids[i]) != -1) {
- return false;
- }
- }
- if (output.hasOwnProperty('javascript')) {
- if (output.javascript.indexOf(uuids[i]) != -1) {
- return false;
- }
- }
- }
- // keep all others
- return true;
- };
-
- // Filter the ouputs
- this.outputs = this.outputs.filter(myfilter);
- };
- ''' % self.uuid
- display(Javascript(js))
-
- def __call__(self, iterable):
- """Use a ProgressBar to iterate through an iterable."""
-
- try:
- self.maxval = len(iterable)
- except:
- if self.maxval is None:
- self.maxval = UnknownLength
-
- self.__iterable = iter(iterable)
- return self
-
-
- def __iter__(self):
- return self
-
-
- def __next__(self):
- try:
- value = next(self.__iterable)
- if self.start_time is None: self.start()
- else: self.update(self.currval + 1)
- return value
- except StopIteration:
- self.finish()
- raise
-
-
- # Create an alias so that Python 2.x won't complain about not being
- # an iterator.
- next = __next__
-
-
- def _env_size(self):
- """Tries to find the term_width from the environment."""
-
- return int(os.environ.get('COLUMNS', self._DEFAULT_TERMSIZE)) - 1
-
-
- def _handle_resize(self, signum=None, frame=None):
- """Tries to catch resize signals sent from the terminal."""
-
- h, w = array('h', ioctl(self.fd, termios.TIOCGWINSZ, '\0' * 8))[:2]
- self.term_width = w
-
-
- def percentage(self):
- """Returns the progress as a percentage."""
- return self.currval * 100.0 / self.maxval
-
- percent = property(percentage)
-
-
- def _format_widgets(self):
- result = []
- expanding = []
- width = self.term_width
-
- for index, widget in enumerate(self.widgets):
- if isinstance(widget, widgets.WidgetHFill):
- result.append(widget)
- expanding.insert(0, index)
- else:
- widget = widgets.format_updatable(widget, self)
- result.append(widget)
- width -= len(widget)
-
- count = len(expanding)
- while count:
- portion = max(int(math.ceil(width * 1. / count)), 0)
- index = expanding.pop()
- count -= 1
-
- widget = result[index].update(self, portion)
- width -= len(widget)
- result[index] = widget
-
- return result
-
-
- def _format_line(self):
- """Joins the widgets and justifies the line."""
-
- widgets = ''.join(self._format_widgets())
-
- if self.left_justify: return widgets.ljust(self.term_width)
- else: return widgets.rjust(self.term_width)
-
-
- def _format_html(self):
- html = '<div class="pb" id="%s"><table class="pb ui-widget"><tr>\n' % self.uuid
- for widget in self.widgets:
- if isinstance(widget, widgets.WidgetHFill):
- td_class = 'pb_widget_fill'
- else:
- td_class = 'pb_widget'
-
- html += ('<td class="%s">' % td_class) + \
- widgets.format_updatable_html(widget, self) + \
- '</td>\n'
- html += '</tr></table><div>'
- return html
-
-
- def _need_update(self):
- """Returns whether the ProgressBar should redraw the line."""
- if self.currval >= self.next_update or self.finished: return True
-
- delta = time.time() - self.last_update_time
- return self._time_sensitive and delta > self.poll
-
-
- def _update_widgets(self):
- """Checks all widgets for the time sensitive bit."""
-
- self._time_sensitive = any(getattr(w, 'TIME_SENSITIVE', False)
- for w in self.widgets)
-
-
- def update(self, value=None, attr={}):
- """Updates the ProgressBar to a new value."""
-
- if value is not None and value is not UnknownLength:
- if (self.maxval is not UnknownLength
- and not 0 <= value <= self.maxval):
-
- raise ValueError('Value out of range')
-
- self.currval = value
-
- self.attr.update(attr)
-
- if not self._need_update(): return
- if self.start_time is None:
- raise RuntimeError('You must call "start" before calling "update"')
-
- now = time.time()
- self.seconds_elapsed = now - self.start_time
- self.next_update = self.currval + self.update_interval
-
- if ipython == 'ipython-notebook':
- if not self.html_written:
- # We have yet to display the HTML, do that first
- from IPython.display import HTML, display
- display(HTML(self._format_html()))
- self.html_written = True
- else:
- # The HTML has been written once, now update with JS
- from IPython.display import Javascript, display
- for widget in self.widgets:
- js = widgets.updatable_js(widget, self)
- if js:
- display(Javascript(js))
- else:
- self.fd.write('\r' + self._format_line())
- self.fd.flush()
-
- self.last_update_time = now
-
-
- def start(self):
- """Starts measuring time, and prints the bar at 0%.
-
- It returns self so you can use it like this:
- >>> pbar = ProgressBar().start()
- >>> for i in range(100):
- ... # do something
- ... pbar.update(i+1)
- ...
- >>> pbar.finish()
- """
-
- if self.maxval is None:
- self.maxval = self._DEFAULT_MAXVAL
-
- self.num_intervals = max(100, self.term_width)
- self.next_update = 0
-
- if self.maxval is not UnknownLength:
- if self.maxval < 0: raise ValueError('Value out of range')
- self.update_interval = self.maxval / self.num_intervals
-
-
- self.start_time = self.last_update_time = time.time()
- self.html_written = False
- self.finished = False
- self.update(0)
-
- return self
-
-
- def finish(self):
- """Puts the ProgressBar bar in the finished state."""
-
- self.finished = True
- self.update(self.maxval)
- self.start_time = None
-
- # Clean up notebook stuff, quite differently from regular
- if not ipython == 'ipython-notebook':
- self.fd.write('\n')
- else:
- from IPython.display import Javascript, display
- # First delete the node that held the progress bar from the page
- js = """var element = document.getElementById('%s');
- element.parentNode.removeChild(element);""" % self.uuid
- display(Javascript(js))
-
- # Then also remove its trace from the cell output (so it doesn't get
- # stored with the notebook). This needs to be done for all widgets as
- # well as for progressBar
- uuids = [str(self.uuid)]
- uuids += [w.uuid for w in self.widgets if isinstance(w, widgets.Widget)]
- display(Javascript('this.cleanProgressBar(%s)' % uuids))
-
- if self.signal_set:
- signal.signal(signal.SIGWINCH, signal.SIG_DFL)
diff -r fa9e7188734481e9958debac3c74bd87412f5180 -r b8192257604644d2bb7a3534100df39fee93b072 yt/extern/progressbar/widgets.py
--- a/yt/extern/progressbar/widgets.py
+++ /dev/null
@@ -1,388 +0,0 @@
-#!/usr/bin/python
-# -*- coding: utf-8 -*-
-#
-# progressbar - Text progress bar library for Python.
-# Copyright (c) 2005 Nilton Volpato
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library; if not, write to the Free Software
-# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
-"""Default ProgressBar widgets."""
-
-from __future__ import division
-
-import datetime
-import math
-import uuid
-
-try:
- from abc import ABCMeta, abstractmethod
-except ImportError:
- AbstractWidget = object
- abstractmethod = lambda fn: fn
-else:
- AbstractWidget = ABCMeta('AbstractWidget', (object,), {})
-
-
-def format_updatable(updatable, pbar):
- if hasattr(updatable, 'update'): return updatable.update(pbar)
- else: return updatable
-
-def format_updatable_html(updatable, pbar):
- if hasattr(updatable, 'update_html'): return updatable.update_html(pbar)
- else: return updatable
-
-def updatable_js(updatable, pbar):
- if hasattr(updatable, 'update_js'): return updatable.update_js(pbar)
- else: return None
-
-
-class Widget(AbstractWidget):
- """The base class for all widgets.
-
- The ProgressBar will call the widget's update value when the widget should
- be updated. The widget's size may change between calls, but the widget may
- display incorrectly if the size changes drastically and repeatedly.
-
- The boolean TIME_SENSITIVE informs the ProgressBar that it should be
- updated more often because it is time sensitive.
- """
-
- TIME_SENSITIVE = False
- __slots__ = ()
- uuid = None
-
- @abstractmethod
- def update(self, pbar):
- """Updates the widget.
-
- pbar - a reference to the calling ProgressBar
- """
-
- def update_html(self, pbar):
- if self.uuid is None:
- self.uuid = str(uuid.uuid4())
- return '<div id="%s">%s</div>' % (self.uuid, self.update(pbar))
-
- def update_js(self, pbar):
- if self.uuid is None:
- self.uuid = str(uuid.uuid4())
- return "$('div#%s').text('%s');" % (self.uuid, self.update(pbar))
-
-
-class WidgetHFill(Widget):
- """The base class for all variable width widgets.
-
- This widget is much like the \\hfill command in TeX, it will expand to
- fill the line. You can use more than one in the same line, and they will
- all have the same width, and together will fill the line.
- """
-
- DEFAULT_WIDTH = 50
-
- @abstractmethod
- def update(self, pbar, width=DEFAULT_WIDTH):
- """Updates the widget providing the total width the widget must fill.
-
- pbar - a reference to the calling ProgressBar
- width - The total width the widget must fill
- """
-
-
-class Timer(Widget):
- """Widget which displays the elapsed seconds."""
-
- __slots__ = ('format_string',)
- TIME_SENSITIVE = True
-
- def __init__(self, format='Elapsed Time: %s'):
- self.format_string = format
-
- @staticmethod
- def format_time(seconds):
- """Formats time as the string "HH:MM:SS"."""
-
- return str(datetime.timedelta(seconds=int(seconds)))
-
-
- def update(self, pbar):
- """Updates the widget to show the elapsed time."""
-
- return self.format_string % self.format_time(pbar.seconds_elapsed)
-
-
-class ETA(Timer):
- """Widget which attempts to estimate the time of arrival."""
-
- TIME_SENSITIVE = True
-
- def update(self, pbar):
- """Updates the widget to show the ETA or total time when finished."""
-
- if pbar.currval == 0:
- return 'ETA: --:--:--'
- elif pbar.finished:
- return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
- else:
- elapsed = pbar.seconds_elapsed
- eta = elapsed * pbar.maxval / pbar.currval - elapsed
- return 'ETA: %s' % self.format_time(eta)
-
-
-class FileTransferSpeed(Widget):
- """Widget for showing the transfer speed (useful for file transfers)."""
-
- FORMAT = '%6.2f %s%s/s'
- PREFIXES = ' kMGTPEZY'
- __slots__ = ('unit',)
-
- def __init__(self, unit='B'):
- self.unit = unit
-
- def update(self, pbar):
- """Updates the widget with the current SI prefixed speed."""
-
- if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: # =~ 0
- scaled = power = 0
- else:
- speed = pbar.currval / pbar.seconds_elapsed
- power = int(math.log(speed, 1000))
- scaled = speed / 1000.**power
-
- return self.FORMAT % (scaled, self.PREFIXES[power], self.unit)
-
-
-class AnimatedMarker(Widget):
- """An animated marker for the progress bar which defaults to appear as if
- it were rotating.
- """
-
- __slots__ = ('markers', 'curmark')
-
- def __init__(self, markers='|/-\\'):
- self.markers = markers
- self.curmark = -1
-
- def update(self, pbar):
- """Updates the widget to show the next marker or the first marker when
- finished"""
-
- if pbar.finished: return self.markers[0]
-
- self.curmark = (self.curmark + 1) % len(self.markers)
- return self.markers[self.curmark]
-
-# Alias for backwards compatibility
-RotatingMarker = AnimatedMarker
-
-
-class Counter(Widget):
- """Displays the current count."""
-
- __slots__ = ('format_string',)
-
- def __init__(self, format='%d'):
- self.format_string = format
-
- def update(self, pbar):
- return self.format_string % pbar.currval
-
-
-class Attribute(Widget):
- """Displays the values of ProgressBar attributes.
-
- attr_name - ProgressBar attribute dictionary key or list of keys
- format_string - Format for the output. Attributes are looked up according
- to attr_name and then used as a tuple with this format string, i.e.
- format_string % attr_tuple
- fallback - If an attribute lookup fails, this string is displayed instead.
-
- """
-
- __slots__ = ('attr_name', 'format_string', 'fallback')
-
- def __init__(self, attr_name, format='%s', fallback='?'):
- self.attr_name = attr_name
- self.format_string = format
- self.fallback = fallback
-
- def update(self, pbar):
- try:
- if isinstance(self.attr_name, basestring) or len(self.attr_name) == 1:
- # If attr_name is just a string or a single item,
- # use it as the key as is
- format_vars = (pbar.attr[self.attr_name],)
- else:
- # else, expand it as a tuple of attributes
- format_vars = tuple([pbar.attr[a] for a in self.attr_name])
- return self.format_string % format_vars
- except KeyError:
- return self.fallback
-
-
-class Percentage(Widget):
- """Displays the current percentage as a number with a percent sign."""
-
- def update(self, pbar):
- return '%3d%%' % pbar.percentage()
-
-
-class FormatLabel(Timer):
- """Displays a formatted label."""
-
- mapping = {
- 'elapsed': ('seconds_elapsed', Timer.format_time),
- 'finished': ('finished', None),
- 'last_update': ('last_update_time', None),
- 'max': ('maxval', None),
- 'seconds': ('seconds_elapsed', None),
- 'start': ('start_time', None),
- 'value': ('currval', None)
- }
-
- __slots__ = ('format_string',)
- def __init__(self, format):
- self.format_string = format
-
- def update(self, pbar):
- context = {}
- for name, (key, transform) in self.mapping.items():
- try:
- value = getattr(pbar, key)
-
- if transform is None:
- context[name] = value
- else:
- context[name] = transform(value)
- except: pass
-
- return self.format_string % context
-
-
-class SimpleProgress(Widget):
- """Returns progress as a count of the total (e.g.: "5 of 47")."""
-
- __slots__ = ('sep',)
-
- def __init__(self, sep=' of '):
- self.sep = sep
-
- def update(self, pbar):
- return '%d%s%d' % (pbar.currval, self.sep, pbar.maxval)
-
-
-class Bar(WidgetHFill):
- """A progress bar which stretches to fill the line."""
-
- __slots__ = ('marker', 'left', 'right', 'fill', 'fill_left')
-
- def __init__(self, marker='#', left='|', right='|', fill=' ',
- fill_left=True):
- """Creates a customizable progress bar.
-
- marker - string or updatable object to use as a marker
- left - string or updatable object to use as a left border
- right - string or updatable object to use as a right border
- fill - character to use for the empty part of the progress bar
- fill_left - whether to fill from the left or the right
- """
- self.marker = marker
- self.left = left
- self.right = right
- self.fill = fill
- self.fill_left = fill_left
-
- def update(self, pbar, width=WidgetHFill.DEFAULT_WIDTH):
- """Updates the progress bar and its subcomponents."""
-
- left, marked, right = (format_updatable(i, pbar) for i in
- (self.left, self.marker, self.right))
-
- width -= len(left) + len(right)
- # Marked must *always* have length of 1
- if pbar.maxval:
- marked *= int(pbar.currval / pbar.maxval * width)
- else:
- marked = ''
-
- if self.fill_left:
- return '%s%s%s' % (left, marked.ljust(width, self.fill), right)
- else:
- return '%s%s%s' % (left, marked.rjust(width, self.fill), right)
-
-
- def update_html(self, pbar):
- if self.uuid is None:
- self.uuid = str(uuid.uuid4())
- return """
- <div class="pb_bar" id="%s"></div>
- <script type="text/javascript">
- $("div#%s").progressbar({value: 0, max: %d});
- </script>
- """ % (self.uuid, self.uuid,pbar.maxval)
-
-
- def update_js(self, pbar):
- if self.uuid is None:
- self.uuid = str(uuid.uuid4())
- return """
- var $myPB = $("div#{divid}")
- if ($myPB.hasClass('ui-progressbar')) {{
- $myPB.progressbar('value', {pbar.currval:d});
- }} else {{
- $myPB.progressbar({{value: 0, max: {pbar.maxval:d}}});
- }}
- """.format(divid=self.uuid, pbar=pbar)
-
-
-class ReverseBar(Bar):
- """A bar which has a marker which bounces from side to side."""
-
- def __init__(self, marker='#', left='|', right='|', fill=' ',
- fill_left=False):
- """Creates a customizable progress bar.
-
- marker - string or updatable object to use as a marker
- left - string or updatable object to use as a left border
- right - string or updatable object to use as a right border
- fill - character to use for the empty part of the progress bar
- fill_left - whether to fill from the left or the right
- """
- self.marker = marker
- self.left = left
- self.right = right
- self.fill = fill
- self.fill_left = fill_left
-
-
-class BouncingBar(Bar):
- def update(self, pbar, width=WidgetHFill.DEFAULT_WIDTH):
- """Updates the progress bar and its subcomponents."""
-
- left, marker, right = (format_updatable(i, pbar) for i in
- (self.left, self.marker, self.right))
-
- width -= len(left) + len(right)
-
- if pbar.finished: return '%s%s%s' % (left, width * marker, right)
-
- position = int(pbar.currval % (width * 2 - 1))
- if position > width: position = width * 2 - position
- lpad = self.fill * (position - 1)
- rpad = self.fill * (width - len(marker) - len(lpad))
-
- # Swap if we want to bounce the other way
- if not self.fill_left: rpad, lpad = lpad, rpad
-
- return '%s%s%s%s%s' % (left, lpad, marker, rpad, right)
diff -r fa9e7188734481e9958debac3c74bd87412f5180 -r b8192257604644d2bb7a3534100df39fee93b072 yt/funcs.py
--- a/yt/funcs.py
+++ b/yt/funcs.py
@@ -337,6 +337,7 @@
maxval = max(maxval, 1)
from yt.config import ytcfg
if ytcfg.getboolean("yt", "suppressStreamLogging") or \
+ "__IPYTHON__" in dir(__builtin__) or \
ytcfg.getboolean("yt", "__withintesting"):
return DummyProgressBar()
elif ytcfg.getboolean("yt", "__withinreason"):
@@ -344,13 +345,12 @@
return ExtProgressBar(title, maxval)
elif ytcfg.getboolean("yt", "__parallel"):
return ParallelProgressBar(title, maxval)
- else:
- widgets = [ title,
- pb.Percentage(), ' ',
- pb.Bar(marker=pb.RotatingMarker()),
- ' ', pb.ETA(), ' ']
- pbar = pb.ProgressBar(widgets=widgets,
- maxval=maxval).start()
+ widgets = [ title,
+ pb.Percentage(), ' ',
+ pb.Bar(marker=pb.RotatingMarker()),
+ ' ', pb.ETA(), ' ']
+ pbar = pb.ProgressBar(widgets=widgets,
+ maxval=maxval).start()
return pbar
def only_on_root(func, *args, **kwargs):
Repository URL: https://bitbucket.org/yt_analysis/yt/
--
This is a commit notification from bitbucket.org. You are receiving
this because you have the service enabled, addressing the recipient of
this email.
More information about the yt-svn
mailing list