rem stringlengths 0 322k | add stringlengths 0 2.05M | context stringlengths 8 228k |
|---|---|---|
query= 'update content set ReadStatus=0, FirstTimeReading = \'true\' where BookID is Null and ContentID not like \'file:///mnt/sd/%\'' | query= 'update content set ReadStatus=0, FirstTimeReading = \'true\' where BookID is Null and ReadStatus = 1 and ContentID not like \'file:///mnt/sd/%\'' | def update_device_database_collections(self, booklists, collections_attributes, oncard): |
def abspath(self, index, index_is_id=False): | def abspath(self, index, index_is_id=False, create_dirs=True): | def abspath(self, index, index_is_id=False): 'Return the absolute path to the directory containing this books files as a unicode string.' path = os.path.join(self.library_path, self.path(index, index_is_id=index_is_id)) if not os.path.exists(path): os.makedirs(path) return path |
if not os.path.exists(path): | if create_dirs and not os.path.exists(path): | def abspath(self, index, index_is_id=False): 'Return the absolute path to the directory containing this books files as a unicode string.' path = os.path.join(self.library_path, self.path(index, index_is_id=index_is_id)) if not os.path.exists(path): os.makedirs(path) return path |
path = os.path.join(self.abspath(id, index_is_id=True), 'cover.jpg') | path = os.path.join(self.abspath(id, index_is_id=True, create_dirs=False), 'cover.jpg') | def has_cover(self, index, index_is_id=False): id = index if index_is_id else self.id(index) try: path = os.path.join(self.abspath(id, index_is_id=True), 'cover.jpg') except: # Can happen if path has not yet been set return False return os.access(path, os.R_OK) |
h = [ float(count)/totalLines for count in hRaw ] | if totalLines > 0: h = [ float(count)/totalLines for count in hRaw ] else: h = [] | def line_histogram(self, percent): ''' Creates a broad histogram of the document to determine whether it incorporates hard line breaks. Lines are sorted into 20 'buckets' based on length. percent is the percentage of lines that should be in a single bucket to return true The majority of the lines will exist in 1-2 buc... |
for root, dirs, files in os.walk(self.rootdir): | base = self.rootdir if isinstance(base, unicode): base = base.encode(filesystem_encoding) for root, dirs, files in os.walk(base): | def namelist(self): names = [] for root, dirs, files in os.walk(self.rootdir): for fname in files: fname = os.path.join(root, fname) fname = fname.replace('\\', '/') names.append(fname) return names |
self.normal_aus_tooltip = unicode(self.author_sort.toolTip()) | base = unicode(self.author_sort.toolTip()) self.ok_aus_tooltip = '<p>' + textwrap.fill(base+'<br><br>'+ _(' The green color indicates that the current ' 'author sort matches the current author')) self.bad_aus_tooltip = '<p>'+textwrap.fill(base + '<br><br>'+ _(' The red color indicates that the current ' 'author sort do... | def __init__(self, window, row, db, accepted_callback=None, cancel_all=False): ResizableDialog.__init__(self, window) self.bc_box.layout().setAlignment(self.cover, Qt.AlignCenter|Qt.AlignHCenter) self.cancel_all = False self.normal_aus_tooltip = unicode(self.author_sort.toolTip()) if cancel_all: self.__abort_button = s... |
self.author_sort.setToolTip(textwrap.fill('<p>'+self.normal_aus_tooltip+'<br><br>'+ _(' The green color indicates that the current ' 'author sort matches the current author'))) | def __init__(self, window, row, db, accepted_callback=None, cancel_all=False): ResizableDialog.__init__(self, window) self.bc_box.layout().setAlignment(self.cover, Qt.AlignCenter|Qt.AlignHCenter) self.cancel_all = False self.normal_aus_tooltip = unicode(self.author_sort.toolTip()) if cancel_all: self.__abort_button = s... | |
tt = self.normal_aus_tooltip if not normal: tt = '<p>'+textwrap.fill(tt + '<br><br>'+ _(' The red color indicates that the current ' 'author sort does not match the current author')) | tt = self.ok_aus_tooltip if normal else self.bad_aus_tooltip | def mark_author_sort(self, normal=True): if normal: col = 'rgb(0, 255, 0, 20%)' else: col = 'rgb(255, 0, 0, 20%)' self.author_sort.setStyleSheet('QLineEdit { color: black; ' 'background-color: %s; }'%col) tt = self.normal_aus_tooltip if not normal: tt = '<p>'+textwrap.fill(tt + '<br><br>'+ _(' The red color indicates t... |
self.cache.pop(id_, None) self.load_queue.put(id_) | cover = self.cache.pop(id_, None) if cover is not None: self.load_queue.put(id_) | def refresh(self, ids): with self.lock: for id_ in ids: self.cache.pop(id_, None) self.load_queue.put(id_) |
item_not_zero_func = (lambda x: x[2] > 0) | def get_categories(self, sort='name', ids=None, icon_map=None): self.books_list_filter.change([] if not ids else ids) | |
avg=r[3], sort=r[4], | avg=avgr(r), sort=r[4], | def get_categories(self, sort='name', ids=None, icon_map=None): self.books_list_filter.change([] if not ids else ids) |
while emleft > 0: | while emleft > 1: | 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... |
l = int(leading) t = int(trailing) | l = max(0, int(leading)) t = max(0, int(trailing)) | def _shorten(self, val, leading, center_string, trailing): l = int(leading) t = int(trailing) if len(val) > l + len(center_string) + t: return val[0:l] + center_string + val[-t:] else: return val |
return val[0:l] + center_string + val[-t:] | return val[0:l] + center_string + ('' if t == 0 else val[-t:]) | def _shorten(self, val, leading, center_string, trailing): l = int(leading) t = int(trailing) if len(val) > l + len(center_string) + t: return val[0:l] + center_string + val[-t:] else: return val |
def _xmlescape(data): | def _xmlescape(data,entities={}): | def _xmlescape(data): data = data.replace('&', '&') data = data.replace('>', '>') data = data.replace('<', '<') return data |
import calibre.ebooks.chardet as chardet | import calibre.ebooks.chardet as chardet if _debug: import chardet.constants chardet.constants._debug = 1 | def _xmlescape(data): data = data.replace('&', '&') data = data.replace('>', '>') data = data.replace('<', '<') return data |
sgmllib.charref = re.compile('& | sgmllib.charref = re.compile('& if sgmllib.endbracket.search(' <').start(0): class EndBracketMatch: endbracket = re.compile('''([^'"<>]|"[^"]*"(?=>|/|\s|\w+=)|'[^']*'(?=>|/|\s|\w+=))*(?=[<>])|.*?(?=[<>])''') def search(self,string,index=0): self.match = self.endbracket.match(string,index) if self.match: return self de... | def _xmlescape(data): data = data.replace('&', '&') data = data.replace('>', '>') data = data.replace('<', '<') return data |
return urlparse.urljoin(base, uri) | try: return urlparse.urljoin(base, uri) except: uri = urlparse.urlunparse([urllib.quote(part) for part in urlparse.urlparse(uri)]) return urlparse.urljoin(base, uri) | def _urljoin(base, uri): uri = _urifixer.sub(r'\1\3', uri) return urlparse.urljoin(base, uri) |
'http://www.w3.org/XML/1998/namespace': 'xml', 'http://schemas.pocketsoap.com/rss/myDescModule/': 'szf' | 'http://www.w3.org/1999/xlink': 'xlink', 'http://www.w3.org/XML/1998/namespace': 'xml' | def _urljoin(base, uri): uri = _urifixer.sub(r'\1\3', uri) return urlparse.urljoin(base, uri) |
can_be_relative_uri = ['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'license', 'icon', 'logo'] | can_be_relative_uri = ['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'icon', 'logo'] | def _urljoin(base, uri): uri = _urifixer.sub(r'\1\3', uri) return urlparse.urljoin(base, uri) |
self.feeddata['language'] = baselang | self.feeddata['language'] = baselang.replace('_','-') | def __init__(self, baseuri=None, baselang=None, encoding='utf-8'): if _debug: sys.stderr.write('initializing FeedParser\n') if not self._matchnamespaces: for k, v in self.namespaces.items(): self._matchnamespaces[k.lower()] = v self.feeddata = FeedParserDict() # feed-level data self.encoding = encoding # character enco... |
self.feeddata['language'] = lang | self.feeddata['language'] = lang.replace('_','-') | def unknown_starttag(self, tag, attrs): if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs)) # normalize attrs attrs = [(k.lower(), v) for k, v in attrs] attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] # track xml:base and xml:lang attrsD = dict(attrs) baseuri = attrsD.get('xml:bas... |
tag = tag.split(':')[-1] return self.handle_data('<%s%s>' % (tag, ''.join([' %s="%s"' % t for t in attrs])), escape=0) | if tag.find(':') <> -1: prefix, tag = tag.split(':', 1) namespace = self.namespacesInUse.get(prefix, '') if tag=='math' and namespace=='http://www.w3.org/1998/Math/MathML': attrs.append(('xmlns',namespace)) if tag=='svg' and namespace=='http://www.w3.org/2000/svg': attrs.append(('xmlns',namespace)) if tag == 'svg': sel... | def unknown_starttag(self, tag, attrs): if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs)) # normalize attrs attrs = [(k.lower(), v) for k, v in attrs] attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] # track xml:base and xml:lang attrsD = dict(attrs) baseuri = attrsD.get('xml:bas... |
return self.push(prefix + suffix, 1) | unknown_tag = prefix + suffix if len(attrsD) == 0: return self.push(unknown_tag, 1) else: context = self._getContext() context[unknown_tag] = attrsD | def unknown_starttag(self, tag, attrs): if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs)) # normalize attrs attrs = [(k.lower(), v) for k, v in attrs] attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] # track xml:base and xml:lang attrsD = dict(attrs) baseuri = attrsD.get('xml:bas... |
def name2cp(k): import htmlentitydefs if hasattr(htmlentitydefs, 'name2codepoint'): return htmlentitydefs.name2codepoint[k] k = htmlentitydefs.entitydefs[k] if k.startswith('& return int(k[2:-1]) return ord(k) try: name2cp(ref) | try: name2codepoint[ref] | def handle_entityref(self, ref): # called for each entity reference, e.g. for '©', ref will be 'copy' if not self.elementstack: return if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref) if ref in ('lt', 'gt', 'quot', 'amp', 'apos'): text = '&%s;' % ref else: # entity resolution graciously don... |
else: text = unichr(name2cp(ref)).encode('utf-8') | else: text = unichr(name2codepoint[ref]).encode('utf-8') | def name2cp(k): import htmlentitydefs if hasattr(htmlentitydefs, 'name2codepoint'): # requires Python 2.3 return htmlentitydefs.name2codepoint[k] k = htmlentitydefs.entitydefs[k] if k.startswith('&#') and k.endswith(';'): return int(k[2:-1]) # not in latin-1 return ord(k) |
if k == -1: k = len(self.rawdata) | if k == -1: k = len(self.rawdata) return k | def parse_declaration(self, i): # override internal declaration handler to handle CDATA blocks if _debug: sys.stderr.write('entering parse_declaration\n') if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0) return ... |
return k+1 | if k >= 0: return k+1 else: return k | def parse_declaration(self, i): # override internal declaration handler to handle CDATA blocks if _debug: sys.stderr.write('entering parse_declaration\n') if self.rawdata[i:i+9] == '<![CDATA[': k = self.rawdata.find(']]>', i) if k == -1: k = len(self.rawdata) self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0) return ... |
if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types: | if is_htmlish and RESOLVE_RELATIVE_URIS: | def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop() output = ''.join(pieces) if stripWhitespace: output = output.strip() if not expectingText: return output |
output = _resolveRelativeURIs(output, self.baseuri, self.encoding) | output = _resolveRelativeURIs(output, self.baseuri, self.encoding, self.contentparams.get('type', 'text/html')) if is_htmlish and element in ['content', 'description', 'summary']: mfresults = _parseMicroformats(output, self.baseuri, self.encoding) if mfresults: for tag in mfresults.get('tags', []): self._addTag(tag... | def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop() output = ''.join(pieces) if stripWhitespace: output = output.strip() if not expectingText: return output |
if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types: | if is_htmlish and SANITIZE_HTML: | def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop() output = ''.join(pieces) if stripWhitespace: output = output.strip() if not expectingText: return output |
output = _sanitizeHTML(output, self.encoding) | output = _sanitizeHTML(output, self.encoding, self.contentparams.get('type', 'text/html')) | def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop() output = ''.join(pieces) if stripWhitespace: output = output.strip() if not expectingText: return output |
if element == 'title' and self.hasTitle: return output | def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop() output = ''.join(pieces) if stripWhitespace: output = output.strip() if not expectingText: return output | |
elif (self.infeed or self.insource) and (not self.intextinput) and (not self.inimage): | elif (self.infeed or self.insource): | def pop(self, element, stripWhitespace=1): if not self.elementstack: return if self.elementstack[-1][0] != element: return element, expectingText, pieces = self.elementstack.pop() output = ''.join(pieces) if stripWhitespace: output = output.strip() if not expectingText: return output |
def lookslikehtml(self, str): if self.version.startswith('atom'): return if self.contentparams.get('type','text/html') != 'text/plain': return if not (re.search(r'</(\w+)>',str) or re.search("& if filter(lambda t: t.lower() not in _HTMLSanitizer.acceptable_elements, re.findall(r'</?(\w+)',str)): return from htmle... | def popContent(self, tag): value = self.pop(tag) self.incontent -= 1 self.contentparams.clear() return value | |
if not self.version: | if not self.version or not self.version.startswith('rss'): | def _start_rss(self, attrsD): versionmap = {'0.91': 'rss091u', '0.92': 'rss092', '0.93': 'rss093', '0.94': 'rss094'} if not self.version: attr_version = attrsD.get('version', '') version = versionmap.get(attr_version) if version: self.version = version elif attr_version.startswith('2.'): self.version = 'rss20' else: se... |
self.inimage = 1 self.push('image', 0) | def _start_image(self, attrsD): self.inimage = 1 self.push('image', 0) context = self._getContext() context.setdefault('image', FeedParserDict()) | |
self.inimage = 1 self.hasTitle = 0 self.push('image', 0) | def _start_image(self, attrsD): self.inimage = 1 self.push('image', 0) context = self._getContext() context.setdefault('image', FeedParserDict()) | |
self.intextinput = 1 self.push('textinput', 0) | def _start_textinput(self, attrsD): self.intextinput = 1 self.push('textinput', 0) context = self._getContext() context.setdefault('textinput', FeedParserDict()) | |
context['textinput']['name'] = value | context['name'] = value | def _end_name(self): value = self.pop('name') if self.inpublisher: self._save_author('name', value, 'publisher') elif self.inauthor: self._save_author('name', value) elif self.incontributor: self._save_contributor('name', value) elif self.intextinput: context = self._getContext() context['textinput']['name'] = value |
context['image']['width'] = value | context['width'] = value | def _end_width(self): value = self.pop('width') try: value = int(value) except: value = 0 if self.inimage: context = self._getContext() context['image']['width'] = value |
context['image']['height'] = value | context['height'] = value | def _end_height(self): value = self.pop('height') try: value = int(value) except: value = 0 if self.inimage: context = self._getContext() context['image']['height'] = value |
elif self.inimage: context = self._getContext() context['image']['href'] = value elif self.intextinput: context = self._getContext() context['textinput']['link'] = value | def _end_url(self): value = self.pop('href') if self.inauthor: self._save_author('href', value) elif self.incontributor: self._save_contributor('href', value) elif self.inimage: context = self._getContext() context['image']['href'] = value elif self.intextinput: context = self._getContext() context['textinput']['link']... | |
author = context.get(key) | author, email = context.get(key), None | def _sync_author_detail(self, key='author'): context = self._getContext() detail = context.get('%s_detail' % key) if detail: name = detail.get('name') email = detail.get('email') if name and email: context[key] = '%s (%s)' % (name, email) elif name: context[key] = name elif email: context[key] = email else: author = co... |
emailmatch = re.search(r'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))''', author) if not emailmatch: return email = emailmatch.group(0) author = author.replace(email, '') author = author.replace('()', '') author = author.strip() if author an... | emailmatch = re.search(r'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))(\?subject=\S+)?''', author) if emailmatch: email = emailmatch.group(0) author = author.replace(email, '') author = author.replace('()', '') author = author.replace('<>', '... | def _sync_author_detail(self, key='author'): context = self._getContext() detail = context.get('%s_detail' % key) if detail: name = detail.get('name') email = detail.get('email') if name and email: context[key] = '%s (%s)' % (name, email) elif name: context[key] = name elif email: context[key] = email else: author = co... |
self.push('license', 1) | context = self._getContext() | def _start_cc_license(self, attrsD): self.push('license', 1) value = self._getAttribute(attrsD, 'rdf:resource') if value: self.elementstack[-1][2].append(value) self.pop('license') |
if value: self.elementstack[-1][2].append(value) self.pop('license') | attrsD = FeedParserDict() attrsD['rel']='license' if value: attrsD['href']=value context.setdefault('links', []).append(attrsD) | def _start_cc_license(self, attrsD): self.push('license', 1) value = self._getAttribute(attrsD, 'rdf:resource') if value: self.elementstack[-1][2].append(value) self.pop('license') |
self.pop('license') | value = self.pop('license') context = self._getContext() attrsD = FeedParserDict() attrsD['rel']='license' if value: attrsD['href']=value context.setdefault('links', []).append(attrsD) del context['license'] _end_creativeCommons_license = _end_creativecommons_license def _addXFN(self, relationships, href, name): conte... | def _end_creativecommons_license(self): self.pop('license') |
tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'label': label})) | tags.append(value) | def _addTag(self, term, scheme, label): context = self._getContext() tags = context.setdefault('tags', []) if (not term) and (not scheme) and (not label): return value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label}) if value not in tags: tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'la... |
attrsD.setdefault('type', 'text/html') | if attrsD['rel'] == 'self': attrsD.setdefault('type', 'application/atom+xml') else: attrsD.setdefault('type', 'text/html') context = self._getContext() | def _start_link(self, attrsD): attrsD.setdefault('rel', 'alternate') attrsD.setdefault('type', 'text/html') attrsD = self._itsAnHrefDamnIt(attrsD) if attrsD.has_key('href'): attrsD['href'] = self.resolveURI(attrsD['href']) expectingText = self.infeed or self.inentry or self.insource context = self._getContext() context... |
context = self._getContext() | def _start_link(self, attrsD): attrsD.setdefault('rel', 'alternate') attrsD.setdefault('type', 'text/html') attrsD = self._itsAnHrefDamnIt(attrsD) if attrsD.has_key('href'): attrsD['href'] = self.resolveURI(attrsD['href']) expectingText = self.infeed or self.inentry or self.insource context = self._getContext() context... | |
if attrsD['rel'] == 'enclosure': self._start_enclosure(attrsD) | def _start_link(self, attrsD): attrsD.setdefault('rel', 'alternate') attrsD.setdefault('type', 'text/html') attrsD = self._itsAnHrefDamnIt(attrsD) if attrsD.has_key('href'): attrsD['href'] = self.resolveURI(attrsD['href']) expectingText = self.infeed or self.inentry or self.insource context = self._getContext() context... | |
if self.intextinput: context['textinput']['link'] = value if self.inimage: context['image']['link'] = value | def _end_link(self): value = self.pop('link') context = self._getContext() if self.intextinput: context['textinput']['link'] = value if self.inimage: context['image']['link'] = value | |
if self.intextinput: context['textinput']['title'] = value elif self.inimage: context['image']['title'] = value | self.hasTitle = 1 | def _end_title(self): value = self.popContent('title') context = self._getContext() if self.intextinput: context['textinput']['title'] = value elif self.inimage: context['image']['title'] = value |
_end_media_title = _end_title | def _end_media_title(self): hasTitle = self.hasTitle self._end_title() self.hasTitle = hasTitle | def _end_title(self): value = self.popContent('title') context = self._getContext() if self.intextinput: context['textinput']['title'] = value elif self.inimage: context['image']['title'] = value |
context = self._getContext() if self.intextinput: context['textinput']['description'] = value elif self.inimage: context['image']['description'] = value | def _end_description(self): if self._summaryKey == 'content': self._end_content() else: value = self.popContent('description') context = self._getContext() if self.intextinput: context['textinput']['description'] = value elif self.inimage: context['image']['description'] = value self._summaryKey = None | |
self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD)) | context = self._getContext() attrsD['rel']='enclosure' context.setdefault('links', []).append(FeedParserDict(attrsD)) | def _start_enclosure(self, attrsD): attrsD = self._itsAnHrefDamnIt(attrsD) self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD)) href = attrsD.get('href') if href: context = self._getContext() if not context.get('id'): context['id'] = href |
if href: context = self._getContext() if not context.get('id'): context['id'] = href | if href and not context.get('id'): context['id'] = href | def _start_enclosure(self, attrsD): attrsD = self._itsAnHrefDamnIt(attrsD) self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD)) href = attrsD.get('href') if href: context = self._getContext() if not context.get('id'): context['id'] = href |
self.decls = {} | def __init__(self, baseuri, baselang, encoding): if _debug: sys.stderr.write('trying StrictFeedParser\n') xml.sax.handler.ContentHandler.__init__(self) _FeedParserMixin.__init__(self, baseuri, baselang, encoding) self.bozo = 0 self.exc = None | |
if uri == 'http://www.w3.org/1999/xlink': self.decls['xmlns:'+prefix] = uri | def startPrefixMapping(self, prefix, uri): self.trackNamespace(prefix, uri) | |
if prefix: localname = prefix + ':' + localname | def startElementNS(self, name, qname, attrs): namespace, localname = name lowernamespace = str(namespace or '').lower() if lowernamespace.find('backend.userland.com/rss') <> -1: # match any backend.userland.com namespace namespace = 'http://backend.userland.com/rss' lowernamespace = namespace if qname and qname.find(':... | |
if _debug: sys.stderr.write('startElementNS: qname = %s, namespace = %s, givenprefix = %s, prefix = %s, attrs = %s, localname = %s\n' % (qname, namespace, givenprefix, prefix, attrs.items(), localname)) | def startElementNS(self, name, qname, attrs): namespace, localname = name lowernamespace = str(namespace or '').lower() if lowernamespace.find('backend.userland.com/rss') <> -1: # match any backend.userland.com namespace namespace = 'http://backend.userland.com/rss' lowernamespace = namespace if qname and qname.find(':... | |
attrsD = {} | attrsD, self.decls = self.decls, {} if localname=='math' and namespace=='http://www.w3.org/1998/Math/MathML': attrsD['xmlns']=namespace if localname=='svg' and namespace=='http://www.w3.org/2000/svg': attrsD['xmlns']=namespace if prefix: localname = prefix.lower() + ':' + localname elif namespace and not qname: for na... | def startElementNS(self, name, qname, attrs): namespace, localname = name lowernamespace = str(namespace or '').lower() if lowernamespace.find('backend.userland.com/rss') <> -1: # match any backend.userland.com namespace namespace = 'http://backend.userland.com/rss' lowernamespace = namespace if qname and qname.find(':... |
elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param'] def __init__(self, encoding): | special = re.compile('''[<>'"]''') bare_ampersand = re.compile("&(?! elements_no_end_tag = [ 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr' ] def __init__(self, encoding, type): | def fatalError(self, exc): self.error(exc) raise exc |
def parse_starttag(self,i): j=sgmllib.SGMLParser.parse_starttag(self, i) if self.type == 'application/xhtml+xml': if j>2 and self.rawdata[j-2:j]=='/>': self.unknown_endtag(self.lasttag) return j | def _shorttag_replace(self, match): tag = match.group(1) if tag in self.elements_no_end_tag: return '<' + tag + ' />' else: return '<' + tag + '></' + tag + '>' | |
data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data) | data = re.sub(r'<([^<>\s]+?)\s*/>', self._shorttag_replace, data) | def feed(self, data): data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'<!\1', data) #data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data) data = data.replace(''', "'") data... |
attrs = [(k.lower(), v) for k, v in attrs] | attrs = dict([(k.lower(), v) for k, v in attrs]).items() | def normalize_attrs(self, attrs): # utility method to be called by descendants attrs = [(k.lower(), v) for k, v in attrs] attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs] return attrs |
for key, value in attrs: if type(value) != type(u''): value = unicode(value, self.encoding, 'replace') uattrs.append((unicode(key, self.encoding), value)) strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs]).encode(self.encoding) | strattrs='' if attrs: for key, value in attrs: value=value.replace('>','>').replace('<','<').replace('"','"') value = self.bare_ampersand.sub("&", value) if type(value) != type(u''): try: value = unicode(value, self.encoding) except: value = unicode(value, 'iso-8859-1') uattrs.append((unicode(key, self.... | def unknown_starttag(self, tag, attrs): # called for each start tag # attrs is a list of (attr, value) tuples # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')] if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag) uattrs = [] # thanks to Kevin Marks for this breathtak... |
self.pieces.append('& | if ref.startswith('x'): value = unichr(int(ref[1:],16)) else: value = unichr(int(ref)) if value in _cp1252.keys(): self.pieces.append('& else: self.pieces.append('& | def handle_charref(self, ref): # called for each character reference, e.g. for ' ', ref will be '160' # Reconstruct the original character reference. self.pieces.append('&#%(ref)s;' % locals()) |
self.pieces.append('&%(ref)s;' % locals()) | if name2codepoint.has_key(ref): self.pieces.append('&%(ref)s;' % locals()) else: self.pieces.append('&%(ref)s' % locals()) | def handle_entityref(self, ref): # called for each entity reference, e.g. for '©', ref will be 'copy' # Reconstruct the original entity reference. self.pieces.append('&%(ref)s;' % locals()) |
if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text) | if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_data, text=%s\n' % text) | def handle_data(self, text): # called for each block of plain text, i.e. outside of any tag and # not containing any character or entity references # Store the original text verbatim. if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text) self.pieces.append(text) |
def __init__(self, baseuri, baselang, encoding): | def __init__(self, baseuri, baselang, encoding, entities): | def __init__(self, baseuri, baselang, encoding): sgmllib.SGMLParser.__init__(self) _FeedParserMixin.__init__(self, baseuri, baselang, encoding) |
def strattrs(self, attrs): return ''.join([' %s="%s"' % (n,v.replace('"','"')) for n,v in attrs]) class _MicroformatsParser: STRING = 1 DATE = 2 URI = 3 NODE = 4 EMAIL = 5 known_xfn_relationships = ['contact', 'acquaintance', 'friend', 'met', 'co-worker', 'coworker', 'colleague', 'co-resident', 'coresident', 'ne... | def decodeEntities(self, element, data): data = data.replace('<', '<') data = data.replace('<', '<') data = data.replace('>', '>') data = data.replace('>', '>') data = data.replace('&', '&') data = data.replace('&', '&') data = data.replace('"', '"') data = data.r... | |
def __init__(self, baseuri, encoding): _BaseHTMLProcessor.__init__(self, encoding) | def __init__(self, baseuri, encoding, type): _BaseHTMLProcessor.__init__(self, encoding, type) | def __init__(self, baseuri, encoding): _BaseHTMLProcessor.__init__(self, encoding) self.baseuri = baseuri |
return _urljoin(self.baseuri, uri) | return _urljoin(self.baseuri, uri.strip()) | def resolveURI(self, uri): return _urljoin(self.baseuri, uri) |
def _resolveRelativeURIs(htmlSource, baseURI, encoding): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding) | def _resolveRelativeURIs(htmlSource, baseURI, encoding, type): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding, type) | def unknown_starttag(self, tag, attrs): attrs = self.normalize_attrs(attrs) attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs] _BaseHTMLProcessor.unknown_starttag(self, tag, attrs) |
acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big', 'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset', 'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input', 'ins', 'kbd',... | acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'big', 'blockquote', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'command', 'datagrid', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'em', 'event-so... | def _resolveRelativeURIs(htmlSource, baseURI, encoding): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding) p.feed(htmlSource) return p.output() |
'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing', 'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols', 'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled', 'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace', 'id', 'ismap', 'label... | 'action', 'align', 'alt', 'autocomplete', 'autofocus', 'axis', 'background', 'balance', 'bgcolor', 'bgproperties', 'border', 'bordercolor', 'bordercolordark', 'bordercolorlight', 'bottompadding', 'cellpadding', 'cellspacing', 'ch', 'challenge', 'char', 'charoff', 'choff', 'charset', 'checked', 'cite', 'class', 'clear',... | def _resolveRelativeURIs(htmlSource, baseURI, encoding): if _debug: sys.stderr.write('entering _resolveRelativeURIs\n') p = _RelativeURIResolver(baseURI, encoding) p.feed(htmlSource) return p.output() |
self.mathmlOK = 0 self.svgOK = 0 | def reset(self): _BaseHTMLProcessor.reset(self) self.unacceptablestack = 0 | |
if not tag in self.acceptable_elements: | acceptable_attributes = self.acceptable_attributes keymap = {} if not tag in self.acceptable_elements or self.svgOK: | def unknown_starttag(self, tag, attrs): if not tag in self.acceptable_elements: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack += 1 return attrs = self.normalize_attrs(attrs) attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes] _BaseHTMLProcessor.unknown_startta... |
return attrs = self.normalize_attrs(attrs) attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes] _BaseHTMLProcessor.unknown_starttag(self, tag, attrs) | if self.type.endswith('html'): if not dict(attrs).get('xmlns'): if tag=='svg': attrs.append( ('xmlns','http://www.w3.org/2000/svg') ) if tag=='math': attrs.append( ('xmlns','http://www.w3.org/1998/Math/MathML') ) if tag=='math' and ('xmlns','http://www.w3.org/1998/Math/MathML') in attrs: self.mathmlOK += 1 if tag=='s... | def unknown_starttag(self, tag, attrs): if not tag in self.acceptable_elements: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack += 1 return attrs = self.normalize_attrs(attrs) attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes] _BaseHTMLProcessor.unknown_startta... |
return | if self.mathmlOK and tag in self.mathml_elements: if tag == 'math' and self.mathmlOK: self.mathmlOK -= 1 elif self.svgOK and tag in self.svg_elements: tag = self.svg_elem_map.get(tag,tag) if tag == 'svg' and self.svgOK: self.svgOK -= 1 else: return | def unknown_endtag(self, tag): if not tag in self.acceptable_elements: if tag in self.unacceptable_elements_with_end_tag: self.unacceptablestack -= 1 return _BaseHTMLProcessor.unknown_endtag(self, tag) |
def _sanitizeHTML(htmlSource, encoding): p = _HTMLSanitizer(encoding) | def sanitize_style(self, style): style=re.compile('url\s*\(\s*[^\s)]+?\s*\)\s*').sub(' ',style) if not re.match("""^([:,; if re.sub("\s*[-\w]+\s*:\s*[^:;]*;?", '', style).strip(): return '' clean = [] for prop,value in re.findall("([-\w]+)\s*:\s*([^:;]*)",style): if not value: continue if prop.lower() in self.acce... | def _sanitizeHTML(htmlSource, encoding): p = _HTMLSanitizer(encoding) p.feed(htmlSource) data = p.output() if TIDY_MARKUP: # loop through list of preferred Tidy interfaces looking for one that's installed, # then set up a common _tidy function to wrap the interface-specific API. _tidy = None for tidy_interface in PREFE... |
def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers): | def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, extra_headers): | def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers): """URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object i... |
If the modified argument is supplied, it must be a tuple of 9 integers as returned by gmtime() in the standard Python time module. This MUST be in GMT (Greenwich Mean Time). The formatted date/time will be used as the value of an If-Modified-Since request header. | If the modified argument is supplied, it can be a tuple of 9 integers (as returned by gmtime() in the standard Python time module) or a date string in any format supported by feedparser. Regardless, it MUST be in GMT (Greenwich Mean Time). It will be reformatted into an RFC 1123-compliant date and used as the value of ... | def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers): """URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object i... |
request = urllib2.Request(url_file_stream_or_string) request.add_header('User-Agent', agent) if etag: request.add_header('If-None-Match', etag) if modified: short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'... | request = _build_urllib2_request(url_file_stream_or_string, agent, etag, modified, referrer, auth, extra_headers) | def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers): """URL, filename, or string --> stream This function lets you define parsers that take any input source (URL, pathname to local or network file, or actual data as a string) and deal with it in a uniform manner. Returned object i... |
_iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO', 'YY-?MM-?DD', 'YY-?OOO', 'YYYY', | _iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-0MM?-?DD', 'YYYY-MM', 'YYYY-?OOO', 'YY-?MM-?DD', 'YY-?OOO', 'YYYY', | def registerDateHandler(func): '''Register a date handler function (takes string, returns 9-tuple date in GMT)''' _date_handlers.insert(0, func) |
second = int(params.get('second', 0)) | second = int(float(params.get('second', 0))) | def _parse_date_iso8601(dateString): '''Parse a variety of ISO-8601-compatible formats like 20040105''' m = None for _iso8601_match in _iso8601_matches: m = _iso8601_match(dateString) if m: break if not m: return if m.span() == (0, 0): return params = m.groupdict() ordinal = params.get('ordinal', 0) if ordinal: ordinal... |
daylight_savings_flag = 0 | daylight_savings_flag = -1 | def _parse_date_iso8601(dateString): '''Parse a variety of ISO-8601-compatible formats like 20040105''' m = None for _iso8601_match in _iso8601_matches: m = _iso8601_match(dateString) if m: break if not m: return if m.span() == (0, 0): return params = m.groupdict() ordinal = params.get('ordinal', 0) if ordinal: ordinal... |
registerDateHandler(_parse_date_rfc822) | registerDateHandler(_parse_date_rfc822) def _parse_date_perforce(aDateString): """parse a date in yyyy/mm/dd hh:mm:ss TTT format""" _my_date_pattern = re.compile( \ r'(\w{,3}), (\d{,4})/(\d{,2})/(\d{2}) (\d{,2}):(\d{2}):(\d{2}) (\w{,3})') dow, year, month, day, hour, minute, second, tz = \ _my_date_pattern.search(aD... | def _parse_date_rfc822(dateString): '''Parse an RFC822, RFC1123, RFC2822, or asctime-style date''' data = dateString.split() if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames: del data[0] if len(data) == 4: s = data[3] i = s.find('+') if i > 0: data[3:] = [s[:i], s[i+1:]] else: data.append('') dateStr... |
entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE) data = entity_pattern.sub('', data) doctype_pattern = re.compile(r'<!DOCTYPE([^>]*?)>', re.MULTILINE) doctype_results = doctype_pattern.findall(data) | start = re.search('<\w',data) start = start and start.start() or -1 head,data = data[:start+1], data[start+1:] entity_pattern = re.compile(r'^\s*<!ENTITY([^>]*?)>', re.MULTILINE) entity_results=entity_pattern.findall(head) head = entity_pattern.sub('', head) doctype_pattern = re.compile(r'^\s*<!DOCTYPE([^>]*?)>', re.M... | def _stripDoctype(data): '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data) rss_version may be 'rss091n' or None stripped_data is the same XML document, minus the DOCTYPE ''' entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE) data = entity_pattern.sub('', data) doctype_pattern = re.... |
data = doctype_pattern.sub('', data) return version, data def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' | replacement='' if len(doctype_results)==1 and entity_results: safe_pattern=re.compile('\s+(\w+)\s+"(& safe_entities=filter(lambda e: safe_pattern.match(e),entity_results) if safe_entities: replacement='<!DOCTYPE feed [\n <!ENTITY %s>\n]>' % '>\n <!ENTITY '.join(safe_entities) data = doctype_pattern.sub(replacement, h... | def _stripDoctype(data): '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data) rss_version may be 'rss091n' or None stripped_data is the same XML document, minus the DOCTYPE ''' entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE) data = entity_pattern.sub('', data) doctype_pattern = re.... |
f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers) | f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, extra_headers) | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
data = '' | data = None | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
result['etag'] = info.getheader('ETag') | etag = info.getheader('ETag') if etag: result['etag'] = etag | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
result['version'], data = _stripDoctype(data) | if data is not None: result['version'], data, entities = _stripDoctype(data) | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
if not data: | if data is None: | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
'%s, %s, utf-8, and windows-1252 but nothing worked' % \ | '%s, %s, utf-8, windows-1252, and iso-8859-2 but nothing worked' % \ | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '') | feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '', entities) | def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]): '''Parse a feed from a URL, file, stream, or string''' result = FeedParserDict() result['feed'] = FeedParserDict() result['entries'] = [] if _XML_AVAILABLE: result['bozo'] = 0 if type(handlers) == types.InstanceType:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.