Fix pep8 across codebase

* Further whitespace fixes by autopep8
 * Using pep8 v1.6.2 (not currently used by pyflakes)
 * Update config for pep8 and flake8 in tox.ini
   * A separate pep8 entry for running autopep8. The ignores prevent
     blank lines being added after docstrings.
   * .tox and E133 are ignored in flake8 by default.
This commit is contained in:
Calum Lind 2015-10-20 19:41:47 +01:00
parent 82ac1bdfe0
commit 32bc20d8ce
32 changed files with 179 additions and 164 deletions

View File

@ -12,6 +12,8 @@
# Minor modifications made by Andrew Resch to replace the BTFailure errors with Exceptions # Minor modifications made by Andrew Resch to replace the BTFailure errors with Exceptions
from types import DictType, IntType, ListType, LongType, StringType, TupleType
def decode_int(x, f): def decode_int(x, f):
f += 1 f += 1
@ -75,8 +77,6 @@ def bdecode(x):
return r return r
from types import DictType, IntType, ListType, LongType, StringType, TupleType
class Bencached(object): class Bencached(object):

View File

@ -177,7 +177,9 @@ class PreferencesManager(component.Component):
if value: if value:
import random import random
listen_ports = [] listen_ports = []
randrange = lambda: random.randrange(49152, 65525)
def randrange():
return random.randrange(49152, 65525)
listen_ports.append(randrange()) listen_ports.append(randrange())
listen_ports.append(listen_ports[0] + 10) listen_ports.append(listen_ports[0] + 10)
else: else:

View File

@ -379,10 +379,10 @@ class TorrentManager(component.Component):
lt.add_torrent_params_flags_t.flag_update_subscribe | lt.add_torrent_params_flags_t.flag_update_subscribe |
lt.add_torrent_params_flags_t.flag_apply_ip_filter) lt.add_torrent_params_flags_t.flag_apply_ip_filter)
# Set flags: enable duplicate_is_error & override_resume_data, disable auto_managed. # Set flags: enable duplicate_is_error & override_resume_data, disable auto_managed.
add_torrent_params["flags"] = ((default_flags add_torrent_params["flags"] = ((default_flags |
| lt.add_torrent_params_flags_t.flag_duplicate_is_error lt.add_torrent_params_flags_t.flag_duplicate_is_error |
| lt.add_torrent_params_flags_t.flag_override_resume_data) lt.add_torrent_params_flags_t.flag_override_resume_data) ^
^ lt.add_torrent_params_flags_t.flag_auto_managed) lt.add_torrent_params_flags_t.flag_auto_managed)
if options["seed_mode"]: if options["seed_mode"]:
add_torrent_params["flags"] |= lt.add_torrent_params_flags_t.flag_seed_mode add_torrent_params["flags"] |= lt.add_torrent_params_flags_t.flag_seed_mode

View File

@ -203,7 +203,7 @@ def start_daemon():
# Write pid file before chuid # Write pid file before chuid
if options.pidfile: if options.pidfile:
with open(options.pidfile, "wb") as _file: with open(options.pidfile, "wb") as _file:
_file.write("%s\n" % os.getpid()) _file.write("%s\n" % os.getpid())
if not deluge.common.windows_check(): if not deluge.common.windows_check():
if options.user: if options.user:

View File

@ -121,8 +121,9 @@ class SchedulerSelectWidget(gtk.DrawingArea):
if self.get_point(event) != self.hover_point: if self.get_point(event) != self.hover_point:
self.hover_point = self.get_point(event) self.hover_point = self.get_point(event)
self.hover_label.set_text(self.hover_days[self.hover_point[1]] + " " + str(self.hover_point[0]) self.hover_label.set_text(self.hover_days[self.hover_point[1]] +
+ ":00 - " + str(self.hover_point[0]) + ":59") " " + str(self.hover_point[0]) +
":00 - " + str(self.hover_point[0]) + ":59")
if self.mouse_press: if self.mouse_press:
points = [[self.hover_point[0], self.start_point[0]], [self.hover_point[1], self.start_point[1]]] points = [[self.hover_point[0], self.start_point[0]], [self.hover_point[1], self.start_point[1]]]

View File

