From aa18879e9717dfe2d30f249549e9a43d6dd6da4f Mon Sep 17 00:00:00 2001 From: Rahul Bothra Date: Tue, 10 Jul 2018 16:08:44 +0530 Subject: [PATCH] Port to Python 3 * remove call to sys.setdefaultencoding default encoding is 'utf-8' by default in Python 3 * remove use of statvfs statvfs does not exist in python 3 * TODO was fixed in af6ce2e * Remove unused function * flake fixes * Fix unicode encoding error * Use a list to iterate over, supporting Python 3 * Encode 'str' instance into 'utf-8' Co-authored-by: Aniket21mathur --- Makefile.am | 2 +- bin/sugar-backlight-setup | 4 +- bin/sugar-control-panel | 2 +- bin/sugar-erase-bundle | 8 ++-- bin/sugar-install-bundle | 8 ++-- bin/sugar-launch | 6 +-- bin/sugar.in | 2 +- configure.ac | 2 +- extensions/cpsection/aboutcomputer/model.py | 18 +++---- extensions/cpsection/aboutme/model.py | 20 ++++---- extensions/cpsection/aboutme/view.py | 6 +-- .../cpsection/backup/backends/volume.py | 9 ++-- extensions/cpsection/backup/backupmanager.py | 4 +- extensions/cpsection/backup/view.py | 8 ++-- extensions/cpsection/datetime/model.py | 4 +- extensions/cpsection/frame/model.py | 6 +-- extensions/cpsection/keyboard/view.py | 5 -- extensions/cpsection/language/model.py | 10 ++-- extensions/cpsection/language/view.py | 4 +- .../cpsection/modemconfiguration/model.py | 4 +- extensions/cpsection/network/model.py | 8 ++-- extensions/cpsection/network/view.py | 12 ++--- extensions/cpsection/power/model.py | 2 +- extensions/cpsection/power/view.py | 6 +-- .../cpsection/webaccount/web_service.py | 1 - extensions/deviceicon/network.py | 4 +- extensions/deviceicon/touchpad.py | 2 +- src/jarabe/apisocket.py | 5 +- src/jarabe/controlpanel/cmd.py | 48 +++++++++---------- src/jarabe/controlpanel/gui.py | 4 +- src/jarabe/desktop/activitieslist.py | 8 +++- src/jarabe/desktop/favoriteslayout.py | 12 ++--- src/jarabe/desktop/favoritesview.py | 8 +++- src/jarabe/desktop/groupbox.py | 2 +- src/jarabe/desktop/homebox.py | 7 +-- src/jarabe/desktop/keydialog.py | 6 +-- src/jarabe/desktop/meshbox.py | 17 +++---- src/jarabe/desktop/networkviews.py | 14 +++--- src/jarabe/desktop/schoolserver.py | 14 +++--- src/jarabe/desktop/snowflakelayout.py | 10 ++-- src/jarabe/desktop/viewtoolbar.py | 2 + src/jarabe/frame/clipboard.py | 16 +++---- src/jarabe/frame/clipboardicon.py | 2 +- src/jarabe/frame/clipboardmenu.py | 8 ++-- src/jarabe/frame/clipboardobject.py | 12 ++--- src/jarabe/frame/clipboardpanelwindow.py | 2 +- src/jarabe/frame/clipboardtray.py | 4 +- src/jarabe/frame/eventarea.py | 6 +-- src/jarabe/intro/window.py | 12 ++--- src/jarabe/journal/expandedentry.py | 2 +- src/jarabe/journal/journalactivity.py | 3 +- src/jarabe/journal/journaltoolbox.py | 8 +--- src/jarabe/journal/listmodel.py | 4 +- src/jarabe/journal/misc.py | 1 + src/jarabe/journal/model.py | 7 ++- src/jarabe/journal/palettes.py | 2 +- src/jarabe/journal/projectview.py | 2 +- src/jarabe/journal/volumestoolbar.py | 13 +++-- src/jarabe/main.py | 9 +--- src/jarabe/model/adhoc.py | 2 +- src/jarabe/model/brightness.py | 2 +- src/jarabe/model/buddy.py | 2 + src/jarabe/model/bundleregistry.py | 12 ++--- src/jarabe/model/filetransfer.py | 2 +- src/jarabe/model/friends.py | 4 +- src/jarabe/model/invites.py | 2 +- src/jarabe/model/neighborhood.py | 26 +++++----- src/jarabe/model/network.py | 14 +++--- src/jarabe/model/screenshot.py | 4 +- src/jarabe/model/telepathyclient.py | 2 +- src/jarabe/model/update/aslo.py | 2 +- src/jarabe/model/update/microformat.py | 12 ++--- src/jarabe/util/downloader.py | 4 +- src/jarabe/util/normalize.py | 4 +- .../util/telepathy/connection_watcher.py | 6 +-- src/jarabe/view/buddyicon.py | 7 ++- src/jarabe/view/keyhandler.py | 6 +-- src/jarabe/view/palettes.py | 9 ++-- src/jarabe/view/viewhelp.py | 4 +- src/jarabe/view/viewhelp_webkit1.py | 2 +- src/jarabe/webservice/accountsmanager.py | 2 +- .../cpsection/webaccount/web_service.py | 1 - tests/test_downloader.py | 8 ++-- tests/test_microformat.py | 4 +- 84 files changed, 284 insertions(+), 296 deletions(-) diff --git a/Makefile.am b/Makefile.am index 3d9a2c580b..092cb08011 100644 --- a/Makefile.am +++ b/Makefile.am @@ -30,4 +30,4 @@ lint: test: lint check-po PYTHONPATH=$(pkgdatadir)/extensions:$(PYTHONPATH) \ - python -m sugar3.test.discover $(top_srcdir)/tests + python3 -m sugar3.test.discover $(top_srcdir)/tests diff --git a/bin/sugar-backlight-setup b/bin/sugar-backlight-setup index 4121d0ee23..4bebccfc0b 100644 --- a/bin/sugar-backlight-setup +++ b/bin/sugar-backlight-setup @@ -1,4 +1,4 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 # Copyright (C) 2015 Martin Abente Lahaye # @@ -60,7 +60,7 @@ def _main(): try: SugarBacklightSetup() except Exception as err: - print 'Could not create device link: %s' % str(err) + print('Could not create device link: %s' % str(err)) sys.exit(1) if __name__ == '__main__': diff --git a/bin/sugar-control-panel b/bin/sugar-control-panel index 79a8faac10..00196d51fd 100644 --- a/bin/sugar-control-panel +++ b/bin/sugar-control-panel @@ -1,4 +1,4 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 # Copyright (C) 2008, Red Hat, Inc. # # This program is free software: you can redistribute it and/or modify diff --git a/bin/sugar-erase-bundle b/bin/sugar-erase-bundle index b8657a883e..04583b5b5f 100755 --- a/bin/sugar-erase-bundle +++ b/bin/sugar-erase-bundle @@ -1,4 +1,4 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 import os import sys @@ -8,8 +8,8 @@ DBusGMainLoop(set_as_default=True) from jarabe.model import bundleregistry def cmd_help(): - print 'Usage: sugar-erase-bundle bundle_id [...] \n\n\ - Erase activity bundles\n' + print('Usage: sugar-erase-bundle bundle_id [...] \n\n\ + Erase activity bundles\n') if len(sys.argv) < 2: cmd_help() @@ -19,7 +19,7 @@ for name in sys.argv[1:]: registry = bundleregistry.get_registry() bundle = registry.get_bundle(name) if not bundle: - print 'Cannot find %s bundle.' % name + print('Cannot find %s bundle.' % name) continue registry.uninstall(bundle, delete_profile=True) diff --git a/bin/sugar-install-bundle b/bin/sugar-install-bundle index dac71bd67a..c1600c019a 100755 --- a/bin/sugar-install-bundle +++ b/bin/sugar-install-bundle @@ -1,4 +1,4 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 import os import sys @@ -9,8 +9,8 @@ DBusGMainLoop(set_as_default=True) def cmd_help(): - print 'Usage: sugar-install-bundle activitybundle.xo [...] \n\n\ - Install activity bundles\n' + print('Usage: sugar-install-bundle activitybundle.xo [...] \n\n\ + Install activity bundles\n') if len(sys.argv) < 2: cmd_help() @@ -24,4 +24,4 @@ for name in sys.argv[1:]: # by triggering a GFileMonitor ATTRIBUTE_CHANGED event. os.utime(path, None) - print "%s: '%s' installed." % (sys.argv[0], name) + print("%s: '%s' installed." % (sys.argv[0], name)) diff --git a/bin/sugar-launch b/bin/sugar-launch index 6c52e7745a..04d3554316 100644 --- a/bin/sugar-launch +++ b/bin/sugar-launch @@ -1,4 +1,4 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 # Copyright (C) 2007, Red Hat, Inc. # @@ -35,12 +35,12 @@ parser.add_argument("-u", "--uri", help='URI to load') args = parser.parse_args() -print args.bundle_id +print(args.bundle_id) bus = dbus.SessionBus() proxy = bus.get_object('org.laptop.Shell', '/org/laptop/Shell') path = dbus.Interface(proxy, 'org.laptop.Shell').GetBundlePath(args.bundle_id) if not path: - print 'Cannot find %s bundle.' % args.bundle_id + print('Cannot find %s bundle.' % args.bundle_id) sys.exit(1) activity = ActivityBundle(path) diff --git a/bin/sugar.in b/bin/sugar.in index 5485b90263..b7e8d60e66 100644 --- a/bin/sugar.in +++ b/bin/sugar.in @@ -80,4 +80,4 @@ cat > "$debug_file_path" << EOF EOF fi -exec python2 -m jarabe.main +exec python3 -m jarabe.main diff --git a/configure.ac b/configure.ac index b3b3a84170..30f368a5e8 100644 --- a/configure.ac +++ b/configure.ac @@ -12,7 +12,7 @@ AM_INIT_AUTOMAKE([1.9 foreign dist-xz no-dist-gzip]) AM_MAINTAINER_MODE -PYTHON=python2 +PYTHON=python3 AM_PATH_PYTHON AC_PATH_PROG([EMPY], [empy]) diff --git a/extensions/cpsection/aboutcomputer/model.py b/extensions/cpsection/aboutcomputer/model.py index 5e79cb3be7..af1d18ca4f 100644 --- a/extensions/cpsection/aboutcomputer/model.py +++ b/extensions/cpsection/aboutcomputer/model.py @@ -45,7 +45,7 @@ def get_aboutcomputer(): def print_aboutcomputer(): - print get_aboutcomputer() + print(get_aboutcomputer()) def _get_serial_number(): @@ -74,7 +74,7 @@ def print_serial_number(): serial_no = get_serial_number() if serial_no is None: serial_no = _not_available - print serial_no + print(serial_no) def get_build_number(): @@ -87,12 +87,12 @@ def get_build_number(): try: popen = subprocess.Popen(['lsb_release', '-ds'], stdout=subprocess.PIPE) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise else: build_no, stderr_ = popen.communicate() - build_no = build_no.strip() + build_no = build_no.strip().decode() if build_no is None or not build_no: build_no = _not_available @@ -101,7 +101,7 @@ def get_build_number(): def print_build_number(): - print get_build_number() + print(get_build_number()) def get_firmware_number(): @@ -154,7 +154,7 @@ def get_secondary_licenses(): def print_firmware_number(): - print get_firmware_number() + print(get_firmware_number()) def get_wireless_firmware(): @@ -206,15 +206,15 @@ def get_wireless_firmware(): return _not_available if len(firmware_info) == 1: - return firmware_info.values()[0] + return list(firmware_info.values())[0] return ', '.join(['%(interface)s: %(info)s' % {'interface': interface, 'info': info} - for interface, info in firmware_info.items()]) + for interface, info in list(firmware_info.items())]) def print_wireless_firmware(): - print get_wireless_firmware() + print(get_wireless_firmware()) def _read_file(path): diff --git a/extensions/cpsection/aboutme/model.py b/extensions/cpsection/aboutme/model.py index 0f30dbda14..9eac808a5e 100644 --- a/extensions/cpsection/aboutme/model.py +++ b/extensions/cpsection/aboutme/model.py @@ -39,7 +39,7 @@ def get_nick(): def print_nick(): - print get_nick() + print(get_nick()) def set_nick(nick): @@ -48,8 +48,8 @@ def set_nick(nick): """ if not nick: raise ValueError(_('You must enter a name.')) - if not isinstance(nick, unicode): - nick = unicode(nick, 'utf-8') + if not isinstance(nick, str): + nick = str(nick, 'utf-8') settings = Gio.Settings('org.sugarlabs.user') settings.set_string('nick', nick) return 1 @@ -74,14 +74,14 @@ def print_color(): fill_tuple = (color, hue) if stroke_tuple is not None: - print ('stroke: color=%s hue=%s') % (stroke_tuple[0], - stroke_tuple[1]) + print(('stroke: color=%s hue=%s') % (stroke_tuple[0], + stroke_tuple[1])) else: - print ('stroke: %s') % (tmp[0]) + print(('stroke: %s') % (tmp[0])) if fill_tuple is not None: - print ('fill: color=%s hue=%s') % (fill_tuple[0], fill_tuple[1]) + print(('fill: color=%s hue=%s') % (fill_tuple[0], fill_tuple[1])) else: - print ('fill: %s') % (tmp[1]) + print(('fill: %s') % (tmp[1])) def set_color(stroke, fill, stroke_modifier='medium', fill_modifier='medium'): @@ -93,10 +93,10 @@ def set_color(stroke, fill, stroke_modifier='medium', fill_modifier='medium'): """ if stroke_modifier not in _MODIFIERS or fill_modifier not in _MODIFIERS: - print (_('Error in specified color modifiers.')) + print((_('Error in specified color modifiers.'))) return if stroke not in _COLORS or fill not in _COLORS: - print (_('Error in specified colors.')) + print((_('Error in specified colors.'))) return if stroke_modifier == fill_modifier: diff --git a/extensions/cpsection/aboutme/view.py b/extensions/cpsection/aboutme/view.py index eb0afa36e4..83aa6a06a2 100644 --- a/extensions/cpsection/aboutme/view.py +++ b/extensions/cpsection/aboutme/view.py @@ -189,7 +189,7 @@ def __init__(self, model, alerts): self._nick_entry.connect('changed', self.__nick_changed_cb) - for picker in self._pickers.values(): + for picker in list(self._pickers.values()): picker.connect('color-changed', self.__color_changed_cb) self._gender_pickers.connect('gender-changed', @@ -353,7 +353,7 @@ def undo(self): save_age(self._saved_age) def _update_pickers(self, color): - for picker in self._pickers.values(): + for picker in list(self._pickers.values()): picker.props.color = color self._gender_pickers.update_color(color) self._age_pickers.update_color(color) @@ -381,7 +381,7 @@ def __nick_timeout_cb(self, widget): return False try: self._model.set_nick(widget.get_text()) - except ValueError, detail: + except ValueError as detail: self._nick_alert.props.msg = detail self._nick_valid = False self._nick_alert.show() diff --git a/extensions/cpsection/backup/backends/volume.py b/extensions/cpsection/backup/backends/volume.py index 72e421d449..aea5cd9386 100644 --- a/extensions/cpsection/backup/backends/volume.py +++ b/extensions/cpsection/backup/backends/volume.py @@ -15,7 +15,6 @@ import os import shutil -import statvfs import tarfile import logging from datetime import datetime @@ -28,8 +27,8 @@ from sugar3 import profile from jarabe.journal import model -from backend_tools import Backend, PreConditionsError, PreConditionsChoose -from backend_tools import get_valid_file_name +from .backend_tools import Backend, PreConditionsError, PreConditionsChoose +from .backend_tools import get_valid_file_name DIR_SIZE = 4096 DS_SOURCE_NAME = 'datastore' @@ -209,7 +208,7 @@ def verify_preconditions(self, option=None): raise PreConditionsError(_('Not enough space in disk')) def _do_continue(self): - tarinfo = self._tarfile.next() + tarinfo = next(self._tarfile) if tarinfo is not None: self._tarfile.extract(tarinfo, path='/') self._bytes += DIR_SIZE if tarinfo.isdir() else tarinfo.size @@ -244,7 +243,7 @@ def cancel(self): def _get_volume_space(path): stat = os.statvfs(path) - return stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL] + return stat[0] * stat[4] def _get_datastore_size(): diff --git a/extensions/cpsection/backup/backupmanager.py b/extensions/cpsection/backup/backupmanager.py index 33a5a30b0a..2f0285bb20 100644 --- a/extensions/cpsection/backup/backupmanager.py +++ b/extensions/cpsection/backup/backupmanager.py @@ -47,7 +47,7 @@ def __init__(self): module = _load_module(module_name) if module is not None: if hasattr(module, 'get_name'): - logging.error('FOUND BACKEND %s', module.get_name()) + logging.debug('FOUND BACKEND %s', module.get_name()) self._backends.append(module) def get_backends(self): @@ -66,7 +66,7 @@ def need_stop_activities(self): def _load_module(module): try: module = import_module('%s.%s' % (BACKENDS_MODULE, module)) - except ImportError, e: + except ImportError as e: module = None logging.error('ImportError: %s' % (e)) return module diff --git a/extensions/cpsection/backup/view.py b/extensions/cpsection/backup/view.py index 904ed59a32..0ed3d27f37 100644 --- a/extensions/cpsection/backup/view.py +++ b/extensions/cpsection/backup/view.py @@ -28,10 +28,10 @@ from jarabe.controlpanel.sectionview import SectionView -from backupmanager import BackupManager -from backupmanager import OPERATION_BACKUP, OPERATION_RESTORE -from backends.backend_tools import PreConditionsError -from backends.backend_tools import PreConditionsChoose +from .backupmanager import BackupManager +from .backupmanager import OPERATION_BACKUP, OPERATION_RESTORE +from .backends.backend_tools import PreConditionsError +from .backends.backend_tools import PreConditionsChoose class BackupView(SectionView): diff --git a/extensions/cpsection/datetime/model.py b/extensions/cpsection/datetime/model.py index 3e23dd7fe5..c5bcb37b51 100644 --- a/extensions/cpsection/datetime/model.py +++ b/extensions/cpsection/datetime/model.py @@ -50,7 +50,7 @@ def read_all_timezones(fn=_zone_tab): timezones.append(line[2]) timezones.sort() - for offset in xrange(-12, 15): + for offset in range(-12, 15): if offset < 0: tz = 'UTC%d' % offset elif offset > 0: @@ -67,7 +67,7 @@ def get_timezone(): def print_timezone(): - print get_timezone() + print(get_timezone()) def fix_UTC_time_zone(timezone): diff --git a/extensions/cpsection/frame/model.py b/extensions/cpsection/frame/model.py index 6d077b6cb2..6955942204 100644 --- a/extensions/cpsection/frame/model.py +++ b/extensions/cpsection/frame/model.py @@ -25,7 +25,7 @@ def get_corner_delay(): def print_corner_delay(): - print get_corner_delay() + print(get_corner_delay()) def set_corner_delay(delay): @@ -44,7 +44,7 @@ def get_edge_delay(): def print_edge_delay(): - print get_edge_delay() + print(get_edge_delay()) def set_edge_delay(delay): @@ -63,7 +63,7 @@ def get_trigger_size(): def print_trigger_size(): - print '{}px'.format(get_trigger_size()) + print('{}px'.format(get_trigger_size())) def set_trigger_size(size): diff --git a/extensions/cpsection/keyboard/view.py b/extensions/cpsection/keyboard/view.py index 8e876cde60..6e4de9710e 100644 --- a/extensions/cpsection/keyboard/view.py +++ b/extensions/cpsection/keyboard/view.py @@ -42,11 +42,6 @@ _iso_639_1_to_2 = {} -# TODO: This cpsection adds checks for xklavier in bin/sugar-session and -# src/jarabe/controlpanel/gui.py. We should get rid of these checks -# once python-xklavier has been packaged for all major distributions -# For more information, see: http://dev.sugarlabs.org/ticket/407 - def _build_ISO_639_dictionary(): """ The keyboard section of the control panel requires a conversion diff --git a/extensions/cpsection/language/model.py b/extensions/cpsection/language/model.py index 126689501b..032ea18da4 100644 --- a/extensions/cpsection/language/model.py +++ b/extensions/cpsection/language/model.py @@ -30,7 +30,7 @@ def read_all_languages(): fdp = subprocess.Popen(['locale', '-av'], stdout=subprocess.PIPE) - lines = fdp.stdout.read().split('\n') + lines = fdp.stdout.read().decode().split('\n') locales = [] for line in lines: @@ -142,12 +142,12 @@ def print_languages(): found_lang = False for lang in languages: if lang[2].split('.')[0] == code.split('.')[0]: - print lang[0].replace(' ', '_') + '/' + \ - lang[1].replace(' ', '_') + print(lang[0].replace(' ', '_') + '/' + + lang[1].replace(' ', '_')) found_lang = True break if not found_lang: - print (_('Language for code=%s could not be determined.') % code) + print((_('Language for code=%s could not be determined.') % code)) def set_languages(languages): @@ -170,7 +170,7 @@ def set_languages(languages): if code == languages: set_languages_list([locale_str]) return 1 - print (_("Sorry I do not speak \'%s\'.") % languages) + print((_("Sorry I do not speak \'%s\'.") % languages)) def set_languages_list(languages): diff --git a/extensions/cpsection/language/view.py b/extensions/cpsection/language/view.py index 25cb54495f..4617ebac1f 100644 --- a/extensions/cpsection/language/view.py +++ b/extensions/cpsection/language/view.py @@ -140,7 +140,7 @@ def _add_row(self, locale_code=None): locale_country = country language_palette = [] - key_list = self._language_dict.keys() + key_list = list(self._language_dict.keys()) for language_key in sorted(key_list): language_palette.append( {'label': self._language_dict[language_key], @@ -327,7 +327,7 @@ def __remove_button_clicked_cb(self, button): def _language_changed(self, widget, event, item): i = item['index'] - for language_key in self._language_dict.keys(): + for language_key in list(self._language_dict.keys()): if self._language_dict[language_key] == item['label']: new_country_list = \ self._build_country_list(language_key, idx=i) diff --git a/extensions/cpsection/modemconfiguration/model.py b/extensions/cpsection/modemconfiguration/model.py index 85326717a7..fb645537a8 100755 --- a/extensions/cpsection/modemconfiguration/model.py +++ b/extensions/cpsection/modemconfiguration/model.py @@ -215,7 +215,7 @@ def __init__(self): # Check service provider database file exists try: tree = ElementTree(file=PROVIDERS_PATH) - except (IOError, SyntaxError), e: + except (IOError, SyntaxError) as e: msg = ("Mobile broadband provider database: Could not read " "provider information %s error=%s") % (PROVIDERS_PATH, e) logging.warning(msg) @@ -317,7 +317,7 @@ def _get_initial_config(self): provider_name = self._settings.get_string(CONF_SP_PROVIDER) if not provider_name: - provider_name = u'' + provider_name = '' else: provider_name = provider_name.decode('utf-8') diff --git a/extensions/cpsection/network/model.py b/extensions/cpsection/network/model.py index 66093141af..88d89f6f22 100644 --- a/extensions/cpsection/network/model.py +++ b/extensions/cpsection/network/model.py @@ -15,8 +15,6 @@ # along with this program. If not, see . # -import logging - import gi gi.require_version('NM', '1.0') from gettext import gettext as _ @@ -62,7 +60,7 @@ def get_jabber(): def print_jabber(): - print get_jabber() + print(get_jabber()) def set_jabber(server): @@ -82,7 +80,7 @@ def get_radio(): def print_radio(): - print ('off', 'on')[get_radio()] + print(('off', 'on')[get_radio()]) def set_radio(state): @@ -119,7 +117,7 @@ def get_publish_information(): def print_publish_information(): - print get_publish_information() + print(get_publish_information()) def set_publish_information(value): diff --git a/extensions/cpsection/network/view.py b/extensions/cpsection/network/view.py index 47f4353ba0..2d131deb6d 100644 --- a/extensions/cpsection/network/view.py +++ b/extensions/cpsection/network/view.py @@ -597,7 +597,7 @@ def setup(self): try: radio_state = self._model.get_radio() - except self._model.ReadError, detail: + except self._model.ReadError as detail: self._radio_alert.props.msg = detail self._radio_alert.show() else: @@ -675,7 +675,7 @@ def _verify_settings(self): icon.show() def _apply_proxy_settings(self): - for setting in self._proxy_settings.values(): + for setting in list(self._proxy_settings.values()): if (Gio.Settings.get_has_unapplied(setting)): setting.apply() @@ -683,7 +683,7 @@ def apply(self): self._apply_jabber(self._entry.get_text()) self._model.set_social_help(self._social_help_entry.get_text()) settings_changed = False - for setting in self._proxy_settings.values(): + for setting in list(self._proxy_settings.values()): if (Gio.Settings.get_has_unapplied(setting)): settings_changed = True if settings_changed: @@ -697,9 +697,9 @@ def apply(self): def undo(self): self._button.disconnect(self._radio_change_handler) self._radio_alert.hide() - for setting in self._proxy_settings.values(): + for setting in list(self._proxy_settings.values()): setting.revert() - for alert in self._proxy_inline_alerts.values(): + for alert in list(self._proxy_inline_alerts.values()): alert.hide() def _validate(self): @@ -712,7 +712,7 @@ def __radio_toggled_cb(self, widget, data=None): radio_state = widget.get_active() try: self._model.set_radio(radio_state) - except self._model.ReadError, detail: + except self._model.ReadError as detail: self._radio_alert.props.msg = detail self._radio_valid = False else: diff --git a/extensions/cpsection/power/model.py b/extensions/cpsection/power/model.py index c52477739c..901cb059d5 100644 --- a/extensions/cpsection/power/model.py +++ b/extensions/cpsection/power/model.py @@ -55,7 +55,7 @@ def get_automatic_pm(): def print_automatic_pm(): - print ('off', 'on')[get_automatic_pm()] + print(('off', 'on')[get_automatic_pm()]) def set_automatic_pm(enabled): diff --git a/extensions/cpsection/power/view.py b/extensions/cpsection/power/view.py index 95f889f8e5..d77c956ed0 100644 --- a/extensions/cpsection/power/view.py +++ b/extensions/cpsection/power/view.py @@ -88,7 +88,7 @@ def __init__(self, model, alerts): def setup(self): try: automatic_state = self._model.get_automatic_pm() - except Exception, detail: + except Exception as detail: self._automatic_pm_alert.props.msg = detail self._automatic_pm_alert.show() else: @@ -114,8 +114,8 @@ def __automatic_pm_toggled_cb(self, widget, data=None): state = widget.get_active() try: self._model.set_automatic_pm(state) - except Exception, detail: - print detail + except Exception as detail: + print(detail) self._automatic_pm_alert.props.msg = detail else: self._automatic_pm_valid = True diff --git a/extensions/cpsection/webaccount/web_service.py b/extensions/cpsection/webaccount/web_service.py index 3c8c0fe2df..998acb120d 100644 --- a/extensions/cpsection/webaccount/web_service.py +++ b/extensions/cpsection/webaccount/web_service.py @@ -14,7 +14,6 @@ # along with this program. If not, see . - class WebService(): def get_icon_name(self): raise "Not implemented" diff --git a/extensions/deviceicon/network.py b/extensions/deviceicon/network.py index 506d417721..0841e3d190 100644 --- a/extensions/deviceicon/network.py +++ b/extensions/deviceicon/network.py @@ -515,8 +515,8 @@ def _update_properties(self, properties): self._color = profile.get_color() else: sha_hash = hashlib.sha1() - data = self._ssid + hex(self._flags) - sha_hash.update(data) + data = self._ssid.decode() + hex(self._flags) + sha_hash.update(data.encode('utf-8')) digest = hash(sha_hash.digest()) index = digest % len(xocolor.colors) diff --git a/extensions/deviceicon/touchpad.py b/extensions/deviceicon/touchpad.py index 97927a2727..d39dcb84a2 100644 --- a/extensions/deviceicon/touchpad.py +++ b/extensions/deviceicon/touchpad.py @@ -129,7 +129,7 @@ def _write_touchpad_mode_str(mode_str): """ Write the touchpad mode to the node path. """ try: node_file_handle = open(NODE_PATH, 'w') - except IOError, e: + except IOError as e: logging.error('Error opening %s for writing: %s', NODE_PATH, e) return node_file_handle.write(mode_str) diff --git a/src/jarabe/apisocket.py b/src/jarabe/apisocket.py index 6c9ad0c874..f9db18568b 100644 --- a/src/jarabe/apisocket.py +++ b/src/jarabe/apisocket.py @@ -17,6 +17,7 @@ import os import struct import time +import binascii import dbus from gi.repository import GLib @@ -287,7 +288,7 @@ def __init__(self): self._server = Server() self._server.connect("session-started", self._session_started_cb) self._port = self._server.start() - self._key = os.urandom(16).encode("hex") + self._key = binascii.hexlify(os.urandom(16)).decode() self._apis = {} self._apis["activity"] = ActivityAPI @@ -298,7 +299,7 @@ def setup_environment(self): os.environ["SUGAR_APISOCKET_KEY"] = self._key def _open_stream(self, client, request): - for stream_id in xrange(0, 255): + for stream_id in range(0, 255): if stream_id not in client.stream_monitors: client.stream_monitors[stream_id] = StreamMonitor() break diff --git a/src/jarabe/controlpanel/cmd.py b/src/jarabe/controlpanel/cmd.py index 306f9d85c1..0b459734da 100644 --- a/src/jarabe/controlpanel/cmd.py +++ b/src/jarabe/controlpanel/cmd.py @@ -35,7 +35,7 @@ def cmd_help(): """Print the help to the screen""" # TRANS: Translators, there's a empty line at the end of this string, # which must appear in the translated string (msgstr) as well. - print _('Usage: sugar-control-panel [ option ] key [ args ... ] \n\ + print(_('Usage: sugar-control-panel [ option ] key [ args ... ] \n\ Control for the sugar environment. \n\ Options: \n\ -h show this help message and exit \n\ @@ -44,13 +44,13 @@ def cmd_help(): -g key get the current value of the key \n\ -s key set the current value for the key \n\ -c key clear the current value for the key \n\ - ') + ')) def note_restart(): """Instructions how to restart sugar""" - print _('To apply your changes you have to restart Sugar.\n' + - 'Hit ctrl+alt+erase on the keyboard to trigger a restart.') + print(_('To apply your changes you have to restart Sugar.\n' + + 'Hit ctrl+alt+erase on the keyboard to trigger a restart.')) def load_modules(): @@ -96,22 +96,22 @@ def main(): if method: found += 1 if found == 1: - print method.__doc__ + print(method.__doc__) else: - print _same_option_warning % \ - {'key': key, 'module': module} + print(_same_option_warning % \ + {'key': key, 'module': module}) if found == 0: - print _no_option_error % key + print(_no_option_error % key) if option in ('-l'): for module in modules: methods = dir(module) - print '%s:' % module.__name__.split('.')[1] + print('%s:' % module.__name__.split('.')[1]) for method in methods: if method.startswith('get_'): - print ' %s' % method[4:] + print(' %s' % method[4:]) elif method.startswith('clear_'): - print ' %s (use the -c argument with this option)' \ - % method[6:] + print(' %s (use the -c argument with this option)' + % method[6:]) if option in ('-g'): for module in modules: method = getattr(module, 'print_' + key, None) @@ -121,12 +121,12 @@ def main(): try: method() except Exception as detail: - print _general_error % detail + print(_general_error % detail) else: - print _same_option_warning % \ - {'key': key, 'module': module} + print(_same_option_warning % \ + {'key': key, 'module': module}) if found == 0: - print _no_option_error % key + print(_no_option_error % key) if option in ('-s'): for module in modules: method = getattr(module, 'set_' + key, None) @@ -137,14 +137,14 @@ def main(): try: note = method(*args) except Exception as detail: - print _general_error % detail + print(_general_error % detail) if note == _RESTART: note_restart() else: - print _same_option_warning % \ - {'key': key, 'module': module} + print(_same_option_warning % \ + {'key': key, 'module': module}) if found == 0: - print _no_option_error % key + print(_no_option_error % key) if option in ('-c'): for module in modules: method = getattr(module, 'clear_' + key, None) @@ -155,11 +155,11 @@ def main(): try: note = method(*args) except Exception as detail: - print _general_error % detail + print(_general_error % detail) if note == _RESTART: note_restart() else: - print _same_option_warning % \ - {'key': key, 'module': module} + print(_same_option_warning % \ + {'key': key, 'module': module}) if found == 0: - print _no_option_error % key + print(_no_option_error % key) diff --git a/src/jarabe/controlpanel/gui.py b/src/jarabe/controlpanel/gui.py index fba6bd0248..44c2669074 100644 --- a/src/jarabe/controlpanel/gui.py +++ b/src/jarabe/controlpanel/gui.py @@ -197,7 +197,7 @@ def _setup_options(self): row = 0 column = 2 - options = self._options.keys() + options = list(self._options.keys()) options.sort() for option in options: @@ -497,7 +497,7 @@ def __getattr__(self, name): return getattr(self._module, name) def undo(self): - for key in self._options.keys(): + for key in list(self._options.keys()): method = getattr(self._module, 'set_' + key, None) if method and self._options[key] is not None: try: diff --git a/src/jarabe/desktop/activitieslist.py b/src/jarabe/desktop/activitieslist.py index 458f8a1cbb..510979680d 100644 --- a/src/jarabe/desktop/activitieslist.py +++ b/src/jarabe/desktop/activitieslist.py @@ -243,14 +243,18 @@ def set_filter(self, query): of matching activities. """ - self._query = normalize_string(query.decode('utf-8')) + if isinstance(query, bytes): + query = query.decode() + self._query = normalize_string(query) self.get_model().refilter() matches = self.get_model().iter_n_children(None) return matches def __model_visible_cb(self, model, tree_iter, data): title = model[tree_iter][self._model.column_title] - title = normalize_string(title.decode('utf-8')) + if isinstance(title, bytes): + title = title.decode('utf-8') + title = normalize_string(title) return title is not None and title.find(self._query) > -1 def create_palette(self, path, column): diff --git a/src/jarabe/desktop/favoriteslayout.py b/src/jarabe/desktop/favoriteslayout.py index 24b72e079f..d3979eabcf 100644 --- a/src/jarabe/desktop/favoriteslayout.py +++ b/src/jarabe/desktop/favoriteslayout.py @@ -177,7 +177,10 @@ def allocate_children(self, allocation, children): x = y = None if hasattr(child, "get_positioning_data"): - md5hash = hashlib.md5(child.get_positioning_data()) + positioning_data = child.get_positioning_data() + if isinstance(positioning_data, str): + positioning_data = positioning_data.encode('utf-8') + md5hash = hashlib.md5(positioning_data) digest = abs(hash(md5hash.digest())) w = (self._grid.width - (width * 3)) h = (self._grid.height - (width * 3)) @@ -243,7 +246,7 @@ def allocate_children(self, allocation, children): x = min(x, allocation.width - child_requisition.width) y = min(y, allocation.height - child_requisition.height) elif hasattr(child, 'get_bundle_id'): - name_hash = hashlib.md5(child.get_bundle_id()) + name_hash = hashlib.md5(child.get_bundle_id().decode()) x = int(name_hash.hexdigest()[:5], 16) % \ (allocation.width - child_requisition.width) y = int(name_hash.hexdigest()[-5:], 16) % \ @@ -396,7 +399,7 @@ def _calculate_angle_and_radius(self, icon_count, icon_size): def allocate_children(self, allocation, children): radius, icon_size = self._calculate_radius_and_icon_size(len(children)) - children.sort(self.compare_activities) + children.sort(key = lambda x:(x.get_activity_name().lower(), x.get_activity_name())) height = allocation.height + allocation.y for n in range(len(children)): child = children[n] @@ -423,9 +426,6 @@ def allocate_children(self, allocation, children): child_allocation.height = new_height child.size_allocate(child_allocation) - def compare_activities(self, icon_a, icon_b): - return cmp(icon_a.get_activity_name(), icon_b.get_activity_name()) - _SUNFLOWER_CONSTANT = style.STANDARD_ICON_SIZE * .75 """Chose a constant such that STANDARD_ICON_SIZE icons are nicely spaced.""" diff --git a/src/jarabe/desktop/favoritesview.py b/src/jarabe/desktop/favoritesview.py index 5557a24a9f..d2bfa37e55 100644 --- a/src/jarabe/desktop/favoritesview.py +++ b/src/jarabe/desktop/favoritesview.py @@ -358,7 +358,9 @@ def set_filter(self, query): query = query.strip() for icon in self.get_children(): if icon not in [self._owner_icon, self._activity_icon]: - activity_name = icon.get_activity_name().decode('utf-8') + activity_name = icon.get_activity_name() + if isinstance(activity_name, bytes): + activity_name = activity_name.decode() normalized_name = normalize_string(activity_name) if normalized_name.find(query) > -1: icon.alpha = 1.0 @@ -370,7 +372,9 @@ def _get_selected(self, query): selected = [] for icon in self.get_children(): if icon not in [self._owner_icon, self._activity_icon]: - activity_name = icon.get_activity_name().decode('utf-8') + activity_name = icon.get_activity_name() + if isinstance(activity_name, bytes): + activity_name = activity_name.decode() normalized_name = normalize_string(activity_name) if normalized_name.find(query) > -1: selected.append(icon) diff --git a/src/jarabe/desktop/groupbox.py b/src/jarabe/desktop/groupbox.py index 9cd265e404..056307dd80 100644 --- a/src/jarabe/desktop/groupbox.py +++ b/src/jarabe/desktop/groupbox.py @@ -70,7 +70,7 @@ def _friend_removed_cb(self, data_model, key): icon.destroy() def _toolbar_query_changed_cb(self, toolbar, query): - self._query = normalize_string(query.decode('utf-8')) + self._query = normalize_string(query) for icon in self.get_children(): if hasattr(icon, 'set_filter'): icon.set_filter(self._query) diff --git a/src/jarabe/desktop/homebox.py b/src/jarabe/desktop/homebox.py index 1946c4f870..104439c42c 100644 --- a/src/jarabe/desktop/homebox.py +++ b/src/jarabe/desktop/homebox.py @@ -84,7 +84,7 @@ def __desktop_view_icons_changed_cb(self, model): (self._list_view_index)) def __toolbar_query_changed_cb(self, toolbar, query): - self._query = normalize_string(query.decode('utf-8')) + self._query = normalize_string(query) self._list_view.set_filter(self._query) for i in range(desktop.get_number_of_views()): self._favorites_boxes[i].set_filter(self._query) @@ -173,11 +173,6 @@ def resume(self): def suspend(self): pass - def has_activities(self): - # TODO: Do we need this? - # return self._donut.has_activities() - return False - def set_resume_mode(self, resume_mode, favorite_view=0): self._resume_mode = resume_mode self._favorites_boxes[favorite_view].set_resume_mode(resume_mode) diff --git a/src/jarabe/desktop/keydialog.py b/src/jarabe/desktop/keydialog.py index 5b4057decd..6912002e1b 100644 --- a/src/jarabe/desktop/keydialog.py +++ b/src/jarabe/desktop/keydialog.py @@ -197,8 +197,8 @@ def _get_security(self): def print_security(self): (key, auth_alg) = self._get_security() - print 'Key: %s' % key - print 'Auth: %d' % auth_alg + print('Key: %s' % key) + print('Auth: %d' % auth_alg) def create_security(self): (key, auth_alg) = self._get_security() @@ -254,7 +254,7 @@ def _get_security(self): def print_security(self): key = self._get_security() - print 'Key: %s' % key + print('Key: %s' % key) def create_security(self): wsec = {'psk': self._get_security()} diff --git a/src/jarabe/desktop/meshbox.py b/src/jarabe/desktop/meshbox.py index 6358a712a0..ddc350faf3 100644 --- a/src/jarabe/desktop/meshbox.py +++ b/src/jarabe/desktop/meshbox.py @@ -163,7 +163,7 @@ def set_filter(self, query): self._icon.alpha = _FILTERED_ALPHA else: self._icon.alpha = 1.0 - for icon in self._icons.itervalues(): + for icon in list(self._icons.values()): if hasattr(icon, 'set_filter'): icon.set_filter(query) @@ -284,7 +284,7 @@ def __secrets_request_cb(self, **kwargs): 'SpecificObject') found = False if ap_o != '/': - for net in self._box.wireless_networks.values(): + for net in list(self._box.wireless_networks.values()): if net.find_ap(ap_o) is not None: found = True net.create_keydialog(kwargs['response']) @@ -509,7 +509,8 @@ def _ap_props_changed_cb(self, ap, old_hash_value): hash_value = ap.network_hash() if old_hash_value == hash_value: # no change in network identity, so just update signal strengths - self.wireless_networks[hash_value].update_strength() + if hash_value in self.wireless_networks: + self.wireless_networks[hash_value].update_strength() return # properties change includes a change of the identity of the network @@ -532,7 +533,7 @@ def remove_access_point(self, ap_o): # we don't keep an index of ap object path to network, but since # we'll only ever have a handful of networks, just try them all... - for net in self.wireless_networks.values(): + for net in list(self.wireless_networks.values()): ap = net.find_ap(ap_o) if not ap: continue @@ -581,7 +582,7 @@ def enable_olpc_mesh(self, mesh_device): # the OLPC mesh can be recognised as a "normal" wifi network. remove # any such normal networks if they have been created - for hash_value, net in self.wireless_networks.iteritems(): + for hash_value, net in list(self.wireless_networks.items()): if not net.is_olpc_mesh(): continue @@ -600,17 +601,17 @@ def disable_olpc_mesh(self, mesh_device): def suspend(self): if not self._suspended: self._suspended = True - for net in self.wireless_networks.values() + self._mesh: + for net in list(self.wireless_networks.values()) + self._mesh: net.props.paused = True def resume(self): if self._suspended: self._suspended = False - for net in self.wireless_networks.values() + self._mesh: + for net in list(self.wireless_networks.values()) + self._mesh: net.props.paused = False def _toolbar_query_changed_cb(self, toolbar, query): - self._query = normalize_string(query.decode('utf-8')) + self._query = normalize_string(query) for icon in self.get_children(): if hasattr(icon, 'set_filter'): icon.set_filter(self._query) diff --git a/src/jarabe/desktop/networkviews.py b/src/jarabe/desktop/networkviews.py index 2b0646c029..da45014f0c 100644 --- a/src/jarabe/desktop/networkviews.py +++ b/src/jarabe/desktop/networkviews.py @@ -79,8 +79,8 @@ def __init__(self, initial_ap): self._color = profile.get_color() else: sha_hash = hashlib.sha1() - data = self._ssid + hex(self._flags) - sha_hash.update(data) + data = self._ssid.decode() + hex(self._flags) + sha_hash.update(data.encode('utf-8')) digest = hash(sha_hash.digest()) index = digest % len(xocolor.colors) @@ -204,7 +204,7 @@ def _update_icon(self): if self._mode == network.NM_802_11_MODE_ADHOC and \ network.is_sugar_adhoc_network(self._ssid): channel = max([1] + [ap.channel for ap in - self._access_points.values()]) + list(self._access_points.values())]) if self._device_state == network.NM_DEVICE_STATE_ACTIVATED and \ self._active_ap is not None: icon_name = 'network-adhoc-%s-connected' % channel @@ -297,7 +297,7 @@ def _update_color(self): self.props.alpha = 1.0 def __disconnect_activate_cb(self, item): - ap_paths = self._access_points.keys() + ap_paths = list(self._access_points.keys()) network.disconnect_access_points(ap_paths) def __forget_activate_cb(self, item): @@ -422,7 +422,7 @@ def update_strength(self): # display the strength of the strongest AP that makes up this # network, also considering that there may be no APs new_strength = max([0] + [ap.strength for ap in - self._access_points.values()]) + list(self._access_points.values())]) if new_strength != self._strength: self._strength = new_strength @@ -450,14 +450,14 @@ def find_ap(self, ap_path): return self._access_points[ap_path] def get_first_ap(self): - return self._access_points.values()[0] + return list(self._access_points.values())[0] def is_olpc_mesh(self): return self._mode == network.NM_802_11_MODE_ADHOC \ and self._ssid == 'olpc-mesh' def remove_all_aps(self): - for ap in self._access_points.values(): + for ap in list(self._access_points.values()): ap.disconnect() self._access_points = {} self._active_ap = None diff --git a/src/jarabe/desktop/schoolserver.py b/src/jarabe/desktop/schoolserver.py index 2b022a311e..1947d9f9ca 100644 --- a/src/jarabe/desktop/schoolserver.py +++ b/src/jarabe/desktop/schoolserver.py @@ -15,9 +15,9 @@ import logging from gettext import gettext as _ -import xmlrpclib +import xmlrpc.client import socket -import httplib +import http.client import os from string import ascii_uppercase import random @@ -87,7 +87,7 @@ class RegisterError(Exception): pass -class _TimeoutHTTP(httplib.HTTP): +class _TimeoutHTTP(http.client.HTTPConnection): def __init__(self, host='', port=None, strict=None, timeout=None): if port == 0: @@ -99,7 +99,7 @@ def __init__(self, host='', port=None, strict=None, timeout=None): port, strict, timeout=_REGISTER_TIMEOUT)) -class _TimeoutTransport(xmlrpclib.Transport): +class _TimeoutTransport(xmlrpc.client.Transport): def make_connection(self, host): host, extra_headers, x509_ = self.get_host_info(host) @@ -132,13 +132,13 @@ def register_laptop(url=_REGISTER_URL): url = 'http://' + jabber_server + ':8080/' if sys.hexversion < 0x2070000: - server = xmlrpclib.ServerProxy(url, _TimeoutTransport()) + server = xmlrpc.client.ServerProxy(url, _TimeoutTransport()) else: socket.setdefaulttimeout(_REGISTER_TIMEOUT) - server = xmlrpclib.ServerProxy(url) + server = xmlrpc.client.ServerProxy(url) try: data = server.register(sn, nick, uuid_, profile.pubkey) - except (xmlrpclib.Error, TypeError, socket.error): + except (xmlrpc.client.Error, TypeError, socket.error): logging.exception('Registration: cannot connect to server') raise RegisterError(_('Cannot connect to the server.')) finally: diff --git a/src/jarabe/desktop/snowflakelayout.py b/src/jarabe/desktop/snowflakelayout.py index 98f7209ea6..e5b9d0accb 100644 --- a/src/jarabe/desktop/snowflakelayout.py +++ b/src/jarabe/desktop/snowflakelayout.py @@ -37,7 +37,7 @@ def __init__(self): def do_realize(self): self.set_realized(True) self.set_window(self.get_parent_window()) - for child in self._children.keys(): + for child in list(self._children.keys()): child.set_parent_window(self.get_parent_window()) self.queue_resize() @@ -47,7 +47,7 @@ def do_add(self, child): child.set_parent(self) def do_forall(self, include_internals, callback): - for child in self._children.keys(): + for child in list(self._children.keys()): callback(child) def do_remove(self, child): @@ -91,7 +91,7 @@ def do_size_allocate(self, allocation): r = self._get_radius() index = 0 - for child, centered in self._children.items(): + for child, centered in list(self._children.items()): child_request = child.size_request() child_width, child_height = \ child_request.width, child_request.height @@ -124,7 +124,7 @@ def do_size_allocate(self, allocation): def _get_radius(self): radius = int(_BASE_DISTANCE + _CHILDREN_FACTOR * self._nflakes) - for child, centered in self._children.items(): + for child, centered in list(self._children.items()): if centered: child_request = child.size_request() child_width, child_height = \ @@ -135,7 +135,7 @@ def _get_radius(self): def _calculate_size(self): thickness = 0 - for child in self._children.keys(): + for child in list(self._children.keys()): child_request = child.size_request() child_width, child_height = \ child_request.width, child_request.height diff --git a/src/jarabe/desktop/viewtoolbar.py b/src/jarabe/desktop/viewtoolbar.py index 7b1b203f5c..5a2ddb422f 100644 --- a/src/jarabe/desktop/viewtoolbar.py +++ b/src/jarabe/desktop/viewtoolbar.py @@ -147,6 +147,8 @@ def _entry_activated_cb(self, entry): new_query = entry.props.text if self._query != new_query: self._query = new_query + if isinstance(self._query, bytes): + self._query = self._query.decode() self.emit('query-changed', self._query) def _entry_changed_cb(self, entry): diff --git a/src/jarabe/frame/clipboard.py b/src/jarabe/frame/clipboard.py index a4784357b3..d08ea49348 100644 --- a/src/jarabe/frame/clipboard.py +++ b/src/jarabe/frame/clipboard.py @@ -16,7 +16,7 @@ import logging import os import shutil -import urlparse +import urllib.parse import tempfile from gi.repository import GObject @@ -37,9 +37,9 @@ class Clipboard(GObject.GObject): 'object-added': (GObject.SignalFlags.RUN_FIRST, None, ([object])), 'object-deleted': (GObject.SignalFlags.RUN_FIRST, None, - ([long])), + ([int])), 'object-selected': (GObject.SignalFlags.RUN_FIRST, None, - ([long])), + ([int])), 'object-state-changed': (GObject.SignalFlags.RUN_FIRST, None, ([object])), } @@ -123,18 +123,18 @@ def set_object_percent(self, object_id, percent): def _process_object(self, cb_object): formats = cb_object.get_formats() - for format_name, format_ in formats.iteritems(): + for format_name, format_ in list(formats.items()): if format_.is_on_disk() and not format_.owns_disk_data: new_uri = self._copy_file(format_.get_data()) format_.set_data(new_uri) # Add a text/plain format to objects that are text but lack it - if 'text/plain' not in formats.keys(): - if 'UTF8_STRING' in formats.keys(): + if 'text/plain' not in list(formats.keys()): + if 'UTF8_STRING' in list(formats.keys()): self.add_object_format( cb_object.get_id(), 'text/plain', data=formats['UTF8_STRING'].get_data(), on_disk=False) - elif 'text/unicode' in formats.keys(): + elif 'text/unicode' in list(formats.keys()): self.add_object_format( cb_object.get_id(), 'text/plain', data=formats['UTF8_STRING'].get_data(), on_disk=False) @@ -150,7 +150,7 @@ def get_object_data(self, object_id, format_type): return format_ def _copy_file(self, original_uri): - uri = urlparse.urlparse(original_uri) + uri = urllib.parse.urlparse(original_uri) path = uri.path # pylint: disable=E1101 directory_, file_name = os.path.split(path) diff --git a/src/jarabe/frame/clipboardicon.py b/src/jarabe/frame/clipboardicon.py index 62e2296b31..6a4c3275e2 100644 --- a/src/jarabe/frame/clipboardicon.py +++ b/src/jarabe/frame/clipboardicon.py @@ -197,7 +197,7 @@ def _notify_active_cb(self, widget, pspec): def _get_targets(self): targets = [] - for format_type in self._cb_object.get_formats().keys(): + for format_type in list(self._cb_object.get_formats().keys()): targets.append(Gtk.TargetEntry.new(format_type, Gtk.TargetFlags.SAME_APP, 0)) return targets diff --git a/src/jarabe/frame/clipboardmenu.py b/src/jarabe/frame/clipboardmenu.py index d7c75cfdbb..24ca6d45f9 100644 --- a/src/jarabe/frame/clipboardmenu.py +++ b/src/jarabe/frame/clipboardmenu.py @@ -15,7 +15,7 @@ from gettext import gettext as _ import tempfile -import urlparse +import urllib.parse import os import logging from gi.repository import Gio @@ -187,7 +187,7 @@ def _write_to_temp_file(self, data): return file_path def _copy_to_journal(self): - formats = self._cb_object.get_formats().keys() + formats = list(self._cb_object.get_formats().keys()) most_significant_mime_type = mime.choose_most_significant(formats) format_ = self._cb_object.get_formats()[most_significant_mime_type] @@ -195,7 +195,7 @@ def _copy_to_journal(self): if most_significant_mime_type == 'text/uri-list': uri = format_.get_data() if uri.startswith('file://'): - parsed_url = urlparse.urlparse(uri) + parsed_url = urllib.parse.urlparse(uri) file_path = parsed_url.path # pylint: disable=E1101 transfer_ownership = False mime_type = mime.get_for_file(file_path) @@ -205,7 +205,7 @@ def _copy_to_journal(self): mime_type = 'text/uri-list' else: if format_.is_on_disk(): - parsed_url = urlparse.urlparse(format_.get_data()) + parsed_url = urllib.parse.urlparse(format_.get_data()) file_path = parsed_url.path # pylint: disable=E1101 transfer_ownership = False mime_type = mime.get_for_file(file_path) diff --git a/src/jarabe/frame/clipboardobject.py b/src/jarabe/frame/clipboardobject.py index d0a6c3875a..20935c626b 100644 --- a/src/jarabe/frame/clipboardobject.py +++ b/src/jarabe/frame/clipboardobject.py @@ -15,7 +15,7 @@ import os import logging -import urlparse +import urllib.parse from gi.repository import Gio from gi.repository import Gtk @@ -33,7 +33,7 @@ def __init__(self, object_path, name): self._formats = {} def destroy(self): - for format_ in self._formats.itervalues(): + for format_ in list(self._formats.values()): format_.destroy() def get_id(self): @@ -83,7 +83,7 @@ def is_bundle(self): if not self._formats: return False else: - return self._formats.keys()[0] == ActivityBundle.MIME_TYPE + return list(self._formats.keys())[0] == ActivityBundle.MIME_TYPE def get_percent(self): return self._percent @@ -101,10 +101,10 @@ def get_mime_type(self): if not self._formats: return '' - format_ = mime.choose_most_significant(self._formats.keys()) + format_ = mime.choose_most_significant(list(self._formats.keys())) if format_ == 'text/uri-list': uri_data = self._formats[format_].get_data() - uri = urlparse.urlparse(uri_data, 'file') + uri = urllib.parse.urlparse(uri_data, 'file') scheme = uri.scheme # pylint: disable=E1101 if scheme == 'file': path = uri.path # pylint: disable=E1101 @@ -128,7 +128,7 @@ def __init__(self, mime_type, data, on_disk): def destroy(self): if self._on_disk: - uri = urlparse.urlparse(self._data) + uri = urllib.parse.urlparse(self._data) path = uri.path # pylint: disable=E1101 if os.path.isfile(path): os.remove(path) diff --git a/src/jarabe/frame/clipboardpanelwindow.py b/src/jarabe/frame/clipboardpanelwindow.py index cd6a847def..297b7b3b59 100644 --- a/src/jarabe/frame/clipboardpanelwindow.py +++ b/src/jarabe/frame/clipboardpanelwindow.py @@ -14,7 +14,7 @@ # along with this program. If not, see . import logging -from urlparse import urlparse +from urllib.parse import urlparse import hashlib from gi.repository import Gtk diff --git a/src/jarabe/frame/clipboardtray.py b/src/jarabe/frame/clipboardtray.py index 16bd379bfa..3a5b3df019 100644 --- a/src/jarabe/frame/clipboardtray.py +++ b/src/jarabe/frame/clipboardtray.py @@ -70,7 +70,7 @@ def __init__(self): cb_service.connect('object-deleted', self._object_deleted_cb) def owns_clipboard(self): - for icon in self._icons.values(): + for icon in list(self._icons.values()): if icon.owns_clipboard: return True return False @@ -105,7 +105,7 @@ def _add_selection(self, object_id, selection): def _object_added_cb(self, cb_service, cb_object): if self._icons: - group = self._icons.values()[0] + group = list(self._icons.values())[0] else: group = None diff --git a/src/jarabe/frame/eventarea.py b/src/jarabe/frame/eventarea.py index 02023965d7..24c94ef7ff 100644 --- a/src/jarabe/frame/eventarea.py +++ b/src/jarabe/frame/eventarea.py @@ -146,13 +146,13 @@ def _drag_leave_cb(self, widget, drag_context, timestamp): return True def show(self): - for box in self._boxes.itervalues(): + for box in list(self._boxes.values()): box.show() def hide(self): - for box in self._boxes.itervalues(): + for box in list(self._boxes.values()): box.hide() def _window_stacking_changed_cb(self, screen): - for box in self._boxes.itervalues(): + for box in list(self._boxes.values()): box.get_window().raise_() diff --git a/src/jarabe/intro/window.py b/src/jarabe/intro/window.py index 2c1566098b..bf32834871 100644 --- a/src/jarabe/intro/window.py +++ b/src/jarabe/intro/window.py @@ -18,7 +18,7 @@ import logging from gettext import gettext as _ import pwd -import commands +import subprocess from gi.repository import Gtk from gi.repository import Gdk @@ -81,7 +81,7 @@ def create_profile(user_profile): logging.debug("Generating user keypair") cmd = "ssh-keygen -q -t dsa -f %s -C '' -N ''" % (keypath, ) - (s, o) = commands.getstatusoutput(cmd) + (s, o) = subprocess.getstatusoutput(cmd) if s != 0: logging.error('Could not generate key pair: %d %s', s, o) @@ -365,7 +365,7 @@ def _setup_age_page(self): button_box.show() if not self.PAGES[self._page]: - self.next() + next(self) def _update_next_button(self): self._next_button.set_sensitive(self._current_page.props.valid) @@ -382,9 +382,9 @@ def back(self): self._setup_page() def _next_activated_cb(self, widget): - self.next() + next(self) - def next(self): + def __next__(self): if self._current_page.props.valid or not self.PAGES[self._page]: if self._page == self.PAGE_LAST: self.done() @@ -446,7 +446,7 @@ def _create_profile_cb(self, user_profile): def __key_press_cb(self, widget, event): if Gdk.keyval_name(event.keyval) == 'Return': - self._intro_box.next() + next(self._intro_box) return True elif Gdk.keyval_name(event.keyval) == 'Escape': self._intro_box.back() diff --git a/src/jarabe/journal/expandedentry.py b/src/jarabe/journal/expandedentry.py index 7a99dabfe1..bf63aa4121 100644 --- a/src/jarabe/journal/expandedentry.py +++ b/src/jarabe/journal/expandedentry.py @@ -446,7 +446,7 @@ def _create_buddy_list(self): vbox.pack_start(halign, False, False, 0) if self._metadata.get('buddies'): - buddies = json.loads(self._metadata['buddies']).values() + buddies = list(json.loads(self._metadata['buddies']).values()) vbox.pack_start(BuddyList(buddies), False, False, 0) return vbox else: diff --git a/src/jarabe/journal/journalactivity.py b/src/jarabe/journal/journalactivity.py index d00c7ff465..cfbcb6c40a 100644 --- a/src/jarabe/journal/journalactivity.py +++ b/src/jarabe/journal/journalactivity.py @@ -25,7 +25,6 @@ from gi.repository import GdkX11 from gi.repository import Gio import dbus -import statvfs import os from sugar3.graphics.alert import ErrorAlert @@ -553,7 +552,7 @@ def _check_available_space(self): if self._critical_space_alert: return stat = os.statvfs(env.get_profile_path()) - free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL] + free_space = stat[0] * stat[4] if free_space < (_SPACE_THRESHOLD * 1024 * 1024): self._critical_space_alert = ModalAlert() self._critical_space_alert.connect('destroy', diff --git a/src/jarabe/journal/journaltoolbox.py b/src/jarabe/journal/journaltoolbox.py index 72281f5d47..1b7be6f80a 100644 --- a/src/jarabe/journal/journaltoolbox.py +++ b/src/jarabe/journal/journaltoolbox.py @@ -458,13 +458,7 @@ def refresh_filters(self): 'callback': self._what_palette_cb, 'id': bundle_id}) finally: - def _cmp(a, b): - if a['label'] < b['label']: - return -1 - else: - return 1 - - for item in sorted(what_list_activities, _cmp): + for item in sorted(what_list_activities, key = lambda x:x['label']): self._what_list.append(item) if self._what_widget_contents is not None: diff --git a/src/jarabe/journal/listmodel.py b/src/jarabe/journal/listmodel.py index 6702353071..c577a2e0e5 100644 --- a/src/jarabe/journal/listmodel.py +++ b/src/jarabe/journal/listmodel.py @@ -214,7 +214,7 @@ def do_get_value(self, iterator, column): buddies = [] if metadata.get('buddies'): try: - buddies = json.loads(metadata['buddies']).values() + buddies = list(json.loads(metadata['buddies']).values()) except json.decoder.JSONDecodeError as exception: logging.warning('Cannot decode buddies for %r: %s', metadata['uid'], exception) @@ -224,7 +224,7 @@ def do_get_value(self, iterator, column): metadata['uid'], buddies) buddies = [] - for n_ in xrange(0, 3): + for n_ in range(0, 3): if buddies: try: nick, color = buddies.pop(0) diff --git a/src/jarabe/journal/misc.py b/src/jarabe/journal/misc.py index 4a804e9056..69dab28199 100644 --- a/src/jarabe/journal/misc.py +++ b/src/jarabe/journal/misc.py @@ -422,6 +422,7 @@ def get_mount_color(mount): sha_hash.update(str(time.time())) else: mount_name = os.path.basename(path) + mount_name = mount_name.encode('utf-8') sha_hash.update(mount_name) digest = hash(sha_hash.digest()) diff --git a/src/jarabe/journal/model.py b/src/jarabe/journal/model.py index cefcfbc383..846286a0ec 100644 --- a/src/jarabe/journal/model.py +++ b/src/jarabe/journal/model.py @@ -291,9 +291,8 @@ def setup_ready(self): else: # timestamp keygetter = itemgetter(2) - self._file_list.sort(lambda a, b: cmp(b, a), - key=keygetter, - reverse=(self._sort[0] == '-')) + self._file_list.sort(key=keygetter, + reverse=not self._sort[0] == '-') self.ready.send(self) def find(self, query): @@ -949,7 +948,7 @@ def get_documents_path(): try: pipe = subprocess.Popen(['xdg-user-dir', 'DOCUMENTS'], stdout=subprocess.PIPE) - documents_path = os.path.normpath(pipe.communicate()[0].strip()) + documents_path = os.path.normpath(pipe.communicate()[0].strip().decode()) if os.path.exists(documents_path) and \ os.environ.get('HOME') != documents_path: _documents_path = documents_path diff --git a/src/jarabe/journal/palettes.py b/src/jarabe/journal/palettes.py index d53802df9e..a2084bb540 100644 --- a/src/jarabe/journal/palettes.py +++ b/src/jarabe/journal/palettes.py @@ -627,7 +627,7 @@ def __confirmation_response_cb(self, alert, response): # this is only in the case the operation already started # and the user want stop it. self._stop_batch_execution() - elif hasattr(self, '_object_index') == False: + elif not hasattr(self, '_object_index'): self._object_index = 0 GLib.idle_add(self._operate_by_uid_internal) diff --git a/src/jarabe/journal/projectview.py b/src/jarabe/journal/projectview.py index e1402c4c4d..73f362e040 100644 --- a/src/jarabe/journal/projectview.py +++ b/src/jarabe/journal/projectview.py @@ -113,7 +113,7 @@ def _description_tags_focus_out_event_cb(self, text_view, event): self._update_entry() def _update_entry(self): - #updating description + # updating description bounds = self._description.get_buffer().get_bounds() old_description = self.project_metadata.get('description', None) new_description = self._description.get_buffer().get_text( diff --git a/src/jarabe/journal/volumestoolbar.py b/src/jarabe/journal/volumestoolbar.py index c941b96d7a..db4b057199 100644 --- a/src/jarabe/journal/volumestoolbar.py +++ b/src/jarabe/journal/volumestoolbar.py @@ -16,7 +16,6 @@ import logging import os -import statvfs from gettext import gettext as _ from gi.repository import GObject @@ -24,7 +23,7 @@ from gi.repository import GLib from gi.repository import Gtk from gi.repository import Gdk -import cPickle +import pickle import xapian import json import tempfile @@ -100,8 +99,8 @@ def _convert_entries(root): def _convert_entry(root, document): try: - metadata_loaded = cPickle.loads(document.get_data()) - except cPickle.PickleError as e: + metadata_loaded = pickle.loads(document.get_data()) + except pickle.PickleError as e: logging.debug('Convert DS-0 Journal entries: ' 'error converting metadata: %s', e) return @@ -117,7 +116,7 @@ def _convert_entry(root, document): if uid is None: return - for key, value in metadata_loaded.items(): + for key, value in list(metadata_loaded.items()): metadata[str(key)] = str(value[0]) if 'uid' not in metadata: @@ -368,8 +367,8 @@ def __init__(self, mount): def __popup_cb(self, palette): stat = os.statvfs(env.get_profile_path()) - free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL] - total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS] + free_space = stat[0] * stat[4] + total_space = stat[0] * stat[2] fraction = (total_space - free_space) / float(total_space) self._progress_bar.props.fraction = fraction diff --git a/src/jarabe/main.py b/src/jarabe/main.py index c84664e95c..fbdd1135f1 100755 --- a/src/jarabe/main.py +++ b/src/jarabe/main.py @@ -28,11 +28,6 @@ import subprocess import shutil -# Change the default encoding to avoid UnicodeDecodeError -# http://lists.sugarlabs.org/archive/sugar-devel/2012-August/038928.html -reload(sys) -sys.setdefaultencoding('utf-8') - # Disable overlay scrolling before GTK is loaded os.environ['GTK_OVERLAY_SCROLLING'] = '0' os.environ['LIBOVERLAY_SCROLLBAR'] = '0' @@ -247,7 +242,7 @@ def cleanup_temporary_files(): except OSError as e: # temporary files cleanup is not critical; it should not prevent # sugar from starting if (for example) the disk is full or read-only. - print 'temporary files cleanup failed: %s' % e + print('temporary files cleanup failed: %s' % e) def setup_timezone(): @@ -377,7 +372,7 @@ def main(): try: Gtk.main() except KeyboardInterrupt: - print 'Ctrl+C pressed, exiting...' + print('Ctrl+C pressed, exiting...') _stop_window_manager() diff --git a/src/jarabe/model/adhoc.py b/src/jarabe/model/adhoc.py index bc5ba172ce..e7172ce666 100644 --- a/src/jarabe/model/adhoc.py +++ b/src/jarabe/model/adhoc.py @@ -269,7 +269,7 @@ def is_sugar_adhoc_access_point(self, ap_object_path): Return: Boolean """ - for access_point in self._networks.values(): + for access_point in list(self._networks.values()): if access_point is not None: if access_point.model.object_path == ap_object_path: return True diff --git a/src/jarabe/model/brightness.py b/src/jarabe/model/brightness.py index 77ab270805..717385bf6b 100644 --- a/src/jarabe/model/brightness.py +++ b/src/jarabe/model/brightness.py @@ -81,7 +81,7 @@ def _helper_read(self, option): result, output, error, status = GLib.spawn_command_line_sync(cmd) if status != 0: return None - return output.rstrip('\0\n') + return output.rstrip(b'\0\n') def _helper_write(self, option, value): cmd = 'pkexec sugar-backlight-helper --%s %d' % (option, value) diff --git a/src/jarabe/model/buddy.py b/src/jarabe/model/buddy.py index d561d6bb67..6683a52bb8 100644 --- a/src/jarabe/model/buddy.py +++ b/src/jarabe/model/buddy.py @@ -160,6 +160,8 @@ def _sync_properties_on_connection(self, connection): if CONNECTION_INTERFACE_BUDDY_INFO in connection: properties = {} if self.props.key is not None: + if isinstance(self.props.key, str): + self.props.key = self.props.key.encode() properties['key'] = dbus.ByteArray(self.props.key) if self.props.color is not None: properties['color'] = self.props.color.to_string() diff --git a/src/jarabe/model/bundleregistry.py b/src/jarabe/model/bundleregistry.py index 97ffe169ae..fb238f3ba2 100644 --- a/src/jarabe/model/bundleregistry.py +++ b/src/jarabe/model/bundleregistry.py @@ -196,12 +196,12 @@ def _load_favorites(self): if not isinstance(favorite_bundles, dict): raise ValueError('Invalid format in %s.' % favorites_path) if favorite_bundles: - first_key = favorite_bundles.keys()[0] - if not isinstance(first_key, basestring): + first_key = list(favorite_bundles.keys())[0] + if not isinstance(first_key, str): raise ValueError('Invalid format in %s.' % favorites_path) - first_value = favorite_bundles.values()[0] + first_value = list(favorite_bundles.values())[0] if first_value is not None and \ not isinstance(first_value, dict): raise ValueError('Invalid format in %s.' % @@ -222,7 +222,7 @@ def _load_hidden_activities(self): def _convert_old_favorites(self): for i in range(desktop.get_number_of_views()): - for key in self._favorite_bundles[i].keys(): + for key in list(self._favorite_bundles[i].keys()): data = self._favorite_bundles[i][key] if data is None: data = {} @@ -273,8 +273,8 @@ def _scan_directory(self, path): logging.exception('Error while processing installed activity' ' bundle %s:', bundle_dir) - bundle_dirs = bundles.keys() - bundle_dirs.sort(lambda d1, d2: cmp(bundles[d1], bundles[d2])) + bundle_dirs = list(bundles.keys()) + bundle_dirs.sort(key=lambda x: bundles[x]) for folder in bundle_dirs: try: self.add_bundle(folder, emit_signals=False) diff --git a/src/jarabe/model/filetransfer.py b/src/jarabe/model/filetransfer.py index 06b043a6b5..5ca5d84ae6 100644 --- a/src/jarabe/model/filetransfer.py +++ b/src/jarabe/model/filetransfer.py @@ -365,7 +365,7 @@ def file_transfer_available(): test_file_name = '/home/humitos/test.py' test_temp_file = tempfile.mkstemp()[1] - print test_temp_file + print(test_temp_file) test_input_stream = Gio.File.new_for_path(test_file_name).read(None) test_output_stream = Gio.File.new_for_path(test_temp_file)\ .append_to(Gio.FileCreateFlags.PRIVATE, None) diff --git a/src/jarabe/model/friends.py b/src/jarabe/model/friends.py index 524b336a6c..c1d9460acc 100644 --- a/src/jarabe/model/friends.py +++ b/src/jarabe/model/friends.py @@ -15,7 +15,7 @@ import os import logging -from ConfigParser import ConfigParser +from configparser import ConfigParser from gi.repository import GObject @@ -135,7 +135,7 @@ def remove(self, buddy_info): self.emit('friend-removed', buddy_info.get_key()) def __iter__(self): - return self._friends.values().__iter__() + return list(self._friends.values()).__iter__() def load(self): cp = ConfigParser() diff --git a/src/jarabe/model/invites.py b/src/jarabe/model/invites.py index c35da33c45..4ad0ebfccb 100644 --- a/src/jarabe/model/invites.py +++ b/src/jarabe/model/invites.py @@ -292,7 +292,7 @@ def remove_invite(self, invite): self.emit('invite-removed', invite) def __iter__(self): - return self._dispatch_operations.values().__iter__() + return list(self._dispatch_operations.values()).__iter__() def get_instance(): diff --git a/src/jarabe/model/neighborhood.py b/src/jarabe/model/neighborhood.py index be5e9faa92..86c35a4ab7 100644 --- a/src/jarabe/model/neighborhood.py +++ b/src/jarabe/model/neighborhood.py @@ -335,11 +335,11 @@ def _update_status(self, status): 'Connection.GetSelfHandle')) self.emit('connected') else: - for contact_handle, contact_id in self._buddy_handles.items(): + for contact_handle, contact_id in list(self._buddy_handles.items()): if contact_id is not None: self.emit('buddy-removed', contact_id) - for room_handle, activity_id in self._activity_handles.items(): + for room_handle, activity_id in list(self._activity_handles.items()): self.emit('activity-removed', activity_id) self._buddy_handles = {} @@ -442,7 +442,7 @@ def __active_activity_changed_cb(self, model, home_activity): room_handle = 0 home_activity_id = home_activity.get_activity_id() - for handle, activity_id in self._activity_handles.items(): + for handle, activity_id in list(self._activity_handles.items()): if home_activity_id == activity_id: room_handle = handle break @@ -477,7 +477,7 @@ def __aliases_changed_cb(self, aliases): def __presences_changed_cb(self, presences): logging.debug('_Account.__presences_changed_cb %r', presences) - for handle, presence in presences.iteritems(): + for handle, presence in list(presences.items()): if handle in self._buddy_handles: presence_type, status_, message_ = presence if presence_type == CONNECTION_PRESENCE_TYPE_OFFLINE: @@ -653,9 +653,9 @@ def __got_buddy_info_cb(self, handle, nick, properties): def __get_contact_attributes_cb(self, attributes): logging.debug('_Account.__get_contact_attributes_cb %r', - attributes.keys()) + list(attributes.keys())) - for handle in attributes.keys(): + for handle in list(attributes.keys()): nick = attributes[handle][CONNECTION_INTERFACE_ALIASING + '/alias'] if handle == self._self_handle: @@ -815,7 +815,7 @@ def _get_published_name(self): the room name, the published name and the host name. """ - public_key_hash = sha1(get_profile().pubkey).hexdigest() + public_key_hash = sha1(get_profile().pubkey.encode('utf-8')).hexdigest() return public_key_hash[:8] def _ensure_link_local_account(self, account_paths): @@ -893,7 +893,7 @@ def _ensure_server_account(self, account_paths): return _Account(account_path) def _get_jabber_account_id(self): - public_key_hash = sha1(get_profile().pubkey).hexdigest() + public_key_hash = sha1(get_profile().pubkey.encode('utf-8')).hexdigest() server = self._settings_collaboration.get_string('jabber-server') return '%s@%s' % (public_key_hash, server) @@ -1108,16 +1108,16 @@ def __buddy_left_activity_cb(self, account, contact_id, activity_id): self._activities[activity_id].remove_buddy(self._buddies[contact_id]) def get_buddies(self): - return self._buddies.values() + return list(self._buddies.values()) def get_buddy_by_key(self, key): - for buddy in self._buddies.values(): + for buddy in list(self._buddies.values()): if buddy.key == key: return buddy return None def get_buddy_by_handle(self, contact_handle): - for buddy in self._buddies.values(): + for buddy in list(self._buddies.values()): if not buddy.is_owner() and buddy.handle == contact_handle: return buddy return None @@ -1126,13 +1126,13 @@ def get_activity(self, activity_id): return self._activities.get(activity_id, None) def get_activity_by_room(self, room_handle): - for activity in self._activities.values(): + for activity in list(self._activities.values()): if activity.room_handle == room_handle: return activity return None def get_activities(self): - return self._activities.values() + return list(self._activities.values()) def get_model(): diff --git a/src/jarabe/model/network.py b/src/jarabe/model/network.py index 4a8672801c..d27b53b705 100644 --- a/src/jarabe/model/network.py +++ b/src/jarabe/model/network.py @@ -25,7 +25,7 @@ import dbus import dbus.service from gi.repository import GObject -import ConfigParser +import configparser from gi.repository import Gio import ctypes @@ -701,7 +701,7 @@ def network_hash(self): else: fl |= 1 << 6 - hashstr = str(fl) + '@' + self.ssid + hashstr = str(fl) + '@' + self.ssid.decode() return hash(hashstr) def _update_properties(self, properties): @@ -957,12 +957,12 @@ def _migrate_old_wifi_connections(): if not os.path.exists(config_path): return - config = ConfigParser.ConfigParser() + config = configparser.ConfigParser() try: if not config.read(config_path): logging.error('Error reading the nm config file') return - except ConfigParser.ParsingError: + except configparser.ParsingError: logging.exception('Error reading the nm config file') return @@ -1005,7 +1005,7 @@ def _migrate_old_wifi_connections(): if config.has_option(section, 'pairwise'): value = config.get(section, 'pairwise') settings.wireless_security.pairwise = value - except ConfigParser.Error: + except configparser.Error: logging.exception('Error reading section') else: add_connection(settings) @@ -1095,7 +1095,7 @@ def _is_non_printable(char): """ Return True if char is a non-printable unicode character, False otherwise """ - return (char < u' ') or (u'~' < char < u'\xA0') or (char == u'\xAD') + return (char < ' ') or ('~' < char < '\xA0') or (char == '\xAD') def ssid_to_display_name(ssid): @@ -1123,7 +1123,7 @@ def ssid_to_display_name(ssid): """ for encoding in ['utf-8', 'iso-8859-1', 'windows-1251']: try: - display_name = unicode(ssid, encoding) + display_name = str(ssid, encoding) except UnicodeDecodeError: continue diff --git a/src/jarabe/model/screenshot.py b/src/jarabe/model/screenshot.py index 036dd7eb5a..3f2f261393 100644 --- a/src/jarabe/model/screenshot.py +++ b/src/jarabe/model/screenshot.py @@ -17,7 +17,7 @@ import os import tempfile from gettext import gettext as _ -import StringIO +import io import cairo from gi.repository import Gdk @@ -114,6 +114,6 @@ def _get_preview_data(screenshot_surface): cr.set_source_surface(screenshot_surface) cr.paint() - preview_str = StringIO.StringIO() + preview_str = io.StringIO() preview_surface.write_to_png(preview_str) return dbus.ByteArray(preview_str.getvalue()) diff --git a/src/jarabe/model/telepathyclient.py b/src/jarabe/model/telepathyclient.py index db214541d9..ff213a6b4d 100644 --- a/src/jarabe/model/telepathyclient.py +++ b/src/jarabe/model/telepathyclient.py @@ -151,7 +151,7 @@ def Set(self, interface_name, property_name, value): def GetAll(self, interface_name): if interface_name in self._prop_getters: r = {} - for k, v in self._prop_getters[interface_name].items(): + for k, v in list(self._prop_getters[interface_name].items()): r[k] = v() return r else: diff --git a/src/jarabe/model/update/aslo.py b/src/jarabe/model/update/aslo.py index 943d1d0481..033039d620 100644 --- a/src/jarabe/model/update/aslo.py +++ b/src/jarabe/model/update/aslo.py @@ -128,7 +128,7 @@ def __downloader_complete_cb(self, downloader, result): link = document.find(_FIND_LINK).text try: - size = long(document.find(_FIND_SIZE).text) * 1024 + size = int(document.find(_FIND_SIZE).text) * 1024 except ValueError: _logger.exception('Exception occurred while parsing size') size = 0 diff --git a/src/jarabe/model/update/microformat.py b/src/jarabe/model/update/microformat.py index 447f01f9fb..e100be0ff4 100644 --- a/src/jarabe/model/update/microformat.py +++ b/src/jarabe/model/update/microformat.py @@ -27,11 +27,11 @@ import logging from tempfile import NamedTemporaryFile -from StringIO import StringIO -from ConfigParser import ConfigParser +from io import StringIO +from configparser import ConfigParser from zipfile import ZipFile -from urlparse import urljoin -from HTMLParser import HTMLParser +from urllib.parse import urljoin +from html.parser import HTMLParser from gi.repository import GLib from gi.repository import GObject @@ -231,7 +231,7 @@ def _filter_results(self): # version installed. Queue the remaining ones to be checked. registry = bundleregistry.get_registry() self._bundles_to_check = [] - for bundle_id, data in self._parser.results.iteritems(): + for bundle_id, data in list(self._parser.results.items()): # filter optional activities for automatic updates if self._auto and data[2] is True: logging.debug('filtered optional activity %s', bundle_id) @@ -365,7 +365,7 @@ def run(self): try: name = self._do_name_lookup() self._complete(name) - except Exception, e: + except Exception as e: self._complete(e) def _do_name_lookup(self): diff --git a/src/jarabe/util/downloader.py b/src/jarabe/util/downloader.py index 3a82589626..9c3e0f8148 100644 --- a/src/jarabe/util/downloader.py +++ b/src/jarabe/util/downloader.py @@ -16,7 +16,7 @@ import os -from urlparse import urlparse +from urllib.parse import urlparse import tempfile import gi @@ -81,7 +81,7 @@ def _setup_message(self, method="GET"): self._message.connect('got-chunk', self._got_chunk_cb) self._message.connect('got-headers', self._headers_cb, None) if self._request_headers is not None: - for header_key in self._request_headers.keys(): + for header_key in list(self._request_headers.keys()): self._message.request_headers.append( header_key, self._request_headers[header_key]) diff --git a/src/jarabe/util/normalize.py b/src/jarabe/util/normalize.py index b6aea5ef9a..276f051a0a 100644 --- a/src/jarabe/util/normalize.py +++ b/src/jarabe/util/normalize.py @@ -18,7 +18,7 @@ def normalize_string(unicode_string): - u"""Return unicode_string normalized for searching. + """Return unicode_string normalized for searching. >>> normalize_string(u'Mónica Viñao') 'monica vinao' @@ -27,4 +27,4 @@ def normalize_string(unicode_string): 'abaco' """ - return normalize('NFKD', unicode_string).encode('ASCII', 'ignore').lower() + return normalize('NFKD', unicode_string).lower() diff --git a/src/jarabe/util/telepathy/connection_watcher.py b/src/jarabe/util/telepathy/connection_watcher.py index 1c2ae9d3a5..7ba5d72fbc 100644 --- a/src/jarabe/util/telepathy/connection_watcher.py +++ b/src/jarabe/util/telepathy/connection_watcher.py @@ -137,7 +137,7 @@ def _remove_connection(self, service_name, path): self.emit('connection-removed', conn) def get_connections(self): - return self._connections.values() + return list(self._connections.values()) def __error_handler_cb(exception): logging.debug('Exception from asynchronous method call:\n%s' % exception) @@ -154,10 +154,10 @@ def get_instance(): dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) def connection_added_cb(conn_watcher, conn): - print 'new connection', conn["service_name"] + print('new connection', conn["service_name"]) def connection_removed_cb(conn_watcher, conn): - print 'removed connection', conn["service_name"] + print('removed connection', conn["service_name"]) watcher = ConnectionWatcher() watcher.connect('connection-added', connection_added_cb) diff --git a/src/jarabe/view/buddyicon.py b/src/jarabe/view/buddyicon.py index a54b3d7f61..8847a9aaa6 100644 --- a/src/jarabe/view/buddyicon.py +++ b/src/jarabe/view/buddyicon.py @@ -66,8 +66,11 @@ def _update_color(self): palette.props.icon.props.xo_color = self._buddy.get_color() def set_filter(self, query): - normalized_name = normalize_string( - self._buddy.get_nick().decode('utf-8')) + if isinstance(self._buddy.get_nick(), bytes): + nick = self._buddy.get_nick().decode() + else: + nick = self._buddy.get_nick() + normalized_name = normalize_string(nick) self._filtered = (normalized_name.find(query) == -1) \ and not self._buddy.is_owner() self._update_color() diff --git a/src/jarabe/view/keyhandler.py b/src/jarabe/view/keyhandler.py index df98b5c9cd..91ae7f6173 100644 --- a/src/jarabe/view/keyhandler.py +++ b/src/jarabe/view/keyhandler.py @@ -101,7 +101,7 @@ def __init__(self, frame): except Exception: logging.exception('Exception while loading extension:') - self._key_grabber.grab_keys(_actions_table.keys()) + self._key_grabber.grab_keys(list(_actions_table.keys())) def _change_volume(self, step=None, value=None): if step is not None: @@ -193,7 +193,7 @@ def handle_open_controlpanel(self, event_time): panel.show() def handle_dump_ui_tree(self, event_time): - print uitree.get_root().dump() + print(uitree.get_root().dump()) def _key_pressed_cb(self, grabber, keycode, state, event_time): key = grabber.get_key(keycode, state) @@ -221,7 +221,7 @@ def _key_pressed_cb(self, grabber, keycode, state, event_time): if hasattr(action, 'handle_key_press'): action.handle_key_press(key) - elif isinstance(action, basestring): + elif isinstance(action, str): method = getattr(self, 'handle_' + action) method(event_time) else: diff --git a/src/jarabe/view/palettes.py b/src/jarabe/view/palettes.py index dba57a1f90..51a527479e 100644 --- a/src/jarabe/view/palettes.py +++ b/src/jarabe/view/palettes.py @@ -15,7 +15,6 @@ import os import signal -import statvfs from gettext import gettext as _ import logging @@ -255,8 +254,8 @@ def __open_activate_cb(self, menu_item): def __popup_cb(self, palette): stat = os.statvfs(env.get_profile_path()) - free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL] - total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS] + free_space = stat[0] * stat[4] + total_space = stat[0] * stat[2] fraction = (total_space - free_space) / float(total_space) self._progress_bar.props.fraction = fraction @@ -322,8 +321,8 @@ def __unmount_cb(self, mount, result, user_data): def __popup_cb(self, palette): mount_point = self._mount.get_root().get_path() stat = os.statvfs(mount_point) - free_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BAVAIL] - total_space = stat[statvfs.F_BSIZE] * stat[statvfs.F_BLOCKS] + free_space = stat[0] * stat[4] + total_space = stat[0] * stat[2] fraction = (total_space - free_space) / float(total_space) self._progress_bar.props.fraction = fraction diff --git a/src/jarabe/view/viewhelp.py b/src/jarabe/view/viewhelp.py index f7d8a1a4d9..fa02c1d1f9 100644 --- a/src/jarabe/view/viewhelp.py +++ b/src/jarabe/view/viewhelp.py @@ -36,7 +36,7 @@ try: - olpc_build = file('/boot/olpc_build', 'r').readline() + olpc_build = open('/boot/olpc_build', 'r').readline() except: olpc_build = '' @@ -114,7 +114,7 @@ def get_help_url_and_title(activity): _logger.error('helplink.json malformed, or can\'t be read') if links: - if link_id in links.keys(): + if link_id in list(links.keys()): return links[link_id], title return None, title diff --git a/src/jarabe/view/viewhelp_webkit1.py b/src/jarabe/view/viewhelp_webkit1.py index 8ae7841e27..b0b47e993c 100644 --- a/src/jarabe/view/viewhelp_webkit1.py +++ b/src/jarabe/view/viewhelp_webkit1.py @@ -103,7 +103,7 @@ def load_state(self, state, url): def _items_history_as_list(self, history): back_items = [] - for n in reversed(range(1, history.get_back_length() + 1)): + for n in reversed(list(range(1, history.get_back_length() + 1))): item = history.get_nth_item(n * -1) back_items.append(item) diff --git a/src/jarabe/webservice/accountsmanager.py b/src/jarabe/webservice/accountsmanager.py index 98daef73b7..c7c52d28ab 100644 --- a/src/jarabe/webservice/accountsmanager.py +++ b/src/jarabe/webservice/accountsmanager.py @@ -102,7 +102,7 @@ def get_all_accounts(): _ensure_module_repository() accounts = [] - for service, service_info in _module_repository.iteritems(): + for service, service_info in list(_module_repository.items()): accounts.append(service_info['account']) return accounts diff --git a/tests/extensions/cpsection/webaccount/web_service.py b/tests/extensions/cpsection/webaccount/web_service.py index 3c8c0fe2df..998acb120d 100644 --- a/tests/extensions/cpsection/webaccount/web_service.py +++ b/tests/extensions/cpsection/webaccount/web_service.py @@ -14,7 +14,6 @@ # along with this program. If not, see . - class WebService(): def get_icon_name(self): raise "Not implemented" diff --git a/tests/test_downloader.py b/tests/test_downloader.py index 6dd2787463..4b82f7e259 100644 --- a/tests/test_downloader.py +++ b/tests/test_downloader.py @@ -16,8 +16,8 @@ import os import unittest import threading -import SimpleHTTPServer -import SocketServer +import http.server +import socketserver from gi.repository import Gtk from gi.repository import GLib @@ -37,8 +37,8 @@ class TestDownloader(unittest.TestCase): def setUp(self): - handler = SimpleHTTPServer.SimpleHTTPRequestHandler - self._server = SocketServer.TCPServer(("", 0), handler) + handler = http.server.SimpleHTTPRequestHandler + self._server = socketserver.TCPServer(("", 0), handler) self._port = self._server.server_address[1] self._server_thread = threading.Thread(target=self._run_http_server) self._server_thread.daemon = True diff --git a/tests/test_microformat.py b/tests/test_microformat.py index 8d396e9dd9..4ce3ebe4f3 100644 --- a/tests/test_microformat.py +++ b/tests/test_microformat.py @@ -33,8 +33,8 @@ def test_html_parser(self): parser.close() results = parser.results - self.assertIn('org.sugarlabs.AbacusActivity', results.keys()) - self.assertIn('org.laptop.WebActivity', results.keys()) + self.assertIn('org.sugarlabs.AbacusActivity', list(results.keys())) + self.assertIn('org.laptop.WebActivity', list(results.keys())) # test that we picked the newest version version, url = results['org.sugarlabs.AbacusActivity']