pythonifying code:

- replace has_key() by key in dict
- remove len() method from sequence and mapping types when mapping to bool
This commit is contained in:
M2j 2012-04-29 17:31:56 +02:00
parent ac3655135e
commit c6c62bdcad
30 changed files with 87 additions and 117 deletions

View File

@ -209,7 +209,7 @@ class Theme(object):
val = int(element_text[1:], 16) val = int(element_text[1:], 16)
except ValueError: # nope except ValueError: # nope
pass pass
elif DELPHI_COLORS.has_key(element_text): elif element_text in DELPHI_COLORS:
val = DELPHI_COLORS[element_text] val = DELPHI_COLORS[element_text]
delphi_color_change = True delphi_color_change = True
else: else:

View File

@ -730,7 +730,7 @@ class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
if self.liveController.display.isVisible(): if self.liveController.display.isVisible():
self.liveController.display.setFocus() self.liveController.display.setFocus()
self.activateWindow() self.activateWindow()
if len(self.arguments): if self.arguments:
args = [] args = []
for a in self.arguments: for a in self.arguments:
args.extend([a]) args.extend([a])

View File

@ -127,7 +127,7 @@ class MediaController(object):
invalidMediaPlayers = [mediaPlayer for mediaPlayer in savedPlayers \ invalidMediaPlayers = [mediaPlayer for mediaPlayer in savedPlayers \
if not mediaPlayer in self.mediaPlayers or \ if not mediaPlayer in self.mediaPlayers or \
not self.mediaPlayers[mediaPlayer].check_available()] not self.mediaPlayers[mediaPlayer].check_available()]
if len(invalidMediaPlayers) > 0: if invalidMediaPlayers:
for invalidPlayer in invalidMediaPlayers: for invalidPlayer in invalidMediaPlayers:
savedPlayers.remove(invalidPlayer) savedPlayers.remove(invalidPlayer)
set_media_players(savedPlayers, overriddenPlayer) set_media_players(savedPlayers, overriddenPlayer)
@ -141,7 +141,7 @@ class MediaController(object):
Check if there is a running media Player and do updating stuff (e.g. Check if there is a running media Player and do updating stuff (e.g.
update the UI) update the UI)
""" """
if len(self.curDisplayMediaPlayer.keys()) == 0: if not self.curDisplayMediaPlayer:
self.timer.stop() self.timer.stop()
else: else:
for display in self.curDisplayMediaPlayer.keys(): for display in self.curDisplayMediaPlayer.keys():

View File