@ -1,27 +1,3 @@
"""
rencode -- Web safe object pickling/unpickling.
Public domain, Connelly Barnes 2006-2007.
The rencode module is a modified version of bencode from the
BitTorrent project. For complex, heterogeneous data structures with
many small elements, r-encodings take up significantly less space than
b-encodings:
>>> len(rencode.dumps({'a':0, 'b':[1,2], 'c':99}))
13
>>> len(bencode.bencode({'a':0, 'b':[1,2], 'c':99}))
26
The rencode format is not standardized, and may change with different
rencode module versions, so you should check that you are using the
same rencode version throughout your project.
"""
__version__ = '1.0.2'
__all__ = ['dumps', 'loads']
# Original bencode module by Petru Paler, et al. # Original bencode module by Petru Paler, et al.
# #
# Modifications by Connelly Barnes: # Modifications by Connelly Barnes:
@ -62,10 +38,33 @@ __all__ = ['dumps', 'loads']
# (The rencode module is licensed under the above license as well). # (The rencode module is licensed under the above license as well).
# #
"""
rencode -- Web safe object pickling/unpickling.
Public domain, Connelly Barnes 2006-2007.
The rencode module is a modified version of bencode from the
BitTorrent project. For complex, heterogeneous data structures with
many small elements, r-encodings take up significantly less space than
b-encodings:
>>> len(rencode.dumps({'a':0, 'b':[1,2], 'c':99}))
13
>>> len(bencode.bencode({'a':0, 'b':[1,2], 'c':99}))
26
The rencode format is not standardized, and may change with different
rencode module versions, so you should check that you are using the
same rencode version throughout your project.
"""
import struct import struct
from threading import Lock from threading import Lock
from types import DictType, FloatType, IntType, ListType, LongType, NoneType, StringType, TupleType, UnicodeType from types import DictType, FloatType, IntType, ListType, LongType, NoneType, StringType, TupleType, UnicodeType
__version__ = '1.0.2'
__all__ = ['dumps', 'loads']
# Default number of bits for serialized floats, either 32 or 64 (also a parameter for dumps()). # Default number of bits for serialized floats, either 32 or 64 (also a parameter for dumps()).
DEFAULT_FLOAT_BITS = 32 DEFAULT_FLOAT_BITS = 32
@ -414,8 +413,8 @@ def test():
f2 = struct.unpack('!f', struct.pack('!f', 29.3))[0] f2 = struct.unpack('!f', struct.pack('!f', 29.3))[0]
f3 = struct.unpack('!f', struct.pack('!f', -0.6))[0] f3 = struct.unpack('!f', struct.pack('!f', -0.6))[0]
ld = (({'a': 15, 'bb': f1, 'ccc': f2, '': (f3, (), False, True, '')}, ('a', 10 ** 20), ld = (({'a': 15, 'bb': f1, 'ccc': f2, '': (f3, (), False, True, '')}, ('a', 10 ** 20),
tuple(range(-100000, 100000)), 'b' * 31, 'b' * 62, 'b' * 64, 2 ** 30, 2 ** 33, 2 ** 62, 2 ** 64, tuple(range(-100000, 100000)), 'b' * 31, 'b' * 62, 'b' * 64, 2 ** 30, 2 ** 33, 2 ** 62, 2 ** 64,
2 ** 30, 2 ** 33, 2 ** 62, 2 ** 64, False, False, True, -1, 2, 0),) 2 ** 30, 2 ** 33, 2 ** 62, 2 ** 64, False, False, True, -1, 2, 0),)
assert loads(dumps(ld)) == ld assert loads(dumps(ld)) == ld
d = dict(zip(range(-100000, 100000), range(-100000, 100000))) d = dict(zip(range(-100000, 100000), range(-100000, 100000)))
d.update({'a': 20, 20: 40, 40: 41, f1: f2, f2: f3, f3: False, False: True, True: False}) d.update({'a': 20, 20: 40, 40: 41, f1: f2, f2: f3, f3: False, False: True, True: False})

View File

