rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
if hundredsComponent and tensComponent: | elif hundredsComponent and tensComponent: | def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number |
else: prints(" NumberToText.stringFromInt(): empty result translating %d" % intToTranslate) | def stringFromInt(self, intToTranslate): # Convert intToTranslate to string # intToTranslate is a three-digit number | |
if self.verbose: | if False and self.verbose: | def fetchBooksByAuthor(self): # Generate a list of titles sorted by author from the database |
rules.insert(0 | rules.insert(0, | def __call__(self, html, remove_special_chars=None): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGNER elif self.is_pdftohtml(html): rules = self.PDFTOHTML else: rule... |
w += '="%s%%"' % width | w += '="%s"' % width | def dump_text(self, elem, stylizer, page, tag_stack=[]): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return [] |
rpages = [] | pagelist_template = u'''\ <div class="pagelist"> <ul> {pages} </ul> </div> ''' rpages, lpages = [], [] | def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/br... |
start=pos+1, end=pos+len(pg), prefix=prefix)) | start=start, end=end, prefix=prefix)) lpages.append(' '*20 + (u'<li><a href=" ' onclick="gp_internal(\'{id}\'); return false;"> ' '{start} to {end}</a></li>').format(start=start, end=end, id='page%d'%i)) | def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/br... |
gp_start = gp_end = '' if len(pages) > 1: gp_start = '<a href=" (_('Go to') + '…') gp_end = '</a>' | def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/br... | |
<span class="start">0</span> to <span class="end">0</span> of {num} | {gp_start} <span class="start">0</span> to <span class="end">0</span> {gp_end}of {num} | def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/br... |
next=_('Next'), num=num) | next=_('Next'), num=num, gp_start=gp_start, gp_end=gp_end) | def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/br... |
pages=rpages, navbar=navbar) | pages=rpages, navbar=navbar, pagelist=pagelist, goto=xml(_('Go to'), True) + '…') | def render_book_list(ids, prefix, suffix=''): # {{{ pages = [] num = len(ids) pos = 0 delta = 25 while ids: page = list(ids[:delta]) pages.append((page, pos)) ids = ids[delta:] pos += len(page) page_template = u'''\ <div class="page" id="page{0}"> <div class="load_data" title="{1}"> <span class="url" title="{prefix}/br... |
try: self.root = os.getcwdu() except: pass | def __init__(self, stream, mode='r', root=None): try: self.archive = ZipFile(stream, mode=mode) except BadZipfile: raise EPubException("not a ZIP .epub OCF container") self.root = root if self.root is None: try: self.root = os.getcwdu() except: pass if hasattr(stream, 'name'): self.root = os.path.abspath(os.path.dirnam... | |
if self.series.currentIndex() > -1: mi.series = unicode(self.series.currentText()).strip() | series = unicode(self.series.currentText()).strip() if series: mi.series = series | def get_metadata(self): title, authors = self.get_title_and_authors() mi = MetaInformation(title, authors) publisher = unicode(self.publisher.text()).strip() if publisher: mi.publisher = publisher author_sort = unicode(self.author_sort.text()).strip() if author_sort: mi.author_sort = author_sort comments = unicode(self... |
def create_exth(self, exth=None): | def create_exth(self, new_title=None, exth=None): | def create_exth(self, exth=None): # Add an EXTH block to record 0, rewrite the stream # self.hexdump(self.record0) |
new_record0.write(title_in_file) | if new_title: new_title = (new_title or _('Unknown')).encode(self.codec, 'replace') new_record0.write(new_title) else: new_record0.write(title_in_file) | def create_exth(self, exth=None): # Add an EXTH block to record 0, rewrite the stream # self.hexdump(self.record0) |
self.create_exth(exth) | self.create_exth(exth=exth, new_title=mi.title) | def update(self, mi): if self.type != "BOOKMOBI": raise MobiError("Setting metadata only supported for MOBI files of type 'BOOK'.\n" "\tThis is a '%s' file of type '%s'" % (self.type[0:4], self.type[4:8])) |
d = error_dialog(self.window, _('Cannot read'), | d = error_dialog(self, _('Cannot read'), | def select_cover(self, checked): 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 per... |
d = error_dialog(self.window, _('Error reading file'), | d = error_dialog(self, _('Error reading file'), | def select_cover(self, checked): 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 per... |
d = error_dialog(self.window, | d = error_dialog(self, | def select_cover(self, checked): 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 per... |
error_dialog(self.window, _('No permission'), | error_dialog(self, _('No permission'), | def _add_formats(self, paths): added = False if not paths: return added bad_perms = [] for _file in paths: _file = os.path.abspath(_file) if not os.access(_file, os.R_OK): bad_perms.append(_file) continue |
fromstring = functools.partial(etree.fromstring, parser=RECOVER_PARSER) | parser = etree.XMLParser(no_network=True, huge_tree=True) | def _parse_xhtml(self, data): self.oeb.log.debug('Parsing', self.href, '...') # Convert to Unicode and normalize line endings data = self.oeb.decode(data) data = self.oeb.html_preprocessor(data) |
data = fromstring(data) | data = etree.fromstring(data, parser=parser) | def first_pass(data): try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.log.exception('Initial parse failed:') repl = lambda m: ENTITYDEFS.get(m.group(1), m.group(0)) data = ENTITY_RE.sub(repl, data) try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.logger.warn('Parsing file ... |
data = fromstring(data) | data = etree.fromstring(data, parser=RECOVER_PARSER) | def first_pass(data): try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.log.exception('Initial parse failed:') repl = lambda m: ENTITYDEFS.get(m.group(1), m.group(0)) data = ENTITY_RE.sub(repl, data) try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.logger.warn('Parsing file ... |
data = fromstring(data) | data = etree.fromstring(data) | def first_pass(data): try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.log.exception('Initial parse failed:') repl = lambda m: ENTITYDEFS.get(m.group(1), m.group(0)) data = ENTITY_RE.sub(repl, data) try: data = fromstring(data) except etree.XMLSyntaxError, err: self.oeb.logger.warn('Parsing file ... |
self.applied_items.sort(key=lambda x:sort_key(self.all_items[x])) | self.applied_items.sort(key=lambda x:sort_key(self.all_items[x].name)) | def apply_tags(self, node=None): if self.current_cat_name is None: return nodes = self.available_items_box.selectedItems() if node is None else [node] for node in nodes: index = self.all_items[node.data(Qt.UserRole).toPyObject()].index if index not in self.applied_items: self.applied_items.append(index) self.applied_it... |
self.author = author | self.book_author = author | def __call__(self, title, author, publisher, isbn, verbose, log=None, extra=None): self.worker = Thread(target=self._fetch) self.worker.daemon = True self.title = title self.verbose = verbose self.author = author self.publisher = publisher self.isbn = isbn self.log = log if log is not None else default_log self.extra =... |
self.results = search(self.title, self.author, self.publisher, | self.results = search(self.title, self.book_author, self.publisher, | def fetch(self): from calibre.ebooks.metadata.google_books import search try: self.results = search(self.title, self.author, self.publisher, self.isbn, max_results=10, verbose=self.verbose) except Exception, e: self.exception = e self.tb = traceback.format_exc() |
if self.author: args.extend(['--author', self.author]) | if self.book_author: args.extend(['--author', self.book_author]) | def fetch(self): if not self.site_customization: return from calibre.ebooks.metadata.isbndb import option_parser, create_books args = ['isbndb'] if self.isbn: args.extend(['--isbn', self.isbn]) else: if self.title: args.extend(['--title', self.title]) if self.author: args.extend(['--author', self.author]) if self.publi... |
self.results = get_social_metadata(self.title, self.author, | self.results = get_social_metadata(self.title, self.book_author, | def fetch(self): if not self.isbn: return from calibre.ebooks.metadata.amazon import get_social_metadata try: self.results = get_social_metadata(self.title, self.author, self.publisher, self.isbn) except Exception, e: self.exception = e self.tb = traceback.format_exc() |
if not title or title == _('Unknown'): | if not title or title == _('Unknown') or 'USER_CONTENT' in title: | def __init__(self, raw, codec, title): self.doctype = raw[:4] self.length, self.num_items = struct.unpack('>LL', raw[4:12]) raw = raw[12:] pos = 0 self.mi = MetaInformation(_('Unknown'), [_('Unknown')]) self.has_fake_cover = True left = self.num_items |
_('You are tying to save files into the calibre ' | _('You are trying to save files into the calibre ' | def save_to_disk(self, checked, single_dir=False, single_format=None): rows = self.current_view().selectionModel().selectedRows() if not rows or len(rows) == 0: return error_dialog(self, _('Cannot save to disk'), _('No books selected'), show=True) path = choose_dir(self, 'save to disk dialog', _('Choose destination dir... |
stylesheet = None for item in self.oeb.manifest: if item.media_type.lower() in OEB_STYLES: stylesheet = item break | if stylesheet is not None: from cssutils.css import CSSRule for lb in XPath('//h:ul[@class]|//h:ol[@class]')(root): sel = '.'+lb.get('class') for rule in stylesheet.data.cssRules.rulesOfType(CSSRule.STYLE_RULE): if sel == rule.selectorList.selectorText: val = rule.style.removeProperty('margin-left') pval = rule.style.... | def workaround_ade_quirks(self): ''' Perform various markup transforms to get the output to render correctly in the quirky ADE. ''' from calibre.ebooks.oeb.base import XPath, XHTML, OEB_STYLES, barename, urlunquote |
collections = [x.strip() for x in | collections = [x.lower().strip() for x in | def sync_booklists(self, booklists, end_session=True): debug_print('PRS505: started sync_booklists') c = self.initialize_XML_cache() blists = {} for i in c.paths: if booklists[i] is not None: blists[i] = booklists[i] opts = self.settings() if opts.extra_customization: collections = [x.strip() for x in opts.extra_custom... |
res = re.sub('(?<=\n)\n{2}', u'<p>\u00a0</p>\n', res) | res = re.sub('(?<=\n)\n{2}', u'<p>\u00a0</p>\n'.encode('utf-8'), res) | def convert(self, stream, options, file_ext, log, accelerators): from calibre.ebooks.metadata.meta import get_metadata from calibre.ebooks.metadata.opf2 import OPFCreator from calibre.ebooks.rtf2xml.ParseRtf import RtfInvalidCodeException self.options = options self.log = log self.log('Converting RTF to XML...') #Name ... |
self.datetime = time.gmtime() | try: self.datetime = time.gmtime(os.path.getctime(self.path)) except: self.datetime = time.gmtime() | def __init__(self, prefix, lpath, size=None, other=None): from calibre.ebooks.metadata.meta import path_to_ext |
if islinux and not linux_scanner.ok: raise RuntimeError('DeviceScanner requires the /sys filesystem to work.') | def __init__(self, *args): if isosx and osx_scanner is None: raise RuntimeError('The Python extension usbobserver must be available on OS X.') if islinux and not linux_scanner.ok: raise RuntimeError('DeviceScanner requires the /sys filesystem to work.') self.scanner = win_scanner if iswindows else osx_scanner if isosx ... | |
dev.reset(detected_device=detected_device, | try: dev.reset(detected_device=detected_device, | def do_connect(self, connected_devices, device_kind): for dev, detected_device in connected_devices: if dev.OPEN_FEEDBACK_MESSAGE is not None: self.open_feedback_slot(dev.OPEN_FEEDBACK_MESSAGE) dev.reset(detected_device=detected_device, report_progress=self.report_progress) try: dev.open() except: prints('Unable to ope... |
try: | def do_connect(self, connected_devices, device_kind): for dev, detected_device in connected_devices: if dev.OPEN_FEEDBACK_MESSAGE is not None: self.open_feedback_slot(dev.OPEN_FEEDBACK_MESSAGE) dev.reset(detected_device=detected_device, report_progress=self.report_progress) try: dev.open() except: prints('Unable to ope... | |
prints('Unable to open device', str(dev)) traceback.print_exc() | tb = traceback.format_exc() if DEBUG or tb not in self.reported_errors: self.reported_errors.add(tb) prints('Unable to open device', str(dev)) prints(tb) | def do_connect(self, connected_devices, device_kind): for dev, detected_device in connected_devices: if dev.OPEN_FEEDBACK_MESSAGE is not None: self.open_feedback_slot(dev.OPEN_FEEDBACK_MESSAGE) dev.reset(detected_device=detected_device, report_progress=self.report_progress) try: dev.open() except: prints('Unable to ope... |
prints('Connect to device failed, retrying in 5 seconds...') | if DEBUG: prints('Connect to device failed, retrying in 5 seconds...') | def detect_device(self): self.scanner.scan() if self.is_device_connected: connected, detected_device = \ self.scanner.is_device_connected(self.connected_device, only_presence=True) if not connected: self.connected_device_removed() else: possibly_connected_devices = [] for device in self.devices: if device in self.eject... |
prints('Device connect failed again, giving up') | if DEBUG: prints('Device connect failed again, giving up') | def detect_device(self): self.scanner.scan() if self.is_device_connected: connected, detected_device = \ self.scanner.is_device_connected(self.connected_device, only_presence=True) if not connected: self.connected_device_removed() else: possibly_connected_devices = [] for device in self.devices: if device in self.eject... |
self.valign = 'baseline' self.nest = False | def __init__(self): self.rendered = False self.left = 0. self.halign = 'auto' self.indent = 0. self.fsize = 3 self.ids = set() self.valign = 'baseline' self.nest = False self.italic = False self.bold = False self.strikethrough = False self.underline = False self.preserve = False self.family = 'serif' self.bgcolor = 'tr... | |
and self.valign == other.valign \ | def __eq__(self, other): return self.fsize == other.fsize \ and self.italic == other.italic \ and self.bold == other.bold \ and self.href == other.href \ and self.valign == other.valign \ and self.preserve == other.preserve \ and self.family == other.family \ and self.bgcolor == other.bgcolor \ and self.fgcolor == othe... | |
valign = istate.valign | 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... | |
if valign == 'super': parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.SubElement(parent, XHTML('sup')) elif valign == 'sub': parent = inline if istate.nest and bstate.inline is not None: parent = bstate.inline istate.nest = False inline = etree.Sub... | if fsize != 3: | 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 mobimlize_elem(self, elem, stylizer, bstate, istates): | def mobimlize_elem(self, elem, stylizer, bstate, istates, ignore_valign=False): | def mobimlize_elem(self, elem, stylizer, bstate, istates): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return style = stylizer.style(elem) # <mbp:frame-set/> does not exist lalalala if style['display'] in ('none', 'oeb-page-head', 'oeb-page-foot') \ or style['visibility'] == 'hidden': ... |
valign = style['vertical-align'] if valign in ('super', 'text-top') or asfloat(valign) > 0: istate.nest = istate.valign in ('sub', 'super') istate.valign = 'super' elif valign == 'sub' or asfloat(valign) < 0: istate.nest = istate.valign in ('sub', 'super') istate.valign = 'sub' else: istate.valign = 'baseline' | def mobimlize_elem(self, elem, stylizer, bstate, istates): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return style = stylizer.style(elem) # <mbp:frame-set/> does not exist lalalala if style['display'] in ('none', 'oeb-page-head', 'oeb-page-foot') \ or style['visibility'] == 'hidden': ... | |
self.qaction.triggered.connect(self.add_books_to_library) | def location_selected(self, loc): enabled = loc != 'library' self.qaction.setEnabled(enabled) self.qaction.triggered.connect(self.add_books_to_library) | |
if data.get('id', None) == self.data.get('id', None): | if data.get('id', True) == self.data.get('id', False): | def show_data(self, data): self.animation.stop() if data.get('id', None) == self.data.get('id', None): return self.data = {'id':data.get('id', None)} if data.has_key('cover'): self.pixmap = QPixmap.fromImage(data.pop('cover')) if self.pixmap.isNull(): self.pixmap = self.default_pixmap else: self.pixmap = self.default_p... |
WARNING: This completely regenrates your datbase. You will | WARNING: This completely regenerates your datbase. You will | def restore_database_option_parser(): parser = get_parser(_( ''' %prog restore_database [options] Restore this database from the metadata stored in OPF files in each directory of the calibre library. This is useful if your metadata.db file has been corrupted. WARNING: This completely regenrates your datbase. You will... |
if size < 1024*1024: divisor, suffix = 1024., "KB" elif size < 1024*1024*1024: divisor, suffix = 1024*1024, "MB" elif size < 1024*1024*1024*1024: divisor, suffix = 1024*1024*1024, "GB" | for i, candidate in enumerate(('KB', 'MB', 'GB', 'TB', 'PB', 'EB')): if size < 1024**(i+2): divisor, suffix = 1024**(i+1), candidate break | def human_readable(size): """ Convert a size in bytes into a human readable form """ divisor, suffix = 1, "B" if size < 1024*1024: divisor, suffix = 1024., "KB" elif size < 1024*1024*1024: divisor, suffix = 1024*1024, "MB" elif size < 1024*1024*1024*1024: divisor, suffix = 1024*1024*1024, "GB" size = str(float(size)/di... |
raise 'Bad domain name (circular) at ' + str(off) | raise ValueError('Bad domain name (circular) at ' + str(off)) | def readName(self): '''Reads a domain name from the packet''' result = '' off = self.offset next = -1 first = off |
raise 'Bad domain name at ' + str(off) | raise ValueError('Bad domain name at ' + str(off)) | def readName(self): '''Reads a domain name from the packet''' result = '' off = self.offset next = -1 first = off |
self.current_index = len(self.ids) | def do_one(self, id): 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, do_series_restart, \ series_start_value, do_title_case, clear_series = self.args | |
self.search_box.set_search_string(ss) | self.search_box.clear_to_help() | def delete_search_button_clicked(self): if not confirm('<p>'+_('The selected search will be ' '<b>permanently deleted</b>. Are you sure?') +'</p>', 'saved_search_delete', self): return idx = self.currentIndex if idx < 0: return ss = self.saved_searches.lookup(unicode(self.currentText())) self.saved_searches.delete(unic... |
item = QListWidgetItem(BooksModel.headers[col], self.columns) | try: item = QListWidgetItem(BooksModel.headers[col], self.columns) except KeyError: continue | def __init__(self, window, db, server=None): ResizableDialog.__init__(self, window) self.ICON_SIZES = {0:QSize(48, 48), 1:QSize(32,32), 2:QSize(24,24)} self._category_model = CategoryModel() |
if processed or plumber.input_fmt.lower() in ('pdf', 'rb'): | if hasattr(self.pathtoopf, 'manifest'): self.pathtoopf = write_oebbook(self.pathtoopf, self.base) elif processed or plumber.input_fmt.lower() in ('pdf', 'rb'): | def __enter__(self, processed=False): self.delete_on_exit = [] self._tdir = TemporaryDirectory('_ebook_iter') self.base = self._tdir.__enter__() from calibre.ebooks.conversion.plumber import Plumber, create_oebbook plumber = Plumber(self.pathtoebook, self.base, self.log) plumber.setup_options() if self.pathtoebook.low... |
if hasattr(self.pathtoopf, 'manifest'): self.pathtoopf = write_oebbook(self.pathtoopf, self.base) | def __enter__(self, processed=False): self.delete_on_exit = [] self._tdir = TemporaryDirectory('_ebook_iter') self.base = self._tdir.__enter__() from calibre.ebooks.conversion.plumber import Plumber, create_oebbook plumber = Plumber(self.pathtoebook, self.base, self.log) plumber.setup_options() if self.pathtoebook.low... | |
print "count found in cache: %d, count of files in metadata: %d, need_sync: %s" % \ (len(bl_cache), len(bl), need_sync) | def update_booklist(prefix, path, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(path) in self.FORMATS: try: lpath = path.partition(self.normalize_path(prefix))[2] if lpath.startswith(os.sep): lpath = lpath[len(os.sep):] lpath = lpath.replace('\\', '/') | |
print "Add book to metatdata: " print "prefix: " + prefix | def add_books_to_metadata(self, locations, metadata, booklists): metadata = iter(metadata) for i, location in enumerate(locations): self.report_progress((i+1) / float(len(locations)), _('Adding books to device metadata listing...')) info = metadata.next() blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'ca... | |
print "path: " + lpath | def add_books_to_metadata(self, locations, metadata, booklists): metadata = iter(metadata) for i, location in enumerate(locations): self.report_progress((i+1) / float(len(locations)), _('Adding books to device metadata listing...')) info = metadata.next() blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'ca... | |
self.search_restriction.currentIndexChanged[str].connect(self.apply_search_restriction) | self.search_restriction.activated[str].connect(self.apply_search_restriction) | def initialize(self, library_path, db, listener, actions): opts = self.opts self.last_time = datetime.datetime.now() self.preferences_action, self.quit_action = actions self.library_path = library_path self.spare_servers = [] self.must_restart_before_config = False # Initialize fontconfig in a separate thread as this c... |
self.search.clear_to_help() | self.apply_search_restriction('') | def saved_searches_changed(self): p = prefs['saved_searches'].keys() p.sort() t = unicode(self.search_restriction.currentText()) self.search_restriction.clear() # rebuild the restrictions combobox using current saved searches self.search_restriction.addItem('') for s in p: self.search_restriction.addItem(s) if t: if t ... |
if extension == '.pdf' or extension == '.epub': | elif extension == '.pdf' or extension == '.epub': | def delete_books(self, paths, end_session=True): for i, path in enumerate(paths): self.report_progress((i+1) / float(len(paths)), _('Removing books from device...')) path = self.normalize_path(path) # print "Delete file normalized path: " + path extension = os.path.splitext(path)[1] |
if extension == '.html': | else: | def delete_books(self, paths, end_session=True): for i, path in enumerate(paths): self.report_progress((i+1) / float(len(paths)), _('Removing books from device...')) path = self.normalize_path(path) # print "Delete file normalized path: " + path extension = os.path.splitext(path)[1] |
query = '' for e in (opts.title, opts.author, opts.publisher): if e is not None: query += ' ' + e | query = ' '.join([e for e in (opts.title, opts.author, opts.publisher) \ if e is not None ]) | def build_combined(base_url, opts): query = '' for e in (opts.title, opts.author, opts.publisher): if e is not None: query += ' ' + e query = query.strip() if len(query) == 0: raise ISBNDBError('You must specify at least one of --author, --title or --publisher') query = re.sub(r'\s+', '+', query) if isinstance(query, ... |
ans = [] for x in tans: add = True for y in ans: if y.isbn == x.isbn: add = False if add: ans.append(x) return ans | return dict((book.isbn, book) for book in tans).values() | def create_books(opts, args, timeout=5.): base_url = BASE_URL%dict(key=args[1]) if opts.isbn is not None: url = build_isbn(base_url, opts) else: url = build_combined(base_url, opts) if opts.verbose: print ('ISBNDB query: '+url) tans = [ISBNDBMetadata(book) for book in fetch_metadata(url, timeout=timeout)] ans = [] fo... |
pdf = open(pdf_n, 'rw+b') | pdf = open(pdf_n, 'rwb') | def extract_content(self, output_dir): self.log.info('Extracting PDF...') |
b, _, e = x.rpartition('.') if not b and e: b = e e = '' | b, e = os.path.splitext(x) if e == '.': e = '' | def shorten_components_to(length, components): filepath = os.sep.join(components) extra = len(filepath) - length if extra < 1: return components delta = int(ceil(extra/float(len(components)))) ans = [] for x in components: if delta > len(x): r = x[0] if x is components[-1] else '' else: if x is components[-1]: b, _, e ... |
self.root = os.getcwdu() | try: self.root = os.getcwdu() except: pass | def __init__(self, stream, mode='r', root=None): try: self.archive = ZipFile(stream, mode=mode) except BadZipfile: raise EPubException("not a ZIP .epub OCF container") self.root = root if self.root is None: self.root = os.getcwdu() if hasattr(stream, 'name'): self.root = os.path.abspath(os.path.dirname(stream.name)) su... |
files = [] blocks = [] | def compareFileStream(file1, file2): return cmp(file1.fileName, file2.fileName) | |
self.Parse(inputFile); def Parse(self, inputFile): | self.Open(inputFile) def Open(self, inputFile): | def __init__(self, inputFile = None): if inputFile != None: self.Parse(inputFile); |
self.Parse(snbFile) snbFile.close() def Parse(self, snbFile, metaOnly = False): | def Parse(self, inputFile): self.fileName = inputFile snbFile = open(self.fileName, "rb") snbFile.seek(0) # Read header vmbr = snbFile.read(44) (self.magic, self.rev80, self.revA3, self.revZ1, self.fileCount, self.vfatSize, self.vfatCompressed, self.binStreamSize, self.plainStreamSizeUncompressed, self.revZ2) = struc... | |
except EOFError, e: | except Exception, e: | def Parse(self, inputFile): self.fileName = inputFile snbFile = open(self.fileName, "rb") snbFile.seek(0) # Read header vmbr = snbFile.read(44) (self.magic, self.rev80, self.revA3, self.revZ1, self.fileCount, self.vfatSize, self.vfatCompressed, self.binStreamSize, self.plainStreamSizeUncompressed, self.revZ2) = struc... |
snbFile.close() | def Parse(self, inputFile): self.fileName = inputFile snbFile = open(self.fileName, "rb") snbFile.seek(0) # Read header vmbr = snbFile.read(44) (self.magic, self.rev80, self.revA3, self.revZ1, self.fileCount, self.vfatSize, self.vfatCompressed, self.binStreamSize, self.plainStreamSizeUncompressed, self.revZ2) = struc... | |
print "File Name:\t", self.fileName | if self.fileName: print "File Name:\t", self.fileName | def Dump(self): print "File Name:\t", self.fileName print "File Count:\t", self.fileCount print "VFAT Size(Compressed):\t%d(%d)" % (self.vfatSize, self.vfatCompressed) print "Binary Stream Size:\t", self.binStreamSize print "Plain Stream Uncompressed Size:\t", self.plainStreamSizeUncompressed print "Binary Block Count:... |
.format(fmt, fname, id_, fmt.upper()) for fmt in | .format(f, fname, id_, f.upper()) for f in | def browse_booklist_page(self, ids=None, sort=None): if sort == 'null': sort = None if ids is None: ids = json.dumps('[]') try: ids = json.loads(ids) except: raise cherrypy.HTTPError(404, 'invalid ids') summs = [] for id_ in ids: try: id_ = int(id_) mi = self.db.get_metadata(id_, index_is_id=True) except: continue args... |
fmt_sidx(m.series_index[0], use_roman=True), m.series[0]) | fmt_sidx(m.series_index[0], use_roman=True), unicode(m.series[0])) | def default_cover(self): ''' Create a generic cover for books that dont have a cover ''' from calibre.ebooks.metadata import authors_to_string, fmt_sidx if self.no_default_cover: return None self.log('Generating default cover') m = self.oeb.metadata title = unicode(m.title[0]) authors = [unicode(x) for x in m.creator i... |
default=False, | default=True, | def tpl_replace(objtplname) : |
self.opts.log.info(" refreshing cache at '%s'" % self.__archive_path) self.opts.log.info(' thumb_width: %1.2f" => %1.2f"' % | self.opts.log.warning(" invalidating cache at '%s'" % self.__archive_path) self.opts.log.warning(' thumb_width changed: %1.2f" => %1.2f"' % | def __init__(self, db, opts, plugin, report_progress=DummyReporter(), stylesheet="content/stylesheet.css"): self.__opts = opts self.__authorClip = opts.authorClip self.__authors = None self.__basename = opts.basename self.__bookmarked_books = None self.__booksByAuthor = None self.__booksByDateRead = None self.__booksBy... |
if not mi.title: | if mi.is_null('title'): | def swap(a): if ',' in a: parts = a.split(',', 1) else: parts = a.split(None, 1) if len(parts) > 1: t = parts[-1] parts = parts[:-1] parts.insert(0, t) return ' '.join(parts) |
self.comments = 'SUMMARY:\n'+summ.string | self.comments = 'SUMMARY:\n'+summ | def tostring(e): if not hasattr(e, 'string'): return None ans = e.string if ans is not None: ans = unicode(ans).strip() if not ans: ans = None return ans |
pt.write(self.db.format(id, format, index_is_id=True)) | src = self.db.format(id, format, index_is_id=True, as_file=True) shutil.copyfileobj(src, pt) | def get_preferred_formats_from_ids(self, ids, formats, paths=False, set_metadata=False, specific_format=None, exclude_auto=False, mode='r+b'): ans = [] need_auto = [] if specific_format is not None: formats = [specific_format.lower()] for id in ids: format = None fmts = self.db.formats(id, index_is_id=True) if not fmts... |
def regenerate_headers(self, len_updated_metadata): | def regenerate_headers(self, updated_md_len): | def regenerate_headers(self, len_updated_metadata): |
sh = sorted(headers,key=lambda x:(headers[x],headers[x])) sh.remove('metadata') sh.append('metadata') | def regenerate_headers(self, len_updated_metadata): | |
for tag in sh[:-1]: | for tag in headers.keys(): | def regenerate_headers(self, len_updated_metadata): |
if b['offset'] < original_md_offset: | if b['offset'] <= original_md_offset: | def regenerate_headers(self, len_updated_metadata): |
ths.write(self.encode_vwi(b['offset'] - original_md_len)) ths.write(self.encode_vwi(b['len_uncomp'])) | ths.write(self.encode_vwi(b['offset'] + delta)) if tag == 'metadata': ths.write(self.encode_vwi(updated_md_len)) else: ths.write(self.encode_vwi(b['len_uncomp'])) | def regenerate_headers(self, len_updated_metadata): |
new_md_offset = (len(self.data) - self.base - original_md_len) new_md_len = len_updated_metadata - 1 - len('metadata') - 1 ths.write('c') ths.write(self.encode_vwi(len('metadata'))) ths.write('metadata') ths.write(self.encode_vwi(1)) ths.write(self.encode_vwi(new_md_offset)) ths.write(self.encode_vwi(new_md_len)) t... | def regenerate_headers(self, len_updated_metadata): | |
self.stream.write(updated_metadata) | def update(self,mi): # Collect the original metadata self.get_original_metadata() | |
mi = MetaInformation(title="My New Title", authors=['Smith, John']) set_metadata(open(sys.argv[1], 'rb'), mi) | if False: print get_metadata(open(sys.argv[1], 'rb')) else: import cStringIO data = open(sys.argv[1], 'rb') stream = cStringIO.StringIO() stream.write(data.read()) mi = MetaInformation(title="A Marvelously Long Title", authors=['Riker, Gregory; Riker, Charles']) set_metadata(stream, mi) tokens = sys.argv[1].rpartit... | def set_metadata(stream, mi): mu = MetadataUpdater(stream) mu.update(mi) return |
self.connect(self.action_sync, SIGNAL('triggered(bool)'), self._sync_menu.trigger_default) | def create_device_menu(self): self._sync_menu = DeviceMenu(self) self.action_sync.setMenu(self._sync_menu) self.connect(self._sync_menu, SIGNAL('sync(PyQt_PyObject, PyQt_PyObject, PyQt_PyObject)'), self.dispatch_sync_event) self.connect(self.action_sync, SIGNAL('triggered(bool)'), self._sync_menu.trigger_default) self.... | |
break | continue | def get_matches(self, location, query): matches = set([]) if query and query.strip(): location = location.lower().strip() |
self.log("found " + unicode(self.html_preprocess_sections) + | self.log("marked " + unicode(self.html_preprocess_sections) + | def chapter_head(self, match): chap = match.group('chap') title = match.group('title') if not title: self.html_preprocess_sections = self.html_preprocess_sections + 1 self.log("found " + unicode(self.html_preprocess_sections) + " chapters. - " + unicode(chap)) return '<h2>'+chap+'</h2>\n' else: self.html_preprocess_sec... |
html = re.sub(r"\s*<p>\s*", "\n<p>", html) | html = re.sub(r"\s*<p(?P<style>[^>]*)>\s*", "\n<p"+"\g<style>"+">", html) | def __call__(self, html): self.log("********* Preprocessing HTML *********") |
elif not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query) | else: if ignore_search_restriction: q = u'%s' % query else: q = u'%s (%s)' % (self.search_restriction, query) | def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): q = '' if not ignore_search_restriction: q = self.search_restriction elif not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return list(self._map... |
return [] | return | def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): q = '' if not ignore_search_restriction: q = self.search_restriction elif not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return list(self._map... |
return [] | def search(self, query, return_matches=False, ignore_search_restriction=False): if not query or not query.strip(): q = '' if not ignore_search_restriction: q = self.search_restriction elif not ignore_search_restriction: q = u'%s (%s)' % (self.search_restriction, query) if not q: if return_matches: return list(self._map... | |
base = base or self.width | if base is None: base = self.width | def _unit_convert(self, value, base=None, font=None): ' Return value in pts' if isinstance(value, (int, long, float)): return value try: return float(value) * 72.0 / self._profile.dpi except: pass result = value m = self.UNIT_RE.match(value) if m is not None and m.group(1): value = float(m.group(1)) unit = m.group(2) i... |
for key in item.attrib.keys(): if key.endswith('scheme'): scheme = item.get(key) | for xkey in item.attrib.keys(): if xkey.endswith('scheme'): scheme = item.get(xkey) | def process_encryption(self, encfile, opf, log): key = None for item in opf.identifier_iter(): scheme = None for key in item.attrib.keys(): if key.endswith('scheme'): scheme = item.get(key) if (scheme and scheme.lower() == 'uuid') or \ (item.text and item.text.startswith('urn:uuid:')): key = str(item.text).rpartition('... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.