@ -483,7 +483,7 @@ class ServiceManager(QtGui.QWidget):
service_item = item[u'service_item'].get_service_repr() service_item = item[u'service_item'].get_service_repr()
# Get all the audio files, and ready them for embedding in the # Get all the audio files, and ready them for embedding in the
# service file. # service file.
if len(service_item[u'header'][u'background_audio']) > 0: if service_item[u'header'][u'background_audio']:
for i, filename in \ for i, filename in \
enumerate(service_item[u'header'][u'background_audio']): enumerate(service_item[u'header'][u'background_audio']):
new_file = os.path.join(u'audio', new_file = os.path.join(u'audio',
@ -822,7 +822,7 @@ class ServiceManager(QtGui.QWidget):
""" """
Called by the SlideController to select the next service item. Called by the SlideController to select the next service item.
""" """
if len(self.serviceManagerList.selectedItems()) == 0: if not self.serviceManagerList.selectedItems():
return return
selected = self.serviceManagerList.selectedItems()[0] selected = self.serviceManagerList.selectedItems()[0]
lookFor = 0 lookFor = 0
@ -840,7 +840,7 @@ class ServiceManager(QtGui.QWidget):
""" """
Called by the SlideController to select the previous service item. Called by the SlideController to select the previous service item.
""" """
if len(self.serviceManagerList.selectedItems()) == 0: if not self.serviceManagerList.selectedItems():
return return
selected = self.serviceManagerList.selectedItems()[0] selected = self.serviceManagerList.selectedItems()[0]
prevItem = None prevItem = None

View File

@ -151,7 +151,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
if action is None: if action is None:
continue continue
shortcuts = self._actionShortcuts(action) shortcuts = self._actionShortcuts(action)
if len(shortcuts) == 0: if not shortcuts:
item.setText(1, u'') item.setText(1, u'')
item.setText(2, u'') item.setText(2, u'')
elif len(shortcuts) == 1: elif len(shortcuts) == 1:
@ -195,7 +195,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
return return
shortcuts = self._actionShortcuts(action) shortcuts = self._actionShortcuts(action)
new_shortcuts = [] new_shortcuts = []
if len(shortcuts) != 0: if shortcuts:
new_shortcuts.append(shortcuts[0]) new_shortcuts.append(shortcuts[0])
new_shortcuts.append( new_shortcuts.append(
QtGui.QKeySequence(self.alternatePushButton.text())) QtGui.QKeySequence(self.alternatePushButton.text()))
@ -241,7 +241,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
self.primaryPushButton.setChecked(False) self.primaryPushButton.setChecked(False)
self.alternatePushButton.setChecked(False) self.alternatePushButton.setChecked(False)
else: else:
if len(action.defaultShortcuts) != 0: if action.defaultShortcuts:
primary_label_text = action.defaultShortcuts[0].toString() primary_label_text = action.defaultShortcuts[0].toString()
if len(action.defaultShortcuts) == 2: if len(action.defaultShortcuts) == 2:
alternate_label_text = action.defaultShortcuts[1].toString() alternate_label_text = action.defaultShortcuts[1].toString()
@ -313,7 +313,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
self.refreshShortcutList() self.refreshShortcutList()
primary_button_text = u'' primary_button_text = u''
alternate_button_text = u'' alternate_button_text = u''
if len(temp_shortcuts) != 0: if temp_shortcuts:
primary_button_text = temp_shortcuts[0].toString() primary_button_text = temp_shortcuts[0].toString()
if len(temp_shortcuts) == 2: if len(temp_shortcuts) == 2:
alternate_button_text = temp_shortcuts[1].toString() alternate_button_text = temp_shortcuts[1].toString()
@ -363,7 +363,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
return return
shortcuts = self._actionShortcuts(action) shortcuts = self._actionShortcuts(action)
new_shortcuts = [] new_shortcuts = []
if len(action.defaultShortcuts) != 0: if action.defaultShortcuts:
new_shortcuts.append(action.defaultShortcuts[0]) new_shortcuts.append(action.defaultShortcuts[0])
# We have to check if the primary default shortcut is available. But # We have to check if the primary default shortcut is available. But
# we only have to check, if the action has a default primary # we only have to check, if the action has a default primary
@ -391,7 +391,7 @@ class ShortcutListForm(QtGui.QDialog, Ui_ShortcutListDialog):
return return
shortcuts = self._actionShortcuts(action) shortcuts = self._actionShortcuts(action)
new_shortcuts = [] new_shortcuts = []
if len(shortcuts) != 0: if shortcuts:
new_shortcuts.append(shortcuts[0]) new_shortcuts.append(shortcuts[0])
if len(action.defaultShortcuts) == 2: if len(action.defaultShortcuts) == 2:
new_shortcuts.append(action.defaultShortcuts[1]) new_shortcuts.append(action.defaultShortcuts[1])

View File

@ -555,7 +555,7 @@ class SlideController(Controller):
Process the service item request queue. The key presses can arrive Process the service item request queue. The key presses can arrive
faster than the processing so implement a FIFO queue. faster than the processing so implement a FIFO queue.
""" """
if len(self.keypress_queue): if self.keypress_queue:
while len(self.keypress_queue) and not self.keypress_loop: while len(self.keypress_queue) and not self.keypress_loop:
self.keypress_loop = True self.keypress_loop = True
keypressCommand = self.keypress_queue.popleft() keypressCommand = self.keypress_queue.popleft()
@ -694,7 +694,7 @@ class SlideController(Controller):
if item.is_text(): if item.is_text():
if QtCore.QSettings().value( if QtCore.QSettings().value(
self.parent().songsSettingsSection + u'/display songbar', self.parent().songsSettingsSection + u'/display songbar',
QtCore.QVariant(True)).toBool() and len(self.slideList) > 0: QtCore.QVariant(True)).toBool() and self.slideList:
self.songMenu.show() self.songMenu.show()
if item.is_capable(ItemCapabilities.CanLoop) and \ if item.is_capable(ItemCapabilities.CanLoop) and \
len(item.get_frames()) > 1: len(item.get_frames()) > 1:

View File

@ -444,7 +444,7 @@ class ThemeManager(QtGui.QWidget):
self.firstTime() self.firstTime()
files = SettingsManager.get_files(self.settingsSection, u'.png') files = SettingsManager.get_files(self.settingsSection, u'.png')
# No themes have been found so create one # No themes have been found so create one
if len(files) == 0: if not files:
theme = ThemeXML() theme = ThemeXML()
theme.theme_name = UiStrings().Default theme.theme_name = UiStrings().Default
self._writeTheme(theme, None, None) self._writeTheme(theme, None, None)

View File

@ -267,7 +267,7 @@ def get_application_version():
if code != 0: if code != 0:
raise Exception(u'Error running bzr tags') raise Exception(u'Error running bzr tags')
lines = output.splitlines() lines = output.splitlines()
if len(lines) == 0: if not lines:
tag = u'0.0.0' tag = u'0.0.0'
revision = u'0' revision = u'0'
else: else:

View File

@ -90,7 +90,7 @@ class CategoryActionList(object):
def append(self, name): def append(self, name):
weight = 0 weight = 0
if len(self.actions) > 0: if self.actions:
weight = self.actions[-1][0] + 1 weight = self.actions[-1][0] + 1
self.add(name, weight) self.add(name, weight)
@ -156,7 +156,7 @@ class CategoryList(object):
def append(self, name, actions=None): def append(self, name, actions=None):
weight = 0 weight = 0
if len(self.categories) > 0: if self.categories:
weight = self.categories[-1].weight + 1 weight = self.categories[-1].weight + 1
if actions: if actions:
self.add(name, weight, actions) self.add(name, weight, actions)

View File

@ -101,7 +101,7 @@ class AlertForm(QtGui.QDialog, Ui_AlertDialog):
self.alertTextEdit.setText(u'') self.alertTextEdit.setText(u'')
def onNewClick(self): def onNewClick(self):
if len(self.alertTextEdit.text()) == 0: if not self.alertTextEdit.text():
QtGui.QMessageBox.information(self, QtGui.QMessageBox.information(self,
translate('AlertsPlugin.AlertForm', 'New Alert'), translate('AlertsPlugin.AlertForm', 'New Alert'),
translate('AlertsPlugin.AlertForm', 'You haven\'t specified ' translate('AlertsPlugin.AlertForm', 'You haven\'t specified '

View File

@ -62,7 +62,7 @@ class BiblePlugin(Plugin):
# unicode(UiStrings().Export)) # unicode(UiStrings().Export))
# Set to invisible until we can export bibles # Set to invisible until we can export bibles
self.exportBibleItem.setVisible(False) self.exportBibleItem.setVisible(False)
if len(self.manager.old_bible_databases): if self.manager.old_bible_databases:
self.toolsUpgradeItem.setVisible(True) self.toolsUpgradeItem.setVisible(True)
def finalise(self): def finalise(self):
@ -83,7 +83,7 @@ class BiblePlugin(Plugin):
""" """
Perform tasks on application startup Perform tasks on application startup
""" """
if len(self.manager.old_bible_databases): if self.manager.old_bible_databases:
if QtGui.QMessageBox.information(self.formParent, if QtGui.QMessageBox.information(self.formParent,
translate('OpenLP', 'Information'), translate('OpenLP', translate('OpenLP', 'Information'), translate('OpenLP',
'Bible format has changed.\nYou have to upgrade your ' 'Bible format has changed.\nYou have to upgrade your '

View File

@ -426,8 +426,7 @@ class BibleUpgradeForm(OpenLPWizard):
if meta[u'key'] == u'download_source': if meta[u'key'] == u'download_source':
web_bible = True web_bible = True
self.includeWebBible = True self.includeWebBible = True
if meta.has_key(u'proxy_server'): proxy_server = meta.get(u'proxy_server')
proxy_server = meta[u'proxy_server']
if web_bible: if web_bible:
if meta_data[u'download_source'].lower() == u'crosswalk': if meta_data[u'download_source'].lower() == u'crosswalk':
handler = CWExtract(proxy_server) handler = CWExtract(proxy_server)
@ -572,7 +571,7 @@ class BibleUpgradeForm(OpenLPWizard):
int(verse[u'verse']), unicode(verse[u'text'])) int(verse[u'verse']), unicode(verse[u'text']))
Receiver.send_message(u'openlp_process_events') Receiver.send_message(u'openlp_process_events')
self.newbibles[number].session.commit() self.newbibles[number].session.commit()
if self.success.has_key(number) and not self.success[number]: if not self.success.get(number, True):
self.incrementProgressBar(unicode(translate( self.incrementProgressBar(unicode(translate(
'BiblesPlugin.UpgradeWizardForm', 'BiblesPlugin.UpgradeWizardForm',
'Upgrading Bible %s of %s: "%s"\nFailed')) % 'Upgrading Bible %s of %s: "%s"\nFailed')) %
@ -586,7 +585,7 @@ class BibleUpgradeForm(OpenLPWizard):
'Upgrading Bible %s of %s: "%s"\n' 'Upgrading Bible %s of %s: "%s"\n'
'Complete')) % 'Complete')) %
(number + 1, max_bibles, name)) (number + 1, max_bibles, name))
if self.newbibles.has_key(number): if number in self.newbibles:
self.newbibles[number].session.close() self.newbibles[number].session.close()
# Close the last bible's connection if possible. # Close the last bible's connection if possible.
if old_bible is not None: if old_bible is not None:
@ -599,7 +598,7 @@ class BibleUpgradeForm(OpenLPWizard):
successful_import = 0 successful_import = 0
failed_import = 0 failed_import = 0
for number, filename in enumerate(self.files): for number, filename in enumerate(self.files):
if self.success.has_key(number) and self.success[number]: if self.success.get(number):
successful_import += 1 successful_import += 1
elif self.checkBox[number].checkState() == QtCore.Qt.Checked: elif self.checkBox[number].checkState() == QtCore.Qt.Checked:
failed_import += 1 failed_import += 1

View File

@ -236,7 +236,7 @@ def get_reference_separator(separator_type):
``separator_type`` ``separator_type``
The role and format of the separator. The role and format of the separator.
""" """
if len(REFERENCE_SEPARATORS) == 0: if not REFERENCE_SEPARATORS:
update_reference_separators() update_reference_separators()
return REFERENCE_SEPARATORS[separator_type] return REFERENCE_SEPARATORS[separator_type]
@ -247,7 +247,7 @@ def get_reference_match(match_type):
``match_type`` ``match_type``
The type of match is ``range_separator``, ``range`` or ``full``. The type of match is ``range_separator``, ``range`` or ``full``.
""" """
if len(REFERENCE_MATCHES) == 0: if not REFERENCE_MATCHES:
update_reference_separators() update_reference_separators()
return REFERENCE_MATCHES[match_type] return REFERENCE_MATCHES[match_type]

View File

@ -106,7 +106,7 @@ class BGExtract(object):
verse_list = {} verse_list = {}
# Cater for inconsistent mark up in the first verse of a chapter. # Cater for inconsistent mark up in the first verse of a chapter.
first_verse = verses.find(u'versenum') first_verse = verses.find(u'versenum')
if first_verse and len(first_verse.contents): if first_verse and first_verse.contents:
verse_list[1] = unicode(first_verse.contents[0]) verse_list[1] = unicode(first_verse.contents[0])
for verse in verses(u'sup', u'versenum'): for verse in verses(u'sup', u'versenum'):
raw_verse_num = verse.next raw_verse_num = verse.next

View File

@ -392,7 +392,7 @@ class BibleMediaItem(MediaManagerItem):
if bible in bibles: if bible in bibles:
find_and_set_in_combo_box(self.advancedVersionComboBox, bible) find_and_set_in_combo_box(self.advancedVersionComboBox, bible)
self.initialiseAdvancedBible(unicode(bible)) self.initialiseAdvancedBible(unicode(bible))
elif len(bibles): elif bibles:
self.initialiseAdvancedBible(bibles[0]) self.initialiseAdvancedBible(bibles[0])
bible = QtCore.QSettings().value( bible = QtCore.QSettings().value(
self.settingsSection + u'/quick bible', QtCore.QVariant( self.settingsSection + u'/quick bible', QtCore.QVariant(
@ -878,7 +878,7 @@ class BibleMediaItem(MediaManagerItem):
items = item items = item
else: else:
items = self.listView.selectedItems() items = self.listView.selectedItems()
if len(items) == 0: if not items:
return False return False
bible_text = u'' bible_text = u''
old_item = None old_item = None
@ -949,7 +949,7 @@ class BibleMediaItem(MediaManagerItem):
# Service Item: Title # Service Item: Title
service_item.title = create_separated_list(raw_title) service_item.title = create_separated_list(raw_title)
# Service Item: Theme # Service Item: Theme
if len(self.settings.bible_theme) == 0: if not self.settings.bible_theme:
service_item.theme = None service_item.theme = None
else: else:
service_item.theme = self.settings.bible_theme service_item.theme = self.settings.bible_theme

View File

@ -254,7 +254,7 @@ class EditCustomForm(QtGui.QDialog, Ui_CustomEditDialog):
Checks whether a custom is valid or not. Checks whether a custom is valid or not.
""" """
# We must have a title. # We must have a title.
if len(self.titleEdit.displayText()) == 0: if not self.titleEdit.displayText():
self.titleEdit.setFocus() self.titleEdit.setFocus()
critical_error_message_box( critical_error_message_box(
message=translate('CustomPlugin.EditCustomForm', message=translate('CustomPlugin.EditCustomForm',

View File

@ -258,7 +258,7 @@ class CustomMediaItem(MediaManagerItem):
search_length = 2 search_length = 2
if len(text) > search_length: if len(text) > search_length:
self.onSearchTextButtonClicked() self.onSearchTextButtonClicked()
elif len(text) == 0: elif not text:
self.onClearTextButtonClick() self.onClearTextButtonClick()
def onClearTextButtonClick(self): def onClearTextButtonClick(self):

View File

@ -191,13 +191,13 @@ class EditVerseForm(QtGui.QDialog, Ui_EditVerseDialog):
else: else:
log.debug(unicode(self.getVerse()[0]).split(u'\n')) log.debug(unicode(self.getVerse()[0]).split(u'\n'))
value = unicode(self.getVerse()[0]).split(u'\n')[1] value = unicode(self.getVerse()[0]).split(u'\n')[1]
if len(value) == 0: if not value:
lines = unicode(self.getVerse()[0]).split(u'\n') lines = unicode(self.getVerse()[0]).split(u'\n')
index = 2 index = 2
while index < len(lines) and len(value) == 0: while index < len(lines) and not value:
value = lines[index] value = lines[index]
index += 1 index += 1
if len(value) == 0: if not value:
critical_error_message_box( critical_error_message_box(
message=translate('SongsPlugin.EditSongForm', message=translate('SongsPlugin.EditSongForm',
'You need to type some text in to the verse.')) 'You need to type some text in to the verse.'))

View File

@ -108,7 +108,7 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
item_id = self._getCurrentItemId(list_widget) item_id = self._getCurrentItemId(list_widget)
if item_id != -1: if item_id != -1:
item = self.manager.get_object(item_class, item_id) item = self.manager.get_object(item_class, item_id)
if item and len(item.songs) == 0: if item and not item.songs:
if critical_error_message_box(dlg_title, del_text, self, if critical_error_message_box(dlg_title, del_text, self,
True) == QtGui.QMessageBox.Yes: True) == QtGui.QMessageBox.Yes:
self.manager.delete_object(item_class, item.id) self.manager.delete_object(item_class, item.id)
@ -191,7 +191,7 @@ class SongMaintenanceForm(QtGui.QDialog, Ui_SongMaintenanceDialog):
``edit`` ``edit``
If we edit an item, this should be *True*. If we edit an item, this should be *True*.
""" """
if len(objects) > 0: if objects:
# If we edit an existing object, we need to make sure that we do # If we edit an existing object, we need to make sure that we do
# not return False when nothing has changed. # not return False when nothing has changed.
if edit: if edit:

View File

@ -316,7 +316,7 @@ def clean_song(manager, song):
verse_type, verse_type,
verse[0][u'label'], verse[0][u'label'],
verse[1], verse[1],
verse[0][u'lang'] if verse[0].has_key(u'lang') else None verse[0].get(u'lang')
) )
compare_order.append((u'%s%s' % (verse_type, verse[0][u'label']) compare_order.append((u'%s%s' % (verse_type, verse[0][u'label'])
).upper()) ).upper())

View File

@ -211,7 +211,7 @@ class CCLIFileImport(SongImport):
elif verse_lines[0].startswith(u'('): elif verse_lines[0].startswith(u'('):
verse_type = VerseType.Tags[VerseType.Other] verse_type = VerseType.Tags[VerseType.Other]
verse_text = verse_lines[1] verse_text = verse_lines[1]
if len(verse_text) > 0: if verse_text:
self.addVerse(verse_text, verse_type) self.addVerse(verse_text, verse_type)
check_first_verse_line = False check_first_verse_line = False
# Handle multiple authors # Handle multiple authors

View File

@ -162,15 +162,12 @@ class EasySlidesImport(SongImport):
separatorlines = 0 separatorlines = 0
for line in lines: for line in lines:
line = line.strip() line = line.strip()
if len(line) == 0: if not line:
continue continue
elif line[1:7] == u'region': elif line[1:7] == u'region':
# this is region separator, probably [region 2] # this is region separator, probably [region 2]
region = self._extractRegion(line) region = self._extractRegion(line)
if regionlines.has_key(region): regionlines[region] = 1 + regionlines.get(region, 0)
regionlines[region] = regionlines[region] + 1
else:
regionlines[region] = 1
elif line[0] == u'[': elif line[0] == u'[':
separatorlines = separatorlines + 1 separatorlines = separatorlines + 1
# if the song has separators # if the song has separators
@ -206,7 +203,7 @@ class EasySlidesImport(SongImport):
for line in lines: for line in lines:
line = line.strip() line = line.strip()
if len(line) == 0: if not line:
if separators: if separators:
# separators are used, so empty line means slide break # separators are used, so empty line means slide break
# inside verse # inside verse
@ -215,15 +212,11 @@ class EasySlidesImport(SongImport):
else: else:
# separators are not used, so empty line starts a new verse # separators are not used, so empty line starts a new verse
vt = u'V' vt = u'V'
if verses[reg].has_key(vt): vn = len(verses[reg].get(vt, {})) + 1
vn = len(verses[reg][vt].keys())+1
else:
vn = u'1'
inst = 1 inst = 1
elif line[0:7] == u'[region': elif line[0:7] == u'[region':
reg = self._extractRegion(line) reg = self._extractRegion(line)
if not verses.has_key(reg): verses.setdefault(reg, {})
verses[reg] = {}
if not regionsInVerses: if not regionsInVerses:
vt = u'V' vt = u'V'
vn = u'1' vn = u'1'
@ -238,12 +231,7 @@ class EasySlidesImport(SongImport):
if match: if match:
marker = match.group(1).strip() marker = match.group(1).strip()
vn = match.group(2) vn = match.group(2)
if len(marker) == 0: vt = MarkTypes.get(marker, u'O') if marker else u'V'
vt = u'V'
elif MarkTypes.has_key(marker):
vt = MarkTypes[marker]
else:
vt = u'O'
if regionsInVerses: if regionsInVerses:
region = defaultregion region = defaultregion
inst = 1 inst = 1
@ -252,14 +240,10 @@ class EasySlidesImport(SongImport):
else: else:
if not [reg, vt, vn, inst] in our_verse_order: if not [reg, vt, vn, inst] in our_verse_order:
our_verse_order.append([reg, vt, vn, inst]) our_verse_order.append([reg, vt, vn, inst])
if not verses[reg].has_key(vt): verses[reg].setdefault(vt, {})
verses[reg][vt] = {} verses[reg][vt].setdefault(vn, {})
if not verses[reg][vt].has_key(vn): verses[reg][vt][vn].setdefault(inst, [])
verses[reg][vt][vn] = {} verses[reg][vt][vn][inst].append(self.tidyText(line))
if not verses[reg][vt][vn].has_key(inst):
verses[reg][vt][vn][inst] = []
words = self.tidyText(line)
verses[reg][vt][vn][inst].append(words)
# done parsing # done parsing
versetags = [] versetags = []
@ -286,11 +270,11 @@ class EasySlidesImport(SongImport):
try: try:
order = unicode(song.Sequence).strip().split(u',') order = unicode(song.Sequence).strip().split(u',')
for tag in order: for tag in order:
if len(tag) == 0: if not tag:
continue continue
elif tag[0].isdigit(): elif tag[0].isdigit():
tag = u'V' + tag tag = u'V' + tag
elif SeqTypes.has_key(tag.lower()): elif tag.lower() in SeqTypes:
tag = SeqTypes[tag.lower()] tag = SeqTypes[tag.lower()]
else: else:
continue continue
@ -307,9 +291,7 @@ class EasySlidesImport(SongImport):
def _listHas(self, lst, subitems): def _listHas(self, lst, subitems):
for subitem in subitems: for subitem in subitems:
if isinstance(lst, dict) and lst.has_key(subitem): if subitem in lst:
lst = lst[subitem]
elif isinstance(lst, list) and subitem in lst:
lst = lst[subitem] lst = lst[subitem]
else: else:
return False return False

View File

@ -62,15 +62,15 @@ def strip_rtf(blob, encoding):
if control: if control:
# for delimiters, set control to False # for delimiters, set control to False
if c == '{': if c == '{':
if len(control_word) > 0: if control_word:
depth += 1 depth += 1
control = False control = False
elif c == '}': elif c == '}':
if len(control_word) > 0: if control_word:
depth -= 1 depth -= 1
control = False control = False
elif c == '\\': elif c == '\\':
new_control = (len(control_word) > 0) new_control = bool(control_word)
control = False control = False
elif c.isspace(): elif c.isspace():
control = False control = False
@ -79,7 +79,7 @@ def strip_rtf(blob, encoding):
if len(control_word) == 3 and control_word[0] == '\'': if len(control_word) == 3 and control_word[0] == '\'':
control = False control = False
if not control: if not control:
if len(control_word) == 0: if not control_word:
if c == '{' or c == '}' or c == '\\': if c == '{' or c == '}' or c == '\\':
clear_text.append(c) clear_text.append(c)
else: else:
@ -360,7 +360,7 @@ class EasyWorshipSongImport(SongImport):
field_desc = self.fieldDescs[field_desc_index] field_desc = self.fieldDescs[field_desc_index]
# Return None in case of 'blank' entries # Return None in case of 'blank' entries
if isinstance(field, str): if isinstance(field, str):
if len(field.rstrip('\0')) == 0: if not field.rstrip('\0'):
return None return None
elif field == 0: elif field == 0:
return None return None

View File

@ -295,9 +295,8 @@ class SongMediaItem(MediaManagerItem):
log.debug(u'display results Book') log.debug(u'display results Book')
self.listView.clear() self.listView.clear()
for book in searchresults: for book in searchresults:
songs = sorted(book.songs, key=lambda song: int( songs = sorted(book.songs, key=lambda song:
re.sub(r'[^0-9]', u' ', song.song_number).partition(' ')[0]) int(re.match(r'[0-9]+', u'0' + song.song_number).group()))
if len(re.sub(r'[^\w]', ' ', song.song_number)) else 0)
for song in songs: for song in songs:
# Do not display temporary songs # Do not display temporary songs
if song.temporary: if song.temporary:
@ -331,7 +330,7 @@ class SongMediaItem(MediaManagerItem):
search_length = 3 search_length = 3
if len(text) > search_length: if len(text) > search_length:
self.onSearchTextButtonClicked() self.onSearchTextButtonClicked()
elif len(text) == 0: elif not text:
self.onClearTextButtonClick() self.onClearTextButtonClick()
def onImportClick(self): def onImportClick(self):
@ -491,7 +490,7 @@ class SongMediaItem(MediaManagerItem):
else: else:
# Loop through the verse list and expand the song accordingly. # Loop through the verse list and expand the song accordingly.
for order in song.verse_order.lower().split(): for order in song.verse_order.lower().split():
if len(order) == 0: if not order:
break break
for verse in verseList: for verse in verseList:
if verse[0][u'type'][0].lower() == order[0] and \ if verse[0][u'type'][0].lower() == order[0] and \
@ -530,7 +529,7 @@ class SongMediaItem(MediaManagerItem):
u'authors': u', '.join(author_list)} u'authors': u', '.join(author_list)}
service_item.xml_version = self.openLyrics.song_to_xml(song) service_item.xml_version = self.openLyrics.song_to_xml(song)
# Add the audio file to the service item. # Add the audio file to the service item.
if len(song.media_files) > 0: if song.media_files:
service_item.add_capability(ItemCapabilities.HasBackgroundAudio) service_item.add_capability(ItemCapabilities.HasBackgroundAudio)
service_item.background_audio = \ service_item.background_audio = \
[m.file_name for m in song.media_files] [m.file_name for m in song.media_files]
@ -575,12 +574,12 @@ class SongMediaItem(MediaManagerItem):
editId = song.id editId = song.id
break break
# If there's any backing tracks, copy them over. # If there's any backing tracks, copy them over.
if len(item.background_audio) > 0: if item.background_audio:
self._updateBackgroundAudio(song, item) self._updateBackgroundAudio(song, item)
if add_song and self.addSongFromService: if add_song and self.addSongFromService:
song = self.openLyrics.xml_to_song(item.xml_version) song = self.openLyrics.xml_to_song(item.xml_version)
# If there's any backing tracks, copy them over. # If there's any backing tracks, copy them over.
if len(item.background_audio) > 0: if item.background_audio:
self._updateBackgroundAudio(song, item) self._updateBackgroundAudio(song, item)
editId = song.id editId = song.id
self.onSearchTextButtonClicked() self.onSearchTextButtonClicked()
@ -588,7 +587,7 @@ class SongMediaItem(MediaManagerItem):
# Make sure we temporary import formatting tags. # Make sure we temporary import formatting tags.
song = self.openLyrics.xml_to_song(item.xml_version, True) song = self.openLyrics.xml_to_song(item.xml_version, True)
# If there's any backing tracks, copy them over. # If there's any backing tracks, copy them over.
if len(item.background_audio) > 0: if item.background_audio:
self._updateBackgroundAudio(song, item) self._updateBackgroundAudio(song, item)
editId = song.id editId = song.id
temporary = True temporary = True

View File

@ -122,8 +122,7 @@ class OpenLP1SongImport(SongImport):
cursor.execute( cursor.execute(
u'SELECT settingsid FROM songs WHERE songid = %s' % song_id) u'SELECT settingsid FROM songs WHERE songid = %s' % song_id)
theme_id = cursor.fetchone()[0] theme_id = cursor.fetchone()[0]
if themes.has_key(theme_id): self.themeName = themes.get(theme_id, u'')
self.themeName = themes[theme_id]
verses = lyrics.split(u'\n\n') verses = lyrics.split(u'\n\n')
for verse in verses: for verse in verses:
if verse.strip(): if verse.strip():
@ -191,7 +190,7 @@ class OpenLP1SongImport(SongImport):
# Detect charset by songs. # Detect charset by songs.
cursor.execute(u'SELECT name FROM sqlite_master ' cursor.execute(u'SELECT name FROM sqlite_master '
u'WHERE type = \'table\' AND name = \'tracks\'') u'WHERE type = \'table\' AND name = \'tracks\'')
if len(cursor.fetchall()) > 0: if cursor.fetchall():
cursor.execute(u'SELECT fulltrackname FROM tracks') cursor.execute(u'SELECT fulltrackname FROM tracks')
tracks = cursor.fetchall() tracks = cursor.fetchall()
for track in tracks: for track in tracks:

View File

@ -174,7 +174,7 @@ class OpenSongImport(SongImport):
if semicolon >= 0: if semicolon >= 0:
this_line = this_line[:semicolon] this_line = this_line[:semicolon]
this_line = this_line.strip() this_line = this_line.strip()
if not len(this_line): if not this_line:
continue continue
# skip guitar chords and page and column breaks # skip guitar chords and page and column breaks
if this_line.startswith(u'.') or this_line.startswith(u'---') \ if this_line.startswith(u'.') or this_line.startswith(u'---') \
@ -197,15 +197,12 @@ class OpenSongImport(SongImport):
# the verse tag # the verse tag
verse_tag = content verse_tag = content
verse_num = u'1' verse_num = u'1'
if len(verse_tag) == 0: verse_index = VerseType.from_loose_input(verse_tag) \
verse_index = 0 if verse_tag else 0
else:
verse_index = VerseType.from_loose_input(verse_tag)
verse_tag = VerseType.Tags[verse_index] verse_tag = VerseType.Tags[verse_index]
inst = 1 inst = 1
if [verse_tag, verse_num, inst] in our_verse_order \ if [verse_tag, verse_num, inst] in our_verse_order \
and verses.has_key(verse_tag) \ and verse_num in verses.get(verse_tag, {}):
and verses[verse_tag].has_key(verse_num):
inst = len(verses[verse_tag][verse_num]) + 1 inst = len(verses[verse_tag][verse_num]) + 1
continue continue
# number at start of line.. it's verse number # number at start of line.. it's verse number
@ -213,11 +210,9 @@ class OpenSongImport(SongImport):
verse_num = this_line[0] verse_num = this_line[0]
this_line = this_line[1:].strip() this_line = this_line[1:].strip()
our_verse_order.append([verse_tag, verse_num, inst]) our_verse_order.append([verse_tag, verse_num, inst])
if not verses.has_key(verse_tag): verses.setdefault(verse_tag, {})
verses[verse_tag] = {} verses[verse_tag].setdefault(verse_num, {})
if not verses[verse_tag].has_key(verse_num): if inst not in verses[verse_tag][verse_num]:
verses[verse_tag][verse_num] = {}
if not verses[verse_tag][verse_num].has_key(inst):
verses[verse_tag][verse_num][inst] = [] verses[verse_tag][verse_num][inst] = []
our_verse_order.append([verse_tag, verse_num, inst]) our_verse_order.append([verse_tag, verse_num, inst])
# Tidy text and remove the ____s from extended words # Tidy text and remove the ____s from extended words
@ -252,15 +247,14 @@ class OpenSongImport(SongImport):
if match is not None: if match is not None:
verse_tag = match.group(1) verse_tag = match.group(1)
verse_num = match.group(2) verse_num = match.group(2)
if not len(verse_tag): if not verse_tag:
verse_tag = VerseType.Tags[VerseType.Verse] verse_tag = VerseType.Tags[VerseType.Verse]
else: else:
# Assume it's no.1 if there are no digits # Assume it's no.1 if there are no digits
verse_tag = verse_def verse_tag = verse_def
verse_num = u'1' verse_num = u'1'
verse_def = u'%s%s' % (verse_tag, verse_num) verse_def = u'%s%s' % (verse_tag, verse_num)
if verses.has_key(verse_tag) and \ if verse_num in verses.get(verse_tag, {}):
verses[verse_tag].has_key(verse_num):
self.verseOrderList.append(verse_def) self.verseOrderList.append(verse_def)
else: else:
log.info(u'Got order %s but not in verse tags, dropping' log.info(u'Got order %s but not in verse tags, dropping'

View File

@ -61,9 +61,9 @@ class SongImport(QtCore.QObject):
""" """
self.manager = manager self.manager = manager
QtCore.QObject.__init__(self) QtCore.QObject.__init__(self)
if kwargs.has_key(u'filename'): if u'filename' in kwargs:
self.importSource = kwargs[u'filename'] self.importSource = kwargs[u'filename']
elif kwargs.has_key(u'filenames'): elif u'filenames' in kwargs:
self.importSource = kwargs[u'filenames'] self.importSource = kwargs[u'filenames']
else: else:
raise KeyError(u'Keyword arguments "filename[s]" not supplied.') raise KeyError(u'Keyword arguments "filename[s]" not supplied.')
@ -273,7 +273,7 @@ class SongImport(QtCore.QObject):
Author not checked here, if no author then "Author unknown" is Author not checked here, if no author then "Author unknown" is
automatically added automatically added
""" """
if not self.title or not len(self.verses): if not self.title or not self.verses:
return False return False
else: else:
return True return True
@ -314,13 +314,10 @@ class SongImport(QtCore.QObject):
verse_def = new_verse_def verse_def = new_verse_def
sxml.add_verse_to_lyrics(verse_tag, verse_def[1:], verse_text, lang) sxml.add_verse_to_lyrics(verse_tag, verse_def[1:], verse_text, lang)
song.lyrics = unicode(sxml.extract_xml(), u'utf-8') song.lyrics = unicode(sxml.extract_xml(), u'utf-8')
if not len(self.verseOrderList) and \ if not self.verseOrderList and self.verseOrderListGeneratedUseful:
self.verseOrderListGeneratedUseful:
self.verseOrderList = self.verseOrderListGenerated self.verseOrderList = self.verseOrderListGenerated
for i, current_verse_def in enumerate(self.verseOrderList): self.verseOrderList = map(lambda v: verses_changed_to_other.get(v, v),
if verses_changed_to_other.has_key(current_verse_def): self.verseOrderList)
self.verseOrderList[i] = \
verses_changed_to_other[current_verse_def]
song.verse_order = u' '.join(self.verseOrderList) song.verse_order = u' '.join(self.verseOrderList)
song.copyright = self.copyright song.copyright = self.copyright
song.comments = self.comments song.comments = self.comments

View File

@ -204,7 +204,7 @@ class SongShowPlusImport(SongImport):
elif verse_type == "pre-chorus": elif verse_type == "pre-chorus":
verse_tag = VerseType.Tags[VerseType.PreChorus] verse_tag = VerseType.Tags[VerseType.PreChorus]
else: else:
if not self.otherList.has_key(verse_name): if verse_name not in self.otherList:
if ignore_unique: if ignore_unique:
return None return None
self.otherCount = self.otherCount + 1 self.otherCount = self.otherCount + 1

View File

@ -611,7 +611,7 @@ class OpenLyrics(object):
text += u'{%s}' % element.get(u'name') text += u'{%s}' % element.get(u'name')
# Some formattings may have only start tag. # Some formattings may have only start tag.
# Handle this case if element has no children and contains no text. # Handle this case if element has no children and contains no text.
if len(element) == 0 and not element.text: if not element and not element.text:
use_endtag = False use_endtag = False
# Append text from element. # Append text from element.
if element.text: if element.text:

View File

@ -239,7 +239,7 @@ class SongsPlugin(Plugin):
for sfile in os.listdir(db_dir): for sfile in os.listdir(db_dir):
if sfile.startswith(u'songs_') and sfile.endswith(u'.sqlite'): if sfile.startswith(u'songs_') and sfile.endswith(u'.sqlite'):
song_dbs.append(os.path.join(db_dir, sfile)) song_dbs.append(os.path.join(db_dir, sfile))
if len(song_dbs) == 0: if not song_dbs:
return return
progress = QtGui.QProgressDialog(self.formParent) progress = QtGui.QProgressDialog(self.formParent)
progress.setWindowModality(QtCore.Qt.WindowModal) progress.setWindowModality(QtCore.Qt.WindowModal)