@ -28,8 +28,8 @@ print("\n\n")
if 0: # aclient non-core if 0: # aclient non-core
methods = sorted([m for m in dir(aclient) if not m.startswith('_') methods = sorted([m for m in dir(aclient) if not m.startswith('_')
if m not in ['add_torrent_file', 'has_callback', 'get_method', 'methodHelp', if m not in ['add_torrent_file', 'has_callback', 'get_method', 'methodHelp',
'methodSignature', 'list_methods', 'add_torrent_file_binary']]) 'methodSignature', 'list_methods', 'add_torrent_file_binary']])
for m in methods: for m in methods:
func = getattr(aclient, m) func = getattr(aclient, m)
@ -45,8 +45,8 @@ if 0: # aclient non-core
print("%s" % pydoc.getdoc(func)) print("%s" % pydoc.getdoc(func))
if 1: # baseclient/core if 1: # baseclient/core
methods = sorted([m for m in dir(Core) if m.startswith("export")] methods = sorted([m for m in dir(Core) if m.startswith("export")] +
+ ['export_add_torrent_file_binary']) # HACK ['export_add_torrent_file_binary']) # HACK
for m in methods: for m in methods:

View File

@ -119,9 +119,9 @@ class DelugeTransferProtocolTestCase(unittest.TestCase):
self.transfer = TransferTestClass() self.transfer = TransferTestClass()
self.msg1 = (0, 1, {"key_int": 1242429423}, {"key_str": "some string"}, {"key_bool": True}) self.msg1 = (0, 1, {"key_int": 1242429423}, {"key_str": "some string"}, {"key_bool": True})
self.msg2 = (2, 3, {"key_float": 12424.29423}, self.msg2 = (2, 3, {"key_float": 12424.29423},
{"key_unicode": u"some string"}, {"key_unicode": u"some string"},
{"key_dict_with_tuple": {"key_tuple": (1, 2, 3)}}, {"key_dict_with_tuple": {"key_tuple": (1, 2, 3)}},
{"keylist": [4, "5", 6.7]}) {"keylist": [4, "5", 6.7]})
self.msg1_expected_compressed_base64 = "RAAAADF4nDvKwJjenp1aGZ+ZV+Lgxfv9PYRXXFLU"\ self.msg1_expected_compressed_base64 = "RAAAADF4nDvKwJjenp1aGZ+ZV+Lgxfv9PYRXXFLU"\
"XZyfm6oAZGTmpad3gAST8vNznAEAJhSQ" "XZyfm6oAZGTmpad3gAST8vNznAEAJhSQ"

View File

@ -87,8 +87,7 @@ class Win32IcoFile(object):
# end for (read headers) # end for (read headers)
# order by size and color depth # order by size and color depth
self.entry.sort(lambda x, y: cmp(x['width'], y['width']) self.entry.sort(lambda x, y: cmp(x['width'], y['width']) or cmp(x['color_depth'], y['color_depth']))
or cmp(x['color_depth'], y['color_depth']))
self.entry.reverse() self.entry.reverse()
def sizes(self): def sizes(self):

View File

@ -106,9 +106,9 @@ class TorrentInfo(object):
f["path"] = path f["path"] = path
f["index"] = index f["index"] = index
if "sha1" in f and len(f["sha1"]) == 20: if "sha1" in f and len(f["sha1"]) == 20:
f["sha1"] = f["sha1"].encode('hex') f["sha1"] = f["sha1"].encode('hex')
if "ed2k" in f and len(f["ed2k"]) == 16: if "ed2k" in f and len(f["ed2k"]) == 16:
f["ed2k"] = f["ed2k"].encode('hex') f["ed2k"] = f["ed2k"].encode('hex')
paths[path] = f paths[path] = f
dirname = os.path.dirname(path) dirname = os.path.dirname(path)
while dirname: while dirname:

View File

@ -8,6 +8,6 @@
# #
UI_PATH = __path__[0] UI_PATH = __path__[0]
from deluge.ui.console.main import start from deluge.ui.console.main import start # NOQA
assert start # silence pyflakes assert start # silence pyflakes

View File

@ -200,7 +200,9 @@ class Command(BaseCommand):
col_priority += fp col_priority += fp
rf = format_utils.remove_formatting rf = format_utils.remove_formatting
tlen = lambda s: strwidth(rf(s))
def tlen(s):
return strwidth(rf(s))
if not isinstance(col_filename, unicode): if not isinstance(col_filename, unicode):
col_filename = unicode(col_filename, "utf-8") col_filename = unicode(col_filename, "utf-8")

View File

@ -557,8 +557,11 @@ class AllTorrents(BaseMode, component.Component):
if field in first_element: if field in first_element:
is_string = isinstance(first_element[field], basestring) is_string = isinstance(first_element[field], basestring)
sort_key = lambda s: sg(s)[field] def sort_key(s):
sort_key2 = lambda s: sg(s)[field].lower() return sg(s)[field]
def sort_key2(s):
return sg(s)[field].lower()
# If it's a string, sort case-insensitively but preserve A>a order # If it's a string, sort case-insensitively but preserve A>a order
if is_string: if is_string:
@ -1120,10 +1123,8 @@ class AllTorrents(BaseMode, component.Component):
self.search_string += uchar self.search_string += uchar
still_matching = ( still_matching = (
cname.lower().find(self.search_string.lower()) cname.lower().find(self.search_string.lower()) ==
== cname.lower().find(old_search_string.lower()) and
cname.lower().find(old_search_string.lower())
and
cname.lower().find(self.search_string.lower()) != -1 cname.lower().find(self.search_string.lower()) != -1
) )

View File

@ -827,11 +827,11 @@ class InputPopup(Popup):
def add_select_input(self, message, name, opts, vals, default_index=0): def add_select_input(self, message, name, opts, vals, default_index=0):
self.inputs.append(SelectInput(self, message, name, opts, vals, default_index, self.inputs.append(SelectInput(self, message, name, opts, vals, default_index,
additional_formatting=self.additional_formatting)) additional_formatting=self.additional_formatting))
def add_checked_input(self, message, name, checked=False): def add_checked_input(self, message, name, checked=False):
self.inputs.append(CheckedInput(self, message, name, checked, self.inputs.append(CheckedInput(self, message, name, checked,
additional_formatting=self.additional_formatting)) additional_formatting=self.additional_formatting))
# def add_checked_plus_input(self, message, name, child) # def add_checked_plus_input(self, message, name, child)

View File

@ -254,7 +254,9 @@ def torrent_action(idx, data, mode, ids):
options[key] = "multiple" options[key] = "multiple"
def create_popup(status): def create_popup(status):
cb = lambda result, ids=ids: _do_set_torrent_options(ids, result) def cb(result, ids=ids):
return _do_set_torrent_options(ids, result)
option_popup = InputPopup(mode, "Set torrent options (Esc to cancel)", close_cb=cb, height_req=22) option_popup = InputPopup(mode, "Set torrent options (Esc to cancel)", close_cb=cb, height_req=22)
for (field, field_type) in torrent_options: for (field, field_type) in torrent_options:

View File

@ -346,8 +346,8 @@ class TorrentDetail(BaseMode, component.Component):
xchar = "-" xchar = "-"
r = format_utils.format_row(["%s%s %s" % (" " * depth, xchar, fl[0]), r = format_utils.format_row(["%s%s %s" % (" " * depth, xchar, fl[0]),
fsize(fl[2]), fl[5], fsize(fl[2]), fl[5],
format_utils.format_priority(fl[6])], format_utils.format_priority(fl[6])],
self.column_widths) self.column_widths)
self.add_string(off, "%s%s" % (color_string, r), trim=False) self.add_string(off, "%s%s" % (color_string, r), trim=False)
@ -617,9 +617,11 @@ class TorrentDetail(BaseMode, component.Component):
# show popup for priority selections # show popup for priority selections
def show_priority_popup(self, was_empty): def show_priority_popup(self, was_empty):
func = lambda idx, data, we=was_empty: self.do_priority(idx, data, we) def popup_func(idx, data, we=was_empty):
return self.do_priority(idx, data, we)
if self.marked: if self.marked:
self.popup = SelectablePopup(self, "Set File Priority", func) self.popup = SelectablePopup(self, "Set File Priority", popup_func)
self.popup.add_line("_Do Not Download", data=FILE_PRIORITY["Do Not Download"], foreground="red") self.popup.add_line("_Do Not Download", data=FILE_PRIORITY["Do Not Download"], foreground="red")
self.popup.add_line("_Normal Priority", data=FILE_PRIORITY["Normal Priority"]) self.popup.add_line("_Normal Priority", data=FILE_PRIORITY["Normal Priority"])
self.popup.add_line("_High Priority", data=FILE_PRIORITY["High Priority"], foreground="yellow") self.popup.add_line("_High Priority", data=FILE_PRIORITY["High Priority"], foreground="yellow")

View File

@ -32,8 +32,8 @@ class AboutDialog:
self.about.set_copyright( self.about.set_copyright(
_("Copyright %(year_start)s-%(year_end)s Deluge Team") % {"year_start": 2007, "year_end": 2015}) _("Copyright %(year_start)s-%(year_end)s Deluge Team") % {"year_start": 2007, "year_end": 2015})
self.about.set_comments( self.about.set_comments(
_("A peer-to-peer file sharing program\nutilizing the BitTorrent protocol.") _("A peer-to-peer file sharing program\nutilizing the BitTorrent protocol.") +
+ "\n\n" + _("Client:") + " %s\n" % version) "\n\n" + _("Client:") + " %s\n" % version)
self.about.set_version(version) self.about.set_version(version)
self.about.set_authors([ self.about.set_authors([
_("Current Developers:"), "Andrew Resch", "Damien Churchill", _("Current Developers:"), "Andrew Resch", "Damien Churchill",

View File

@ -373,7 +373,7 @@ class FilesTab(Tab):
ret += chunk_size ret += chunk_size
else: else:
self.treestore.append(parent_iter, [key, self.treestore.append(parent_iter, [key,
value[1]["size"], "", 0, 0, value[0], gtk.STOCK_FILE]) value[1]["size"], "", 0, 0, value[0], gtk.STOCK_FILE])
ret += value[1]["size"] ret += value[1]["size"]
return ret return ret
@ -493,9 +493,9 @@ class FilesTab(Tab):
paths = self.listview.get_selection().get_selected_rows()[1] paths = self.listview.get_selection().get_selected_rows()[1]
if cursor_path[0] not in paths: if cursor_path[0] not in paths:
row = self.treestore.get_iter(cursor_path[0]) row = self.treestore.get_iter(cursor_path[0])
self.listview.get_selection().unselect_all() self.listview.get_selection().unselect_all()
self.listview.get_selection().select_iter(row) self.listview.get_selection().select_iter(row)
for widget in self.file_menu_priority_items: for widget in self.file_menu_priority_items:
widget.set_sensitive(not (self.__compact or self.__is_seed)) widget.set_sensitive(not (self.__compact or self.__is_seed))

View File

@ -126,7 +126,7 @@ class FilterTreeView(component.Component):
self.update_row("state", state, 0, _(state)) self.update_row("state", state, 0, _(state))
self.cat_nodes["tracker_host"] = self.treestore.append(None, ["cat", "tracker_host", self.cat_nodes["tracker_host"] = self.treestore.append(None, ["cat", "tracker_host",
_("Trackers"), 0, None, False]) _("Trackers"), 0, None, False])
self.update_row("tracker_host", "All", 0, _("All")) self.update_row("tracker_host", "All", 0, _("All"))
self.update_row("tracker_host", "Error", 0, _("Error")) self.update_row("tracker_host", "Error", 0, _("Error"))
self.update_row("tracker_host", "", 0, _("None")) self.update_row("tracker_host", "", 0, _("None"))

View File

@ -59,8 +59,11 @@ log = logging.getLogger(__name__)
try: try:
from setproctitle import setproctitle, getproctitle from setproctitle import setproctitle, getproctitle
except ImportError: except ImportError:
setproctitle = lambda t: None def setproctitle(title):
getproctitle = lambda: None return
def getproctitle():
return
class Gtk(_UI): class Gtk(_UI):
@ -364,93 +367,93 @@ class GtkUI(object):
self.__start_non_classic() self.__start_non_classic()
def __start_non_classic(self): def __start_non_classic(self):
# Autoconnect to a host # Autoconnect to a host
if self.config["autoconnect"]: if self.config["autoconnect"]:
def update_connection_manager(): def update_connection_manager():
if not self.connectionmanager.running: if not self.connectionmanager.running:
return return
self.connectionmanager.builder.get_object("button_refresh").emit("clicked") self.connectionmanager.builder.get_object("button_refresh").emit("clicked")
def close_connection_manager(): def close_connection_manager():
if not self.connectionmanager.running: if not self.connectionmanager.running:
return return
self.connectionmanager.builder.get_object("button_close").emit("clicked") self.connectionmanager.builder.get_object("button_close").emit("clicked")
for host_config in self.connectionmanager.config["hosts"]: for host_config in self.connectionmanager.config["hosts"]:
hostid, host, port, user, passwd = host_config hostid, host, port, user, passwd = host_config
if hostid == self.config["autoconnect_host_id"]: if hostid == self.config["autoconnect_host_id"]:
try_connect = True try_connect = True
# Check to see if we need to start the localhost daemon # Check to see if we need to start the localhost daemon
if self.config["autostart_localhost"] and host in ("localhost", "127.0.0.1"): if self.config["autostart_localhost"] and host in ("localhost", "127.0.0.1"):
log.debug("Autostarting localhost:%s", host) log.debug("Autostarting localhost:%s", host)
try_connect = client.start_daemon( try_connect = client.start_daemon(
port, get_config_dir() port, get_config_dir()
) )
log.debug("Localhost started: %s", try_connect) log.debug("Localhost started: %s", try_connect)
if not try_connect: if not try_connect:
ErrorDialog( ErrorDialog(
_("Error Starting Daemon"), _("Error Starting Daemon"),
_("There was an error starting the daemon " _("There was an error starting the daemon "
"process. Try running it from a console " "process. Try running it from a console "
"to see if there is an error.") "to see if there is an error.")
).run() ).run()
# Daemon Started, let's update it's info # Daemon Started, let's update it's info
reactor.callLater(0.5, update_connection_manager) reactor.callLater(0.5, update_connection_manager)
def on_connect(connector): def on_connect(connector):
component.start() component.start()
reactor.callLater(0.2, update_connection_manager) reactor.callLater(0.2, update_connection_manager)
reactor.callLater(0.5, close_connection_manager) reactor.callLater(0.5, close_connection_manager)
def on_connect_fail(reason, try_counter, def on_connect_fail(reason, try_counter,
host, port, user, passwd): host, port, user, passwd):
if not try_counter: if not try_counter:
return return
if reason.check(AuthenticationRequired, BadLoginError): if reason.check(AuthenticationRequired, BadLoginError):
log.debug("PasswordRequired exception") log.debug("PasswordRequired exception")
dialog = AuthenticationDialog(reason.value.message, reason.value.username) dialog = AuthenticationDialog(reason.value.message, reason.value.username)
def dialog_finished(response_id, host, port): def dialog_finished(response_id, host, port):
if response_id == gtk.RESPONSE_OK: if response_id == gtk.RESPONSE_OK:
reactor.callLater( reactor.callLater(
0.5, do_connect, try_counter - 1, 0.5, do_connect, try_counter - 1,
host, port, dialog.get_username(), host, port, dialog.get_username(),
dialog.get_password()) dialog.get_password())
dialog.run().addCallback(dialog_finished, host, port) dialog.run().addCallback(dialog_finished, host, port)
return return
log.info("Connection to host failed..") log.info("Connection to host failed..")
log.info("Retrying connection.. Retries left: " log.info("Retrying connection.. Retries left: "
"%s", try_counter) "%s", try_counter)
reactor.callLater(0.5, update_connection_manager) reactor.callLater(0.5, update_connection_manager)
reactor.callLater(0.5, do_connect, try_counter - 1, reactor.callLater(0.5, do_connect, try_counter - 1,
host, port, user, passwd) host, port, user, passwd)
def do_connect(try_counter, host, port, user, passwd): def do_connect(try_counter, host, port, user, passwd):
log.debug("Trying to connect to %s@%s:%s", log.debug("Trying to connect to %s@%s:%s",
user, host, port) user, host, port)
d = client.connect(host, port, user, passwd) d = client.connect(host, port, user, passwd)
d.addCallback(on_connect) d.addCallback(on_connect)
d.addErrback(on_connect_fail, try_counter, d.addErrback(on_connect_fail, try_counter,
host, port, user, passwd) host, port, user, passwd)
if try_connect: if try_connect:
reactor.callLater( reactor.callLater(
0.5, do_connect, 6, host, port, user, passwd 0.5, do_connect, 6, host, port, user, passwd
) )
break break
if self.config["show_connection_manager_on_start"]: if self.config["show_connection_manager_on_start"]:
# XXX: We need to call a simulate() here, but this could be a bug in twisted # XXX: We need to call a simulate() here, but this could be a bug in twisted
try: try:
reactor._simulate() reactor._simulate()
except AttributeError: except AttributeError:
# twisted < 12 # twisted < 12
reactor.simulate() reactor.simulate()
self.connectionmanager.show() self.connectionmanager.show()
def __on_disconnect(self): def __on_disconnect(self):
""" """

View File

@ -574,7 +574,6 @@ class ListView:
def add_bool_column(self, header, col_type=bool, hidden=False, def add_bool_column(self, header, col_type=bool, hidden=False,
position=None, status_field=None, sortid=0, position=None, status_field=None, sortid=0,
column_type="bool", tooltip=None, default=True): column_type="bool", tooltip=None, default=True):
"""Add a bool column to the listview""" """Add a bool column to the listview"""
render = gtk.CellRendererToggle() render = gtk.CellRendererToggle()
self.add_column(header, render, col_type, hidden, position, self.add_column(header, render, col_type, hidden, position,

View File

@ -310,7 +310,7 @@ class MainWindow(component.Component):
self.window.set_title("%s%s %s%s - Deluge" % (_("D:"), download_rate, _("U:"), upload_rate)) self.window.set_title("%s%s %s%s - Deluge" % (_("D:"), download_rate, _("U:"), upload_rate))
if self.config["show_rate_in_title"]: if self.config["show_rate_in_title"]:
client.core.get_session_status(["payload_download_rate", client.core.get_session_status(["payload_download_rate",
"payload_upload_rate"]).addCallback(_on_get_session_status) "payload_upload_rate"]).addCallback(_on_get_session_status)
def _on_set_show_rate_in_title(self, key, value): def _on_set_show_rate_in_title(self, key, value):
if value: if value:

View File

@ -266,7 +266,7 @@ class PeersTab(Tab):
if peer["ip"].count(":") == 1: if peer["ip"].count(":") == 1:
# This is an IPv4 address # This is an IPv4 address
ip_int = sum([int(byte) << shift ip_int = sum([int(byte) << shift
for byte, shift in izip(peer["ip"].split(":")[0].split("."), (24, 16, 8, 0))]) for byte, shift in izip(peer["ip"].split(":")[0].split("."), (24, 16, 8, 0))])
peer_ip = peer["ip"] peer_ip = peer["ip"]
else: else:
# This is an IPv6 address # This is an IPv6 address

View File

@ -1035,11 +1035,11 @@ class Preferences(component.Component):
shows.extend(["chk_proxy_host_resolve"]) shows.extend(["chk_proxy_host_resolve"])
hides.extend(["entry_proxy_pass", "entry_proxy_user", "label_proxy_pass", "label_proxy_user"]) hides.extend(["entry_proxy_pass", "entry_proxy_user", "label_proxy_pass", "label_proxy_user"])
shows.extend(["entry_proxy_host", "spin_proxy_port", "label_proxy_host", shows.extend(["entry_proxy_host", "spin_proxy_port", "label_proxy_host",
"label_proxy_port", "chk_proxy_peer_conn"]) "label_proxy_port", "chk_proxy_peer_conn"])
# 3:"Socks5 Auth", 5:"HTTP Auth" # 3:"Socks5 Auth", 5:"HTTP Auth"
elif proxy_type in (3, 5): elif proxy_type in (3, 5):
shows.extend(["entry_proxy_pass", "entry_proxy_user", "entry_proxy_host", "spin_proxy_port", shows.extend(["entry_proxy_pass", "entry_proxy_user", "entry_proxy_host", "spin_proxy_port",
"label_proxy_pass", "label_proxy_user", "label_proxy_host", "label_proxy_port", "label_proxy_pass", "label_proxy_user", "label_proxy_host", "label_proxy_port",
"chk_proxy_host_resolve", "chk_proxy_peer_conn"]) "chk_proxy_host_resolve", "chk_proxy_peer_conn"])
for hide_entry in hides: for hide_entry in hides:

View File

@ -188,7 +188,7 @@ class StatusBar(component.Component):
self._on_dht(configs["dht"]) self._on_dht(configs["dht"])
# Get some config values # Get some config values
client.core.get_config_values(["max_connections_global", "max_download_speed", client.core.get_config_values(["max_connections_global", "max_download_speed",
"max_upload_speed", "dht"]).addCallback(update_config_values) "max_upload_speed", "dht"]).addCallback(update_config_values)
def stop(self): def stop(self):
# When stopped, we just show the not connected thingy # When stopped, we just show the not connected thingy

View File

@ -417,7 +417,7 @@ class TrackerIcons(Component):
elif f.check(NoIconsError, HTMLParseError): elif f.check(NoIconsError, HTMLParseError):
# No icons, try favicon.ico as an act of desperation # No icons, try favicon.ico as an act of desperation
d = self.download_icon([(urljoin(self.host_to_url(host), "favicon.ico"), d = self.download_icon([(urljoin(self.host_to_url(host), "favicon.ico"),
extension_to_mimetype("ico"))], host) extension_to_mimetype("ico"))], host)
d.addCallbacks(self.on_download_icon_complete, self.on_download_icon_fail, d.addCallbacks(self.on_download_icon_complete, self.on_download_icon_fail,
callbackArgs=(host,), errbackArgs=(host,)) callbackArgs=(host,), errbackArgs=(host,))
else: else:

View File

@ -21,7 +21,8 @@ import deluge.log
try: try:
from setproctitle import setproctitle from setproctitle import setproctitle
except ImportError: except ImportError:
setproctitle = lambda t: None def setproctitle(title):
return
def version_callback(option, opt_str, value, parser): def version_callback(option, opt_str, value, parser):

View File

@ -15,10 +15,9 @@ from datetime import datetime, timedelta
from email.utils import formatdate from email.utils import formatdate
from functools import reduce from functools import reduce
from twisted.internet.task import LoopingCall
from deluge import component from deluge import component
from deluge.common import utf8_encoded from deluge.common import utf8_encoded
from twisted.internet.task import LoopingCall
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -39,7 +38,7 @@ class AuthError(Exception):
pass pass
# Import after as json_api imports the above AuthError and AUTH_LEVEL_DEFAULT # Import after as json_api imports the above AuthError and AUTH_LEVEL_DEFAULT
from deluge.ui.web.json_api import export, JSONComponent # isort:skip from deluge.ui.web.json_api import export, JSONComponent # NOQA, isort:skip
def make_checksum(session_id): def make_checksum(session_id):

View File

@ -12,7 +12,9 @@ import zlib
from deluge import common from deluge import common
_ = lambda x: gettext.gettext(x).decode("utf-8")
def _(text):
gettext.gettext(text).decode("utf-8")
def escape(text): def escape(text):

View File

@ -36,9 +36,9 @@ class Web(_UI):
help="Set the base path that the ui is running on (proxying)", help="Set the base path that the ui is running on (proxying)",
action="store", default=None) action="store", default=None)
if not (deluge.common.windows_check() or deluge.common.osx_check()): if not (deluge.common.windows_check() or deluge.common.osx_check()):
group.add_option("-d", "--do-not-daemonize", dest="donotdaemonize", group.add_option("-d", "--do-not-daemonize", dest="donotdaemonize",
help="Do not daemonize the web interface", help="Do not daemonize the web interface",
action="store_true", default=False) action="store_true", default=False)
group.add_option("-P", "--pidfile", dest="pidfile", type="str", group.add_option("-P", "--pidfile", dest="pidfile", type="str",
help="Use pidfile to store process id", help="Use pidfile to store process id",
action="store", default=None) action="store", default=None)

View File

@ -34,7 +34,7 @@ if module_exists('closure'):
def minify_closure(file_in, file_out): def minify_closure(file_in, file_out):
import subprocess import subprocess
subprocess.call(['closure', '--js', file_in, '--js_output_file', file_out, subprocess.call(['closure', '--js', file_in, '--js_output_file', file_out,
'-W', 'QUIET']) '-W', 'QUIET'])
elif module_exists('slimit'): elif module_exists('slimit'):
from slimit import minify from slimit import minify
elif module_exists('jsmin'): elif module_exists('jsmin'):

View File

@ -6,8 +6,11 @@
[flake8] [flake8]
max-line-length = 120 max-line-length = 120
builtins = _,__request__ builtins = _,__request__
ignore = E133 exclude = .git,dist,build
exclude = .tox,.git,dist,build
[pep8]
max-line-length = 120
ignore = E301,E309
[tox] [tox]
envlist = py27, flake8, isort, docs envlist = py27, flake8, isort, docs