rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
q = ''
def __init__(self, title=None, author=None, publisher=None, isbn=None, keywords=None, max_results=20): assert not(title is None and author is None and publisher is None \ and isbn is None and keywords is None) assert (max_results < 21)
q += isbn
q = isbn
def __init__(self, title=None, author=None, publisher=None, isbn=None, keywords=None, max_results=20): assert not(title is None and author is None and publisher is None \ and isbn is None and keywords is None) assert (max_results < 21)
if title is not None: q += title if author is not None: q += author if publisher is not None: q += publisher if keywords is not None: q += keywords
q = ' '.join([i for i in (title, author, publisher, keywords) \ if i is not None])
def __init__(self, title=None, author=None, publisher=None, isbn=None, keywords=None, max_results=20): assert not(title is None and author is None and publisher is None \ and isbn is None and keywords is None) assert (max_results < 21)
self.repub = re.compile(r'\s*.diteur\s*', re.I) self.reauteur = re.compile(r'\s*auteur.*', re.I) self.reautclean = re.compile(r'\s*\(.*\)\s*')
self.repub = re.compile(u'\s*.diteur\s*', re.I) self.reauteur = re.compile(u'\s*auteur.*', re.I) self.reautclean = re.compile(u'\s*\(.*\)\s*')
def __init__(self): self.repub = re.compile(r'\s*.diteur\s*', re.I) self.reauteur = re.compile(r'\s*auteur.*', re.I) self.reautclean = re.compile(r'\s*\(.*\)\s*')
return title.replace('\n', '')
return unicode(title.replace('\n', ''))
def get_title(self, entry): title = deepcopy(entry.find("div[@id='book-info']")) title.remove(title.find("dl[@title='Informations sur le livre']")) title = ' '.join([i.text_content() for i in title.iterchildren()]) return title.replace('\n', '')
authortext.append(elt.text_content())
authortext.append(unicode(elt.text_content()))
def get_authors(self, entry): author = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") authortext = [] for x in author.getiterator('dt'): if self.reauteur.match(x.text): elt = x.getnext() i = 0 while elt.tag <> 'dt' and i < 20: authortext.append(elt.text_content()) elt = elt.getnext() i += 1 b...
return 'RESUME:\n' + entry.xpath("//p[@id='book-description']")[0].text
return 'RESUME:\n' + unicode(entry.xpath("//p[@id='book-description']")[0].text)
def get_description(self, entry, verbose): try: return 'RESUME:\n' + entry.xpath("//p[@id='book-description']")[0].text except: report(verbose) return None
return publitext
return unicode(publitext).strip()
def get_publisher(self, entry): publisher = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") publitext = None for x in publisher.getiterator('dt'): if self.repub.match(x.text): publitext = x.getnext().text_content() break return publitext
if not len(d):
if len(d) == 0:
def get_date(self, entry, verbose): date = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") for x in date.getiterator('dt'): if x.text == 'Date de parution': d = x.getnext().text_content() break if not len(d): return None try: default = utcnow().replace(day=15) d = replace_monthsfr(d) d = parse...
break return isbntext
isbntext = isbntext.replace('-', '') break return unicode(isbntext)
def get_ISBN(self, entry): isbn = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") isbntext = None for x in isbn.getiterator('dt'): if x.text == 'ISBN': isbntext = x.getnext().text_content() if not check_isbn(isbntext): return None break return isbntext
return langtext
return unicode(langtext).strip()
def get_language(self, entry): language = entry.find("div[@id='book-info']/dl[@title='Informations sur le livre']") langtext = None for x in language.getiterator('dt'): if x.text == 'Langue': langtext = x.getnext().text_content() break return langtext
verbose=False, max_results=5, keywords=None):
max_results=5, verbose=False, keywords=None):
def search(title=None, author=None, publisher=None, isbn=None, verbose=False, max_results=5, keywords=None): br = browser() entries = Query(title=title, author=author, isbn=isbn, publisher=publisher, keywords=keywords, max_results=max_results)(br, verbose) if entries is None: return #List of entry ans = ResultList() ...
if entries is None:
if entries is None or len(entries) == 0:
def search(title=None, author=None, publisher=None, isbn=None, verbose=False, max_results=5, keywords=None): br = browser() entries = Query(title=title, author=author, isbn=isbn, publisher=publisher, keywords=keywords, max_results=max_results)(br, verbose) if entries is None: return #List of entry ans = ResultList() ...
container = soup.find('container')
container = soup.find(name=re.compile(r'container$', re.I))
def __init__(self, stream=None): if not stream: return soup = BeautifulStoneSoup(stream.read()) container = soup.find('container') if not container: raise OCFException("<container/> element missing") if container.get('version', None) != '1.0': raise EPubException("unsupported version of OCF") rootfiles = container.find...
raise OCFException("<container/> element missing")
raise OCFException("<container> element missing")
def __init__(self, stream=None): if not stream: return soup = BeautifulStoneSoup(stream.read()) container = soup.find('container') if not container: raise OCFException("<container/> element missing") if container.get('version', None) != '1.0': raise EPubException("unsupported version of OCF") rootfiles = container.find...
rootfiles = container.find('rootfiles')
rootfiles = container.find(re.compile(r'rootfiles$', re.I))
def __init__(self, stream=None): if not stream: return soup = BeautifulStoneSoup(stream.read()) container = soup.find('container') if not container: raise OCFException("<container/> element missing") if container.get('version', None) != '1.0': raise EPubException("unsupported version of OCF") rootfiles = container.find...
for rootfile in rootfiles.findAll('rootfile'):
for rootfile in rootfiles.findAll(re.compile(r'rootfile$', re.I)):
def __init__(self, stream=None): if not stream: return soup = BeautifulStoneSoup(stream.read()) container = soup.find('container') if not container: raise OCFException("<container/> element missing") if container.get('version', None) != '1.0': raise EPubException("unsupported version of OCF") rootfiles = container.find...
if self.get_extra(key):
if self.get_extra(key) is not None:
def format_field_extended(self, key, series_with_index=True): from calibre.ebooks.metadata import authors_to_string ''' returns the tuple (field_name, formatted_value) '''
cursor = QTextCursor(self.preview.document()) extsel = QTextEdit.ExtraSelection() extsel.cursor = cursor extsel.format.setBackground(QBrush(Qt.yellow))
def do_test(self): selections = [] if self.regex_valid(): text = qstring_to_unicode(self.preview.toPlainText()) regex = qstring_to_unicode(self.regex.text())
cursor = QTextCursor(self.preview.document()) cursor.setPosition(match.start(), QTextCursor.MoveAnchor) cursor.setPosition(match.end(), QTextCursor.KeepAnchor) sel = QTextEdit.ExtraSelection() sel.cursor = cursor sel.format.setBackground(QBrush(Qt.yellow)) selections.append(sel)
es = QTextEdit.ExtraSelection(extsel) es.cursor.setPosition(match.start(), QTextCursor.MoveAnchor) es.cursor.setPosition(match.end(), QTextCursor.KeepAnchor) selections.append(es)
def do_test(self): selections = [] if self.regex_valid(): text = qstring_to_unicode(self.preview.toPlainText()) regex = qstring_to_unicode(self.regex.text())
chars = list(range(8)) + [0x0B, 0x0E, 0x0F] + list(range(0x10, 0x19)) illegal_chars = re.compile(u'|'.join(map(unichr, chars))) txt = illegal_chars.sub('', txt)
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning ...
length_byte = len(txt.encode('utf-8'))
if isinstance(txt, unicode): txt = txt.encode('utf-8') length_byte = len(txt)
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning ...
if (len(filter(lambda x: len(x.encode('utf-8')) > chunk_size, txt.split('\n\n')))) : txt = u'\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')])
if (len(filter(lambda x: len(x) > chunk_size, txt.split('\n\n')))) : txt = '\n\n'.join([split_string_separator(line, chunk_size) for line in txt.split('\n\n')]) if isbytestring(txt): txt = txt.decode('utf-8')
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning ...
lines.append('<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' ')))
lines.append(u'<p>%s</p>' % prepare_string_for_xml(line.replace('\n', ' ')))
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning ...
return HTML_TEMPLATE % (title, '\n'.join(lines))
return HTML_TEMPLATE % (title, u'\n'.join(lines))
def convert_basic(txt, title='', epub_split_size_kb=0): # Strip whitespace from the beginning and end of the line. Also replace # all line breaks with \n. txt = '\n'.join([line.strip() for line in txt.splitlines()]) # Condense redundant spaces txt = re.sub('[ ]{2,}', ' ', txt) # Remove blank lines from the beginning ...
txt = re.sub(u'(?<=.)\n(?=.)', u'\n\n', txt)
txt = re.sub(u'(?<=.)\n(?=.)', '\n\n', txt)
def separate_paragraphs_single_line(txt): txt = txt.replace('\r\n', '\n') txt = txt.replace('\r', '\n') txt = re.sub(u'(?<=.)\n(?=.)', u'\n\n', txt) return txt
txt = re.sub('(?miu)^(\t+|[ ]{2,})(?=.)', '\n\t', txt)
txt = re.sub(u'(?miu)^(\t+|[ ]{2,})(?=.)', '\n\t', txt)
def separate_paragraphs_print_formatted(txt): txt = re.sub('(?miu)^(\t+|[ ]{2,})(?=.)', '\n\t', txt) return txt
self.addItems(QStringList(list(set(config[opt_name]))))
items = [] for item in config[opt_name]: if item not in items: items.append(item) self.addItems(QStringList(items))
def initialize(self, opt_name, colorize=False, help_text=_('Search')): self.as_you_type = config['search_as_you_type'] self.opt_name = opt_name self.addItems(QStringList(list(set(config[opt_name])))) try: self.line_edit.setPlaceholderText(help_text) except: # Using Qt < 4.7 pass self.colorize = colorize self.clear()
config[self.opt_name] = [unicode(self.itemText(i)) for i in
history = [unicode(self.itemText(i)) for i in
def _do_search(self, store_in_history=True): text = unicode(self.currentText()).strip() if not text: return self.clear() self.search.emit(text)
print "this is a pdf" chapter_line_open = "<(?P<outer>p)[^>]*>(\s*<[ibu][^>]*>)?\s*" chapter_line_close = "\s*(</[ibu][^>]*>\s*)?</(?P=outer)>" title_line_open = "<(?P<outer2>p)[^>]*>\s*" title_line_close = "\s*</(?P=outer2)>"
chapter_line_open = "<(?P<outer>p)[^>]*>(\s*<[ibu][^>]*>)?\s*" chapter_line_close = "\s*(</[ibu][^>]*>\s*)?</(?P=outer)>" title_line_open = "<(?P<outer2>p)[^>]*>\s*" title_line_close = "\s*</(?P=outer2)>"
def markup_chapters(self, html, wordcount, blanks_between_paragraphs): # Typical chapters are between 2000 and 7000 words, use the larger number to decide the # minimum of chapters to search for self.min_chapters = 1 if wordcount > 7000: self.min_chapters = wordcount / 7000 print "minimum chapters required are: "+str(s...
if isinstance(xbounds, basestring): xbounds = self._get_or_create_datasource(xbounds).get_data() if xbounds is None: xs = arange(array_data.shape[1]) elif isinstance(xbounds, tuple): xs = linspace(xbounds[0], xbounds[1], array_data.shape[1]) elif isinstance(xbounds, ndarray): if len(xbounds.shape) == 1 and len(xbounds)...
return self._create_2d_plot(cls, name, origin, xbounds, ybounds, value, hide_grids, **kwargs)
def img_plot(self, data, name=None, colormap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds image plots to this Plot object.
xs = arange(array_data.shape[1])
xs = arange(num_x_ticks)
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
xs = linspace(xbounds[0], xbounds[1], array_data.shape[1])
xs = linspace(xbounds[0], xbounds[1], num_x_ticks)
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
if len(xbounds.shape) == 1 and len(xbounds) == array_data.shape[1]: xs = linspace(xbounds[0], xbounds[-1], array_data.shape[1])
if len(xbounds.shape) == 1 and len(xbounds) == num_x_ticks: xs = linspace(xbounds[0], xbounds[-1], num_x_ticks) elif len(xbounds.shape) == 1 and len(xbounds) == num_x_ticks-1: raise ValueError("The xbounds array of an image plot needs to have 1 more element that its corresponding data shape, because it represents the ...
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
xs = linspace(xbounds[0,0],xbounds[0,-1],array_data.shape[1])
xs = xbounds[0,:]
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
ys = arange(array_data.shape[0])
ys = arange(num_y_ticks)
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
ys = linspace(ybounds[0], ybounds[1], array_data.shape[0])
ys = linspace(ybounds[0], ybounds[1], num_y_ticks)
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
if len(ybounds.shape) == 1 and len(ybounds) == array_data.shape[0]: ys = linspace(ybounds[0], ybounds[-1], array_data.shape[0])
if len(ybounds.shape) == 1 and len(ybounds) == num_y_ticks: ys = linspace(ybounds[0], ybounds[-1], num_y_ticks) elif len(ybounds.shape) == 1 and len(ybounds) == num_y_ticks-1: raise ValueError("The ybounds array of an image plot needs to have 1 more element that its corresponding data shape, because it represents the ...
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
ys = linspace(ybounds[0,0],ybounds[-1,0],array_data.shape[0])
ys = ybounds[:,0]
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
value=value,
value=value_ds,
def contour_plot(self, data, type="line", name=None, poly_cmap=None, xbounds=None, ybounds=None, origin=None, hide_grids=True, **styles): """ Adds contour plots to this Plot object.
class PlotFrame(DemoFrame): def _create_window(self): self.controller = TimerController() container = _create_plot_component(self.controller) self.Bind(wx.EVT_CLOSE, self.onClose) timerId = wx.NewId() self.timer = wx.Timer(self, timerId) self.Bind(wx.EVT_TIMER, self.controller.onTimer, id=timerId) self.timer.St...
from enthought.etsconfig.api import ETSConfig if ETSConfig.enable_toolkit == "wx": import wx class PlotFrame(DemoFrame): def _create_window(self): self.controller = TimerController() container = _create_plot_component(self.controller) self.Bind(wx.EVT_CLOSE, self.onClose) timerId = wx.NewId() self.timer = wx....
def configure_traits(self, *args, **kws): # Start up the timer! We should do this only when the demo actually # starts and not when the demo object is created. self.timer = Timer(20, self.controller.onTimer) return super(Demo, self).configure_traits(*args, **kws)
_stream = None
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectru...
pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE,
global _stream if _stream is None: pa = pyaudio.PyAudio() _stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE,
def get_audio_data(): pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(stream.read(NUM_SAMPLES), dtype=short) stream.close() normalized_data = audio_data / 32768.0 return (abs(fft(normalized_data))[:NUM_SA...
audio_data = fromstring(stream.read(NUM_SAMPLES), dtype=short) stream.close()
audio_data = fromstring(_stream.read(NUM_SAMPLES), dtype=short)
def get_audio_data(): pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(stream.read(NUM_SAMPLES), dtype=short) stream.close() normalized_data = audio_data / 32768.0 return (abs(fft(normalized_data))[:NUM_SA...
demo_main(PlotFrame, size=size, title=title)
try: demo_main(PlotFrame, size=size, title=title) finally: if _stream is not None: _stream.close()
def closeEvent(self, event): # stop the timer if getattr(self, "timer", None): self.timer.stop() return super(PlotFrame, self).closeEvent(event)
@on_trait_change("_xrange.updated,_yrange.updated") def _subranges_updated(self): self.updated = True
def _sources_changed(self, old, new): for source in old: source.on_trait_change(self.refresh, "data_changed", remove=True) for source in new: source.on_trait_change(self.refresh, "data_changed") # the _xdata and _ydata of the sources may be created anew on every # access, so we can't just add/delete from _xrange and _y...
plot.img_plot("imagedata", xbounds=x, ybounds=y, colormap=jet)
plot.img_plot("imagedata", colormap=jet)
def __init__(self): # Create the data and the PlotData object. For a 2D plot, we need to # take the row of X points and Y points and create a grid from them # using meshgrid(). x = linspace(0, 10, 50) y = linspace(0, 5, 50) xgrid, ygrid = meshgrid(x, y) z = exp(-(xgrid*xgrid + ygrid*ygrid) / 100) plotdata = ArrayPlotD...
gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height)
def _draw_plot(self, gc, view_bounds=None, mode="normal"): self._gather_points() if len(self._cached_data_pts) == 0: return index = self.index_mapper.map_screen(self._cached_data_pts[0]) vals = [] for v in self._cached_data_pts[1:]: if v is None: vals.append(None) else: vals.append(self.value_mapper.map_screen(v)) gc....
if len(index) == 0: return elif len(index) == 1:
if len(index) == 1:
def _draw_plot(self, gc, view_bounds=None, mode="normal"): self._gather_points() if len(self._cached_data_pts) == 0: return index = self.index_mapper.map_screen(self._cached_data_pts[0]) vals = [] for v in self._cached_data_pts[1:]: if v is None: vals.append(None) else: vals.append(self.value_mapper.map_screen(v)) gc....
self._render(gc, left, right, *vals) gc.restore_state()
with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height) self._render(gc, left, right, *vals)
def _draw_plot(self, gc, view_bounds=None, mode="normal"): self._gather_points() if len(self._cached_data_pts) == 0: return index = self.index_mapper.map_screen(self._cached_data_pts[0]) vals = [] for v in self._cached_data_pts[1:]: if v is None: vals.append(None) else: vals.append(self.value_mapper.map_screen(v)) gc....
x_axis = Instance(PlotAxis)
x_axis = Instance(AbstractOverlay)
def set_grid(self, attr_name, new): """ Setter function used by GridProperty. """ if (attr_name,self.orientation) in [("index_grid","v"), ("value_grid","h")]: self.y_grid = new else: self.y_grid = new
y_axis = Instance(PlotAxis)
y_axis = Instance(AbstractOverlay)
def set_grid(self, attr_name, new): """ Setter function used by GridProperty. """ if (attr_name,self.orientation) in [("index_grid","v"), ("value_grid","h")]: self.y_grid = new else: self.y_grid = new
if self.selection_mode == "single":
if self.selection_mode == "single" or not modifier_down:
def normal_left_down(self, event): """ Handles the left mouse button being pressed when the tool is in the 'normal' state. If selecting is enabled and the cursor is within **threshold** of a data point, the method calls the subclass's _select" or _deselect methods to perform the appropriate action, given the current s...
gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) try:
with gc: gc.clip_to_rect(self.x, self.y, self.width, self.height)
def _render(self, gc, pts): gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) try: if not self.index: gc.restore_state() return name = self.selection_metadata_name md = self.index.metadata if name in md and md[name] is not None and len(md[name]) > 0: # FIXME: when will we ever encounter multiple ...
gc.restore_state()
def _render(self, gc, pts): gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) try: if not self.index: gc.restore_state() return name = self.selection_metadata_name md = self.index.metadata if name in md and md[name] is not None and len(md[name]) > 0: # FIXME: when will we ever encounter multiple ...
finally: gc.restore_state()
def _render(self, gc, pts): gc.save_state() gc.clip_to_rect(self.x, self.y, self.width, self.height) try: if not self.index: gc.restore_state() return name = self.selection_metadata_name md = self.index.metadata if name in md and md[name] is not None and len(md[name]) > 0: # FIXME: when will we ever encounter multiple ...
try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet
self.model = model = Model() cmap = jet
def _create_window(self): # Create the model try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap)
imgplot = centerplot.img_plot("xy", xbounds=model.xs, ybounds=model.ys, colormap=cmap)[0]
imgplot = centerplot.img_plot("xy", xbounds=(model.xs[0], model.xs[-1]), ybounds=(model.ys[0], model.ys[-1]), colormap=cmap)[0]
def _create_window(self): # Create the model try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap)
imgplot = rightplot.img_plot("yz", xbounds=model.zs, ybounds=model.ys, colormap=cmap)[0]
imgplot = rightplot.img_plot("yz", xbounds=(model.zs[0], model.zs[-1]), ybounds=(model.ys[0], model.ys[-1]), colormap=cmap)[0]
def _create_window(self): # Create the model try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap)
imgplot = bottomplot.img_plot("xz", xbounds=model.xs, ybounds=model.zs, colormap=cmap)[0]
imgplot = bottomplot.img_plot("xz", xbounds=(model.xs[0], model.xs[-1]), ybounds=(model.zs[0], model.zs[-1]), colormap=cmap)[0]
def _create_window(self): # Create the model try: self.model = model = BrainModel() cmap = bone except SystemExit: sys.exit() except: print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap)
if not RectZoomTool in existing_tools: cont.overlays.append(RectZoomTool(cont, drag_button="right"))
if not ZoomTool in existing_tools: cont.overlays.append(ZoomTool(cont, tool_mode="box", always_on=True, drag_button="right"))
def _do_plot_boilerplate(kwargs, image=False): """ Used by various plotting functions. Checks/handles hold state, returns a Plot object for the plotting function to use. """ if kwargs.has_key("hold"): hold(kwargs["hold"]) del kwargs["hold"] # Check for an active window; if none, open one. if len(session.windows) == ...
self.set(**postponed)
def __init__(self, *args, **kw): super(BarPlot, self).__init__(*args, **kw) # update colors to use the correct alpha channel self.line_color_ = self.line_color_[0:3] + (self.alpha,) self.fill_color_ = self.fill_color_[0:3] + (self.alpha,)
def map_index(self, screen_pt, threshold=2.0, outside_returns_none=True, \
def map_index(self, screen_pt, threshold=2.0, outside_returns_none=True,
def map_index(self, screen_pt, threshold=2.0, outside_returns_none=True, \ index_only=False): """ Maps a screen space point to an index into the plot's index array(s). Implements the AbstractPlotRenderer interface. """ data_pt = self.map_data(screen_pt) if ((data_pt < self.index_mapper.range.low) or \ (data_pt > self....
half = threshold / 2.0
def map_index(self, screen_pt, threshold=2.0, outside_returns_none=True, \ index_only=False): """ Maps a screen space point to an index into the plot's index array(s). Implements the AbstractPlotRenderer interface. """ data_pt = self.map_data(screen_pt) if ((data_pt < self.index_mapper.range.low) or \ (data_pt > self....
x = numpy.linspace(-5,5,100) y = numpy.linspace(-5,5,100)
xy_range = (-5, 5) x = numpy.linspace(xy_range[0], xy_range[1] ,100) y = numpy.linspace(xy_range[0], xy_range[1] ,100)
def __init__(self): #The delegates views don't work unless we caller the superclass __init__ super(CursorTest, self).__init__() container = HPlotContainer(padding=0, spacing=20) self.plot = container #a subcontainer for the first plot. #I'm not sure why this is required. Without it, the layout doesn't work right. subc...
xbounds = x, ybounds = y,
xbounds = xy_range, ybounds = xy_range,
def __init__(self): #The delegates views don't work unless we caller the superclass __init__ super(CursorTest, self).__init__() container = HPlotContainer(padding=0, spacing=20) self.plot = container #a subcontainer for the first plot. #I'm not sure why this is required. Without it, the layout doesn't work right. subc...
logger.warning("No datasource for plot")
def _render(self, gc, points): # If there is nothing to render, render nothing if len(points) == 0: logger.warning("No datasource for plot") return if self.fill_direction == 'down': ox, oy = self.map_screen([[0,0]])[0] else: ox, oy = self.map_screen([[self.x_mapper.range.high, self.y_mapper.range.high]])[0] gc.save_st...
if self.face_color_[-1] != 0 and self.face_color_[:3] != (0,0,0): gc.set_fill_color(self.face_color_)
face_col = self.face_color_ if not (len(face_col) == 4 and face_col[-1] == 0): gc.set_fill_color(face_col)
def _render(self, gc, points): # If there is nothing to render, render nothing if len(points) == 0: logger.warning("No datasource for plot") return if self.fill_direction == 'down': ox, oy = self.map_screen([[0,0]])[0] else: ox, oy = self.map_screen([[self.x_mapper.range.high, self.y_mapper.range.high]])[0] gc.save_st...
if self.edge_color_[-1] != 0 and self.edge_color_ != self.face_color_: gc.set_stroke_color(self.edge_color_)
edge_col = self.edge_color_ if (not (len(edge_col) == 4 and edge_col[-1] == 0)) and edge_col != face_col: gc.set_stroke_color(edge_col)
def _render(self, gc, points): # If there is nothing to render, render nothing if len(points) == 0: logger.warning("No datasource for plot") return if self.fill_direction == 'down': ox, oy = self.map_screen([[0,0]])[0] else: ox, oy = self.map_screen([[self.x_mapper.range.high, self.y_mapper.range.high]])[0] gc.save_st...
tick_indices = [] for tick in tick_list: for i, pos in enumerate(self.positions): if allclose(pos, tick): tick_indices.append(i) break
pos_index = [] pos = [] pos_min = None pos_max = None for i, position in enumerate(self.positions): if datalow <= position <= datahigh: pos_max = max(position, pos_max) if pos_max is not None else position pos_min = min(position, pos_min) if pos_min is not None else position pos_index.append(i) pos.append(position) if ...
def _compute_tick_positions(self, gc, component=None): """ Calculates the positions for the tick marks. Overrides PlotAxis. """ if (self.mapper is None): self._reset_cache() self._cache_valid = True return datalow = self.mapper.range.low datahigh = self.mapper.range.high screenhigh = self.mapper.high_pos screenlow = ...
tick_positions = take(self.positions, tick_indices) self._tick_label_list = take(self.labels, tick_indices)
tick_indices = unique1d(searchsorted(pos, tick_list)) tick_indices = tick_indices[tick_indices < len(pos)] tick_positions = take(pos, tick_indices) self._tick_label_list = take(self.labels, take(pos_index, tick_indices))
def _compute_tick_positions(self, gc, component=None): """ Calculates the positions for the tick marks. Overrides PlotAxis. """ if (self.mapper is None): self._reset_cache() self._cache_valid = True return datalow = self.mapper.range.low datahigh = self.mapper.range.high screenhigh = self.mapper.high_pos screenlow = ...
mapped_label_positions = [((self.mapper.map_screen(pos)-screenlow) / \ (screenhigh-screenlow)) for pos in tick_positions] self._tick_positions = [self._axis_vector*tickpos + self._origin_point \ for tickpos in mapped_label_positions] self._tick_label_positions = self._tick_positions
if self.small_haxis_style: mapped_label_positions = [((self.mapper.map_screen(pos)-screenlow) / \ (screenhigh-screenlow)) for pos in tick_positions] self._tick_positions = [self._axis_vector*tickpos + self._origin_point \ for tickpos in mapped_label_positions] self._tick_label_positions = self._tick_positions else: map...
def _compute_tick_positions(self, gc, component=None): """ Calculates the positions for the tick marks. Overrides PlotAxis. """ if (self.mapper is None): self._reset_cache() self._cache_valid = True return datalow = self.mapper.range.low datahigh = self.mapper.range.high screenhigh = self.mapper.high_pos screenlow = ...
render(gc, selected_points)
render(gc, selected_points, self.orientation)
def _render(self, gc, points, selected_points=None): if len(points) == 0: return
render(gc, points)
render(gc, points, self.orientation)
def _render(self, gc, points, selected_points=None): if len(points) == 0: return
def _render_normal(self, gc, points):
@classmethod def _render_normal(cls, gc, points, orientation):
def _render_normal(self, gc, points): for ary in points: if len(ary) > 0: gc.begin_path() gc.lines(ary) gc.stroke_path() return
def _render_hold(self, gc, points):
@classmethod def _render_hold(cls, gc, points, orientation):
def _render_hold(self, gc, points): for starts in points: x,y = starts.T ends = transpose(array( (x[1:], y[:-1]) )) gc.begin_path() gc.line_set(starts[:-1], ends) gc.stroke_path() return
ends = transpose(array( (x[1:], y[:-1]) ))
if orientation == "h": ends = transpose(array( (x[1:], y[:-1]) )) else: ends = transpose(array( (x[:-1], y[1:]) ))
def _render_hold(self, gc, points): for starts in points: x,y = starts.T ends = transpose(array( (x[1:], y[:-1]) )) gc.begin_path() gc.line_set(starts[:-1], ends) gc.stroke_path() return
def _render_connected_hold(self, gc, points):
@classmethod def _render_connected_hold(cls, gc, points, orientation):
def _render_connected_hold(self, gc, points): for starts in points: x,y = starts.T ends = transpose(array( (x[1:], y[:-1]) )) gc.begin_path() gc.line_set(starts[:-1], ends) gc.line_set(ends, starts[1:]) gc.stroke_path() return
ends = transpose(array( (x[1:], y[:-1]) ))
if orientation == "h": ends = transpose(array( (x[1:], y[:-1]) )) else: ends = transpose(array( (x[:-1], y[1:]) ))
def _render_connected_hold(self, gc, points): for starts in points: x,y = starts.T ends = transpose(array( (x[1:], y[:-1]) )) gc.begin_path() gc.line_set(starts[:-1], ends) gc.line_set(ends, starts[1:]) gc.stroke_path() return
frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2)
frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2)
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum...
times = linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES)
times = linspace(0.0, float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES)
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum...
spectrogram_time = linspace( 0.0, float(SPECTROGRAM_LENGTH*NUM_SAMPLES)/float(SAMPLING_RATE), num=SPECTROGRAM_LENGTH) spectrogram_freq = linspace(0.0, float(SAMPLING_RATE/2), num=NUM_SAMPLES/2)
max_time = float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / SAMPLING_RATE max_freq = float(SAMPLING_RATE / 2)
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum...
xbounds=spectrogram_time, ybounds=spectrogram_freq,
xbounds=(0, max_time), ybounds=(0, max_freq),
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum...
_stream = None
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0., float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum...
global _stream if _stream is None: pa = pyaudio.PyAudio() _stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(_stream.read(NUM_SAMPLES), dtype=short)
pa = pyaudio.PyAudio() stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RATE, input=True, frames_per_buffer=NUM_SAMPLES) audio_data = fromstring(stream.read(NUM_SAMPLES), dtype=short) stream.close()
def get_audio_data(): global _stream if _stream is None: # The audio stream is opened the first time this function gets called. # The stream is always closed (if it was opened) in a try finally # block at the end of this file, pa = pyaudio.PyAudio() _stream = pa.open(format=pyaudio.paInt16, channels=1, rate=SAMPLING_RA...
try: demo_main(PlotFrame, size=size, title=title) finally: if _stream is not None: _stream.close()
demo_main(PlotFrame, size=size, title=title)
def onClose(self, event): #sys.exit() self.timer.Stop() event.Skip()
if len(coordinates) < 2: return 1.0 dy = coordinates[1] - coordinates[0]
if len(coordinates) > 1: dy = coordinates[1] - coordinates[0] else: dy = 1.0
def _get_amplitude_scale(self): """ If the amplitude is set to this value, the largest trace deviation from is base y coordinates will be equal to the y coordinate spacing. """ # Note: Like the rest of the current code, this ignores the `scale` attribute.
amp_scale = 0.5 * dy / max_abs
if max_abs == 0: amp_scale = 0.5 * dy else: amp_scale = 0.5 * dy / max_abs
def _get_amplitude_scale(self): """ If the amplitude is set to this value, the largest trace deviation from is base y coordinates will be equal to the y coordinate spacing. """ # Note: Like the rest of the current code, this ignores the `scale` attribute.
tmax = varray.max() tmin = varray.min() if tmax < self.value_range.low or tmin > self.value_range.high:
ylow, yhigh = varray.min(), varray.max() if ylow > self.value_range.high or yhigh < self.value_range.low:
def _gather_points(self): """ Collects the data points that are within the bounds of the plot and caches them. """
self.clip_to_rect(0, 0, trans_width, trans_height)
self.clip_to_rect(0, 0, width, height)
def render_component(self, component, container_coords=False, halign="center", valign="top"): """ Erases the current contents of the graphics context and renders the given component at the maximum possible scaling while preserving aspect ratio. Parameters ---------- component : Component The component to be rendered. ...
component.draw(self, view_bounds=(0, 0, trans_width, trans_height))
component.draw(self, view_bounds=(0, 0, width, height))
def render_component(self, component, container_coords=False, halign="center", valign="top"): """ Erases the current contents of the graphics context and renders the given component at the maximum possible scaling while preserving aspect ratio. Parameters ---------- component : Component The component to be rendered. ...
_trace_data = Property(Array, depends_on=['index', 'value', 'yindex', 'amplitude', 'scale', 'offset'])
_trace_data = Property(Array, depends_on=['index', 'index.data_changed', 'value', 'value.data_changed', 'yindex', 'yindex.data_changed', 'amplitude', 'scale', 'offset'])
def time_ms(t): s = "%5.1f ms" % (t * 1000) return s
zoom_to_mouse = Bool(True)
zoom_to_mouse = Bool(False)
def revert(self, zoom_tool): if isinstance(zoom_tool.component.index_mapper, GridMapper): index_mapper = zoom_tool.component.index_mapper._xmapper value_mapper = zoom_tool.component.index_mapper._ymapper else: index_mapper = zoom_tool.component.index_mapper value_mapper = zoom_tool.component.value_mapper zoom_tool._zo...
gc.draw_marker_at_points(screen_pts, 3, DOT_MARKER)
if hasattr(gc, 'draw_marker_at_points'): gc.draw_marker_at_points(screen_pts, 3, DOT_MARKER) else: gc.save_state() for sx,sy in screen_pts: gc.translate_ctm(sx, sy) gc.begin_path() self.marker.add_to_path(gc, 3) gc.draw_path(self.marker.draw_mode) gc.translate_ctm(-sx, -sy) gc.restore_state()
def overlay(self, component, gc, view_bounds=None, mode='normal'): x_range = self._get_selection_index_screen_range() y_range = self._get_selection_value_screen_range() if len(x_range) == 0: return x1, x2 = x_range y1, y2 = y_range
rotation=self.tick_label_rotate_angle, *tl_bounds) + \
rotation=0, *tl_bounds) + \
def _draw_labels(self, gc): """ Draws the tick labels for the axis. """ for i in range(len(self._tick_label_positions)): #We want a more sophisticated scheme than just 2 decimals all the time ticklabel = self.ticklabel_cache[i] tl_bounds = self._tick_label_bounding_boxes[i]
if self.fixed_preferred_size == "":
if self.fixed_preferred_size is not None:
def get_preferred_size(self, components=None): """ Returns the size (width,height) that is preferred for this component.
hostname = os.uname()[1]
hostname = socket.gethostname()
def get_hostname(): hostname = os.uname()[1] # Convert the machine's hostname into alphanumeric characters, suitable for python module names # Note: We don't want to use \W because it also matches underscores. # The string segment "._." would end up as "___" instead of "_". hostname = re.sub('[^a-zA-Z0-9]+', '_'...
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0]
def cache_object(key, value=None, ext=None): if ext: key = '{0}__{1}'.format(ext, key) key, key_hr = buffer(pickle.dumps(key, -1)), key
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() ...
if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) try: trace, ts = next(cur)
if value is None: cur.execute('SELECT value, ts FROM object_cache WHERE key = ?', (key,)) try: value, ts = next(cur)
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() ...
if ts < time() - optz.trace_cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(trace))
if ts < time() - optz.cache_obsoletion: raise KeyError(ts) return pickle.loads(bytes(value))
def cache_trace(dst, trace=None): if isinstance(dst, types.StringTypes): dst = unpack(b'!i', socket.inet_aton(dst))[0] cur = geoip_db.cursor() if trace is None: cur.execute('SELECT trace, ts FROM trace_cache WHERE dst = ?', (dst,)) # exit() try: trace, ts = next(cur) except StopIteration: raise KeyError if ts < time() ...