rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
if not sys.argv[1:]: print __doc__ sys.exit(0) | try: from optparse import OptionParser except: OptionParser = None if OptionParser: optionParser = OptionParser(version=__version__, usage="%prog [options] url_or_filename_or_-") optionParser.set_defaults(format="pprint") optionParser.add_option("-A", "--user-agent", dest="agent", metavar="AGENT", help="User-Agent for... | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
from pprint import pprint | serializer = globals().get(options.format.capitalize() + 'Serializer', Serializer) | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
print url print result = parse(url) pprint(result) print | results = parse(url, etag=options.etag, modified=options.modified, agent=options.agent, referrer=options.referrer) serializer(results).write(sys.stdout) | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
ap = self.action_preferences pm.addAction(ap) | pm.addAction(QIcon(I('config.svg')), _('Preferences'), self.do_config) | def __init__(self): md = QMenu() md.addAction(_('Edit metadata individually'), partial(self.edit_metadata, False, bulk=False)) md.addSeparator() md.addAction(_('Edit metadata in bulk'), partial(self.edit_metadata, False, bulk=True)) md.addSeparator() md.addAction(_('Download metadata and covers'), partial(self.download... |
warnings = [(x[0], unicode(x[1])) for x in \ | warnings = [(x[0], force_unicode(x[1])) for x in \ | def hangcheck(self): if self.fetcher.is_alive() and \ time.time() - self.start_time < self.HANG_TIME: return self._hangcheck.stop() try: if self.fetcher.is_alive(): error_dialog(self, _('Could not find metadata'), _('The metadata download seems to have stalled. ' 'Try again later.')).exec_() self.terminate() return sel... |
d = error_dialog(self.window, _('Cannot read'), | d = error_dialog(self.parent(), _('Cannot read'), | def select_cover(self): files = choose_images(self, 'change cover dialog', _('Choose cover for ') + unicode(self.title.text())) if not files: return _file = files[0] if _file: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): d = error_dialog(self.window, _('Cannot read'), _('You do not have permission t... |
d = error_dialog(self.window, _('Error reading file'), | d = error_dialog(self.parent(), _('Error reading file'), | def select_cover(self): files = choose_images(self, 'change cover dialog', _('Choose cover for ') + unicode(self.title.text())) if not files: return _file = files[0] if _file: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): d = error_dialog(self.window, _('Cannot read'), _('You do not have permission t... |
self.books = [] if isinstance(root, unicode): root = root.encode(filesystem_encoding) | def run(self): root = os.path.abspath(self.path) self.books = [] if isinstance(root, unicode): root = root.encode(filesystem_encoding) try: for dirpath in os.walk(root): if self.canceled: return self.emit(SIGNAL('update(PyQt_PyObject)'), _('Searching in')+' '+dirpath[0]) self.books += list(self.db.find_books_in_directo... | |
for dirpath in os.walk(root): if self.canceled: return self.emit(SIGNAL('update(PyQt_PyObject)'), _('Searching in')+' '+dirpath[0]) self.books += list(self.db.find_books_in_directory(dirpath[0], self.single_book_per_directory)) except Exception, err: import traceback traceback.print_exc() | self.walk(root) except: | def run(self): root = os.path.abspath(self.path) self.books = [] if isinstance(root, unicode): root = root.encode(filesystem_encoding) try: for dirpath in os.walk(root): if self.canceled: return self.emit(SIGNAL('update(PyQt_PyObject)'), _('Searching in')+' '+dirpath[0]) self.books += list(self.db.find_books_in_directo... |
msg = unicode(err) except: msg = repr(err) self.emit(SIGNAL('found(PyQt_PyObject)'), msg) return | if isinstance(root, unicode): root = root.encode(filesystem_encoding) self.walk(root) except Exception, err: import traceback traceback.print_exc() try: msg = unicode(err) except: msg = repr(err) self.emit(SIGNAL('found(PyQt_PyObject)'), msg) return | def run(self): root = os.path.abspath(self.path) self.books = [] if isinstance(root, unicode): root = root.encode(filesystem_encoding) try: for dirpath in os.walk(root): if self.canceled: return self.emit(SIGNAL('update(PyQt_PyObject)'), _('Searching in')+' '+dirpath[0]) self.books += list(self.db.find_books_in_directo... |
rows = self.gui.library_view.selectionModel().selectedRows() | rows = list(self.gui.library_view.selectionModel().selectedRows()) | def view_specific_format(self, triggered): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot view'), _('No book selected')) d.exec_() return |
row = rows[0].row() formats = self.gui.library_view.model().db.formats(row).upper().split(',') d = ChooseFormatDialog(self.gui, _('Choose the format to view'), formats) | db = self.gui.library_view.model().db rows = [r.row() for r in rows] formats = [db.formats(row) for row in rows] formats = [list(f.upper().split(',')) if f else None for f in formats] all_fmts = set([]) for x in formats: for f in x: all_fmts.add(f) d = ChooseFormatDialog(self.gui, _('Choose the format to view'), list(s... | def view_specific_format(self, triggered): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot view'), _('No book selected')) d.exec_() return |
format = d.format() self.view_format(row, format) | fmt = d.format() orig_num = len(rows) rows = [rows[i] for i in range(len(rows)) if formats[i] and fmt in formats[i]] if self._view_check(len(rows)): for row in rows: self.view_format(row, fmt) if len(rows) < orig_num: info_dialog(self.gui, _('Format unavailable'), _('Not all the selected books were available in' ' the ... | def view_specific_format(self, triggered): rows = self.gui.library_view.selectionModel().selectedRows() if not rows or len(rows) == 0: d = error_dialog(self.gui, _('Cannot view'), _('No book selected')) d.exec_() return |
ac('edit', _('Edit meta info'), 'edit_input.svg', _('E')) | ac('edit', _('Edit metadata'), 'edit_input.svg', _('E')) | def ac(name, text, icon, shortcut=None, tooltip=None): action = QAction(QIcon(I(icon)), text, self) text = tooltip if tooltip else text action.setToolTip(text) action.setStatusTip(text) action.setWhatsThis(text) action.setAutoRepeat(False) action.setObjectName('action_'+name) if shortcut: action.setShortcut(shortcut) s... |
prints('Updating booklist:', i) | prints('Updating XML Cache:', i) | def update(self, booklists, collections_attributes): playlist_map = self.get_playlist_map() |
self._details = unicode(err) + '\n\n' + \ | try: ex = unicode(err) except: try: ex = str(err).decode(preferred_encoding, 'replace') except: ex = repr(err) self._details = ex + '\n\n' + \ | def run(self): self.start_work() try: self.result = self.func(*self.args, **self.kwargs) if self._aborted: return except (Exception, SystemExit), err: if self._aborted: return self.failed = True self._details = unicode(err) + '\n\n' + \ traceback.format_exc() self.exception = err finally: self.job_done() |
if ent.lower().startswith(u' num = int(ent[2:], 16) if encoding is None or num > 255: return check(my_unichr(num)) return check(chr(num).decode(encoding)) if ent.startswith(u' | if ent.startswith(' | def check(ch): return result_exceptions.get(ch, ch) |
num = int(ent[1:]) except ValueError: | if ent[1] in ('x', 'X'): num = int(ent[2:], 16) else: num = int(ent[1:]) except: | def check(ch): return result_exceptions.get(ch, ch) |
href = '/browse/matches/%s/%s'%(q, id_) | href = '/browse/matches/%s/%s'%(quote(q), quote(id_)) | def item(i): templ = (u'<div title="{4}" class="category-item">' '<div class="category-name">{0}</div><div>{1}</div>' '<div>{2}' '<span class="href">{3}</span></div></div>') rating, rstring = render_rating(i.avg_rating) name = xml(i.name) if datatype == 'rating': name = xml(_('%d stars')%int(i.avg_rating)) id_ = i.id i... |
.format(xml(x, True), xml(y), xml(_('Browse books by')), | .format(xml(x, True), xml(quote(y)), xml(_('Browse books by')), | def getter(x): return category_meta[x]['name'].lower() |
p = PT(text, STRONG(__appname__), A(url, href=url), style='text-align:left') | p = PT(text, STRONG(__appname__), A(url, href=url), style='text-align:left; max-width: 100%; overflow: hidden;') | def _generate(self, bottom, feed, art, number_of_articles_in_feed, two_levels, url, __appname__, prefix='', center=True, extra_css=None, style=None): head = HEAD(TITLE('navbar')) if style: head.append(STYLE(style, type='text/css')) if extra_css: head.append(STYLE(extra_css, type='text/css')) |
_css_url_re = re.compile(r'url\((.*?)\)', re.I) | _css_url_re = re.compile(r'url\s*\((.*?)\)', re.I) | def CALIBRE(name): return '{%s}%s' % (CALIBRE_NS, name) |
def iterlinks(root): | def iterlinks(root, find_links_in_css=True): | def iterlinks(root): ''' Iterate over all links in a OEB Document. :param root: A valid lxml.etree element. ''' assert etree.iselement(root) link_attrs = set(html.defs.link_attrs) link_attrs.add(XLINK('href')) for el in root.iter(): attribs = el.attrib try: tag = el.tag except UnicodeDecodeError: continue if tag == ... |
for el, attrib, link, pos in iterlinks(root): | for el, attrib, link, pos in iterlinks(root, find_links_in_css=False): | def rewrite_links(root, link_repl_func, resolve_base_href=False): ''' Rewrite all the links in the document. For each link ``link_repl_func(link)`` will be called, and the return value will replace the old link. Note that links may not be absolute (unless you first called ``make_links_absolute()``), and may be intern... |
return self.simple_error('', _('The lookup name must contain only lower case letters, digits and underscores, and start with a letter')) | return self.simple_error('', _('The lookup name must contain only ' 'lower case letters, digits and underscores, and start with a letter')) | def accept(self): col = unicode(self.column_name_box.text()) if not col: return self.simple_error('', _('No lookup name was provided')) if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col: return self.simple_error('', _('The lookup name must contain only lower case letters, digits and unders... |
return self.simple_error('', _('Lookup names cannot end with _index, because these names are reserved for the index of a series column.')) | return self.simple_error('', _('Lookup names cannot end with _index, ' 'because these names are reserved for the index of a series column.')) | def accept(self): col = unicode(self.column_name_box.text()) if not col: return self.simple_error('', _('No lookup name was provided')) if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col: return self.simple_error('', _('The lookup name must contain only lower case letters, digits and unders... |
if not self.editing_col or self.parent.custcols[col]['colnum'] != self.orig_column_number: | if not self.editing_col or \ self.parent.custcols[col]['colnum'] != self.orig_column_number: | def accept(self): col = unicode(self.column_name_box.text()) if not col: return self.simple_error('', _('No lookup name was provided')) if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col: return self.simple_error('', _('The lookup name must contain only lower case letters, digits and unders... |
if not self.editing_col or self.parent.custcols[t]['colnum'] != self.orig_column_number: | if not self.editing_col or \ self.parent.custcols[t]['colnum'] != self.orig_column_number: | def accept(self): col = unicode(self.column_name_box.text()) if not col: return self.simple_error('', _('No lookup name was provided')) if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col: return self.simple_error('', _('The lookup name must contain only lower case letters, digits and unders... |
return self.simple_error('', _('You must enter a template for composite fields')%col_heading) | return self.simple_error('', _('You must enter a template for composite fields')) | def accept(self): col = unicode(self.column_name_box.text()) if not col: return self.simple_error('', _('No lookup name was provided')) if re.match('^\w*$', col) is None or not col[0].isalpha() or col.lower() != col: return self.simple_error('', _('The lookup name must contain only lower case letters, digits and unders... |
inline = etree.SubElement(inline, XHTML('sup')) | parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sup')) | def mobimlize_content(self, tag, text, bstate, istates): 'Convert text content' if text or tag != 'br': bstate.content = True istate = istates[-1] para = bstate.para if tag in SPECIAL_TAGS and not text: para = para if para is not None else bstate.body elif para is None or tag in ('td', 'th'): body = bstate.body if bsta... |
inline = etree.SubElement(inline, XHTML('sub')) | parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sub')) | def mobimlize_content(self, tag, text, bstate, istates): 'Convert text content' if text or tag != 'br': bstate.content = True istate = istates[-1] para = bstate.para if tag in SPECIAL_TAGS and not text: para = para if para is not None else bstate.body elif para is None or tag in ('td', 'th'): body = bstate.body if bsta... |
def get_publisher(self, entry): publisher = entry publitext = None for x in publisher.getiterator('dt'): if self.repub.match(x.text): publitext = x.getnext().text_content() break return unicode(publitext) def get_date(self, entry, verbose): date = entry d = '' for x in date.getiterator('dt'): if x.text == 'Date de p... | def get_book_info(self, entry, mi): entry = entry.find("dl[@title='Informations sur le livre']") for x in entry.getiterator('dt'): if x.text == 'ISBN': isbntext = x.getnext().text_content().replace('-', '') if check_isbn(isbntext): mi.isbn = unicode(isbntext) elif self.repub.match(x.text): mi.publisher = unicode(x.getn... | |
(re.compile(u'¨\s*(<br.*?>)*\s*e', re.UNICODE), lambda match: u'ë'), (re.compile(u'¨\s*(<br.*?>)*\s*E', re.UNICODE), lambda match: u'Ë'), (re.compile(u'¨\s*(<br.*?>)*\s*i', re.UNICODE), lambda match: u'ï'), (re.compile(u'¨\s*(<br.*?>)*\s*I', re.UNICODE), lambda match: u'Ï'), (re.compile(u'¨\s*(<br.*?>)*\s*a', re.UNICOD... | def __call__(self, data, add_namespace=False): from calibre.ebooks.oeb.base import XHTML_CSS_NAMESPACE data = self.PAGE_PAT.sub('', data) if not add_namespace: return data ans, namespaced = [], False for line in data.splitlines(): ll = line.lstrip() if not (namespaced or ll.startswith('@import') or ll.startswith('@char... | |
(re.compile(u'`\s*(<br.*?>)*\s*e', re.UNICODE), lambda match: u'è'), (re.compile(u'`\s*(<br.*?>)*\s*E', re.UNICODE), lambda match: u'È'), (re.compile(u'`\s*(<br.*?>)*\s*i', re.UNICODE), lambda match: u'ì'), (re.compile(u'`\s*(<br.*?>)*\s*I', re.UNICODE), lambda match: u'Ì'), (re.compile(u'`\s*(<br.*?>)*\s*a', re.UNICOD... | (re.compile(u'´\s*(<br.*?>)*\s*a', re.UNICODE), lambda match: u'á'), (re.compile(u'´\s*(<br.*?>)*\s*A', re.UNICODE), lambda match: u'Á'), (re.compile(u'´\s*(<br.*?>)*\s*c', re.UNICODE), lambda match: u'ć'), (re.compile(u'´\s*(<br.*?>)*\s*C', re.UNICODE), lambda match: u'Ć'), | def __call__(self, data, add_namespace=False): from calibre.ebooks.oeb.base import XHTML_CSS_NAMESPACE data = self.PAGE_PAT.sub('', data) if not add_namespace: return data ans, namespaced = [], False for line in data.splitlines(): ll = line.lstrip() if not (namespaced or ll.startswith('@import') or ll.startswith('@char... |
(re.compile(u'´\s*(<br.*?>)*\s*a', re.UNICODE), lambda match: u'á'), (re.compile(u'´\s*(<br.*?>)*\s*A', re.UNICODE), lambda match: u'Á'), | (re.compile(u'´\s*(<br.*?>)*\s*o', re.UNICODE), lambda match: u'ó'), (re.compile(u'´\s*(<br.*?>)*\s*O', re.UNICODE), lambda match: u'Ó'), (re.compile(u'´\s*(<br.*?>)*\s*n', re.UNICODE), lambda match: u'ń'), (re.compile(u'´\s*(<br.*?>)*\s*N', re.UNICODE), lambda match: u'Ń'), (re.compile(u'´\s*(<br.*?>)*\s*s', re.UNICOD... | def __call__(self, data, add_namespace=False): from calibre.ebooks.oeb.base import XHTML_CSS_NAMESPACE data = self.PAGE_PAT.sub('', data) if not add_namespace: return data ans, namespaced = [], False for line in data.splitlines(): ll = line.lstrip() if not (namespaced or ll.startswith('@import') or ll.startswith('@char... |
(re.compile(u'ˆ\s*(<br.*?>)*\s*e', re.UNICODE), lambda match: u'ê'), (re.compile(u'ˆ\s*(<br.*?>)*\s*E', re.UNICODE), lambda match: u'Ê'), (re.compile(u'ˆ\s*(<br.*?>)*\s*i', re.UNICODE), lambda match: u'î'), (re.compile(u'ˆ\s*(<br.*?>)*\s*I', re.UNICODE), lambda match: u'Î'), (re.compile(u'ˆ\s*(<br.*?>)*\s*a', re.UNICOD... | def __call__(self, data, add_namespace=False): from calibre.ebooks.oeb.base import XHTML_CSS_NAMESPACE data = self.PAGE_PAT.sub('', data) if not add_namespace: return data ans, namespaced = [], False for line in data.splitlines(): ll = line.lstrip() if not (namespaced or ll.startswith('@import') or ll.startswith('@char... | |
stream = path if hasattr(path, 'read') else open(path, 'rb') stream.seek(0) matches = self.data.get_matches('title', title) if matches: tag_matches = self.data.get_matches('tags', _('Catalog')) matches = matches.intersection(tag_matches) db_id, existing = None, False if matches: db_id = list(matches)[0] if db_id is Non... | with open(path, 'rb') as stream: matches = self.data.get_matches('title', '='+title) if matches: tag_matches = self.data.get_matches('tags', '='+_('Catalog')) matches = matches.intersection(tag_matches) db_id = None if matches: db_id = list(matches)[0] if db_id is None: obj = self.conn.execute('INSERT INTO books(title,... | def add_catalog(self, path, title): format = os.path.splitext(path)[1][1:].lower() stream = path if hasattr(path, 'read') else open(path, 'rb') stream.seek(0) matches = self.data.get_matches('title', title) if matches: tag_matches = self.data.get_matches('tags', _('Catalog')) matches = matches.intersection(tag_matches)... |
self.javascript('$("body").css("padding-bottom", "%dpx")' % amount) | padding = '%dpx'%amount try: old_padding = unicode(self.javascript('$("body").css("padding-bottom")').toString()) except: old_padding = '' if old_padding != padding: self.javascript('$("body").css("padding-bottom", "%s")' % padding) | def set_bottom_padding(self, amount): self.javascript('$("body").css("padding-bottom", "%dpx")' % amount) |
self.func() | self.doit() | def run(self): try: self.func() except Exception, err: import traceback try: err = unicode(err) except: err = repr(err) self.error = (err, traceback.format_exc()) |
QObject.connect(self.series, SIGNAL('currentIndexChanged(int)'), self.series_changed) QObject.connect(self.series, SIGNAL('editTextChanged(QString)'), self.series_changed) QObject.connect(self.tag_editor_button, SIGNAL('clicked()'), self.tag_editor) | self.series.currentIndexChanged[int].connect(self.series_changed) self.series.editTextChanged.connect(self.series_changed) self.tag_editor_button.clicked.connect(self.tag_editor) | def __init__(self, window, rows, db): QDialog.__init__(self, window) Ui_MetadataBulkDialog.__init__(self) self.setupUi(self) self.db = db self.ids = [db.id(r) for r in rows] self.box_title.setText('<p>' + _('Editing meta information for <b>%d books</b>') % len(rows)) self.write_series = False self.changed = False |
def tag_editor(self): | def tag_editor(self, *args): | def tag_editor(self): d = TagEditor(self, self.db, None) d.exec_() if d.result() == QDialog.Accepted: tag_string = ', '.join(d.tags) self.tags.setText(tag_string) self.tags.update_tags_cache(self.db.all_tags()) self.remove_tags.update_tags_cache(self.db.all_tags()) |
self.changed = bool(self.ids) for w in getattr(self, 'custom_column_widgets', []): w.gui_val def doit(): for id in self.ids: if do_swap_ta: title = self.db.title(id, index_is_id=True) aum = self.db.authors(id, index_is_id=True) if aum: aum = [a.strip().replace('|', ',') for a in aum.split(',')] new_title = authors_t... | args = (remove, add, au, aus, do_aus, rating, pub, do_series, do_autonumber, do_remove_format, remove_format, do_swap_ta, do_remove_conv, do_auto_author, series) | def accept(self): if len(self.ids) < 1: return QDialog.accept(self) |
self.worker.finished.connect(bb.accept, type=Qt.QueuedConnection) | self.worker = Worker(args, self.db, self.ids, Dispatcher(bb.accept, parent=bb)) self.worker.start() | def doit(): for id in self.ids: if do_swap_ta: title = self.db.title(id, index_is_id=True) aum = self.db.authors(id, index_is_id=True) if aum: aum = [a.strip().replace('|', ',') for a in aum.split(',')] new_title = authors_to_string(aum) self.db.set_title(id, new_title, notify=False) if title: new_authors = string_to_a... |
self.library_view.resizeRowsToContents() | def __init__(self, listener, opts, actions, parent=None): self.preferences_action, self.quit_action = actions self.spare_servers = [] MainWindow.__init__(self, opts, parent) # Initialize fontconfig in a separate thread as this can be a lengthy # process if run for the first time on this machine from calibre.utils.fonts... | |
view.resizeRowsToContents() | def metadata_downloaded(self, job): ''' Called once metadata has been read for all books on the device. ''' if job.failed: if isinstance(job.exception, ExpatError): error_dialog(self, _('Device database corrupted'), _(''' <p>The database of books on the reader is corrupted. Try the following: <ol> <li>Unplug the reader... | |
view.resizeRowsToContents() | def location_selected(self, location): ''' Called when a location icon is clicked (e.g. Library) ''' page = 0 if location == 'library' else 1 if location == 'main' else 2 if location == 'carda' else 3 self.stack.setCurrentIndex(page) view = self.memory_view if page == 1 else \ self.card_a_view if page == 2 else \ self.... | |
which = unhexlify(cid) | which = unhexlify(cid).decode('utf-8') | def browse_matches(self, category=None, cid=None, list_sort=None): if list_sort: list_sort = unquote(list_sort) if not cid: raise cherrypy.HTTPError(404, 'invalid category id: %r'%cid) categories = self.categories_cache() |
wand.save(dest+'8') os.rename(dest+'8', dest) | if dest.lower().endswith('.png'): dest += '8' wand.save(dest) if dest.endswith('8'): dest = dest[:-1] os.rename(dest+'8', dest) | def process_pages(self): from calibre.utils.magick import PixelWand for i, wand in enumerate(self.pages): pw = PixelWand() pw.color = 'white' |
doc = etree.fromstring(xml, parser=parser) | try: doc = etree.fromstring(xml, parser=parser) except: self.log.warn('Failed to parse XML. Trying to recover') parser = etree.XMLParser(no_network=True, huge_tree=True, recover=True) doc = etree.fromstring(xml, parser=parser) | def convert(self, stream, options, file_ext, log, accelerators): self.log = log self.log('Generating XML') from calibre.ebooks.lrf.lrfparser import LRFDocument d = LRFDocument(stream) d.parse() xml = d.to_xml(write_files=True) if options.verbose > 2: open('lrs.xml', 'wb').write(xml.encode('utf-8')) parser = etree.XMLPa... |
extra.append(_('TAGS: %s<br />')%format_tag_string(tags, ',', | extra.append(_('TAGS: %s<br />')%xml(format_tag_string(tags, ',', | def ACQUISITION_ENTRY(item, version, db, updated, CFM, CKEYS, prefix): FM = db.FIELD_MAP title = item[FM['title']] if not title: title = _('Unknown') authors = item[FM['authors']] if not authors: authors = _('Unknown') authors = ' & '.join([i.replace('|', ',') for i in authors.split(',')]) extra = [] rating = item[FM['... |
no_tag_count=True)) | no_tag_count=True))) | def ACQUISITION_ENTRY(item, version, db, updated, CFM, CKEYS, prefix): FM = db.FIELD_MAP title = item[FM['title']] if not title: title = _('Unknown') authors = item[FM['authors']] if not authors: authors = _('Unknown') authors = ' & '.join([i.replace('|', ',') for i in authors.split(',')]) extra = [] rating = item[FM['... |
(series, | (xml(series), | def ACQUISITION_ENTRY(item, version, db, updated, CFM, CKEYS, prefix): FM = db.FIELD_MAP title = item[FM['title']] if not title: title = _('Unknown') authors = item[FM['authors']] if not authors: authors = _('Unknown') authors = ' & '.join([i.replace('|', ',') for i in authors.split(',')]) extra = [] rating = item[FM['... |
extra.append('%s: %s<br />'%(name, format_tag_string(val, ',', | extra.append('%s: %s<br />'%(xml(name), xml(format_tag_string(val, ',', | def ACQUISITION_ENTRY(item, version, db, updated, CFM, CKEYS, prefix): FM = db.FIELD_MAP title = item[FM['title']] if not title: title = _('Unknown') authors = item[FM['authors']] if not authors: authors = _('Unknown') authors = ' & '.join([i.replace('|', ',') for i in authors.split(',')]) extra = [] rating = item[FM['... |
no_tag_count=True))) | no_tag_count=True)))) | def ACQUISITION_ENTRY(item, version, db, updated, CFM, CKEYS, prefix): FM = db.FIELD_MAP title = item[FM['title']] if not title: title = _('Unknown') authors = item[FM['authors']] if not authors: authors = _('Unknown') authors = ' & '.join([i.replace('|', ',') for i in authors.split(',')]) extra = [] rating = item[FM['... |
extra.append('%s: %s<br />'%(name, val)) | extra.append('%s: %s<br />'%(xml(name), xml(unicode(val)))) | def ACQUISITION_ENTRY(item, version, db, updated, CFM, CKEYS, prefix): FM = db.FIELD_MAP title = item[FM['title']] if not title: title = _('Unknown') authors = item[FM['authors']] if not authors: authors = _('Unknown') authors = ' & '.join([i.replace('|', ',') for i in authors.split(',')]) extra = [] rating = item[FM['... |
cover += '\0' * (size - len(cover)) self.cover_record[:] = cover | if len(cover) <= size: cover += '\0' * (size - len(cover)) self.cover_record[:] = cover | def update_exth_record(rec): recs.append(rec) if rec[0] in self.original_exth_records: self.original_exth_records.pop(rec[0]) |
thumbnail += '\0' * (size - len(thumbnail)) self.thumbnail_record[:] = thumbnail return | if len(thumbnail) <= size: thumbnail += '\0' * (size - len(thumbnail)) self.thumbnail_record[:] = thumbnail return | def update_exth_record(rec): recs.append(rec) if rec[0] in self.original_exth_records: self.original_exth_records.pop(rec[0]) |
return len(extensions) == 1 and iter(extensions).next() in ('jpg', 'jpeg', 'png') | comic_extensions = set(['jpg', 'jpeg', 'png']) return len(extensions - comic_extensions) == 0 | def is_comic(list_of_names): extensions = set([x.rpartition('.')[-1].lower() for x in list_of_names]) return len(extensions) == 1 and iter(extensions).next() in ('jpg', 'jpeg', 'png') |
THUMB_WIDTH = 75 THUMB_HEIGHT = 100 | def numberTranslate(self): hundredsNumber = 0 thousandsNumber = 0 hundredsString = "" thousandsString = "" resultString = "" self.suffix = '' | |
self.__totalSteps = 10.0 | self.__totalSteps = 11.0 | def __init__(self, db, opts, plugin, report_progress=DummyReporter(), stylesheet="content/stylesheet.css"): self.__opts = opts self.__authors = None self.__basename = opts.basename self.__booksByAuthor = None self.__booksByTitle = None self.__catalogPath = PersistentTemporaryDirectory("_epub_mobi_catalog", prefix='') s... |
if self.opts.fmt == 'mobi': imgTag['style'] = 'width: %dpx; height:%dpx;' % (self.THUMB_WIDTH, self.THUMB_HEIGHT) | def generateHTMLDescriptions(self): # Write each title to a separate HTML file in contentdir self.updateProgressFullStep("'Descriptions'") | |
factor = 2 if self.opts.fmt == 'epub' else 1 pw.MagickThumbnailImage(thumb, factor*self.THUMB_WIDTH, factor*self.THUMB_HEIGHT) | pw.MagickThumbnailImage(thumb, self.thumbWidth, self.thumbHeight) | def generateThumbnail(self, title, image_dir, thumb_file): import calibre.utils.PythonMagickWand as pw try: img = pw.NewMagickWand() if img < 0: raise RuntimeError('generateThumbnail(): Cannot create wand') # Read the cover if not pw.MagickReadImage(img, title['cover'].encode(filesystem_encoding)): self.opts.log.error(... |
formatter = (lambda x:u'\u2605'*int(round(x/2.))) | formatter = (lambda x:u'\u2605'*int(x/2)) | def get_categories(self, sort='name', ids=None, icon_map=None): self.books_list_filter.change([] if not ids else ids) |
re.compile(r'<\?[^<>]+encoding=[\'"](.*?)[\'"][^<>]*>', | re.compile(r'<\?[^<>]+encoding\s*=\s*[\'"](.*?)[\'"][^<>]*>', | def detect(aBuf): import calibre.ebooks.chardet.universaldetector as universaldetector u = universaldetector.UniversalDetector() u.reset() u.feed(aBuf) u.close() return u.result |
re.compile(r'''<meta\s+?[^<>]+?content=['"][^'"]*?charset=([-a-z0-9]+)[^'"]*?['"][^<>]*>''', | re.compile(r'''<meta\s+?[^<>]+?content\s*=\s*['"][^'"]*?charset=([-a-z0-9]+)[^'"]*?['"][^<>]*>''', | def detect(aBuf): import calibre.ebooks.chardet.universaldetector as universaldetector u = universaldetector.UniversalDetector() u.reset() u.feed(aBuf) u.close() return u.result |
val = fm['is_multiple'].join(res) | val = res if fm['is_custom']: val = fm['is_multiple'].join(val) | def apply_pattern(val): try: return self.s_r_obj.sub(self.s_r_func, val) except: return val |
if field == 'authors': val = string_to_authors(val) | def apply_pattern(val): try: return self.s_r_obj.sub(self.s_r_func, val) except: return val | |
if self.use_author_sort and book.author_sort is not None: record.set('author', clean(book.author_sort)) | if self.use_author_sort: if book.author_sort: aus = book.author_sort else: debug_print('Author_sort is None for book', book.lpath) aus = authors_to_sort_string(book.authors) record.set('author', clean(aus)) | def clean(x): if isbytestring(x): x = x.decode(preferred_encoding, 'replace') x.replace(u'\0', '') return x |
msg = MIMEText(text) | msg = MIMEText(text, 'plain', 'utf-8') | def create_mail(from_, to, subject, text=None, attachment_data=None, attachment_type=None, attachment_name=None): assert text or attachment_data from email.mime.multipart import MIMEMultipart outer = MIMEMultipart() outer['Subject'] = subject outer['To'] = to outer['From'] = from_ outer.preamble = 'You will not see t... |
def get_cover(opf, opf_path, stream): | def get_cover(opf, opf_path, stream, reader=None): | def get_cover(opf, opf_path, stream): import posixpath from calibre.ebooks import render_html_svg_workaround from calibre.utils.logging import default_log raster_cover = opf.raster_cover stream.seek(0) zf = ZipFile(stream) if raster_cover: base = posixpath.dirname(opf_path) cpath = posixpath.normpath(posixpath.join(bas... |
cdata = get_cover(reader.opf, reader.opf_path, stream) | cdata = get_cover(reader.opf, reader.opf_path, stream, reader=reader) | def get_metadata(stream, extract_cover=True): """ Return metadata as a :class:`MetaInformation` object """ stream.seek(0) reader = OCFZipReader(stream) mi = MetaInformation(reader.opf) if extract_cover: try: cdata = get_cover(reader.opf, reader.opf_path, stream) if cdata is not None: mi.cover_data = ('jpg', cdata) exce... |
self.setHtml(u'<table>%s</table>'%rows) | self.setHtml(templ%(u'<table>%s</table>'%rows)) | def _show_data(self, rows, comments): if self.vertical: if comments: rows += u'<tr><td colspan="2">%s</td></tr>'%comments self.setHtml(u'<table>%s</table>'%rows) else: left_pane = u'<table>%s</table>'%rows right_pane = u'<div>%s</div>'%comments self.setHtml(u'<table><tr><td valign="top" ' 'style="padding-right:2em">%s<... |
self.setHtml(u'<table><tr><td valign="top" ' | self.setHtml(templ%(u'<table><tr><td valign="top" ' | def _show_data(self, rows, comments): if self.vertical: if comments: rows += u'<tr><td colspan="2">%s</td></tr>'%comments self.setHtml(u'<table>%s</table>'%rows) else: left_pane = u'<table>%s</table>'%rows right_pane = u'<div>%s</div>'%comments self.setHtml(u'<table><tr><td valign="top" ' 'style="padding-right:2em">%s<... |
% (left_pane, right_pane)) | % (left_pane, right_pane))) | def _show_data(self, rows, comments): if self.vertical: if comments: rows += u'<tr><td colspan="2">%s</td></tr>'%comments self.setHtml(u'<table>%s</table>'%rows) else: left_pane = u'<table>%s</table>'%rows right_pane = u'<div>%s</div>'%comments self.setHtml(u'<table><tr><td valign="top" ' 'style="padding-right:2em">%s<... |
except ValueError: | except: | def compute_locale_info_for_parse_date(): try: dt = datetime.strptime('1/5/2000', "%x") except ValueError: try: dt = datetime.strptime('1/5/01', '%x') except: return False if dt.month == 5: return True return False |
doc = etree.fromstring(raw) | doc = etree.fromstring(raw.replace('\0', '')) | def convert(self, stream, options, file_ext, log, accelerators): from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.oeb.base import XLINK_NS NAMESPACES = {'f':FB2NS, 'l':XLINK_NS} log.debug('Parsing XML...') raw = stream.read() try: doc = etree.... |
def open(self): USBMS.open(self) | def post_open_callback(self): | def open(self): USBMS.open(self) |
self.orig_timestamp = timestamp | self.orig_timestamp = timestamp.astimezone(utc_tz) | def __init__(self, window, row, db, accepted_callback=None, cancel_all=False): ResizableDialog.__init__(self, window) self.bc_box.layout().setAlignment(self.cover, Qt.AlignCenter|Qt.AlignHCenter) self.cancel_all = False base = unicode(self.author_sort.toolTip()) self.ok_aus_tooltip = '<p>' + textwrap.fill(base+'<br><br... |
obsolete = ' | def migrate_preference(name, default): obsolete = '###OBSOLETE--DON\'T USE ME###' ans = self.prefs.get(name, None) if ans is None: ans = prefs[name] if ans in (None, obsolete): ans = default prefs[name] = obsolete self.prefs[name] = ans | |
if ans in (None, obsolete): | if ans is None: | def migrate_preference(name, default): obsolete = '###OBSOLETE--DON\'T USE ME###' ans = self.prefs.get(name, None) if ans is None: ans = prefs[name] if ans in (None, obsolete): ans = default prefs[name] = obsolete self.prefs[name] = ans |
prefs[name] = obsolete self.prefs[name] = ans | prefs[name] = self.prefs[name] = ans | def migrate_preference(name, default): obsolete = '###OBSOLETE--DON\'T USE ME###' ans = self.prefs.get(name, None) if ans is None: ans = prefs[name] if ans in (None, obsolete): ans = default prefs[name] = obsolete self.prefs[name] = ans |
break | continue | def book_on_device(self, id, format=None, reset=False): loc = [None, None, None] |
title_words = title.split(' ') | title_words = title.split() stop_words = ['a','an','the'] | def generateSortTitle(self, title): # Convert the actual title to a string suitable for sorting. # Convert numbers to strings, ignore leading stop words # The 21-Day Consciousness Cleanse |
hit = re.search('[0-9]+',word) if hit : | if i==0 and re.search('[0-9]+',word): | def generateSortTitle(self, title): # Convert the actual title to a string suitable for sorting. # Convert numbers to strings, ignore leading stop words # The 21-Day Consciousness Cleanse |
if attr == 'series': | if attr == 'series' or \ ('series' in collection_attributes and getattr(book, 'series', None) == category): | def get_collections(self, collection_attributes): from calibre.devices.usbms.driver import debug_print debug_print('Starting get_collections:', prefs['manage_device_metadata']) collections = {} series_categories = set([]) # This map of sets is used to avoid linear searches when testing for # book equality collections_l... |
'''absorbed = set([]) | def coalesce_regions(self): # find contiguous sets of small regions # absorb into a neighboring region (prefer the one with number of cols # closer to the avg number of cols in the set, if equal use larger # region) # merge contiguous regions that can contain each other '''absorbed = set([]) found = True while found: f... | |
prev = None if i == 0 else i-1 next = j if self.regions[j] not in regions else None ''' pass | prev_region = None if i == 0 else i-1 next_region = j if self.regions[j] not in regions else None if prev_region is None and next_region is not None: absorb_into = next_region elif next_region is None and prev_region is not None: absorb_into = prev_region elif prev_region is None and next_region is None: if len(regions... | def coalesce_regions(self): # find contiguous sets of small regions # absorb into a neighboring region (prefer the one with number of cols # closer to the avg number of cols in the set, if equal use larger # region) # merge contiguous regions that can contain each other '''absorbed = set([]) found = True while found: f... |
if not mi.title: | if not mi.title or mi.title == _('Unknown'): | def _run(self): self.key = get_isbndb_key() if not self.key: self.key = None self.fetched_metadata = {} self.failures = {} with self.worker: for id, mi in self.metadata.items(): args = {} if mi.isbn: args['isbn'] = mi.isbn else: if not mi.title: self.failures[id] = \ (str(id), _('Book has neither title nor ISBN')) cont... |
if mi.authors: | if mi.authors and mi.authors[0] != _('Unknown'): | def _run(self): self.key = get_isbndb_key() if not self.key: self.key = None self.fetched_metadata = {} self.failures = {} with self.worker: for id, mi in self.metadata.items(): args = {} if mi.isbn: args['isbn'] = mi.isbn else: if not mi.title: self.failures[id] = \ (str(id), _('Book has neither title nor ISBN')) cont... |
esize = 3 + force_int(size) | try: esize = 3 + force_int(size) except: esize = 3 | def force_int(raw): return int(re.search(r'([0-9+-]+)', raw).group(1)) |
text = re.sub(r'(?imsu)(?P<anchor><a\s+id="calibre_link-\d+"\s*/>)\s*(?P<strong>(<p>)*\s*<strong>.+?</strong>\s*(</p>)*)', lambda mo: '</section><section>%s<title>%s</title>' % (mo.group('anchor'), mo.group('strong')), text) text = re.sub(r'(?imsu)<p>\s*(?P<anchor><a\s+id="calibre_link-\d+"\s*/>)\s*</p>\s*(?P<strong>(<... | def remove_p(t): t = t.replace('<p>', '') t = t.replace('</p>', '') return t text = re.sub(r'(?imsu)(<p>)\s*(?P<anchor><a\s+id="calibre_link-\d+"\s*/>)\s*(</p>)\s*(<p>)\s*(?P<strong><strong>.+?</strong>)\s*(</p>)', lambda mo: '</section><section>%s<title><p>%s</p></title>' % (mo.group('anchor'), remove_p(mo.group('stro... | def sectionize_chapters(self, text): text = re.sub(r'(?imsu)(?P<anchor><a\s+id="calibre_link-\d+"\s*/>)\s*(?P<strong>(<p>)*\s*<strong>.+?</strong>\s*(</p>)*)', lambda mo: '</section><section>%s<title>%s</title>' % (mo.group('anchor'), mo.group('strong')), text) text = re.sub(r'(?imsu)<p>\s*(?P<anchor><a\s+id="calibre_l... |
number = int(self.number) | try: number = int(self.number) except: return | def numberTranslate(self): hundredsNumber = 0 thousandsNumber = 0 hundredsString = "" thousandsString = "" resultString = "" |
print "library.catalog:CatalogBuilder.generateSortTitle(): translating '%s'" % word | def generateSortTitle(self, title): # Convert the actual title to a string suitable for sorting. # Convert numbers to strings, ignore leading stop words # The 21-Day Consciousness Cleanse | |
from calibre.ebooks.oeb.base import XLINK_NS | from calibre.ebooks.oeb.base import XLINK_NS, XHTML_NS | def convert(self, stream, options, file_ext, log, accelerators): from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.oeb.base import XLINK_NS NAMESPACES = {'f':FB2NS, 'l':XLINK_NS} log.debug('Parsing XML...') raw = stream.read() try: doc = etree.... |
open('index.xhtml', 'wb').write(transform.tostring(result)) | index = transform.tostring(result) open('index.xhtml', 'wb').write(index) open('inline-styles.css', 'wb').write(css) | def convert(self, stream, options, file_ext, log, accelerators): from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.oeb.base import XLINK_NS NAMESPACES = {'f':FB2NS, 'l':XLINK_NS} log.debug('Parsing XML...') raw = stream.read() try: doc = etree.... |
if os.path.isabs(member.filename): targetpath = os.path.join(targetpath, member.filename[1:]) else: targetpath = os.path.join(targetpath, member.filename) | fname = decode_arcname(member.filename) if fname.startswith('/'): fname = fname[1:] targetpath = os.path.join(targetpath, fname) | def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. if targetpath[-1:] == "/": targetpath = targetpath[:-1] |
if not isinstance(targetpath, unicode): encoding = detect(targetpath)['encoding'] try: targetpath = targetpath.decode(encoding) except: targetpath = targetpath.decode('utf-8', 'replace') targetpath = targetpath.encode(filesystem_encoding) | def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. if targetpath[-1:] == "/": targetpath = targetpath[:-1] | |
source = self.open(member, pwd=pwd) | def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. if targetpath[-1:] == "/": targetpath = targetpath[:-1] | |
try: target = open(targetpath, "wb") except IOError: targetpath = sanitize_file_name(targetpath) target = open(targetpath, "wb") shutil.copyfileobj(source, target) source.close() target.close() | with closing(self.open(member, pwd=pwd)) as source: with open(targetpath, 'wb') as target: shutil.copyfileobj(source, target) | def _extract_member(self, member, targetpath, pwd): """Extract the ZipInfo object 'member' to a physical file on the path targetpath. """ # build the destination pathname, replacing # forward slashes to platform specific separators. if targetpath[-1:] == "/": targetpath = targetpath[:-1] |
z = ZipFile(zipstream, 'w') path = os.path.join(tdir, *name.split('/')) shutil.copyfileobj(datastream, open(path, 'wb')) for info in names: current = os.path.join(tdir, *info.filename.split('/')) if os.path.isdir(current): z.writestr(info.filename+'/', '', 0700) else: z.write(current, info.filename, compress_type=info.... | with closing(ZipFile(zipstream, 'w')) as z: for info in names: fname = decode_arcname(info.filename) current = os.path.join(tdir, *fname.split('/')) if os.path.isdir(current): z.writestr(info.filename+'/', '', 0700) else: z.write(current, info.filename, compress_type=info.compress_type) | def safe_replace(zipstream, name, datastream): ''' Replace a file in a zip file in a safe manner. This proceeds by extracting and re-creating the zipfile. This is neccessary because :method:`ZipFile.replace` sometimes created corrupted zip files. :param zipstream: Stream from a zip file :param name: The name of... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.