rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
self.listtypes[name] = 'ol'
|
def s_text_list_level_style_number(self, tag, attrs): name = self.tagstack.stackparent()[(STYLENS,'name')] self.listtypes[name] = 'ol' level = attrs[(TEXTNS,'level')] num_format = attrs.get( (STYLENS,'name'),"1") self.prevstyle = self.currentstyle self.currentstyle = ".%s_%s" % ( name.replace(".","_"), level) self.stylestack.append(self.currentstyle) self.styledict[self.currentstyle] = {} if num_format == "1": listtype = "decimal" elif num_format == "I": listtype = "upper-roman" elif num_format == "i": listtype = "lower-roman" elif num_format == "A": listtype = "upper-alpha" elif num_format == "a": listtype = "lower-alpha" else: listtype = "decimal" self.styledict[self.currentstyle][('','list-style-type')] = listtype
|
|
lb_added.artworks[1].data_.set(cover_data)
|
try: lb_added.artworks[1].data_.set(cover_data) except: if DEBUG: self.log.warning(" iTunes automation interface reported an error" " when adding artwork to '%s' in the iTunes Library" % metadata.title) pass
|
def _cover_to_thumb(self, path, metadata, db_added, lb_added, format): ''' assumes pythoncom wrapper for db_added as of iTunes 9.2, iBooks 1.1, can't set artwork for PDF files via automation ''' self.log.info(" ITUNES._cover_to_thumb()")
|
pSeriesTag.insert(1,NavigableString(self.NOT_READ_SYMBOL + '%s' % book['series']))
|
pSeriesTag.insert(1,NavigableString('%s' % book['series']))
|
def generateHTMLBySeries(self): ''' Generate a list of series ''' self.updateProgressFullStep("Fetching series")
|
if 'read' in book and book['read']:
|
for tag in book['tags']: if tag == self.opts.read_tag: book['read'] = True break else: book['read'] = False if book['read']:
|
def generateHTMLBySeries(self): ''' Generate a list of series ''' self.updateProgressFullStep("Fetching series")
|
Suppress(Keyword("not", caseless=True)) + Not
|
Suppress(CaselessKeyword("not")) + Not
|
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whitespace + '()') quoted_query = Suppress('"')+CharsNotIn('"')+Suppress('"') query = quoted_query | word_query Token = Group(location + query).setResultsName('token')
|
Not + Suppress(Keyword("and", caseless=True)) + And
|
Not + Suppress(CaselessKeyword("and")) + And
|
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whitespace + '()') quoted_query = Suppress('"')+CharsNotIn('"')+Suppress('"') query = quoted_query | word_query Token = Group(location + query).setResultsName('token')
|
Not + OneOrMore(~oneOf("and or", caseless=True) + And)
|
Not + OneOrMore(~MatchFirst(list(map(CaselessKeyword, ('and', 'or')))) + And)
|
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whitespace + '()') quoted_query = Suppress('"')+CharsNotIn('"')+Suppress('"') query = quoted_query | word_query Token = Group(location + query).setResultsName('token')
|
And + Suppress(Keyword("or", caseless=True)) + Or
|
And + Suppress(CaselessKeyword("or")) + Or
|
def __init__(self, locations, test=False): self._tests_failed = False # Define a token standard_locations = map(lambda x : CaselessLiteral(x)+Suppress(':'), locations) location = NoMatch() for l in standard_locations: location |= l location = Optional(location, default='all') word_query = CharsNotIn(string.whitespace + '()') quoted_query = Suppress('"')+CharsNotIn('"')+Suppress('"') query = quoted_query | word_query Token = Group(location + query).setResultsName('token')
|
u'Jack Weatherford',
|
u'Jack Weatherford Orc',
|
def universal_set(self): ''' Should return the set of all matches. ''' return set([])
|
res = self.get_extra(tkey) return (unicode(cmeta['name']+'_index'), self.format_series_index(res), res, cmeta)
|
if self.get(tkey): res = self.get_extra(tkey) return (unicode(cmeta['name']+'_index'), self.format_series_index(res), res, cmeta) else: return (unicode(cmeta['name']+'_index'), '', '', cmeta)
|
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) '''
|
def strftime(epoch, zone=None): zone = time.gmtime if islinux: zone = time.localtime
|
def strftime(epoch, zone=time.localtime):
|
def strftime(epoch, zone=None): zone = time.gmtime if islinux: zone = time.localtime src = time.strftime("%w, %d %m %Y %H:%M:%S GMT", zone(epoch)).split() src[0] = INVERSE_DAY_MAP[int(src[0][:-1])]+',' src[2] = INVERSE_MONTH_MAP[int(src[2])] return ' '.join(src)
|
if iswindows and time.daylight: timestamp -= time.altzone - time.timezone
|
def update_text_record(self, record, book, path, bl_index): timestamp = os.path.getmtime(path) # Correct for MS DST time 'adjustment' if iswindows and time.daylight: timestamp -= time.altzone - time.timezone date = strftime(timestamp) if date != record.get('date', None): record.set('date', date) record.set('size', str(os.stat(path).st_size)) title = book.title if book.title else _('Unknown') record.set('title', title) ts = book.title_sort if not ts: ts = title_sort(title) record.set('titleSorter', ts) record.set('author', authors_to_string(book.authors)) ext = os.path.splitext(path)[1] if ext: ext = ext[1:].lower() mime = MIME_MAP.get(ext, None) if mime is None: mime = guess_type('a.'+ext)[0] if mime is not None: record.set('mime', mime) if 'sourceid' not in record.attrib: record.set('sourceid', '1') if 'id' not in record.attrib: num = self.max_id(record.getroottree().getroot()) record.set('id', str(num+1))
|
|
mime = MIME_MAP[name.rpartition('.')[-1].lower()]
|
mime = MIME_MAP.get(name.rpartition('.')[-1].lower(), MIME_MAP['epub'])
|
def add_book(self, mi, name, collections, size, ctime): """ Add a node into the DOM tree, representing a book """ book = self.book_by_path(name) if book is not None: self.remove_book(name)
|
if oldseg != newseg:
|
if oldseg.lower() == newseg.lower() and oldseg != newseg:
|
def set_path(self, index, index_is_id=False): ''' Set the path to the directory containing this books files based on its current title and author. If there was a previous directory, its contents are copied and it is deleted. ''' id = index if index_is_id else self.id(index) path = self.construct_path_name(id) current_path = self.path(id, index_is_id=True).replace(os.sep, '/') formats = self.formats(id, index_is_id=True) formats = formats.split(',') if formats else [] # Check if the metadata used to construct paths has changed fname = self.construct_file_name(id) changed = False for format in formats: name = self.conn.get('SELECT name FROM data WHERE book=? AND format=?', (id, format), all=False) if name and name != fname: changed = True break if path == current_path and not changed: return
|
if not end.endswith('u ') and hasattr(elem, 'text') and elem.text: text.append(u' ')
|
text.append(u' ')
|
def dump_text(self, elem, stylizer, end=''): ''' @elem: The element in the etree that we are working on. @stylizer: The style information attached to the element. @end: The last two characters of the text from the previous element. This is used to determine if a blank line is needed when starting a new block element. '''
|
print "percent is " + str(percent)
|
def line_length(format, raw, percent): ''' raw is the raw text to find the line length to use for wrapping. percentage is a decimal number, 0 - 1 which is used to determine how far in the list of line lengths to use. The list of line lengths is ordered smallest to larged and does not include duplicates. 0.5 is the median value. ''' raw = raw.replace(' ', ' ') if format == 'html': linere = re.compile('(?<=<p).*?(?=</p>)', re.DOTALL) elif format == 'pdf': linere = re.compile('(?<=<br>).*?(?=<br>)', re.DOTALL) lines = linere.findall(raw) print "percent is " + str(percent) lengths = [] for line in lines: if len(line) > 0: lengths.append(len(line)) if not lengths: return 0 lengths = list(set(lengths)) total = sum(lengths) avg = total / len(lengths) max_line = avg * 2 lengths = sorted(lengths) for i in range(len(lengths) - 1, -1, -1): if lengths[i] > max_line: del lengths[i] if percent > 1: percent = 1 if percent < 0: percent = 0 index = int(len(lengths) * percent) - 1 return lengths[index]
|
|
(re.compile(u'(?<=[-–—])\s*<br>\s*(?=[[a-z\d])'), lambda match: ''),
|
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('@charset')): ans.append(XHTML_CSS_NAMESPACE.strip()) namespaced = True ans.append(line)
|
|
(re.compile(r'<br\s*/?>\s*(?P<chap>([A-Z]\s+){4,}\s*([\d\w-]+\s*){0,3}\s*)\s*(<br>\s*){1,3}\s*(?P<title>(<(i|b)>)?(\s*\w+){1,4}\s*(</(i|b)>)?\s*(</?(br|p)[^>]*>))?'), chap_head),
|
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('@charset')): ans.append(XHTML_CSS_NAMESPACE.strip()) namespaced = True ans.append(line)
|
|
end_rules.append( (re.compile(r'(?=<(/?br|p|hr))(<(/?br|p|hr)[^>]*)?>\s*(<(i|b)>(<(i|b)>)?)?\s*(?P<chap>([A-Z-\'"!]{3,})\s*(\d+|[A-Z]+(\s*[A-Z]+)?)?|\d+\.?\s*([\d\w-]+\s*){0,4}\s*)\s*(</(i|b)>(</(i|b)>)?)?\s*(</?p[^>]*>|<br[^>]*>)\n?((?=(<i>)?\s*\w+(\s+\w+)?(</i>)?(<br[^>]*>|</?p[^>]*>))((?P<title>.*)(<br[^>]*>|</?p[^>]*>)))?'), chap_head), )
|
end_rules.append((re.compile(r'(?=<(/?br|p|hr))(<(/?br|p|hr)[^>]*)?>\s*(<(i|b)>(<(i|b)>)?)?\s*(?P<chap>([A-Z-\'"!]{3,})\s*(\d+|[A-Z]+(\s*[A-Z]+)?)?|\d+\.?\s*([\d\w-]+\s*){0,4}\s*)\s*(</(i|b)>(</(i|b)>)?)?\s*(</?p[^>]*>|<br[^>]*>)\n?((?=(<i>)?\s*\w+(\s+\w+)?(</i>)?(<br[^>]*>|</?p[^>]*>))((?P<title>.*)(<br[^>]*>|</?p[^>]*>)))?'), chap_head))
|
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGNER elif is_pdftohtml: rules = self.PDFTOHTML else: rules = []
|
print "The pdf line length returned is " + str(length)
|
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGNER elif is_pdftohtml: rules = self.PDFTOHTML else: rules = []
|
|
(re.compile(r'(?<=.{%i}[a-z,;:)\-IA])\s*(?P<ital></(i|b|u)>)?\s*(<p.*?>)\s*(?=(<(i|b|u)>)?\s*[\w\d(])' % length, re.UNICODE), wrap_lines),
|
(re.compile(r'(?<=.{%i}[a-z,;:)\-IA])\s*(?P<ital></(i|b|u)>)?\s*(<p.*?>\s*)+\s*(?=(<(i|b|u)>)?\s*[\w\d(])' % length, re.UNICODE), wrap_lines),
|
def __call__(self, html, remove_special_chars=None, get_preprocess_html=False): if remove_special_chars is not None: html = remove_special_chars.sub('', html) html = html.replace('\0', '') is_pdftohtml = self.is_pdftohtml(html) if self.is_baen(html): rules = [] elif self.is_book_designer(html): rules = self.BOOK_DESIGNER elif is_pdftohtml: rules = self.PDFTOHTML else: rules = []
|
completer.setCompletionMode(QCompleter.InlineCompletion)
|
completer.setCompletionMode(QCompleter.PopupCompletion)
|
def createEditor(self, parent, option, index): editor = EnLineEdit(parent) if self.auto_complete_function: complete_items = [i[1] for i in self.auto_complete_function()] completer = QCompleter(complete_items, self) completer.setCaseSensitivity(Qt.CaseInsensitive) completer.setCompletionMode(QCompleter.InlineCompletion) editor.setCompleter(completer) return editor
|
self.connect(self, SIGNAL('editTextChanged(QString)'), self.text_edited_slot)
|
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])))) self.help_text = help_text self.colorize = colorize self.clear_to_help() self.connect(self, SIGNAL('editTextChanged(QString)'), self.text_edited_slot)
|
|
self.setEditText('') self.line_edit.setStyleSheet( 'QLineEdit { color: black; background-color: %s; }' % self.normal_background) self.help_state = False
|
if self.help_state: self.setEditText('') self.line_edit.setStyleSheet( 'QLineEdit { color: black; background-color: %s; }' % self.normal_background) self.help_state = False else: self.line_edit.setStyleSheet( 'QLineEdit { color: black; background-color: %s; }' % self.normal_background)
|
def normalize_state(self): self.setEditText('') self.line_edit.setStyleSheet( 'QLineEdit { color: black; background-color: %s; }' % self.normal_background) self.help_state = False
|
if self.help_state: self.normalize_state()
|
self.normalize_state()
|
def key_pressed(self, event): if self.help_state: self.normalize_state() if not self.as_you_type: if event.key() in (Qt.Key_Return, Qt.Key_Enter): self.do_search()
|
if self.help_state: self.normalize_state() def text_edited_slot(self, text):
|
self.normalize_state()
|
def mouse_released(self, event): if self.help_state: self.normalize_state()
|
cachep = os.path.join(prefix, self.CACHE_XML)
|
cachep = os.path.join(prefix, *(self.CACHE_XML.split('/')))
|
def write_cache(prefix): try: cachep = os.path.join(prefix, self.CACHE_XML) if not os.path.exists(cachep): try: os.makedirs(os.path.dirname(cachep), mode=0777) except: time.sleep(5) os.makedirs(os.path.dirname(cachep), mode=0777) with open(cachep, 'wb') as f: f.write(u'''<?xml version="1.0" encoding="UTF-8"?> <cache xmlns="http://www.kinoma.com/FskCache/1"> </cache> '''.encode('utf8')) return True except: import traceback traceback.print_exc() return False
|
try: os.makedirs(os.path.dirname(cachep), mode=0777) except: time.sleep(5) os.makedirs(os.path.dirname(cachep), mode=0777)
|
dname = os.path.dirname(cachep) if not os.path.exists(dname): try: os.makedirs(dname, mode=0777) except: time.sleep(5) os.makedirs(dname, mode=0777)
|
def write_cache(prefix): try: cachep = os.path.join(prefix, self.CACHE_XML) if not os.path.exists(cachep): try: os.makedirs(os.path.dirname(cachep), mode=0777) except: time.sleep(5) os.makedirs(os.path.dirname(cachep), mode=0777) with open(cachep, 'wb') as f: f.write(u'''<?xml version="1.0" encoding="UTF-8"?> <cache xmlns="http://www.kinoma.com/FskCache/1"> </cache> '''.encode('utf8')) return True except: import traceback traceback.print_exc() return False
|
if self.opts.connected_kindle:
|
if self.generateRecentlyRead:
|
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.__booksByTitle = None self.__booksByTitle_noSeriesPrefix = None self.__catalogPath = PersistentTemporaryDirectory("_epub_mobi_catalog", prefix='') self.__contentDir = os.path.join(self.catalogPath, "content") self.__currentStep = 0.0 self.__creator = opts.creator self.__db = db self.__descriptionClip = opts.descriptionClip self.__error = None self.__generateForKindle = True if (self.opts.fmt == 'mobi' and \ self.opts.output_profile and \ self.opts.output_profile.startswith("kindle")) else False self.__genres = None self.__genre_tags_dict = None self.__htmlFileList = [] self.__markerTags = self.getMarkerTags() self.__ncxSoup = None self.__playOrder = 1 self.__plugin = plugin self.__progressInt = 0.0 self.__progressString = '' self.__reporter = report_progress self.__stylesheet = stylesheet self.__thumbs = None self.__thumbWidth = 0 self.__thumbHeight = 0 self.__title = opts.catalog_title self.__totalSteps = 11.0 self.__useSeriesPrefixInTitlesSection = False self.__verbose = opts.verbose
|
self.generateHTMLByDateRead()
|
if self.generateRecentlyRead: self.generateHTMLByDateRead()
|
def buildSources(self): if self.booksByTitle is None: if not self.fetchBooksByTitle(): return False self.fetchBooksByAuthor() self.fetchBookmarks() self.generateHTMLDescriptions() self.generateHTMLByAuthor() if self.opts.generate_titles: self.generateHTMLByTitle() if self.opts.generate_recently_added: self.generateHTMLByDateAdded() self.generateHTMLByDateRead() self.generateHTMLByTags()
|
self.generateNCXByDateRead("Recently Read")
|
if self.generateRecentlyRead: self.generateNCXByDateRead("Recently Read")
|
def buildSources(self): if self.booksByTitle is None: if not self.fetchBooksByTitle(): return False self.fetchBooksByAuthor() self.fetchBookmarks() self.generateHTMLDescriptions() self.generateHTMLByAuthor() if self.opts.generate_titles: self.generateHTMLByTitle() if self.opts.generate_recently_added: self.generateHTMLByDateAdded() self.generateHTMLByDateRead() self.generateHTMLByTags()
|
with open(path) as f:
|
with open(path,'rb') as f:
|
def get_bookmark_data(self, path): ''' Return the timestamp and last_read_location ''' with open(path) as f: stream = StringIO(f.read()) data = StreamSlicer(stream) self.timestamp, = unpack('>I', data[0x24:0x28]) bpar_offset, = unpack('>I', data[0x4e:0x52]) #print "bpar_offset: 0x%x" % bpar_offset lrlo = bpar_offset + 0x0c self.last_read_location = int(unpack('>I', data[lrlo:lrlo+4])[0]) ''' iolr = bpar_offset + 0x14 index_of_last_read, = unpack('>I', data[iolr:iolr+4]) #print "index_of_last_read: 0x%x" % index_of_last_read bpar_len, = unpack('>I', data[bpl:bpl+4]) bpar_len += 8 #print "bpar_len: 0x%x" % bpar_len dro = bpar_offset + bpar_len #print "dro: 0x%x" % dro
|
with open(book_fs) as f:
|
with open(book_fs,'rb') as f:
|
def get_book_length(self, path, formats): # This assumes only one of the possible formats exists on the Kindle book_fs = None for format in formats: fmt = format.rpartition('.')[2] if fmt in ['mobi','prc','azw']: book_fs = path.replace('.mbp','.%s' % fmt) if os.path.exists(book_fs): self.book_format = fmt #print "%s exists on device" % book_fs break else: #print "no files matching library formats exist on device" self.book_length = 0 return # Read the book len from the header with open(book_fs) as f: self.stream = StringIO(f.read()) self.data = StreamSlicer(self.stream) self.nrecs, = unpack('>H', self.data[76:78]) record0 = self.record(0) #self.hexdump(record0) self.book_length = int(unpack('>I', record0[0x04:0x08])[0])
|
if self.opts.connected_kindle:
|
if self.generateRecentlyRead:
|
def hexdump(self, src, length=16): # Diagnostic FILTER=''.join([(len(repr(chr(x)))==3) and chr(x) or '.' for x in range(256)]) N=0; result='' while src: s,src = src[:length],src[length:] hexa = ' '.join(["%02X"%ord(x) for x in s]) s = s.translate(FILTER) result += "%04X %-*s %s\n" % (N, length*3, hexa, s) N+=length print result
|
pass
|
def get_initial_value(self, book_ids): value = None for book_id in book_ids: val = self.db.get_custom(book_id, num=self.col_id, index_is_id=True) if tweaks['bool_custom_columns_are_tristate'] == 'no' and val is None: val = False if value is not None and value != val: return None value = val return value def setup_ui(self, parent): self.widgets = [QLabel('&'+self.col_metadata['name']+':', parent), QComboBox(parent)] w = self.widgets[1] items = [_('Yes'), _('No'), _('Undefined')] icons = [I('ok.png'), I('list_remove.png'), I('blank.png')] for icon, text in zip(icons, items): w.addItem(QIcon(icon), text) def setter(self, val): val = {None: 2, False: 1, True: 0}[val] self.widgets[1].setCurrentIndex(val) def commit(self, book_ids, notify=False): val = self.gui_val val = self.normalize_ui_val(val) if val != self.initial_val: if tweaks['bool_custom_columns_are_tristate'] == 'no' and val is None: val = False self.db.set_custom_bulk(book_ids, val, num=self.col_id, notify=notify)
|
def commit(self, book_ids, notify=False): val = self.gui_val val = self.normalize_ui_val(val) if val != self.initial_val: self.db.set_custom_bulk(book_ids, val, num=self.col_id, notify=notify)
|
except IOError:
|
except:
|
def _generate_images(self): self._oeb.logger.info('Serializing images...') images = [(index, href) for href, index in self._images.items()] images.sort() self._first_image_record = None for _, href in images: item = self._oeb.manifest.hrefs[href] try: data = rescale_image(item.data, self._imagemax) except IOError: self._oeb.logger.warn('Bad image file %r' % item.href) continue self._records.append(data) if self._first_image_record is None: self._first_image_record = len(self._records)-1
|
stream.seek(stream.tell() - block_size + idx - len(prefix))
|
pos = stream.tell() - actual_block_size + idx - len(prefix) stream.seek(pos)
|
def get_document_info(stream): """ Extract the \info block from an RTF file. Return the info block as a string and the position in the file at which it starts. @param stream: File like object pointing to the RTF file. """ block_size = 4096 stream.seek(0) found, block = False, "" while not found: prefix = block[-6:] block = prefix + stream.read(block_size) if len(block) == len(prefix): break idx = block.find(r'{\info') if idx >= 0: found = True stream.seek(stream.tell() - block_size + idx - len(prefix)) else: if block.find(r'\sect') > -1: break if not found: return None, 0 data, count, = cStringIO.StringIO(), 0 pos = stream.tell() while True: ch = stream.read(1) if ch == '\\': data.write(ch + stream.read(1)) continue if ch == '{': count += 1 elif ch == '}': count -= 1 data.write(ch) if count == 0: break return data.getvalue(), pos
|
return None
|
return 'nochange'
|
def get_initial_value(self, book_ids): value = None for book_id in book_ids: val = self.db.get_custom(book_id, num=self.col_id, index_is_id=True) if tweaks['bool_custom_columns_are_tristate'] == 'no' and val is None: val = False if value is not None and value != val: return None value = val return value
|
items = [_('Yes'), _('No'), _('Undefined')] icons = [I('ok.png'), I('list_remove.png'), I('blank.png')]
|
items = [_('Yes'), _('No'), _('Undefined'), _('Do not change')] icons = [I('ok.png'), I('list_remove.png'), I('blank.png'), I('blank.png')]
|
def setup_ui(self, parent): self.widgets = [QLabel('&'+self.col_metadata['name']+':', parent), QComboBox(parent)] w = self.widgets[1] items = [_('Yes'), _('No'), _('Undefined')] icons = [I('ok.png'), I('list_remove.png'), I('blank.png')] for icon, text in zip(icons, items): w.addItem(QIcon(icon), text)
|
def setter(self, val): val = {None: 2, False: 1, True: 0}[val]
|
def getter(self): val = self.widgets[1].currentIndex() return {3: 'nochange', 2: None, 1: False, 0: True}[val] def setter(self, val): val = {'nochange': 3, None: 2, False: 1, True: 0}[val]
|
def setter(self, val): val = {None: 2, False: 1, True: 0}[val] self.widgets[1].setCurrentIndex(val)
|
if val != self.initial_val:
|
if val != self.initial_val and val != 'nochange':
|
def commit(self, book_ids, notify=False): val = self.gui_val val = self.normalize_ui_val(val) if val != self.initial_val: if tweaks['bool_custom_columns_are_tristate'] == 'no' and val is None: val = False self.db.set_custom_bulk(book_ids, val, num=self.col_id, notify=notify)
|
return ('_'+name+'()'+\
|
fname = name.replace('-', '_') return ('_'+fname+'()'+\
|
def opts_and_words(name, op, words): opts = '|'.join(options(op)) words = '|'.join([w.replace("'", "\\'") for w in words]) return ('_'+name+'()'+\
|
complete -F _'''%(opts, words) + name + ' ' + name +"\n\n").encode('utf-8')
|
complete -F _'''%(opts, words) + fname + ' ' + name +"\n\n").encode('utf-8')
|
def opts_and_words(name, op, words): opts = '|'.join(options(op)) words = '|'.join([w.replace("'", "\\'") for w in words]) return ('_'+name+'()'+\
|
src = time.strftime("%w, %d %m %Y %H:%M:%S GMT", zone(epoch)).split()
|
try: src = time.strftime("%w, %d %m %Y %H:%M:%S GMT", zone(epoch)).split() except: src = time.strftime("%w, %d %m %Y %H:%M:%S GMT", zone()).split()
|
def strftime(epoch, zone=time.localtime): src = time.strftime("%w, %d %m %Y %H:%M:%S GMT", zone(epoch)).split() src[0] = INVERSE_DAY_MAP[int(src[0][:-1])]+',' src[2] = INVERSE_MONTH_MAP[int(src[2])] return ' '.join(src)
|
and self.strikethrough == other.strikethrough
|
and self.strikethrough == other.strikethrough \ and self.underline == other.underline
|
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 == other.fgcolor \ and self.strikethrough == other.strikethrough
|
if is_pdftohtml:
|
if is_pdftohtml and length > -1:
|
def dump(raw, where): import os dp = getattr(self.extra_opts, 'debug_pipeline', None) if dp and os.path.exists(dp): odir = os.path.join(dp, 'input') if os.path.exists(odir): odir = os.path.join(odir, where) if not os.path.exists(odir): os.makedirs(odir) name, i = None, 0 while not name or os.path.exists(os.path.join(odir, name)): i += 1 name = '%04d.html'%i with open(os.path.join(odir, name), 'wb') as f: f.write(raw.encode('utf-8'))
|
this_title['description'] = re.sub('&', '&', record['comments'])
|
if re.search('<(?P<tag>.+)>.+</(?P=tag)>|<!--.+-->|<.+/>',record['comments']): self.opts.log(chr(7) + " %d: %s (%s) contains suspect metadata" % \ (this_title['id'], this_title['title'],this_title['author'])) this_title['description'] = prepare_string_for_xml(record['comments'])
|
def fetchBooksByTitle(self): self.updateProgressFullStep("Fetching database")
|
aTag['href'] = "Genre%s.html" % re.sub("\W","",self.convertHTMLEntities(tag))
|
aTag['href'] = "Genre_%s.html" % re.sub("\W","",tag.lower())
|
def generateHTMLDescriptions(self): # Write each title to a separate HTML file in contentdir self.updateProgressFullStep("'Descriptions'")
|
filtered_tags = self.filterDbTags(self.db.all_tags())
|
self.genre_tags_dict = self.filterDbTags(self.db.all_tags())
|
def generateHTMLByTags(self): # Generate individual HTML files for each tag, e.g. Fiction, Nonfiction ... # Note that special tags - ~+*[] - have already been filtered from books[]
|
for tag in filtered_tags:
|
for friendly_tag in self.genre_tags_dict:
|
def generateHTMLByTags(self): # Generate individual HTML files for each tag, e.g. Fiction, Nonfiction ... # Note that special tags - ~+*[] - have already been filtered from books[]
|
tag_list['tag'] = tag
|
tag_list['tag'] = self.genre_tags_dict[friendly_tag]
|
def generateHTMLByTags(self): # Generate individual HTML files for each tag, e.g. Fiction, Nonfiction ... # Note that special tags - ~+*[] - have already been filtered from books[]
|
if 'tags' in book and tag in book['tags']:
|
if 'tags' in book and friendly_tag in book['tags']:
|
def generateHTMLByTags(self): # Generate individual HTML files for each tag, e.g. Fiction, Nonfiction ... # Note that special tags - ~+*[] - have already been filtered from books[]
|
genre_list.append(tag_list)
|
genre_exists = False book_not_in_genre = True if not genre_list: genre_list.append(tag_list) else: for genre in genre_list: if genre['tag'] == tag_list['tag']: genre_exists = True for existing_book in genre['books']: if this_book['title'] == existing_book['title']: book_not_in_genre = False break break if genre_exists: if book_not_in_genre: genre['books'].append(this_book) else: genre_list.append(tag_list) if self.opts.verbose: self.opts.log.info(" Genre summary: %d active genres" % len(genre_list)) for genre in genre_list: self.opts.log.info(" %s: %d titles" % (genre['tag'], len(genre['books'])))
|
def generateHTMLByTags(self): # Generate individual HTML files for each tag, e.g. Fiction, Nonfiction ... # Note that special tags - ~+*[] - have already been filtered from books[]
|
"%s/Genre%s.html" % (self.contentDir, re.sub("\W","", self.convertHTMLEntities(genre['tag'])))) tag_file = "content/Genre%s.html" % (re.sub("\W","", self.convertHTMLEntities(genre['tag'])))
|
"%s/Genre_%s.html" % (self.contentDir, genre['tag'])) tag_file = "content/Genre_%s.html" % genre['tag']
|
def generateHTMLByTags(self): # Generate individual HTML files for each tag, e.g. Fiction, Nonfiction ... # Note that special tags - ~+*[] - have already been filtered from books[]
|
contentTag['src'] = "content/Genre%s.html
|
contentTag['src'] = "content/Genre_%s.html
|
def generateNCXByGenre(self, tocTitle): # Create an NCX section for 'By Genre' # Add each genre as an article # 'tag', 'file', 'authors'
|
textTag.insert(0, self.formatNCXText(NavigableString(genre['tag'])))
|
normalized_tag = None for genre_tag in self.genre_tags_dict: if self.genre_tags_dict[genre_tag] == genre['tag']: normalized_tag = self.genre_tags_dict[genre_tag] break textTag.insert(0, self.formatNCXText(NavigableString(genre_tag)))
|
def generateNCXByGenre(self, tocTitle): # Create an NCX section for 'By Genre' # Add each genre as an article # 'tag', 'file', 'authors'
|
genre_name = re.sub("\W","", self.convertHTMLEntities(genre['tag'])) contentTag['src'] = "content/Genre%s.html
|
contentTag['src'] = "content/Genre_%s.html
|
def generateNCXByGenre(self, tocTitle): # Create an NCX section for 'By Genre' # Add each genre as an article # 'tag', 'file', 'authors'
|
def next_tag(tags): for (i, tag) in enumerate(tags): if i < len(tags) - 1: yield tag + ", " else: yield tag filtered_tags = []
|
normalized_tags = [] friendly_tags = []
|
def filterDbTags(self, tags): # Remove the special marker tags from the database's tag list, # return sorted list of tags representing valid genres
|
filtered_tags.append(tag) filtered_tags.sort() if False: for (i, tag) in enumerate(filtered_tags): if tag == 'Fiction': filtered_tags.insert(0, (filtered_tags.pop(i))) elif tag == 'Nonfiction': filtered_tags.insert(1, (filtered_tags.pop(i))) else: continue
|
normalized_tags.append(re.sub('\W','',tag).lower()) friendly_tags.append(tag) genre_tags_dict = dict(zip(friendly_tags,normalized_tags)) normalized_set = set(normalized_tags) for normalized in normalized_set: if normalized_tags.count(normalized) > 1: self.opts.log.warn(" Warning: multiple tags resolving to genre '%s':" % normalized) for key in genre_tags_dict: if genre_tags_dict[key] == normalized: self.opts.log.warn(" %s" % key)
|
def next_tag(tags): for (i, tag) in enumerate(tags): if i < len(tags) - 1: yield tag + ", " else: yield tag
|
self.opts.log.info(u' %d Genre tags in database (exclude_genre: %s):' % \ (len(filtered_tags), self.opts.exclude_genre)) out_buf = '' for tag in next_tag(filtered_tags): out_buf += tag if len(out_buf) > 72: self.opts.log(u' %s' % out_buf.rstrip()) out_buf = '' self.opts.log(u' %s' % out_buf) return filtered_tags
|
def next_tag(tags): for (i, tag) in enumerate(tags): if i < len(tags) - 1: yield tag + ", " else: yield tag self.opts.log.info(u' %d total genre tags in database (exclude_genre: %s):' % \ (len(genre_tags_dict), self.opts.exclude_genre)) sorted_tags = ['%s => %s' % (key, genre_tags_dict[key]) for key in sorted(genre_tags_dict.keys())] for tag in next_tag(sorted_tags): self.opts.log(u' %s' % tag) return genre_tags_dict
|
def next_tag(tags): for (i, tag) in enumerate(tags): if i < len(tags) - 1: yield tag + ", " else: yield tag
|
aTag['name'] = "Genre%s" % re.sub("\W","", genre)
|
aTag['name'] = "Genre_%s" % genre
|
def generateHTMLByGenre(self, genre, section_head, books, outfile): # Write an HTML file of this genre's book list # Return a list with [(first_author, first_book), (last_author, last_book)]
|
for genre_tag in self.genre_tags_dict: if self.genre_tags_dict[genre_tag] == genre: friendly_tag = genre_tag break
|
def generateHTMLByGenre(self, genre, section_head, books, outfile): # Write an HTML file of this genre's book list # Return a list with [(first_author, first_book), (last_author, last_book)]
|
|
titleTag.insert(0,NavigableString('<b><i>%s</i></b>' % escape(genre)))
|
titleTag.insert(0,NavigableString('<b><i>%s</i></b>' % escape(friendly_tag)))
|
def generateHTMLByGenre(self, genre, section_head, books, outfile): # Write an HTML file of this genre's book list # Return a list with [(first_author, first_book), (last_author, last_book)]
|
if self._is_case_sensitive is not None:
|
if getattr(self, '_is_case_sensitive', None) is not None:
|
def is_case_sensitive(self, path): if self._is_case_sensitive is not None: return self._is_case_sensitive if not path or not os.path.exists(path): return islinux or isfreebsd self._is_case_sensitive = os.path.exists(path.lower()) \ and os.path.exists(path.upper()) return self._is_case_sensitive
|
(gtz_count, ltz_count) = self.update_text_record(record, book, path, i, gtz_count, ltz_count)
|
(gtz_count, ltz_count, use_tz_var) = \ self.update_text_record(record, book, path, i, gtz_count, ltz_count, use_tz_var)
|
def update(self, booklists, collections_attributes): debug_print('Starting update', collections_attributes) for i, booklist in booklists.items(): playlist_map = self.build_id_playlist_map(i) debug_print('Updating XML Cache:', i) root = self.record_roots[i] lpath_map = self.build_lpath_map(root) gtz_count = ltz_count = 0 for book in booklist: path = os.path.join(self.prefixes[i], *(book.lpath.split('/'))) record = lpath_map.get(book.lpath, None) if record is None: record = self.create_text_record(root, i, book.lpath) (gtz_count, ltz_count) = self.update_text_record(record, book, path, i, gtz_count, ltz_count) # Ensure the collections in the XML database are recorded for # this book if book.device_collections is None: book.device_collections = [] book.device_collections = playlist_map.get(book.lpath, []) debug_print('Timezone votes: %d GMT, %d LTZ'%(gtz_count, ltz_count)) self.update_playlists(i, root, booklist, collections_attributes) # Update the device collections because update playlist could have added # some new ones. debug_print('In update/ Starting refresh of device_collections') for i, booklist in booklists.items(): playlist_map = self.build_id_playlist_map(i) for book in booklist: book.device_collections = playlist_map.get(book.lpath, []) self.fix_ids() debug_print('Finished update')
|
debug_print('Timezone votes: %d GMT, %d LTZ'%(gtz_count, ltz_count))
|
debug_print('Timezone votes: %d GMT, %d LTZ, use_tz_var='% (gtz_count, ltz_count, use_tz_var))
|
def update(self, booklists, collections_attributes): debug_print('Starting update', collections_attributes) for i, booklist in booklists.items(): playlist_map = self.build_id_playlist_map(i) debug_print('Updating XML Cache:', i) root = self.record_roots[i] lpath_map = self.build_lpath_map(root) gtz_count = ltz_count = 0 for book in booklist: path = os.path.join(self.prefixes[i], *(book.lpath.split('/'))) record = lpath_map.get(book.lpath, None) if record is None: record = self.create_text_record(root, i, book.lpath) (gtz_count, ltz_count) = self.update_text_record(record, book, path, i, gtz_count, ltz_count) # Ensure the collections in the XML database are recorded for # this book if book.device_collections is None: book.device_collections = [] book.device_collections = playlist_map.get(book.lpath, []) debug_print('Timezone votes: %d GMT, %d LTZ'%(gtz_count, ltz_count)) self.update_playlists(i, root, booklist, collections_attributes) # Update the device collections because update playlist could have added # some new ones. debug_print('In update/ Starting refresh of device_collections') for i, booklist in booklists.items(): playlist_map = self.build_id_playlist_map(i) for book in booklist: book.device_collections = playlist_map.get(book.lpath, []) self.fix_ids() debug_print('Finished update')
|
def update_text_record(self, record, book, path, bl_index, gtz_count, ltz_count):
|
def update_text_record(self, record, book, path, bl_index, gtz_count, ltz_count, use_tz_var):
|
def update_text_record(self, record, book, path, bl_index, gtz_count, ltz_count): ''' Update the Sony database from the book. This is done if the timestamp in the db differs from the timestamp on the file. '''
|
if strftime(timestamp, zone=time.gmtime) == rec_date: gtz_count += 1 elif strftime(timestamp, zone=time.localtime) == rec_date: ltz_count += 1
|
if record.get('tz', None) is not None: use_tz_var = True if strftime(timestamp, zone=time.gmtime) == rec_date: gtz_count += 1 elif strftime(timestamp, zone=time.localtime) == rec_date: ltz_count += 1
|
def clean(x): if isbytestring(x): x = x.decode(preferred_encoding, 'replace') x.replace(u'\0', '') return x
|
if ltz_count >= gtz_count:
|
if use_tz_var:
|
def clean(x): if isbytestring(x): x = x.decode(preferred_encoding, 'replace') x.replace(u'\0', '') return x
|
debug_print("Using localtime TZ for new book", book.lpath)
|
record.set('tz', '0') debug_print("Use localtime TZ and tz='0' for new book", book.lpath) elif ltz_count >= gtz_count: tz = time.localtime debug_print("Use localtime TZ for new book", book.lpath)
|
def clean(x): if isbytestring(x): x = x.decode(preferred_encoding, 'replace') x.replace(u'\0', '') return x
|
debug_print("Using GMT TZ for new book", book.lpath)
|
debug_print("Use GMT TZ for new book", book.lpath)
|
def clean(x): if isbytestring(x): x = x.decode(preferred_encoding, 'replace') x.replace(u'\0', '') return x
|
return (gtz_count, ltz_count)
|
return (gtz_count, ltz_count, use_tz_var)
|
def clean(x): if isbytestring(x): x = x.decode(preferred_encoding, 'replace') x.replace(u'\0', '') return x
|
fa[x]=''
|
fa[x]='random long string'
|
def validate(self): tmpl = preprocess_template(self.opt_template.text()) fa = {} for x in FORMAT_ARG_DESCS.keys(): fa[x]='' try: tmpl.format(**fa) except Exception, err: error_dialog(self, _('Invalid template'), '<p>'+_('The template %s is invalid:')%tmpl + \ '<br>'+str(err), show=True) return False return True
|
raise SystemExit(1)
|
def run(self, path_to_output, opts, db, notification=DummyReporter()): self.fmt = path_to_output.rpartition('.')[2] self.notification = notification
|
|
description = _('Communicate with the PocketBook 602 reader.')
|
description = _('Communicate with the PocketBook 602/603/902 reader.')
|
def can_handle(cls, dev, debug=False): return dev[3] == 'Elonex' and dev[4] == 'eBook'
|
WINDOWS_MAIN_MEM = WINDOWS_CARD_A_MEM = ['PB602', 'PB902']
|
WINDOWS_MAIN_MEM = WINDOWS_CARD_A_MEM = ['PB602', 'PB603', 'PB902']
|
def can_handle(cls, dev, debug=False): return dev[3] == 'Elonex' and dev[4] == 'eBook'
|
if title.lower() == r.title[:len(title)].lower() and r.comments and len(r.comments): results[0].comments = r.comments break
|
try: if title and title.lower() == r.title[:len(title)].lower() \ and r.comments and len(r.comments): results[0].comments = r.comments break except: pass
|
def cleanup_title(s): if s is None: s = _('Unknown') s = s.strip().lower() s = prefix_pat.sub(' ', s) s = trailing_paren_pat.sub('', s) s = whitespace_pat.sub(' ', s) return s.strip()
|
parser = getattr(cli, cmd+'_option_parser')()
|
args = [] if cmd == 'catalog': args = [['doc.xml', '-h']] parser = getattr(cli, cmd+'_option_parser')(*args) if cmd == 'catalog': parser = parser[0]
|
def generate_calibredb_help(preamble, info): from calibre.library.cli import COMMANDS, get_parser import calibre.library.cli as cli preamble = preamble[:preamble.find('\n\n\n', preamble.find('code-block'))] preamble += textwrap.dedent(''' :command:`calibredb` is the command line interface to the |app| database. It has several sub-commands, documented below: ''') global_parser = get_parser('') groups = [] for grp in global_parser.option_groups: groups.append((grp.title.capitalize(), grp.description, grp.option_list)) global_options = '\n'.join(render_options('calibredb', groups, False, False)) lines, toc = [], [] for cmd in COMMANDS: parser = getattr(cli, cmd+'_option_parser')() toc.append(' * :ref:`calibredb-%s`'%cmd) lines += ['.. _calibredb-'+cmd+':', ''] lines += [cmd, '~'*20, ''] usage = parser.usage.strip() usage = [i for i in usage.replace('%prog', 'calibredb').splitlines()] cmdline = ' '+usage[0] usage = usage[1:] usage = [i.replace(cmd, ':command:`%s`'%cmd) for i in usage] lines += ['.. code-block:: none', '', cmdline, ''] lines += usage groups = [(None, None, parser.option_list)] lines += [''] lines += render_options('calibredb '+cmd, groups, False) lines += [''] toc = '\n'.join(toc) raw = preamble + '\n\n'+toc + '\n\n' + global_options+'\n\n'+'\n'.join(lines) update_cli_doc(os.path.join('cli', 'calibredb.rst'), raw, info)
|
self.tags_view.search_item_renamed.emit()
|
item.tag.name = val self.tags_view.search_item_renamed.emit()
|
def setData(self, index, value, role=Qt.EditRole): if not index.isValid(): return NONE # set up to position at the category label path = self.path_for_index(self.parent(index)) val = unicode(value.toString()) if not val: error_dialog(self.tags_view, _('Item is blank'), _('An item cannot be set to nothing. Delete it instead.')).exec_() return False item = index.internalPointer() key = item.parent.category_key # make certain we know about the item's category if key not in self.db.field_metadata: return if key == 'search': if val in saved_searches().names(): error_dialog(self.tags_view, _('Duplicate search name'), _('The saved search name %s is already used.')%val).exec_() return False saved_searches().rename(unicode(item.data(role).toString()), val) self.tags_view.search_item_renamed.emit() else: if key == 'series': self.db.rename_series(item.tag.id, val) elif key == 'publisher': self.db.rename_publisher(item.tag.id, val) elif key == 'tags': self.db.rename_tag(item.tag.id, val) elif key == 'authors': self.db.rename_author(item.tag.id, val) elif self.db.field_metadata[key]['is_custom']: self.db.rename_custom_item(item.tag.id, val, label=self.db.field_metadata[key]['label']) self.tags_view.tag_item_renamed.emit() item.tag.name = val self.refresh() # Should work, because no categories can have disappeared if path: idx = self.index_for_path(path) if idx.isValid(): self.tags_view.setCurrentIndex(idx) self.tags_view.scrollTo(idx, QTreeView.PositionAtCenter) return True
|
self.tags_view.search_item_renamed.connect(self.saved_search.clear_to_help)
|
self.tags_view.search_item_renamed.connect(self.saved_searches_changed)
|
def __init__(self, db): self.library_view.model().count_changed_signal.connect(self.tags_view.recount) self.tags_view.set_database(self.library_view.model().db, self.tag_match, self.sort_by) self.tags_view.tags_marked.connect(self.search.search_from_tags) self.tags_view.tags_marked.connect(self.saved_search.clear_to_help) self.tags_view.tag_list_edit.connect(self.do_tags_list_edit) self.tags_view.user_category_edit.connect(self.do_user_categories_edit) self.tags_view.saved_search_edit.connect(self.do_saved_search_edit) self.tags_view.author_sort_edit.connect(self.do_author_sort_edit) self.tags_view.tag_item_renamed.connect(self.do_tag_item_renamed) self.tags_view.search_item_renamed.connect(self.saved_search.clear_to_help) self.edit_categories.clicked.connect(lambda x: self.do_user_categories_edit())
|
href = self.link_hrefs[href] text.append('\\q="
|
href = ' text.append('\\q="%s"' % href)
|
def dump_text(self, elem, stylizer, page, tag_stack=[]): if not isinstance(elem.tag, basestring) \ or namespace(elem.tag) != XHTML_NS: return []
|
return prefix + unicode(v) + suffix
|
return prefix + v + suffix
|
def get_value(self, key, args, mi): from calibre.library.save_to_disk import explode_string_template_value try: prefix, key, suffix = explode_string_template_value(key) ign, v = mi.format_field(key, series_with_index=False) if v is None: return '' if v == '': return '' return prefix + unicode(v) + suffix except: return key
|
return (name, res, orig_res, cmeta)
|
return (name, unicode(res), orig_res, cmeta)
|
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) ''' if key in self.user_metadata_keys(): res = self.get(key, None) cmeta = self.get_user_metadata(key, make_copy=False) if cmeta['datatype'] != 'composite' and (res is None or res == ''): return (None, None, None, None) orig_res = res cmeta = self.get_user_metadata(key, make_copy=False) if res is None or res == '': return (None, None, None, None) orig_res = res name = unicode(cmeta['name']) datatype = cmeta['datatype'] if datatype == 'text' and cmeta['is_multiple']: res = u', '.join(res) elif datatype == 'series' and series_with_index: res = res + \ ' [%s]'%self.format_series_index(val=self.get_extra(key)) elif datatype == 'datetime': res = format_date(res, cmeta['display'].get('date_format','dd MMM yyyy')) elif datatype == 'bool': res = _('Yes') if res else _('No') return (name, res, orig_res, cmeta)
|
return (name, res, orig_res, fmeta)
|
return (name, unicode(res), orig_res, fmeta)
|
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) ''' if key in self.user_metadata_keys(): res = self.get(key, None) cmeta = self.get_user_metadata(key, make_copy=False) if cmeta['datatype'] != 'composite' and (res is None or res == ''): return (None, None, None, None) orig_res = res cmeta = self.get_user_metadata(key, make_copy=False) if res is None or res == '': return (None, None, None, None) orig_res = res name = unicode(cmeta['name']) datatype = cmeta['datatype'] if datatype == 'text' and cmeta['is_multiple']: res = u', '.join(res) elif datatype == 'series' and series_with_index: res = res + \ ' [%s]'%self.format_series_index(val=self.get_extra(key)) elif datatype == 'datetime': res = format_date(res, cmeta['display'].get('date_format','dd MMM yyyy')) elif datatype == 'bool': res = _('Yes') if res else _('No') return (name, res, orig_res, cmeta)
|
for x in all_input_formats(): mt = guess_type('dummy.'+x)[0] if mt: f.write('MimeType=%s;\n'%mt)
|
f.write('MimeType=%s;\n'%';'.join(mimetypes))
|
def write_mimetypes(f): for x in all_input_formats(): mt = guess_type('dummy.'+x)[0] if mt: f.write('MimeType=%s;\n'%mt)
|
Comment=Viewer for E-books
|
Comment=Viewer for E-books in all the major formats
|
def opts_and_exts(name, op, exts): opts = ' '.join(options(op)) exts.extend([i.upper() for i in exts]) exts='|'.join(exts) fname = name.replace('-', '_') return '_'+fname+'()'+\
|
Comment=E-book library management
|
Comment=E-book library management: Convert, view, share, catalogue all your e-books
|
def opts_and_exts(name, op, exts): opts = ' '.join(options(op)) exts.extend([i.upper() for i in exts]) exts='|'.join(exts) fname = name.replace('-', '_') return '_'+fname+'()'+\
|
fmt = pf if pf in fmts else fmts[0]
|
try: fmt = pf if pf in fmts else fmts[0] except: fmt = None
|
def browse_get_book_args(self, mi, id_): fmts = self.db.formats(id_, index_is_id=True) if not fmts: fmts = '' fmts = [x.lower() for x in fmts.split(',') if x] pf = prefs['output_format'].lower() fmt = pf if pf in fmts else fmts[0] args = {'id':id_, 'mi':mi, } for key in mi.all_field_keys(): val = mi.format_field(key)[1] if not val: val = '' args[key] = xml(val, True) fname = ascii_filename(args['title']) + ' - ' + ascii_filename(args['authors']) return args, fmt, fmts, fname
|
other_fmts = [x for x in fmts if x.lower() != fmt.lower()] if other_fmts: ofmts = [u'<a href="/get/{0}/{1}_{2}.{0}" title="{3}">{3}</a>'\ .format(f, fname, id_, f.upper()) for f in other_fmts] ofmts = ', '.join(ofmts) args['other_formats'] = u'<strong>%s: </strong>' % \ _('Other formats') + ofmts
|
if fmts and fmt: other_fmts = [x for x in fmts if x.lower() != fmt.lower()] if other_fmts: ofmts = [u'<a href="/get/{0}/{1}_{2}.{0}" title="{3}">{3}</a>'\ .format(f, fname, id_, f.upper()) for f in other_fmts] ofmts = ', '.join(ofmts) args['other_formats'] = u'<strong>%s: </strong>' % \ _('Other formats') + ofmts
|
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, fmts, fname = self.browse_get_book_args(mi, id_) args['other_formats'] = '' other_fmts = [x for x in fmts if x.lower() != fmt.lower()] if other_fmts: ofmts = [u'<a href="/get/{0}/{1}_{2}.{0}" title="{3}">{3}</a>'\ .format(f, fname, id_, f.upper()) for f in other_fmts] ofmts = ', '.join(ofmts) args['other_formats'] = u'<strong>%s: </strong>' % \ _('Other formats') + ofmts
|
args['read_tooltip'] = \ _('Read %s in the %s format')%(args['title'], fmt.upper()) args['href'] = '/get/%s/%s_%d.%s'%( fmt, fname, id_, fmt)
|
if fmt: href = '/get/%s/%s_%d.%s'%( fmt, fname, id_, fmt) rt = xml(_('Read %s in the %s format')%(args['title'], fmt.upper()), True) args['get_button'] = \ '<a href="%s" class="read" title="%s">%s</a>' % \ (xml(href, True), rt, xml(_('Get'))) else: args['get_button'] = ''
|
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, fmts, fname = self.browse_get_book_args(mi, id_) args['other_formats'] = '' other_fmts = [x for x in fmts if x.lower() != fmt.lower()] if other_fmts: ofmts = [u'<a href="/get/{0}/{1}_{2}.{0}" title="{3}">{3}</a>'\ .format(f, fname, id_, f.upper()) for f in other_fmts] ofmts = ', '.join(ofmts) args['other_formats'] = u'<strong>%s: </strong>' % \ _('Other formats') + ofmts
|
args['read_string'] = xml(_('Read'), True)
|
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, fmts, fname = self.browse_get_book_args(mi, id_) args['other_formats'] = '' other_fmts = [x for x in fmts if x.lower() != fmt.lower()] if other_fmts: ofmts = [u'<a href="/get/{0}/{1}_{2}.{0}" title="{3}">{3}</a>'\ .format(f, fname, id_, f.upper()) for f in other_fmts] ofmts = ', '.join(ofmts) args['other_formats'] = u'<strong>%s: </strong>' % \ _('Other formats') + ofmts
|
|
print soup.prettify()
|
def generateNCXByDateAdded(self, tocTitle):
|
|
if is_connected and self.sorted_on[0] == 'ondevice': self.resort()
|
def set_device_connected(self, is_connected): self.device_connected = is_connected self.db.refresh_ondevice() self.refresh() self.research() if is_connected and self.sorted_on[0] == 'ondevice': self.resort()
|
|
def sort(self, col, order, reset=True):
|
def sort(self, col, order, reset=True, update_history=True):
|
def sort(self, col, order, reset=True): if not self.db: return self.about_to_be_sorted.emit(self.db.id) ascending = order == Qt.AscendingOrder label = self.column_map[col] self.db.sort(label, ascending) if reset: self.clear_caches() self.reset() self.sorted_on = (label, order) self.sort_history.insert(0, self.sorted_on) self.sorting_done.emit(self.db.index)
|
self.sort_history.insert(0, self.sorted_on)
|
if update_history: self.sort_history.insert(0, self.sorted_on)
|
def sort(self, col, order, reset=True): if not self.db: return self.about_to_be_sorted.emit(self.db.id) ascending = order == Qt.AscendingOrder label = self.column_map[col] self.db.sort(label, ascending) if reset: self.clear_caches() self.reset() self.sorted_on = (label, order) self.sort_history.insert(0, self.sorted_on) self.sorting_done.emit(self.db.index)
|
try: col = self.column_map.index(self.sorted_on[0]) except: col = 0
|
def refresh(self, reset=True): try: col = self.column_map.index(self.sorted_on[0]) except: col = 0 self.db.refresh(field=None) self.sort(col, self.sorted_on[1], reset=reset)
|
|
self.sort(col, self.sorted_on[1], reset=reset) def resort(self, reset=True): try: col = self.column_map.index(self.sorted_on[0]) except ValueError: col = 0 self.sort(col, self.sorted_on[1], reset=reset)
|
self.resort(reset=reset) def resort(self, reset=True, history=5): for col,ord in reversed(self.sort_history[:history]): try: col = self.column_map.index(col) except ValueError: col = 0 self.sort(col, ord, reset=False, update_history=False) if reset: self.reset()
|
def refresh(self, reset=True): try: col = self.column_map.index(self.sorted_on[0]) except: col = 0 self.db.refresh(field=None) self.sort(col, self.sorted_on[1], reset=reset)
|
print "Image name Normalized: " + imagename
|
def update_booklist(mountpath, filename, title, authors, mime, date, ContentType, ImageID): changed = False # if path_to_ext(filename) in self.FORMATS: try: # lpath = os.path.join(path, filename).partition(self.normalize_path(prefix))[2] # if lpath.startswith(os.sep): # lpath = lpath[len(os.sep):] # lpath = lpath.replace('\\', '/') # print "Filename: " + filename filename = self.normalize_path(filename) # print "Normalized FileName: " + filename
|
|
class SMTP_SSL(smtplib.SMTP_SSL): def _get_socket(self, host, port, timeout): smtplib.SMTP_SSL._get_socket(self, host, port, timeout) return self.sock cls = smtplib.SMTP if encryption == 'TLS' else SMTP_SSL
|
cls = smtplib.SMTP if encryption == 'TLS' else smtplib.SMTP_SSL
|
def sendmail(msg, from_, to, localhost=None, verbose=0, timeout=30, relay=None, username=None, password=None, encryption='TLS', port=-1): if relay is None: for x in to: return sendmail_direct(from_, x, msg, timeout, localhost, verbose) import smtplib class SMTP_SSL(smtplib.SMTP_SSL): # Workaround for bug in smtplib.py def _get_socket(self, host, port, timeout): smtplib.SMTP_SSL._get_socket(self, host, port, timeout) return self.sock cls = smtplib.SMTP if encryption == 'TLS' else SMTP_SSL timeout = None # Non-blocking sockets sometimes don't work port = int(port) s = cls(timeout=timeout, local_hostname=localhost) s.set_debuglevel(verbose) if port < 0: port = 25 if encryption == 'TLS' else 465 s.connect(relay, port) if encryption == 'TLS': s.starttls() s.ehlo() if username is not None and password is not None: if encryption == 'SSL': s.sock = s.file.sslobj s.login(username, password) s.sendmail(from_, to, msg) return s.quit()
|
bt = unicode(self.buttonText(self.FinishButton)).replace('&', '') t = unicode(self.finish_page.finish_text.text()) self.finish_page.finish_text.setText(t%bt)
|
self.set_finish_text()
|
def __init__(self, parent): QWizard.__init__(self, parent) self.setWindowTitle(__appname__+' '+_('welcome wizard')) p = QPixmap() p.loadFromData(open(P('content_server/calibre.png'), 'rb').read()) self.setPixmap(self.LogoPixmap, p.scaledToHeight(80, Qt.SmoothTransformation)) self.setPixmap(self.WatermarkPixmap, QPixmap(I('welcome_wizard.svg'))) self.setPixmap(self.BackgroundPixmap, QPixmap(I('wizard.svg'))) self.device_page = DevicePage() self.library_page = LibraryPage() self.connect(self.library_page, SIGNAL('retranslate()'), self.retranslate) self.finish_page = FinishPage() bt = unicode(self.buttonText(self.FinishButton)).replace('&', '') t = unicode(self.finish_page.finish_text.text()) self.finish_page.finish_text.setText(t%bt) self.kindle_page = KindlePage() self.stanza_page = StanzaPage() self.word_player_page = WordPlayerPage() self.setPage(self.library_page.ID, self.library_page) self.setPage(self.device_page.ID, self.device_page) self.setPage(self.finish_page.ID, self.finish_page) self.setPage(self.kindle_page.ID, self.kindle_page) self.setPage(self.stanza_page.ID, self.stanza_page) self.setPage(self.word_player_page.ID, self.word_player_page)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.