PEP8 style fixes and other small style fixes
I used autopep8 on some files and did carefully check the changes. I ignored E501,E302,E231,E225,E222,E221,E241,E203 in my search, and at least E501 on any autopep8 run. Other style fixes not related to PEP8: * Only use new-style classes. I don't think the usage of old-style classes was voluntary. Old-style classes are removed in Python 3. * Convert an if/else to a one-liner in mediawiki, change docstring style change to a comment something that wasn't really appropriate for a docstring. * Unneeded first if condition in meteofrance
This commit is contained in:
parent
1e000acf3a
commit
006e97a8be
99 changed files with 441 additions and 350 deletions
|
|
@ -1 +0,0 @@
|
|||
|
||||
|
|
@ -1 +0,0 @@
|
|||
|
||||
|
|
@ -49,6 +49,7 @@ class QifFormatter(IFormatter):
|
|||
self.count += 1
|
||||
return result
|
||||
|
||||
|
||||
class TransactionsFormatter(IFormatter):
|
||||
MANDATORY_FIELDS = ('date', 'label', 'amount')
|
||||
TYPES = ['', 'Transfer', 'Order', 'Check', 'Deposit', 'Payback', 'Withdrawal', 'Card', 'Loan', 'Bank']
|
||||
|
|
@ -82,6 +83,7 @@ class TransactionsFormatter(IFormatter):
|
|||
result += ' %-10s %-12s %-50s %10.2f' % (item['date'].strftime('%Y-%m-%d'), _type, label[:50], item['amount'])
|
||||
return result
|
||||
|
||||
|
||||
class TransferFormatter(IFormatter):
|
||||
MANDATORY_FIELDS = ('id', 'date', 'origin', 'recipient', 'amount')
|
||||
|
||||
|
|
@ -96,6 +98,7 @@ class TransferFormatter(IFormatter):
|
|||
result += u'Amount: %.2f\n' % item['amount']
|
||||
return result
|
||||
|
||||
|
||||
class RecipientListFormatter(IFormatter):
|
||||
MANDATORY_FIELDS = ('id', 'label')
|
||||
|
||||
|
|
@ -115,6 +118,7 @@ class RecipientListFormatter(IFormatter):
|
|||
|
||||
return u'%s %-30s %s %s' % (self.BOLD, id, self.NC, item['label'])
|
||||
|
||||
|
||||
class AccountListFormatter(IFormatter):
|
||||
MANDATORY_FIELDS = ('id', 'label', 'balance', 'coming')
|
||||
|
||||
|
|
@ -122,13 +126,12 @@ class AccountListFormatter(IFormatter):
|
|||
tot_balance = 0.0
|
||||
tot_coming = 0.0
|
||||
|
||||
|
||||
def flush(self):
|
||||
if self.count < 1:
|
||||
return
|
||||
|
||||
result = u'------------------------------------------%s+----------+----------\n' % (('-' * 15) if not self.interactive else '')
|
||||
result +=u'%s Total %8s %8s' % ((' ' * 15) if not self.interactive else '',
|
||||
result += u'%s Total %8s %8s' % ((' ' * 15) if not self.interactive else '',
|
||||
'%.2f' % self.tot_balance, '%.2f' % self.tot_coming)
|
||||
self.after_format(result)
|
||||
self.tot_balance = 0.0
|
||||
|
|
@ -156,6 +159,7 @@ class AccountListFormatter(IFormatter):
|
|||
self.tot_coming += item['coming']
|
||||
return result
|
||||
|
||||
|
||||
class Boobank(ReplApplication):
|
||||
APPNAME = 'boobank'
|
||||
VERSION = '0.b'
|
||||
|
|
@ -278,7 +282,7 @@ class Boobank(ReplApplication):
|
|||
|
||||
try:
|
||||
amount = float(amount)
|
||||
except (TypeError,ValueError):
|
||||
except (TypeError, ValueError):
|
||||
print >>sys.stderr, 'Error: please give a decimal amount to transfer'
|
||||
return 2
|
||||
|
||||
|
|
|
|||
|
|
@ -124,7 +124,7 @@ class MasstransitHildon():
|
|||
self.main_window.connect("destroy", self.on_main_window_destroy)
|
||||
|
||||
self.refresh_button.connect("clicked", self.on_refresh_button_clicked)
|
||||
|
||||
|
||||
self.retour_button.set_sensitive(False)
|
||||
self.retour_button.connect("clicked", self.on_retour_button_clicked)
|
||||
|
||||
|
|
@ -165,8 +165,8 @@ class MasstransitHildon():
|
|||
text=4
|
||||
))
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
vertical_box = gtk.VBox()
|
||||
vertical_box.pack_start(horizontal_box)
|
||||
horizontal_box.pack_start(self.retour_button)
|
||||
|
|
@ -187,7 +187,7 @@ class MasstransitHildon():
|
|||
|
||||
def fill_touch_selector_entry(self):
|
||||
liste = []
|
||||
|
||||
|
||||
for backend in self.weboob.iter_backends():
|
||||
for station in backend.iter_station_search(""):
|
||||
liste.append(station.name.capitalize())
|
||||
|
|
@ -272,7 +272,7 @@ class MasstransitHildon():
|
|||
|
||||
self.refresh_in_progress = False
|
||||
banner.set_timeout(1)
|
||||
hildon.hildon_gtk_window_set_progress_indicator(self.main_window, 0)
|
||||
hildon.hildon_gtk_window_set_progress_indicator(self.main_window, 0)
|
||||
|
||||
|
||||
class Masstransit(BaseApplication):
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
from .qwebcontentedit import QWebContentEdit
|
||||
|
||||
__all__ = ['QWebContentEdit']
|
||||
|
||||
__all__ = ['QWebContentEdit']
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ from weboob.capabilities.content import ICapContent
|
|||
|
||||
from .main_window import MainWindow
|
||||
|
||||
|
||||
class QWebContentEdit(QtApplication):
|
||||
APPNAME = 'qwebcontentedit'
|
||||
VERSION = '0.b'
|
||||
|
|
@ -34,5 +35,3 @@ class QWebContentEdit(QtApplication):
|
|||
self.main_window = MainWindow(self.config, self.weboob)
|
||||
self.main_window.show()
|
||||
return self.weboob.loop()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -124,8 +124,8 @@ class WeboobRepos(ReplApplication):
|
|||
'--keyring', os.path.realpath(krname),
|
||||
'--import', os.path.realpath(keypath)])
|
||||
# Does not make much sense in our case
|
||||
if os.path.exists(krname+'~'):
|
||||
os.remove(krname+'~')
|
||||
if os.path.exists(krname + '~'):
|
||||
os.remove(krname + '~')
|
||||
if not os.path.exists(krname):
|
||||
raise Exception('No valid key file found.')
|
||||
kr_mtime = mktime(strptime(str(r.key_update), '%Y%m%d%H%M'))
|
||||
|
|
@ -134,7 +134,6 @@ class WeboobRepos(ReplApplication):
|
|||
else:
|
||||
print 'Keyring is up to date'
|
||||
|
||||
|
||||
for name, module in r.modules.iteritems():
|
||||
tarname = os.path.join(repo_path, '%s.tar.gz' % name)
|
||||
if r.signed:
|
||||
|
|
@ -185,7 +184,7 @@ class WeboobRepos(ReplApplication):
|
|||
# Check if all files have an up to date signature
|
||||
for filename in sigfiles:
|
||||
filepath = os.path.realpath(os.path.join(repo_path, filename))
|
||||
sigpath = filepath+'.sig'
|
||||
sigpath = filepath + '.sig'
|
||||
file_mtime = int(os.path.getmtime(filepath))
|
||||
if os.path.exists(sigpath):
|
||||
sig_mtime = int(os.path.getmtime(sigpath))
|
||||
|
|
@ -202,7 +201,6 @@ class WeboobRepos(ReplApplication):
|
|||
os.utime(sigpath, (file_mtime, file_mtime))
|
||||
print 'Signatures are up to date'
|
||||
|
||||
|
||||
@staticmethod
|
||||
def _find_gpg():
|
||||
if os.getenv('GPG_EXECUTABLE'):
|
||||
|
|
@ -221,4 +219,3 @@ class WeboobRepos(ReplApplication):
|
|||
if filename.endswith('.png'):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
|
|
|||
|
|
@ -64,6 +64,7 @@ class NotLoaded(object):
|
|||
class IBaseCap(object):
|
||||
pass
|
||||
|
||||
|
||||
class CapBaseObject(object):
|
||||
FIELDS = None
|
||||
_attribs = None
|
||||
|
|
@ -128,7 +129,7 @@ class CapBaseObject(object):
|
|||
if self.FIELDS is None:
|
||||
yield 'id', self.id
|
||||
for key, value in iter_fields(self):
|
||||
if key not in ('id', 'backend','FIELDS'):
|
||||
if key not in ('id', 'backend', 'FIELDS'):
|
||||
yield key, value
|
||||
else:
|
||||
yield 'id', self.id
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ from weboob.tools.ordereddict import OrderedDict
|
|||
|
||||
__all__ = ['ICapContact', 'Contact']
|
||||
|
||||
|
||||
class ProfileNode(object):
|
||||
HEAD = 0x01
|
||||
SECTION = 0x02
|
||||
|
|
@ -38,6 +39,7 @@ class ProfileNode(object):
|
|||
def __getitem__(self, key):
|
||||
return self.value[key]
|
||||
|
||||
|
||||
class ContactPhoto(CapBaseObject):
|
||||
def __init__(self, name):
|
||||
CapBaseObject.__init__(self, name)
|
||||
|
|
@ -59,6 +61,7 @@ class ContactPhoto(CapBaseObject):
|
|||
len(self.data) if self.data else 0,
|
||||
len(self.thumbnail_data) if self.thumbnail_data else 0)
|
||||
|
||||
|
||||
class Contact(CapBaseObject):
|
||||
STATUS_ONLINE = 0x001
|
||||
STATUS_AWAY = 0x002
|
||||
|
|
@ -83,14 +86,17 @@ class Contact(CapBaseObject):
|
|||
for key, value in kwargs.iteritems():
|
||||
setattr(photo, key, value)
|
||||
|
||||
|
||||
class QueryError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Query(CapBaseObject):
|
||||
def __init__(self, id, message):
|
||||
CapBaseObject.__init__(self, id)
|
||||
self.add_field('message', basestring, message)
|
||||
|
||||
|
||||
class ICapContact(IBaseCap):
|
||||
def iter_contacts(self, status=Contact.STATUS_ALL, ids=None):
|
||||
"""
|
||||
|
|
@ -129,20 +135,20 @@ class ICapContact(IBaseCap):
|
|||
@except QueryError
|
||||
"""
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
def get_notes(self, id):
|
||||
"""
|
||||
Get personal notes about a contact
|
||||
|
||||
|
||||
@param id the ID of the contact
|
||||
@return a unicode object
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
def save_notes(self, id, notes):
|
||||
"""
|
||||
Set personal notes about a contact
|
||||
|
||||
|
||||
@param id the ID of the contact
|
||||
@param notes the unicode object to save as notes
|
||||
"""
|
||||
|
|
|
|||
|
|
@ -28,9 +28,11 @@ from logging import warning
|
|||
|
||||
__all__ = ['BackendsConfig', 'BackendAlreadyExists']
|
||||
|
||||
|
||||
class BackendAlreadyExists(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BackendsConfig(object):
|
||||
class WrongPermissions(Exception):
|
||||
pass
|
||||
|
|
@ -41,13 +43,13 @@ class BackendsConfig(object):
|
|||
mode = os.stat(confpath).st_mode
|
||||
except OSError:
|
||||
if sys.platform == 'win32':
|
||||
fptr = open(confpath,'w')
|
||||
fptr = open(confpath, 'w')
|
||||
fptr.close()
|
||||
else:
|
||||
try:
|
||||
os.mknod(confpath, 0600)
|
||||
except OSError:
|
||||
fptr = open(confpath,'w')
|
||||
fptr = open(confpath, 'w')
|
||||
fptr.close()
|
||||
os.chmod(confpath, 0600)
|
||||
else:
|
||||
|
|
@ -129,5 +131,3 @@ class BackendsConfig(object):
|
|||
with open(self.confpath, 'w') as f:
|
||||
config.write(f)
|
||||
return True
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -356,7 +356,7 @@ class Versions(object):
|
|||
with open(os.path.join(self.path, self.VERSIONS_LIST), 'wb') as fp:
|
||||
config.write(fp)
|
||||
|
||||
class IProgress:
|
||||
class IProgress(object):
|
||||
def progress(self, percent, message):
|
||||
print '=== [%3.0f%%] %s' % (percent*100, message)
|
||||
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
|
||||
|
|
@ -1 +0,0 @@
|
|||
|
||||
|
|
@ -1 +0,0 @@
|
|||
|
||||
|
|
@ -92,7 +92,7 @@ class IFormatter(object):
|
|||
if sys.platform == 'win32':
|
||||
self.termrows = WConio.gettextinfo()[8]
|
||||
else:
|
||||
self.termrows = int( subprocess.Popen('stty size', shell=True, stdout=subprocess.PIPE).communicate()[0].split()[0])
|
||||
self.termrows = int(subprocess.Popen('stty size', shell=True, stdout=subprocess.PIPE).communicate()[0].split()[0])
|
||||
|
||||
def after_format(self, formatted):
|
||||
if self.outfile != sys.stdout:
|
||||
|
|
|
|||
|
|
@ -36,9 +36,9 @@ class WebBrowser(gtk.Window):
|
|||
self.connect('destroy', gtk.main_quit)
|
||||
self.set_default_size(800, 600)
|
||||
self.web_view = webkit.WebView()
|
||||
sw = gtk.ScrolledWindow()
|
||||
sw.add(self.web_view)
|
||||
self.add(sw)
|
||||
sw = gtk.ScrolledWindow()
|
||||
sw.add(self.web_view)
|
||||
self.add(sw)
|
||||
self.show_all()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -62,6 +62,7 @@ class BackendStorage(object):
|
|||
if self.storage:
|
||||
return self.storage.save('backends', self.name)
|
||||
|
||||
|
||||
class BackendConfig(ValuesDict):
|
||||
modname = None
|
||||
instname = None
|
||||
|
|
@ -118,6 +119,7 @@ class BackendConfig(ValuesDict):
|
|||
|
||||
self.weboob.backends_config.add_backend(self.instname, self.modname, dump, edit)
|
||||
|
||||
|
||||
class BaseBackend(object):
|
||||
# Backend name.
|
||||
NAME = None
|
||||
|
|
@ -149,7 +151,8 @@ class BaseBackend(object):
|
|||
# NOT yet filled.
|
||||
OBJECTS = {}
|
||||
|
||||
class ConfigError(Exception): pass
|
||||
class ConfigError(Exception):
|
||||
pass
|
||||
|
||||
def __enter__(self):
|
||||
self.lock.acquire()
|
||||
|
|
@ -184,6 +187,7 @@ class BaseBackend(object):
|
|||
class classprop(object):
|
||||
def __init__(self, fget):
|
||||
self.fget = fget
|
||||
|
||||
def __get__(self, inst, objtype=None):
|
||||
if inst:
|
||||
return self.fget(inst)
|
||||
|
|
|
|||
|
|
@ -1 +0,0 @@
|
|||
|
||||
|
|
@ -28,6 +28,7 @@ from weboob.tools.test import BackendTest
|
|||
|
||||
__all__ = ['GenericComicReaderBackend']
|
||||
|
||||
|
||||
class DisplayPage(BasePage):
|
||||
def get_page(self, gallery):
|
||||
src = self.document.xpath(self.browser.params['img_src_xpath'])[0]
|
||||
|
|
@ -102,7 +103,6 @@ class GenericComicReaderBackend(BaseBackend, ICapGallery):
|
|||
else:
|
||||
return None
|
||||
|
||||
|
||||
gallery = BaseGallery(_id, url=(self.ID_TO_URL % _id))
|
||||
with self.browser:
|
||||
return gallery
|
||||
|
|
@ -116,7 +116,7 @@ class GenericComicReaderBackend(BaseBackend, ICapGallery):
|
|||
|
||||
OBJECTS = {
|
||||
BaseGallery: fill_gallery,
|
||||
BaseImage: fill_image }
|
||||
BaseImage: fill_image}
|
||||
|
||||
|
||||
class GenericComicReaderTest(BackendTest):
|
||||
|
|
@ -126,4 +126,3 @@ class GenericComicReaderTest(BackendTest):
|
|||
it.next()
|
||||
img = it.next()
|
||||
self.backend.fillobj(img, ('url', 'data'))
|
||||
|
||||
|
|
|
|||
|
|
@ -20,11 +20,12 @@
|
|||
# python2.5 compatibility
|
||||
from __future__ import with_statement
|
||||
|
||||
import time
|
||||
import time
|
||||
from weboob.capabilities.messages import ICapMessages, Message, Thread
|
||||
from weboob.tools.backend import BaseBackend
|
||||
from weboob.tools.newsfeed import Newsfeed
|
||||
|
||||
|
||||
class GenericNewspaperBackend(BaseBackend, ICapMessages):
|
||||
"GenericNewspaperBackend class"
|
||||
MAINTAINER = 'Julien Hebert'
|
||||
|
|
@ -71,13 +72,13 @@ class GenericNewspaperBackend(BaseBackend, ICapMessages):
|
|||
content=content.body,
|
||||
signature='URL: %s' % content.url,
|
||||
flags=flags,
|
||||
children= [])
|
||||
children=[])
|
||||
return thread
|
||||
|
||||
def iter_threads(self):
|
||||
for article in Newsfeed(self.RSS_FEED, GenericNewspaperBackend.RSSID).iter_entries():
|
||||
thread = Thread(article.id)
|
||||
thread.title = article.title
|
||||
thread.title = article.title
|
||||
thread.date = article.datetime
|
||||
yield(thread)
|
||||
|
||||
|
|
@ -112,7 +113,7 @@ class GenericNewspaperBackend(BaseBackend, ICapMessages):
|
|||
if time.time() - lastpurge > 7200:
|
||||
self.storage.set('lastpurge', time.time())
|
||||
for id in self.storage.get('seen', default={}):
|
||||
l.append((int(url2id(id)), id))
|
||||
l.append((int(url2id(id)), id))
|
||||
l.sort()
|
||||
l.reverse()
|
||||
tosave = [v[1] for v in l[0:self.RSSSIZE + 10]]
|
||||
|
|
|
|||
|
|
@ -23,8 +23,8 @@ from lxml.etree import Comment
|
|||
|
||||
|
||||
def try_remove(parser, base_element, selector):
|
||||
try :
|
||||
base_element.remove(parser.select(base_element, selector, 1 ))
|
||||
try:
|
||||
base_element.remove(parser.select(base_element, selector, 1))
|
||||
except (BrokenPageError, ValueError):
|
||||
pass
|
||||
|
||||
|
|
@ -33,6 +33,7 @@ def try_drop_tree(parser, base_element, selector):
|
|||
for el in parser.select(base_element, selector):
|
||||
el.drop_tree()
|
||||
|
||||
|
||||
def remove_from_selector_list(parser, base_element, selector_list):
|
||||
for selector in selector_list:
|
||||
base_element.remove(parser.select(base_element, selector, 1))
|
||||
|
|
@ -42,24 +43,28 @@ def try_remove_from_selector_list(parser, base_element, selector_list):
|
|||
for selector in selector_list:
|
||||
try_remove(parser, base_element, selector)
|
||||
|
||||
|
||||
def drop_comments(base_element):
|
||||
for comment in base_element.getiterator(Comment):
|
||||
comment.drop_tree()
|
||||
|
||||
|
||||
|
||||
class NoAuthorElement(BrokenPageError):
|
||||
pass
|
||||
|
||||
|
||||
class NoBodyElement(BrokenPageError):
|
||||
pass
|
||||
|
||||
|
||||
class NoTitleException(BrokenPageError):
|
||||
pass
|
||||
|
||||
|
||||
class NoneMainDiv(AttributeError):
|
||||
pass
|
||||
|
||||
|
||||
class Article(object):
|
||||
author = u''
|
||||
title = u''
|
||||
|
|
@ -71,10 +76,11 @@ class Article(object):
|
|||
self.url = u''
|
||||
self.date = None
|
||||
|
||||
|
||||
class GenericNewsPage(BasePage):
|
||||
__element_body = NotImplementedError
|
||||
__article = Article
|
||||
element_title_selector = NotImplementedError
|
||||
element_title_selector = NotImplementedError
|
||||
main_div = NotImplementedError
|
||||
element_body_selector = NotImplementedError
|
||||
element_author_selector = NotImplementedError
|
||||
|
|
@ -90,7 +96,7 @@ class GenericNewsPage(BasePage):
|
|||
return self.__article.author
|
||||
|
||||
def get_title(self):
|
||||
try :
|
||||
try:
|
||||
return self.parser.select(
|
||||
self.main_div,
|
||||
self.element_title_selector,
|
||||
|
|
@ -108,7 +114,7 @@ class GenericNewsPage(BasePage):
|
|||
return self.get_title()
|
||||
|
||||
def get_element_body(self):
|
||||
try :
|
||||
try:
|
||||
return self.parser.select(self.main_div, self.element_body_selector, 1)
|
||||
except BrokenPageError:
|
||||
raise NoBodyElement("no body on %s" % (self.browser))
|
||||
|
|
|
|||
|
|
@ -21,87 +21,88 @@
|
|||
import hashlib
|
||||
import Image
|
||||
|
||||
|
||||
class VirtKeyboardError(Exception):
|
||||
def __init__(self, msg):
|
||||
Exception.__init__(self, msg)
|
||||
|
||||
|
||||
class VirtKeyboard(object):
|
||||
def __init__(self, file,coords,color):
|
||||
def __init__(self, file, coords, color):
|
||||
# file: virtual keyboard image
|
||||
# coords: dictionary <value to return>:<tuple(x1,y1,x2,y2)>
|
||||
# color: color of the symbols in the image
|
||||
# depending on the image, it can be a single value or a tuple
|
||||
img=Image.open(file)
|
||||
img = Image.open(file)
|
||||
|
||||
self.bands=img.getbands()
|
||||
if isinstance(color,int) and not isinstance(self.bands,str) and len(self.bands)!=1:
|
||||
self.bands = img.getbands()
|
||||
if isinstance(color, int) and not isinstance(self.bands, str) and len(self.bands) != 1:
|
||||
raise VirtKeyboardError("Color requires %i component but only 1 is provided" \
|
||||
% len(self.bands))
|
||||
if not isinstance(color, int) and len(color)!=len(self.bands):
|
||||
if not isinstance(color, int) and len(color) != len(self.bands):
|
||||
raise VirtKeyboardError("Color requires %i components but %i are provided" \
|
||||
% (len(self.bands),len(color)))
|
||||
self.color=color
|
||||
% (len(self.bands), len(color)))
|
||||
self.color = color
|
||||
|
||||
(self.width,self.height)=img.size
|
||||
self.pixar=img.load()
|
||||
self.coords={}
|
||||
self.md5={}
|
||||
(self.width, self.height) = img.size
|
||||
self.pixar = img.load()
|
||||
self.coords = {}
|
||||
self.md5 = {}
|
||||
for i in coords.keys():
|
||||
coord=self.get_symbol_coords(coords[i])
|
||||
if coord==(-1,-1,-1,-1):
|
||||
coord = self.get_symbol_coords(coords[i])
|
||||
if coord == (-1, -1, -1, -1):
|
||||
continue
|
||||
self.coords[i]=coord
|
||||
self.md5[i]=self.checksum(self.coords[i])
|
||||
self.coords[i] = coord
|
||||
self.md5[i] = self.checksum(self.coords[i])
|
||||
|
||||
def get_symbol_coords(self,(x1,y1,x2,y2)):
|
||||
newY1=-1
|
||||
newY2=-1
|
||||
for y in range(y1,min(y2+1,self.height)):
|
||||
empty_line=True
|
||||
for x in range(x1,min(x2+1,self.width)):
|
||||
if self.pixar[x,y] == self.color:
|
||||
empty_line=False
|
||||
if newY1==-1:
|
||||
newY1=y
|
||||
break;
|
||||
else:
|
||||
break
|
||||
if newY1!=-1 and not empty_line:
|
||||
newY2=y
|
||||
newX1=-1
|
||||
newX2=-1
|
||||
for x in range(x1,min(x2+1,self.width)):
|
||||
empty_column=True
|
||||
for y in range(y1,min(y2+1,self.height)):
|
||||
if self.pixar[x,y] == self.color:
|
||||
empty_column=False
|
||||
if newX1==-1:
|
||||
newX1=x
|
||||
def get_symbol_coords(self, (x1, y1, x2, y2)):
|
||||
newY1 = -1
|
||||
newY2 = -1
|
||||
for y in range(y1, min(y2 + 1, self.height)):
|
||||
empty_line = True
|
||||
for x in range(x1, min(x2 + 1, self.width)):
|
||||
if self.pixar[x, y] == self.color:
|
||||
empty_line = False
|
||||
if newY1 == -1:
|
||||
newY1 = y
|
||||
break
|
||||
else:
|
||||
break
|
||||
if newX1!=-1 and not empty_column:
|
||||
newX2=x
|
||||
return (newX1,newY1,newX2,newY2)
|
||||
if newY1 != -1 and not empty_line:
|
||||
newY2 = y
|
||||
newX1 = -1
|
||||
newX2 = -1
|
||||
for x in range(x1, min(x2 + 1, self.width)):
|
||||
empty_column = True
|
||||
for y in range(y1, min(y2 + 1, self.height)):
|
||||
if self.pixar[x, y] == self.color:
|
||||
empty_column = False
|
||||
if newX1 == -1:
|
||||
newX1 = x
|
||||
break
|
||||
else:
|
||||
break
|
||||
if newX1 != -1 and not empty_column:
|
||||
newX2 = x
|
||||
return (newX1, newY1, newX2, newY2)
|
||||
|
||||
def checksum(self,(x1,y1,x2,y2)):
|
||||
def checksum(self, (x1, y1, x2, y2)):
|
||||
s = ''
|
||||
for y in range(y1,min(y2+1,self.height)):
|
||||
for x in range(x1,min(x2+1,self.width)):
|
||||
if self.pixar[x,y]==self.color:
|
||||
for y in range(y1, min(y2 + 1, self.height)):
|
||||
for x in range(x1, min(x2 + 1, self.width)):
|
||||
if self.pixar[x, y] == self.color:
|
||||
s += "."
|
||||
else:
|
||||
s += " "
|
||||
return hashlib.md5(s).hexdigest()
|
||||
|
||||
def get_symbol_code(self,md5sum):
|
||||
def get_symbol_code(self, md5sum):
|
||||
for i in self.md5.keys():
|
||||
if md5sum == self.md5[i]:
|
||||
return i
|
||||
raise VirtKeyboardError('Symbol not found')
|
||||
|
||||
def check_symbols(self,symbols,dirname):
|
||||
def check_symbols(self, symbols, dirname):
|
||||
# symbols: dictionary <symbol>:<md5 value>
|
||||
for s in symbols.keys():
|
||||
try:
|
||||
|
|
@ -109,32 +110,33 @@ class VirtKeyboard(object):
|
|||
except VirtKeyboardError:
|
||||
self.generate_MD5(dirname)
|
||||
raise VirtKeyboardError("Symbol '%s' not found; all symbol hashes are available in %s"\
|
||||
% (s,dirname))
|
||||
% (s, dirname))
|
||||
|
||||
def generate_MD5(self,dir):
|
||||
def generate_MD5(self, dir):
|
||||
for i in self.coords.keys():
|
||||
width=self.coords[i][2]-self.coords[i][0]+1
|
||||
height=self.coords[i][3]-self.coords[i][1]+1
|
||||
img=Image.new(''.join(self.bands),(width,height))
|
||||
matrix=img.load()
|
||||
width = self.coords[i][2] - self.coords[i][0] + 1
|
||||
height = self.coords[i][3] - self.coords[i][1] + 1
|
||||
img = Image.new(''.join(self.bands), (width, height))
|
||||
matrix = img.load()
|
||||
for y in range(height):
|
||||
for x in range(width):
|
||||
matrix[x,y]=self.pixar[self.coords[i][0]+x,self.coords[i][1]+y]
|
||||
img.save(dir+"/"+self.md5[i]+".png")
|
||||
matrix[x, y] = self.pixar[self.coords[i][0] + x, self.coords[i][1] + y]
|
||||
img.save(dir + "/" + self.md5[i] + ".png")
|
||||
|
||||
|
||||
class MappedVirtKeyboard(VirtKeyboard):
|
||||
def __init__(self, file, document, img_element, color, map_attr="onclick"):
|
||||
map_id=img_element.attrib.get("usemap")[1:]
|
||||
map=document.find("//map[@id='"+map_id+"']")
|
||||
map_id = img_element.attrib.get("usemap")[1:]
|
||||
map = document.find("//map[@id='" + map_id + "']")
|
||||
if map is None:
|
||||
map=document.find("//map[@name='"+map_id+"']")
|
||||
map = document.find("//map[@name='" + map_id + "']")
|
||||
|
||||
coords={}
|
||||
coords = {}
|
||||
for area in map.getiterator("area"):
|
||||
code=area.attrib.get(map_attr)
|
||||
area_coords=[]
|
||||
code = area.attrib.get(map_attr)
|
||||
area_coords = []
|
||||
for coord in area.attrib.get("coords").split(','):
|
||||
area_coords.append(int(coord))
|
||||
coords[code]=tuple(area_coords)
|
||||
coords[code] = tuple(area_coords)
|
||||
|
||||
VirtKeyboard.__init__(self,file,coords,color)
|
||||
VirtKeyboard.__init__(self, file, coords, color)
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ class ConfigError(Exception):
|
|||
pass
|
||||
|
||||
|
||||
class IConfig:
|
||||
class IConfig(object):
|
||||
def load(self, default={}):
|
||||
raise NotImplementedError()
|
||||
|
||||
|
|
|
|||
|
|
@ -40,13 +40,12 @@ def retry(ExceptionToCheck, tries=4, delay=3, backoff=2):
|
|||
try_one_last_time = False
|
||||
break
|
||||
except ExceptionToCheck, e:
|
||||
logging.debug(u'%s, Retrying in %d seconds...' % (e,
|
||||
mdelay))
|
||||
logging.debug(u'%s, Retrying in %d seconds...' % (e, mdelay))
|
||||
time.sleep(mdelay)
|
||||
mtries -= 1
|
||||
mdelay *= backoff
|
||||
if try_one_last_time:
|
||||
return f(*args, **kwargs)
|
||||
return
|
||||
return f_retry # true decorator
|
||||
return f_retry # true decorator
|
||||
return deco_retry
|
||||
|
|
|
|||
|
|
@ -35,11 +35,13 @@ COLORS = {
|
|||
'CRITICAL': COLOR_SEQ % ("\033[1;33m\033[1;41m"),
|
||||
}
|
||||
|
||||
|
||||
def getLogger(name, parent=None):
|
||||
if parent:
|
||||
name = parent.name + '.' + name
|
||||
return _getLogger(name)
|
||||
|
||||
|
||||
class ColoredFormatter(Formatter):
|
||||
"""
|
||||
Class written by airmind:
|
||||
|
|
@ -52,9 +54,9 @@ class ColoredFormatter(Formatter):
|
|||
msg = COLORS[levelname] % msg
|
||||
return msg
|
||||
|
||||
|
||||
def createColoredFormatter(stream, format):
|
||||
if (sys.platform != 'win32') and stream.isatty():
|
||||
return ColoredFormatter(format)
|
||||
else:
|
||||
return Formatter(format)
|
||||
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ try:
|
|||
html2text = h2t.html2text
|
||||
except ImportError:
|
||||
warning('python-html2text is not present. HTML pages will not be converted into text.')
|
||||
|
||||
def html2text(html):
|
||||
return html
|
||||
|
||||
|
|
@ -117,6 +118,7 @@ def utc2local(date):
|
|||
date = date.astimezone(tz.tzlocal())
|
||||
return date
|
||||
|
||||
|
||||
def limit(iterator, lim):
|
||||
count = 0
|
||||
iterator = iter(iterator)
|
||||
|
|
@ -125,6 +127,7 @@ def limit(iterator, lim):
|
|||
count += 1
|
||||
raise StopIteration()
|
||||
|
||||
|
||||
def ratelimit(group, delay):
|
||||
"""
|
||||
Simple rate limiting.
|
||||
|
|
|
|||
|
|
@ -29,46 +29,46 @@ if feedparser.__version__ >= '5.0':
|
|||
__all__ = ['Entry', 'Newsfeed']
|
||||
|
||||
|
||||
class Entry:
|
||||
class Entry(object):
|
||||
def __init__(self, entry, rssid_func=None):
|
||||
if hasattr(entry, 'id'):
|
||||
self.id = entry.id
|
||||
else:
|
||||
self.id = None
|
||||
|
||||
if entry.has_key("link"):
|
||||
if "link" in entry:
|
||||
self.link = entry["link"]
|
||||
else:
|
||||
self.link = None
|
||||
|
||||
if entry.has_key("title"):
|
||||
if "title" in entry:
|
||||
self.title = entry["title"]
|
||||
else:
|
||||
self.title = None
|
||||
|
||||
if entry.has_key("author"):
|
||||
if "author" in entry:
|
||||
self.author = entry["author"]
|
||||
else:
|
||||
self.author = None
|
||||
|
||||
if entry.has_key("updated_parsed"):
|
||||
if "updated_parsed" in entry:
|
||||
self.datetime = datetime.datetime(*entry['updated_parsed'][:7])
|
||||
else:
|
||||
self.datetime = None
|
||||
|
||||
if entry.has_key("summary"):
|
||||
if "summary" in entry:
|
||||
self.summary = entry["summary"]
|
||||
else:
|
||||
self.summary = None
|
||||
|
||||
self.content = []
|
||||
if entry.has_key("content"):
|
||||
if "content" in entry:
|
||||
for i in entry["content"]:
|
||||
self.content.append(i.value)
|
||||
elif self.summary:
|
||||
self.content.append(self.summary)
|
||||
|
||||
if entry.has_key("wfw_commentrss"):
|
||||
if "wfw_commentrss" in entry:
|
||||
self.rsscomment = entry["wfw_commentrss"]
|
||||
else:
|
||||
self.rsscomment = None
|
||||
|
|
@ -76,7 +76,8 @@ class Entry:
|
|||
if rssid_func:
|
||||
self.id = rssid_func(self)
|
||||
|
||||
class Newsfeed:
|
||||
|
||||
class Newsfeed(object):
|
||||
def __init__(self, url, rssid_func=None):
|
||||
self.feed = feedparser.parse(url)
|
||||
self.rssid_func = rssid_func
|
||||
|
|
|
|||
|
|
@ -30,7 +30,6 @@ except ImportError:
|
|||
## {{{ http://code.activestate.com/recipes/576693/ (r6)
|
||||
from UserDict import DictMixin
|
||||
|
||||
|
||||
class OrderedDict(dict, DictMixin):
|
||||
|
||||
def __init__(self, *args, **kwds):
|
||||
|
|
|
|||
|
|
@ -24,34 +24,42 @@ import logging
|
|||
__all__ = ['get_parser', 'NoParserFound']
|
||||
|
||||
|
||||
class NoParserFound(Exception): pass
|
||||
class NoParserFound(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def load_lxml():
|
||||
from .lxmlparser import LxmlHtmlParser
|
||||
return LxmlHtmlParser
|
||||
|
||||
|
||||
def load_lxmlsoup():
|
||||
from .lxmlsoupparser import LxmlSoupParser
|
||||
return LxmlSoupParser
|
||||
|
||||
|
||||
def load_html5lib():
|
||||
from .html5libparser import Html5libParser
|
||||
return Html5libParser
|
||||
|
||||
|
||||
def load_elementtidy():
|
||||
from .elementtidyparser import ElementTidyParser
|
||||
return ElementTidyParser
|
||||
|
||||
|
||||
def load_builtin():
|
||||
from .htmlparser import HTMLParser
|
||||
return HTMLParser
|
||||
|
||||
|
||||
def load_json():
|
||||
# This parser doesn't read HTML, don't include it in the
|
||||
# preference_order default value below.
|
||||
from .jsonparser import JsonParser
|
||||
return JsonParser
|
||||
|
||||
|
||||
def get_parser(preference_order=('lxml', 'lxmlsoup')):
|
||||
"""
|
||||
Get a parser from a preference order list.
|
||||
|
|
|
|||
|
|
@ -38,8 +38,8 @@ class Html5libParser(HTMLParser, IParser):
|
|||
"""
|
||||
|
||||
# Default implementation for each type of API.
|
||||
defaults = {'etree': ElementTree,
|
||||
}
|
||||
defaults = {'etree': ElementTree}
|
||||
|
||||
def __init__(self, api='etree'):
|
||||
# if no default implementation is defined for this api, set it to None
|
||||
# to let getTreeBuilder() using the corresponding implementation.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
# For Python 2.5-, this will enable the simliar property mechanism as in
|
||||
# For Python 2.5-, this will enable the similar property mechanism as in
|
||||
# Python 2.6+/3.0+. The code is based on
|
||||
# http://bruynooghe.blogspot.com/2008/04/xsetter-syntax-in-python-25.html
|
||||
|
||||
|
|
@ -27,26 +27,26 @@ import __builtin__
|
|||
|
||||
|
||||
class property(property):
|
||||
def __init__(self, fget, *args, **kwargs):
|
||||
self.__doc__ = fget.__doc__
|
||||
super(property, self).__init__(fget, *args, **kwargs)
|
||||
def __init__(self, fget, *args, **kwargs):
|
||||
self.__doc__ = fget.__doc__
|
||||
super(property, self).__init__(fget, *args, **kwargs)
|
||||
|
||||
def setter(self, fset):
|
||||
cls_ns = sys._getframe(1).f_locals
|
||||
for k, v in cls_ns.iteritems():
|
||||
if v == self:
|
||||
propname = k
|
||||
break
|
||||
cls_ns[propname] = property(self.fget, fset, self.fdel, self.__doc__)
|
||||
return cls_ns[propname]
|
||||
def setter(self, fset):
|
||||
cls_ns = sys._getframe(1).f_locals
|
||||
for k, v in cls_ns.iteritems():
|
||||
if v == self:
|
||||
propname = k
|
||||
break
|
||||
cls_ns[propname] = property(self.fget, fset, self.fdel, self.__doc__)
|
||||
return cls_ns[propname]
|
||||
|
||||
def deleter(self, fdel):
|
||||
cls_ns = sys._getframe(1).f_locals
|
||||
for k, v in cls_ns.iteritems():
|
||||
if v == self:
|
||||
propname = k
|
||||
break
|
||||
cls_ns[propname] = property(self.fget, self.fset, fdel, self.__doc__)
|
||||
return cls_ns[propname]
|
||||
def deleter(self, fdel):
|
||||
cls_ns = sys._getframe(1).f_locals
|
||||
for k, v in cls_ns.iteritems():
|
||||
if v == self:
|
||||
propname = k
|
||||
break
|
||||
cls_ns[propname] = property(self.fget, self.fset, fdel, self.__doc__)
|
||||
return cls_ns[propname]
|
||||
|
||||
__builtin__.property = property
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ from copy import deepcopy
|
|||
from .config.yamlconfig import YamlConfig
|
||||
|
||||
|
||||
class IStorage:
|
||||
class IStorage(object):
|
||||
def load(self, what, name, default={}):
|
||||
raise NotImplementedError()
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue