Merge pull request #111 from Dpeta/lint-req

Fix a decent amount of pylint errors, run autoflake + pyupgrade
This commit is contained in:
Dpeta 2023-01-26 21:59:32 +01:00 committed by GitHub
commit 48e994b9cf
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
26 changed files with 270 additions and 307 deletions

View file

@ -1,3 +1,4 @@
"""
# vim: set autoindent ts=4 sts=4 sw=4 textwidth=79 expandtab:
# -*- coding=UTF-8; tab-width: 4 -*-
# import os
@ -550,3 +551,4 @@ class ConsoleInput(QtWidgets.QLineEdit):
parent.text.area.keyPressEvent(event)
else:
super(ConsoleInput, self).keyPressEvent(event)
"""

View file

@ -1,4 +1,3 @@
import sys
import logging
from string import Template
from time import strftime
@ -12,7 +11,6 @@ except ImportError:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction, QShortcut
import ostools
from dataobjs import PesterHistory
from parsetools import convertTags, lexMessage, mecmd, colorBegin, colorEnd, smiledict
import parsetools
@ -23,7 +21,7 @@ PchumLog = logging.getLogger("pchumLogger")
class PesterTabWindow(QtWidgets.QFrame):
def __init__(self, mainwindow, parent=None, convo="convo"):
super(PesterTabWindow, self).__init__(parent)
super().__init__(parent)
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_QuitOnClose, False)
self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
self.mainwindow = mainwindow
@ -337,7 +335,7 @@ class PesterTabWindow(QtWidgets.QFrame):
class PesterMovie(QtGui.QMovie):
def __init__(self, parent):
super(PesterMovie, self).__init__(parent)
super().__init__(parent)
self.textwindow = parent
@QtCore.pyqtSlot(int)
@ -374,7 +372,7 @@ class PesterMovie(QtGui.QMovie):
class PesterText(QtWidgets.QTextEdit):
def __init__(self, theme, parent=None):
super(PesterText, self).__init__(parent)
super().__init__(parent)
if hasattr(self.parent(), "mainwindow"):
self.mainwindow = self.parent().mainwindow
else:
@ -390,6 +388,7 @@ class PesterText(QtWidgets.QTextEdit):
self.textSelected = False
self.copyAvailable[bool].connect(self.textReady)
self.urls = {}
self.lastmsg = None
for k in smiledict:
self.addAnimation(
QtCore.QUrl("smilies/%s" % (smiledict[k])),
@ -549,9 +548,13 @@ class PesterText(QtWidgets.QTextEdit):
and not parent.isBot(chum.handle)
):
idlethreshhold = 60
if (
not hasattr(self, "lastmsg")
) or datetime.now() - self.lastmsg > timedelta(0, idlethreshhold):
do_idle_send = False
if self.lastmsg is None:
do_idle_send = True
else:
if datetime.now() - self.lastmsg > timedelta(0, idlethreshhold):
do_idle_send = True
if do_idle_send:
verb = window.theme["convo/text/idle"]
idlemsg = me.idlemsg(systemColor, verb)
parent.textArea.append(convertTags(idlemsg))
@ -589,7 +592,7 @@ class PesterText(QtWidgets.QTextEdit):
parent.textInput.keyPressEvent(event)
# Pass to the normal handler.
super(PesterText, self).keyPressEvent(event)
super().keyPressEvent(event)
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.MouseButton.LeftButton:
@ -642,7 +645,7 @@ class PesterInput(QtWidgets.QLineEdit):
stylesheet_path = "convo/input/style"
def __init__(self, theme, parent=None):
super(PesterInput, self).__init__(parent)
super().__init__(parent)
self.changeTheme(theme)
def changeTheme(self, theme):
@ -657,7 +660,7 @@ class PesterInput(QtWidgets.QLineEdit):
def focusInEvent(self, event):
self.parent().clearNewMessage()
self.parent().textArea.textCursor().clearSelection()
super(PesterInput, self).focusInEvent(event)
super().focusInEvent(event)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key.Key_Up:
@ -672,12 +675,12 @@ class PesterInput(QtWidgets.QLineEdit):
elif event.key() in [QtCore.Qt.Key.Key_PageUp, QtCore.Qt.Key.Key_PageDown]:
self.parent().textArea.keyPressEvent(event)
self.parent().mainwindow.idler.time = 0
super(PesterInput, self).keyPressEvent(event)
super().keyPressEvent(event)
class PesterConvo(QtWidgets.QFrame):
def __init__(self, chum, initiated, mainwindow, parent=None):
super(PesterConvo, self).__init__(parent)
super().__init__(parent)
self.setAttribute(QtCore.Qt.WidgetAttribute.WA_QuitOnClose, False)
self.setObjectName(chum.handle)
self.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
@ -686,7 +689,7 @@ class PesterConvo(QtWidgets.QFrame):
theme = self.mainwindow.theme
self.resize(*theme["convo/size"])
self.setStyleSheet(
"QtWidgets.QFrame#%s { %s }" % (chum.handle, theme["convo/style"])
"QtWidgets.QFrame#{} {{ {} }}".format(chum.handle, theme["convo/style"])
)
self.setWindowIcon(self.icon())
self.setWindowTitle(self.title())
@ -995,7 +998,7 @@ class PesterConvo(QtWidgets.QFrame):
def closeEvent(self, event):
self.mainwindow.waitingMessages.messageAnswered(self.title())
for movie in self.textArea.urls:
for movie in self.textArea.urls.copy():
movie.setFileName("") # Required, sometimes, for some reason. . .
movie.stop()
del movie
@ -1007,7 +1010,9 @@ class PesterConvo(QtWidgets.QFrame):
def changeTheme(self, theme):
self.resize(*theme["convo/size"])
self.setStyleSheet(
"QtWidgets.QFrame#%s { %s }" % (self.chum.handle, theme["convo/style"])
"QtWidgets.QFrame#{} {{ {} }}".format(
self.chum.handle, theme["convo/style"]
)
)
margins = theme["convo/margins"]

View file

@ -1,5 +1,4 @@
import logging
import ostools
PchumLog = logging.getLogger("pchumLogger")
try:
@ -34,7 +33,7 @@ _memore = re.compile(r"(\s|^)(#[A-Za-z0-9_]+)")
_handlere = re.compile(r"(\s|^)(@[A-Za-z0-9_]+)")
class pesterQuirk(object):
class pesterQuirk:
def __init__(self, quirk):
if type(quirk) != dict:
raise ValueError("Quirks must be given a dictionary")
@ -112,14 +111,14 @@ class pesterQuirk(object):
elif self.type == "suffix":
return "END WITH: %s" % (self.quirk["value"])
elif self.type == "replace":
return "REPLACE %s WITH %s" % (self.quirk["from"], self.quirk["to"])
return "REPLACE {} WITH {}".format(self.quirk["from"], self.quirk["to"])
elif self.type == "regexp":
return "REGEXP: %s REPLACED WITH %s" % (
return "REGEXP: {} REPLACED WITH {}".format(
self.quirk["from"],
self.quirk["to"],
)
elif self.type == "random":
return "REGEXP: %s RANDOMLY REPLACED WITH %s" % (
return "REGEXP: {} RANDOMLY REPLACED WITH {}".format(
self.quirk["from"],
[r for r in self.quirk["randomlist"]],
)
@ -127,7 +126,7 @@ class pesterQuirk(object):
return "MISPELLER: %d%%" % (self.quirk["percentage"])
class pesterQuirks(object):
class pesterQuirks:
def __init__(self, quirklist):
self.quirklist = []
for q in quirklist:
@ -258,11 +257,10 @@ class pesterQuirks(object):
return final
def __iter__(self):
for q in self.quirklist:
yield q
yield from self.quirklist
class PesterProfile(object):
class PesterProfile:
def __init__(
self,
handle,
@ -345,12 +343,12 @@ class PesterProfile(object):
msg = convertTags(lexmsg[1:], "text")
uppersuffix = suffix.upper()
if time is not None:
handle = "%s %s" % (time.temporal, self.handle)
handle = f"{time.temporal} {self.handle}"
initials = time.pcf + self.initials() + time.number + uppersuffix
else:
handle = self.handle
initials = self.initials() + uppersuffix
return "<c=%s>-- %s%s <c=%s>[%s]</c> %s --</c>" % (
return "<c={}>-- {}{} <c={}>[{}]</c> {} --</c>".format(
syscolor.name(),
handle,
suffix,
@ -360,7 +358,7 @@ class PesterProfile(object):
)
def pestermsg(self, otherchum, syscolor, verb):
return "<c=%s>-- %s <c=%s>[%s]</c> %s %s <c=%s>[%s]</c> at %s --</c>" % (
return "<c={}>-- {} <c={}>[{}]</c> {} {} <c={}>[{}]</c> at {} --</c>".format(
syscolor.name(),
self.handle,
self.colorhtml(),
@ -386,7 +384,7 @@ class PesterProfile(object):
)
def idlemsg(self, syscolor, verb):
return "<c=%s>-- %s <c=%s>[%s]</c> %s --</c>" % (
return "<c={}>-- {} <c={}>[{}]</c> {} --</c>".format(
syscolor.name(),
self.handle,
self.colorhtml(),
@ -396,14 +394,14 @@ class PesterProfile(object):
def memoclosemsg(self, syscolor, initials, verb):
if type(initials) == type(list()):
return "<c=%s><c=%s>%s</c> %s.</c>" % (
return "<c={}><c={}>{}</c> {}.</c>".format(
syscolor.name(),
self.colorhtml(),
", ".join(initials),
verb,
)
else:
return "<c=%s><c=%s>%s%s%s</c> %s.</c>" % (
return "<c={}><c={}>{}{}{}</c> {}.</c>".format(
syscolor.name(),
self.colorhtml(),
initials.pcf,
@ -416,7 +414,7 @@ class PesterProfile(object):
if len(initials) <= 0:
return "<c=%s>Netsplit quits: <c=black>None</c></c>" % (syscolor.name())
else:
return "<c=%s>Netsplit quits: <c=black>%s</c></c>" % (
return "<c={}>Netsplit quits: <c=black>{}</c></c>".format(
syscolor.name(),
", ".join(initials),
)
@ -427,7 +425,7 @@ class PesterProfile(object):
PchumLog.debug("pre pcf+self.initials()")
initials = timeGrammar.pcf + self.initials()
PchumLog.debug("post pcf+self.initials()")
return "<c=%s><c=%s>%s</c> %s %s %s.</c>" % (
return "<c={}><c={}>{}</c> {} {} {}.</c>".format(
syscolor.name(),
self.colorhtml(),
initials,
@ -440,11 +438,13 @@ class PesterProfile(object):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
if type(initials) == type(list()):
if opchum.handle == reason:
return "<c=%s>%s</c> banned <c=%s>%s</c> from responding to memo." % (
opchum.colorhtml(),
opinit,
self.colorhtml(),
", ".join(initials),
return (
"<c={}>{}</c> banned <c={}>{}</c> from responding to memo.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
", ".join(initials),
)
)
else:
return (
@ -501,7 +501,7 @@ class PesterProfile(object):
def memopermabanmsg(self, opchum, opgrammar, syscolor, timeGrammar):
initials = timeGrammar.pcf + self.initials() + timeGrammar.number
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> permabanned <c=%s>%s</c> from the memo." % (
return "<c={}>{}</c> permabanned <c={}>{}</c> from the memo.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@ -512,7 +512,7 @@ class PesterProfile(object):
# (temporal, pcf, when) = (timeGrammar.temporal, timeGrammar.pcf, timeGrammar.when)
timetext = timeDifference(td)
initials = timeGrammar.pcf + self.initials() + timeGrammar.number
return "<c=%s><c=%s>%s %s [%s]</c> %s %s.</c>" % (
return "<c={}><c={}>{} {} [{}]</c> {} {}.</c>".format(
syscolor.name(),
self.colorhtml(),
timeGrammar.temporal,
@ -524,7 +524,7 @@ class PesterProfile(object):
def memoopmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> made <c=%s>%s</c> an OP." % (
return "<c={}>{}</c> made <c={}>{}</c> an OP.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@ -533,7 +533,7 @@ class PesterProfile(object):
def memodeopmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> took away <c=%s>%s</c>'s OP powers." % (
return "<c={}>{}</c> took away <c={}>{}</c>'s OP powers.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@ -542,7 +542,7 @@ class PesterProfile(object):
def memovoicemsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> gave <c=%s>%s</c> voice." % (
return "<c={}>{}</c> gave <c={}>{}</c> voice.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@ -551,7 +551,7 @@ class PesterProfile(object):
def memodevoicemsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s>%s</c> took away <c=%s>%s</c>'s voice." % (
return "<c={}>{}</c> took away <c={}>{}</c>'s voice.".format(
opchum.colorhtml(),
opinit,
self.colorhtml(),
@ -564,7 +564,7 @@ class PesterProfile(object):
modeon = "now"
else:
modeon = "no longer"
return "<c=%s>Memo is %s <c=black>%s</c> by <c=%s>%s</c></c>" % (
return "<c={}>Memo is {} <c=black>{}</c> by <c={}>{}</c></c>".format(
syscolor.name(),
modeon,
modeverb,
@ -574,7 +574,7 @@ class PesterProfile(object):
def memoquirkkillmsg(self, opchum, opgrammar, syscolor):
opinit = opgrammar.pcf + opchum.initials() + opgrammar.number
return "<c=%s><c=%s>%s</c> turned off your quirk.</c>" % (
return "<c={}><c={}>{}</c> turned off your quirk.</c>".format(
syscolor.name(),
opchum.colorhtml(),
opinit,
@ -598,7 +598,7 @@ class PesterProfile(object):
return (True,)
class PesterHistory(object):
class PesterHistory:
def __init__(self):
self.history = []
self.current = 0

View file

@ -19,19 +19,19 @@ class mysteryTime(timedelta):
class CaseInsensitiveDict(dict):
def __setitem__(self, key, value):
super(CaseInsensitiveDict, self).__setitem__(key.lower(), value)
super().__setitem__(key.lower(), value)
def __getitem__(self, key):
return super(CaseInsensitiveDict, self).__getitem__(key.lower())
return super().__getitem__(key.lower())
def __contains__(self, key):
return super(CaseInsensitiveDict, self).__contains__(key.lower())
return super().__contains__(key.lower())
def has_key(self, key):
return key.lower() in super(CaseInsensitiveDict, self)
return key.lower() in super()
def __delitem__(self, key):
super(CaseInsensitiveDict, self).__delitem__(key.lower())
super().__delitem__(key.lower())
class PesterList(list):
@ -41,7 +41,7 @@ class PesterList(list):
class PesterIcon(QtGui.QIcon):
def __init__(self, *x):
super(PesterIcon, self).__init__(x[0])
super().__init__(x[0])
if type(x[0]) in [str, str]:
self.icon_pixmap = QtGui.QPixmap(x[0])
else:
@ -86,7 +86,7 @@ class RightClickTree(QtWidgets.QTreeWidget):
class MultiTextDialog(QtWidgets.QDialog):
def __init__(self, title, parent, *queries):
super(MultiTextDialog, self).__init__(parent)
super().__init__(parent)
self.setWindowTitle(title)
if len(queries) == 0:
return
@ -131,7 +131,7 @@ class MovingWindow(QtWidgets.QFrame):
# https://doc.qt.io/qt-5/qwindow.html#startSystemMove
# This is also the only method that works on Wayland, which doesn't support setting position.
def __init__(self, *x, **y):
super(MovingWindow, self).__init__(*x, **y)
super().__init__(*x, **y)
self.moving = None
self.moveupdate = 0
@ -163,7 +163,7 @@ class MovingWindow(QtWidgets.QFrame):
self.moving = None
class NoneSound(object):
class NoneSound:
def __init__(self, *args, **kwargs):
pass
@ -179,7 +179,7 @@ class NoneSound(object):
class WMButton(QtWidgets.QPushButton):
def __init__(self, icon, parent=None):
super(WMButton, self).__init__(icon, "", parent)
super().__init__(icon, "", parent)
self.setIconSize(icon.realsize())
self.resize(icon.realsize())
self.setFlat(True)

43
irc.py
View file

@ -2,7 +2,6 @@ import logging
import socket
import random
import time
import json
import ssl
try:
@ -11,7 +10,6 @@ except ImportError:
print("PyQt5 fallback (irc.py)")
from PyQt5 import QtCore, QtGui
import ostools
from mood import Mood
from dataobjs import PesterProfile
from generic import PesterList
@ -96,10 +94,10 @@ class PesterIRC(QtCore.QThread):
except socket.timeout as se:
PchumLog.debug("timeout in thread %s" % (self))
self.cli.close()
self.stopIRC = "%s, %s" % (type(se), se)
self.stopIRC = "{}, {}".format(type(se), se)
return
except (OSError, IndexError, ValueError) as se:
self.stopIRC = "%s, %s" % (type(se), se)
self.stopIRC = "{}, {}".format(type(se), se)
PchumLog.debug("socket error, exiting thread")
return
else:
@ -372,7 +370,7 @@ class PesterIRC(QtCore.QThread):
reason = str(l[1])
if len(l) > 2:
for x in l[2:]:
reason += str(":") + str(x)
reason += ":" + str(x)
else:
reason = ""
try:
@ -387,7 +385,7 @@ class PesterIRC(QtCore.QThread):
c = str(channel)
m = str(mode)
cmd = str(command)
PchumLog.debug("c=%s\nm=%s\ncmd=%s" % (c, m, cmd))
PchumLog.debug("c={}\nm={}\ncmd={}".format(c, m, cmd))
if cmd == "":
cmd = None
try:
@ -483,7 +481,7 @@ class PesterIRC(QtCore.QThread):
class PesterHandler(DefaultCommandHandler):
def notice(self, nick, chan, msg):
handle = nick[0 : nick.find("!")]
PchumLog.info('---> recv "NOTICE %s :%s"' % (handle, msg))
PchumLog.info('---> recv "NOTICE {} :{}"'.format(handle, msg))
if (
handle == "ChanServ"
and chan == self.parent.mainwindow.profile().handle
@ -501,13 +499,13 @@ class PesterHandler(DefaultCommandHandler):
mood = Mood(int(value))
self.parent.moodUpdated.emit(nick, mood)
except ValueError:
PchumLog.warning("Invalid mood value, %s, %s" % (nick, mood))
PchumLog.warning("Invalid mood value, {}, {}".format(nick, mood))
elif key.lower() == "color":
color = QtGui.QColor(value) # Invalid color becomes rgb 0,0,0
self.parent.colorUpdated.emit(nick, color)
def tagmsg(self, prefix, tags, *args):
PchumLog.info("TAGMSG: %s %s %s" % (prefix, tags, str(args)))
PchumLog.info("TAGMSG: {} {} {}".format(prefix, tags, str(args)))
message_tags = tags[1:].split(";")
for m in message_tags:
if m.startswith("+pesterchum"):
@ -516,7 +514,7 @@ class PesterHandler(DefaultCommandHandler):
key, value = m.split("=")
except ValueError:
return
PchumLog.info("Pesterchum tag: %s=%s" % (key, value))
PchumLog.info("Pesterchum tag: {}={}".format(key, value))
# PESTERCHUM: syntax check
if (
(value == "BEGIN")
@ -563,7 +561,7 @@ class PesterHandler(DefaultCommandHandler):
msg = "/me" + msg[7:-1]
# CTCPs that don't need to be shown
elif msg[0] == "\x01":
PchumLog.info('---> recv "CTCP %s :%s"' % (handle, msg[1:-1]))
PchumLog.info('---> recv "CTCP {} :{}"'.format(handle, msg[1:-1]))
# VERSION, return version
if msg[1:-1].startswith("VERSION"):
helpers.ctcp_reply(
@ -609,7 +607,7 @@ class PesterHandler(DefaultCommandHandler):
if chan != "#pesterchum":
# We don't need anywhere near that much spam.
PchumLog.info('---> recv "PRIVMSG %s :%s"' % (handle, msg))
PchumLog.info('---> recv "PRIVMSG {} :{}"'.format(handle, msg))
if chan == "#pesterchum":
# follow instructions
@ -740,7 +738,7 @@ class PesterHandler(DefaultCommandHandler):
self.parent.metadata_supported = True
def cap(self, server, nick, subcommand, tag):
PchumLog.info("CAP %s %s %s %s" % (server, nick, subcommand, tag))
PchumLog.info("CAP {} {} {} {}".format(server, nick, subcommand, tag))
# if tag == "message-tags":
# if subcommand == "ACK":
@ -756,7 +754,7 @@ class PesterHandler(DefaultCommandHandler):
def quit(self, nick, reason):
handle = nick[0 : nick.find("!")]
PchumLog.info('---> recv "QUIT %s: %s"' % (handle, reason))
PchumLog.info('---> recv "QUIT {}: {}"'.format(handle, reason))
if handle == self.parent.mainwindow.randhandler.randNick:
self.parent.mainwindow.randhandler.setRunning(False)
server = self.parent.mainwindow.config.server()
@ -769,19 +767,21 @@ class PesterHandler(DefaultCommandHandler):
def kick(self, opnick, channel, handle, reason):
op = opnick[0 : opnick.find("!")]
self.parent.userPresentUpdate.emit(handle, channel, "kick:%s:%s" % (op, reason))
self.parent.userPresentUpdate.emit(
handle, channel, "kick:{}:{}".format(op, reason)
)
# ok i shouldnt be overloading that but am lazy
def part(self, nick, channel, reason="nanchos"):
handle = nick[0 : nick.find("!")]
PchumLog.info('---> recv "PART %s: %s"' % (handle, channel))
PchumLog.info('---> recv "PART {}: {}"'.format(handle, channel))
self.parent.userPresentUpdate.emit(handle, channel, "left")
if channel == "#pesterchum":
self.parent.moodUpdated.emit(handle, Mood("offline"))
def join(self, nick, channel):
handle = nick[0 : nick.find("!")]
PchumLog.info('---> recv "JOIN %s: %s"' % (handle, channel))
PchumLog.info('---> recv "JOIN {}: {}"'.format(handle, channel))
self.parent.userPresentUpdate.emit(handle, channel, "join")
if channel == "#pesterchum":
if handle == self.parent.mainwindow.randhandler.randNick:
@ -871,7 +871,6 @@ class PesterHandler(DefaultCommandHandler):
PchumLog.warning(
"Can't remove channel mode that isn't set."
)
pass
self.parent.userPresentUpdate.emit(
"", channel, channel_mode + ":%s" % (op)
)
@ -887,7 +886,7 @@ class PesterHandler(DefaultCommandHandler):
if l in ["+", "-"]:
cur = l
else:
modes.append("%s%s" % (cur, l))
modes.append("{}{}".format(cur, l))
PchumLog.debug("handles=" + str(handles))
PchumLog.debug("enumerate(modes) = " + str(list(enumerate(modes))))
for (i, m) in enumerate(modes):
@ -911,7 +910,7 @@ class PesterHandler(DefaultCommandHandler):
# self.parent.userPresentUpdate.emit("", channel, m+":%s" % (op))
def nick(self, oldnick, newnick, hopcount=0):
PchumLog.info("%s, %s" % (oldnick, newnick))
PchumLog.info("{}, {}".format(oldnick, newnick))
# svsnick
if oldnick == self.mainwindow.profile().handle:
# Server changed our handle, svsnick?
@ -926,7 +925,9 @@ class PesterHandler(DefaultCommandHandler):
self.parent.myHandleChanged.emit(newnick)
newchum = PesterProfile(newnick, chumdb=self.mainwindow.chumdb)
self.parent.moodUpdated.emit(oldhandle, Mood("offline"))
self.parent.userPresentUpdate.emit("%s:%s" % (oldhandle, newnick), "", "nick")
self.parent.userPresentUpdate.emit(
"{}:{}".format(oldhandle, newnick), "", "nick"
)
if newnick in self.mainwindow.chumList.chums:
self.getMood(newchum)
if oldhandle == self.parent.mainwindow.randhandler.randNick:

View file

@ -1,5 +1,4 @@
import os
import sys
import codecs
import re
import ostools
@ -65,8 +64,8 @@ class PesterLogUserSelect(QtWidgets.QDialog):
instructions = QtWidgets.QLabel("Pick a memo or chumhandle:")
if os.path.exists("%s/%s" % (self.logpath, self.handle)):
chumMemoList = os.listdir("%s/%s/" % (self.logpath, self.handle))
if os.path.exists("{}/{}".format(self.logpath, self.handle)):
chumMemoList = os.listdir("{}/{}/".format(self.logpath, self.handle))
else:
chumMemoList = []
chumslist = config.chums()
@ -166,17 +165,17 @@ class PesterLogViewer(QtWidgets.QDialog):
self.format = "bbcode"
if os.path.exists(
"%s/%s/%s/%s" % (self.logpath, self.handle, chum, self.format)
"{}/{}/{}/{}".format(self.logpath, self.handle, chum, self.format)
):
self.logList = os.listdir(
"%s/%s/%s/%s/" % (self.logpath, self.handle, self.chum, self.format)
"{}/{}/{}/{}/".format(self.logpath, self.handle, self.chum, self.format)
)
else:
self.logList = []
if (
not os.path.exists(
"%s/%s/%s/%s" % (self.logpath, self.handle, chum, self.format)
"{}/{}/{}/{}".format(self.logpath, self.handle, chum, self.format)
)
or len(self.logList) == 0
):
@ -248,7 +247,7 @@ class PesterLogViewer(QtWidgets.QDialog):
for (i, l) in enumerate(self.logList):
my = self.fileToMonthYear(l)
if my[0] != last[0]:
child_1 = QtWidgets.QTreeWidgetItem(["%s %s" % (my[0], my[1])])
child_1 = QtWidgets.QTreeWidgetItem(["{} {}".format(my[0], my[1])])
# child_1.setForeground(0, blackbrush)
self.tree.addTopLevelItem(child_1)
if i == 0:
@ -313,7 +312,7 @@ class PesterLogViewer(QtWidgets.QDialog):
.replace("[url]", "")
.replace("[/url]", "")
)
cline = re.sub("\[color=(#.{6})]", r"<c=\1>", cline)
cline = re.sub(r"\[color=(#.{6})]", r"<c=\1>", cline)
self.textArea.append(convertTags(cline))
textCur = self.textArea.textCursor()
# textCur.movePosition(1)

View file

@ -11,7 +11,6 @@ except ImportError:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction
import ostools
import parsetools
from dataobjs import PesterProfile, PesterHistory
from generic import PesterIcon, RightClickList, mysteryTime
@ -103,7 +102,7 @@ def pcfGrammar(td):
return (temporal, pcf, when)
class TimeGrammar(object):
class TimeGrammar:
def __init__(self, temporal, pcf, when, number="0"):
self.temporal = temporal
self.pcf = pcf
@ -228,7 +227,7 @@ class TimeTracker(list):
class TimeInput(QtWidgets.QLineEdit):
def __init__(self, timeslider, parent):
super(TimeInput, self).__init__(parent)
super().__init__(parent)
self.timeslider = timeslider
self.setText("+0:00")
self.timeslider.valueChanged[int].connect(self.setTime)
@ -260,7 +259,7 @@ class TimeInput(QtWidgets.QLineEdit):
class TimeSlider(QtWidgets.QSlider):
def __init__(self, orientation, parent):
super(TimeSlider, self).__init__(orientation, parent)
super().__init__(orientation, parent)
self.setTracking(True)
self.setMinimum(-50)
self.setMaximum(50)
@ -278,7 +277,7 @@ class TimeSlider(QtWidgets.QSlider):
class MemoTabWindow(PesterTabWindow):
def __init__(self, mainwindow, parent=None):
super(MemoTabWindow, self).__init__(mainwindow, parent, "memos")
super().__init__(mainwindow, parent, "memos")
def addChat(self, convo):
self.convos[convo.channel] = convo
@ -302,7 +301,7 @@ _ctag_begin = re.compile(r"<c=(.*?)>")
class MemoText(PesterText):
def __init__(self, theme, parent=None):
super(MemoText, self).__init__(theme, parent)
super().__init__(theme, parent)
if hasattr(self.parent(), "mainwindow"):
self.mainwindow = self.parent().mainwindow
else:
@ -398,12 +397,7 @@ class MemoText(PesterText):
# new chum! time current
newtime = timedelta(0)
time = TimeTracker(newtime)
# 'handle' undefined?
try:
parent.times[handle] = time
except:
parent.times[chum.handle] = time
parent.times[chum.handle] = time
else:
time = parent.time
@ -1595,7 +1589,7 @@ class PesterMemo(PesterConvo):
t = self.times[h]
grammar = t.getGrammar()
allinitials.append(
"%s%s%s" % (grammar.pcf, chum.initials(), grammar.number)
"{}{}{}".format(grammar.pcf, chum.initials(), grammar.number)
)
self.times[h].removeTime(t.getTime())
if update == "netsplit":
@ -1645,7 +1639,7 @@ class PesterMemo(PesterConvo):
while ttracker.getTime() is not None:
grammar = ttracker.getGrammar()
allinitials.append(
"%s%s%s" % (grammar.pcf, chum.initials(), grammar.number)
"{}{}{}".format(grammar.pcf, chum.initials(), grammar.number)
)
ttracker.removeTime(ttracker.getTime())
msg = chum.memobanmsg(opchum, opgrammar, systemColor, allinitials, reason)
@ -1878,7 +1872,7 @@ class PesterMemo(PesterConvo):
)
if ok:
self.mainwindow.kickUser.emit(
"%s:%s" % (currentHandle, reason), self.channel
"{}:{}".format(currentHandle, reason), self.channel
)
@QtCore.pyqtSlot()

View file

@ -1,4 +1,3 @@
import sys
import re
from os import remove
@ -237,7 +236,7 @@ class PesterQuirkList(QtWidgets.QTreeWidget):
)
if ok:
gname = str(gname)
if re.search("[^A-Za-z0-9_\s]", gname) is not None:
if re.search(r"[^A-Za-z0-9_\s]", gname) is not None:
msgbox = QtWidgets.QMessageBox()
msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME")
msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
@ -1304,9 +1303,7 @@ class PesterOptions(QtWidgets.QDialog):
self.volume.valueChanged[int].connect(self.printValue)
# Disable the volume slider if we can't actually use it.
if parent.canSetVolume():
self.currentVol = QtWidgets.QLabel(
"{0!s}%".format(self.config.volume()), self
)
self.currentVol = QtWidgets.QLabel(f"{self.config.volume()!s}%", self)
# We don't need to explicitly set this, but it helps drive the
# point home
self.volume.setEnabled(True)

View file

@ -1,13 +1,13 @@
try:
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6 import QtCore, QtWidgets
except ImportError:
print("PyQt5 fallback (mood.py)")
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import QtCore, QtWidgets
from generic import PesterIcon
class Mood(object):
class Mood:
moods = [
"chummy",
"rancorous",

View file

@ -1,7 +1,6 @@
import os
import sys
import ctypes
import platform
try:
from PyQt6.QtCore import QStandardPaths
@ -26,20 +25,6 @@ def isOSXBundle():
return isOSX() and (os.path.abspath(".").find(".app") != -1)
def isOSXLeopard():
return isOSX() and platform.mac_ver()[0].startswith("10.5")
def osVer():
if isWin32():
return " ".join(platform.win32_ver())
elif isOSX():
ver = platform.mac_ver()
return " ".join((ver[0], " (", ver[2], ")"))
elif isLinux():
return " ".join(platform.linux_distribution())
def isRoot():
"""Return True if running with elevated privileges."""
# Windows

View file

@ -100,7 +100,7 @@ class IRCClient:
self.username = None
self.host = None
self.port = None
self.connect_cb = None
# self.connect_cb = None
self.timeout = None
self.blocking = None
self.ssl = None
@ -246,7 +246,7 @@ class IRCClient:
passing the 'verify_hostname' parameter. The user is asked if they
want to disable it if this functions raises a certificate validation error,
in which case the function may be called again with 'verify_hostname'."""
PchumLog.info("connecting to %s:%s" % (self.host, self.port))
PchumLog.info("connecting to {}:{}".format(self.host, self.port))
# Open connection
plaintext_socket = socket.create_connection((self.host, self.port))
@ -273,13 +273,13 @@ class IRCClient:
helpers.nick(self, self.nick)
helpers.user(self, self.username, self.realname)
if self.connect_cb:
self.connect_cb(self)
# if self.connect_cb:
# self.connect_cb(self)
def conn(self):
"""returns a generator object."""
try:
buffer = bytes()
buffer = b""
while not self._end:
# Block for connection-killing exceptions
try:
@ -334,14 +334,10 @@ class IRCClient:
except ssl.SSLEOFError as e:
raise e
except OSError as e:
PchumLog.warning("conn exception %s in %s" % (e, self))
PchumLog.warning("conn exception {} in {}".format(e, self))
if self._end:
break
try: # a little dance of compatibility to get the errno
errno = e.errno
except AttributeError:
errno = e[0]
if not self.blocking and errno == 11:
if not self.blocking and e.errno == 11:
pass
else:
raise e
@ -434,7 +430,7 @@ class IRCApp:
warning: if you add a client that has blocking set to true,
timers will no longer function properly"""
PchumLog.info("added client %s (ar=%s)" % (client, autoreconnect))
PchumLog.info("added client {} (ar={})".format(client, autoreconnect))
self._clients[client] = self._ClientDesc(autoreconnect=autoreconnect)
def addTimer(self, seconds, cb):
@ -443,7 +439,7 @@ class IRCApp:
( the only advantage to these timers is they dont use threads )
"""
assert callable(cb)
PchumLog.info("added timer to call %s in %ss" % (cb, seconds))
PchumLog.info("added timer to call {} in {}s".format(cb, seconds))
self._timers.append((time.time() + seconds, cb))
def run(self):

View file

@ -44,7 +44,7 @@ class ProtectedCommandError(CommandError):
return 'Command "%s" is protected' % ".".join(self.cmd)
class CommandHandler(object):
class CommandHandler:
"""The most basic CommandHandler"""
def __init__(self, client):
@ -91,7 +91,7 @@ class CommandHandler(object):
arguments_str = ""
for x in args:
arguments_str += str(x) + " "
PchumLog.debug("processCommand %s(%s)" % (command, arguments_str.strip()))
PchumLog.debug("processCommand {}({})".format(command, arguments_str.strip()))
try:
f = self.get(command)
@ -118,7 +118,7 @@ class CommandHandler(object):
"""The default handler for commands. Override this method to
apply custom behavior (example, printing) unhandled commands.
"""
PchumLog.debug("unhandled command %s(%s)" % (cmd, args))
PchumLog.debug("unhandled command {}({})".format(cmd, args))
class DefaultCommandHandler(CommandHandler):
@ -150,7 +150,7 @@ class DefaultBotCommandHandler(CommandHandler):
def help(self, sender, dest, arg=None):
"""list all available commands or get help on a specific command"""
PchumLog.info("help sender=%s dest=%s arg=%s" % (sender, dest, arg))
PchumLog.info("help sender={} dest={} arg={}".format(sender, dest, arg))
if not arg:
commands = self.getVisibleCommands()
commands.sort()
@ -171,7 +171,7 @@ class DefaultBotCommandHandler(CommandHandler):
if subcommands:
doc += " [sub commands: %s]" % " ".join(subcommands)
helpers.msg(self.client, dest, "%s: %s" % (arg, doc))
helpers.msg(self.client, dest, "{}: {}".format(arg, doc))
class BotCommandHandler(DefaultCommandHandler):
@ -190,7 +190,7 @@ class BotCommandHandler(DefaultCommandHandler):
and calls self.processBotCommand(cmd, sender) if its is.
"""
PchumLog.debug("tryBotCommand('%s' '%s' '%s')" % (prefix, dest, msg))
PchumLog.debug("tryBotCommand('{}' '{}' '{}')".format(prefix, dest, msg))
if dest == self.client.nick:
dest = parse_nick(prefix)[0]

View file

@ -46,13 +46,13 @@ def channel_list(cli):
def kick(cli, handle, channel, reason=""):
cli.send("KICK %s %s %s" % (channel, handle, reason))
cli.send("KICK {} {} {}".format(channel, handle, reason))
def mode(cli, channel, mode, options=None):
PchumLog.debug("mode = " + str(mode))
PchumLog.debug("options = " + str(options))
cmd = "MODE %s %s" % (channel, mode)
cmd = "MODE {} {}".format(channel, mode)
if options:
cmd += " %s" % (options)
cli.send(cmd)
@ -63,11 +63,11 @@ def ctcp(cli, handle, cmd, msg=""):
if msg == "":
cli.send("PRIVMSG", handle, "\x01%s\x01" % (cmd))
else:
cli.send("PRIVMSG", handle, "\x01%s %s\x01" % (cmd, msg))
cli.send("PRIVMSG", handle, "\x01{} {}\x01".format(cmd, msg))
def ctcp_reply(cli, handle, cmd, msg=""):
notice(cli, str(handle), "\x01%s %s\x01" % (cmd.upper(), msg))
notice(cli, str(handle), "\x01{} {}\x01".format(cmd.upper(), msg))
def metadata(cli, target, subcommand, *params):
@ -116,34 +116,29 @@ def quit(cli, msg):
cli.send("QUIT %s" % (msg))
def nick(cli, nick):
cli.send("NICK", nick)
def user(cli, username, realname):
cli.send("USER", username, "0", "*", ":" + realname)
_simple = (
"join",
"part",
"nick",
"notice",
"invite",
)
def join(cli, channel):
"""Protocol potentially allows multiple channels or keys."""
cli.send("JOIN", channel)
def _addsimple():
import sys
def simplecmd(cmd_name):
def f(cli, *args):
cli.send(cmd_name, *args)
return f
m = sys.modules[__name__]
for t in _simple:
setattr(m, t, simplecmd(t.upper()))
def part(cli, channel):
cli.send("PART", channel)
_addsimple()
def notice(cli, target, text):
cli.send("NOTICE", target, text)
def invite(cli, nick, channel):
cli.send("INVITE", nick, channel)
def _addNumerics():

View file

@ -111,14 +111,14 @@ def _addServ(serv, funcs, prefix=""):
setattr(serv, t, simplecmd(t.upper()))
class NickServ(object):
class NickServ:
def __init__(self, nick="NickServ"):
self.name = nick
_addServ(self, _nickservfuncs)
_addServ(self, _nickservsetfuncs, "set")
class ChanServ(object):
class ChanServ:
def __init__(self, nick="ChanServ"):
self.name = nick
_addServ(self, _chanservfuncs)

View file

@ -11,7 +11,6 @@ except ImportError:
from PyQt5 import QtGui, QtWidgets
import dataobjs
import ostools
# karxi: My own contribution to this - a proper lexer.
import pnc.lexercon as lexercon
@ -115,7 +114,7 @@ class colorBegin(lexercon.Chunk):
return "[color=%s]" % (qc.name())
elif format == "ctag":
(r, g, b, a) = qc.getRgb()
return "<c=%s,%s,%s>" % (r, g, b)
return "<c={},{},{}>".format(r, g, b)
class colorEnd(lexercon.Chunk):
@ -171,7 +170,7 @@ class hyperlink(lexercon.Chunk):
def convert(self, format):
if format == "html":
return "<a href='%s'>%s</a>" % (self.string, self.string)
return "<a href='{}'>{}</a>".format(self.string, self.string)
elif format == "bbcode":
return "[url]%s[/url]" % (self.string)
else:
@ -211,7 +210,9 @@ class memolex(lexercon.Chunk):
def convert(self, format):
if format == "html":
return "%s<a href='%s'>%s</a>" % (self.space, self.channel, self.channel)
return "{}<a href='{}'>{}</a>".format(
self.space, self.channel, self.channel
)
else:
return self.string
@ -224,7 +225,7 @@ class chumhandlelex(lexercon.Chunk):
def convert(self, format):
if format == "html":
return "%s<a href='%s'>%s</a>" % (self.space, self.handle, self.handle)
return "{}<a href='{}'>{}</a>".format(self.space, self.handle, self.handle)
else:
return self.string
@ -235,7 +236,7 @@ class smiley(lexercon.Chunk):
def convert(self, format):
if format == "html":
return "<img src='smilies/%s' alt='%s' title='%s' />" % (
return "<img src='smilies/{}' alt='{}' title='{}' />".format(
smiledict[self.string],
self.string,
self.string,
@ -461,7 +462,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
while len(lexed) > 0:
rounds += 1
if debug:
PchumLog.info("[Starting round {}...]".format(rounds))
PchumLog.info(f"[Starting round {rounds}...]")
msg = lexed.popleft()
msglen = 0
is_text = False
@ -502,9 +503,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# instead?
subround += 1
if debug:
PchumLog.info(
"[Splitting round {}-{}...]".format(rounds, subround)
)
PchumLog.info(f"[Splitting round {rounds}-{subround}...]")
point = msg.rfind(" ", 0, lenl)
if point < 0:
# No spaces to break on...ugh. Break at the last space
@ -517,12 +516,12 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# Remove what we just added.
msg = msg[point:]
if debug:
PchumLog.info("msg = {!r}".format(msg))
PchumLog.info(f"msg = {msg!r}")
else:
# Catch the remainder.
stack.append(msg)
if debug:
PchumLog.info("msg caught; stack = {!r}".format(stack))
PchumLog.info(f"msg caught; stack = {stack!r}")
# Done processing. Pluck out the first portion so we can
# continue processing, clean it up a bit, then add the rest to
# our waiting list.
@ -564,7 +563,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working.extend([cte] * len(open_ctags))
if debug:
print(
"\tRound {0} linebreak: Added {1} closing ctags".format(
"\tRound {} linebreak: Added {} closing ctags".format(
rounds, len(open_ctags)
)
)
@ -573,7 +572,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working = "".join(kxpclexer.list_convert(working))
if debug:
print(
"\tRound {0} add: len == {1} (of {2})".format(
"\tRound {} add: len == {} (of {})".format(
rounds, len(working), maxlen
)
)
@ -591,7 +590,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
# We have more to go.
# Reset working, starting it with the unclosed ctags.
if debug:
print("\tRound {0}: More to lex".format(rounds))
print(f"\tRound {rounds}: More to lex")
working = open_ctags[:]
# Calculate the length of the starting tags, add it before
# anything else.
@ -606,7 +605,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
if debug or True:
# This probably shouldn't happen, and if it does, I want to
# know if it *works* properly.
print("\tRound {0}: No more to lex".format(rounds))
print(f"\tRound {rounds}: No more to lex")
# Clean up, just in case.
working = []
open_ctags = []
@ -655,7 +654,7 @@ def kxsplitMsg(lexed, ctx, fmt="pchum", maxlen=None, debug=False):
working = kxpclexer.list_convert(working)
if len(working) > 0:
if debug:
print("Adding end trails: {!r}".format(working))
print(f"Adding end trails: {working!r}")
working = "".join(working)
output.append(working)
@ -722,7 +721,7 @@ def kxhandleInput(ctx, text=None, flavor=None):
# Determine if the line actually *is* OOC.
if is_ooc and not oocDetected:
# If we're supposed to be OOC, apply it artificially.
msg = "(( {} ))".format(msg)
msg = f"(( {msg} ))"
# Also, quirk stuff.
should_quirk = ctx.applyquirks
else:
@ -861,7 +860,7 @@ def kxhandleInput(ctx, text=None, flavor=None):
clientMsg, colorcmd, grammar.pcf, initials, grammar.number
)
# Not sure if this needs a space at the end...?
serverMsg = "<c={1}>{2}: {0}</c>".format(serverMsg, colorcmd, initials)
serverMsg = f"<c={colorcmd}>{initials}: {serverMsg}</c>"
ctx.addMessage(clientMsg, True)
if flavor != "menus":
@ -935,7 +934,7 @@ def nonerep(text):
return text
class parseLeaf(object):
class parseLeaf:
def __init__(self, function, parent):
self.nodes = []
self.function = function
@ -957,7 +956,7 @@ class parseLeaf(object):
return out
class backreference(object):
class backreference:
def __init__(self, number):
self.number = number
@ -1071,7 +1070,7 @@ smiledict = {
":honk:": "honk.png",
}
reverse_smiley = dict((v, k) for k, v in smiledict.items())
reverse_smiley = {v: k for k, v in smiledict.items()}
_smilere = re.compile("|".join(list(smiledict.keys())))

View file

@ -1,7 +1,6 @@
#!/usr/bin/env python3
import os
import sys
import shutil
import argparse
import traceback
import logging
@ -61,11 +60,11 @@ from toast import PesterToastMachine, PesterToast
try:
from PyQt6 import QtCore, QtGui, QtWidgets
from PyQt6.QtGui import QShortcut, QAction, QActionGroup
from PyQt6.QtGui import QAction, QActionGroup
except ImportError:
print("PyQt5 fallback (pesterchum.py)")
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QAction, QShortcut, QActionGroup
from PyQt5.QtWidgets import QAction, QActionGroup
# Data directory
ostools.validateDataDir()
@ -210,7 +209,7 @@ except ImportError:
)
class waitingMessageHolder(object):
class waitingMessageHolder:
def __init__(self, mainwindow, **msgfuncs):
self.mainwindow = mainwindow
self.funcs = msgfuncs
@ -246,14 +245,14 @@ class waitingMessageHolder(object):
class chumListing(QtWidgets.QTreeWidgetItem):
def __init__(self, chum, window):
super(chumListing, self).__init__([chum.handle])
super().__init__([chum.handle])
self.mainwindow = window
self.chum = chum
self.handle = chum.handle
self.setMood(Mood("offline"))
self.status = None
self.setToolTip(
0, "%s: %s" % (chum.handle, window.chumdb.getNotes(chum.handle))
0, "{}: {}".format(chum.handle, window.chumdb.getNotes(chum.handle))
)
def setMood(self, mood):
@ -330,11 +329,9 @@ class chumListing(QtWidgets.QTreeWidgetItem):
0,
QtGui.QBrush(
QtGui.QColor(
(
self.mainwindow.theme["main/chums/moods"][self.mood.name()][
"color"
]
)
self.mainwindow.theme["main/chums/moods"][self.mood.name()][
"color"
]
)
),
)
@ -342,9 +339,7 @@ class chumListing(QtWidgets.QTreeWidgetItem):
self.setForeground(
0,
QtGui.QBrush(
QtGui.QColor(
(self.mainwindow.theme["main/chums/moods/chummy/color"])
)
QtGui.QColor(self.mainwindow.theme["main/chums/moods/chummy/color"])
),
)
@ -379,7 +374,7 @@ class chumArea(RightClickTree):
# This is the class that controls the actual main chumlist, I think.
# Looking into how the groups work might be wise.
def __init__(self, chums, parent=None):
super(chumArea, self).__init__(parent)
super().__init__(parent)
self.notify = False
QtCore.QTimer.singleShot(30000, self.beginNotify)
self.mainwindow = parent
@ -1061,7 +1056,7 @@ class chumArea(RightClickTree):
if ok:
notes = str(notes)
self.mainwindow.chumdb.setNotes(currentChum.handle, notes)
currentChum.setToolTip(0, "%s: %s" % (currentChum.handle, notes))
currentChum.setToolTip(0, "{}: {}".format(currentChum.handle, notes))
@QtCore.pyqtSlot()
def renameGroup(self):
@ -1073,7 +1068,7 @@ class chumArea(RightClickTree):
)
if ok:
gname = str(gname)
if re.search("[^A-Za-z0-9_\s]", gname) is not None:
if re.search(r"[^A-Za-z0-9_\s]", gname) is not None:
msgbox = QtWidgets.QMessageBox()
msgbox.setStyleSheet(
"QMessageBox{ %s }"
@ -1210,7 +1205,7 @@ class trollSlum(chumArea):
class TrollSlumWindow(QtWidgets.QFrame):
def __init__(self, trolls, mainwindow, parent=None):
super(TrollSlumWindow, self).__init__(parent)
super().__init__(parent)
self.mainwindow = mainwindow
theme = self.mainwindow.theme
self.slumlabel = QtWidgets.QLabel(self)
@ -1298,7 +1293,7 @@ class PesterWindow(MovingWindow):
sendMessage = QtCore.pyqtSignal("QString", "QString")
def __init__(self, options, parent=None, app=None):
super(PesterWindow, self).__init__(
super().__init__(
None,
(
QtCore.Qt.WindowType.CustomizeWindowHint
@ -1357,7 +1352,7 @@ class PesterWindow(MovingWindow):
msgBox.setText(
"<html><h3>A profile error occured, "
"trying to switch to default pesterClient profile."
"<br><br>%s<\h3><\html>" % e
r"<br><br>%s<\h3><\html>" % e
)
PchumLog.critical(e)
msgBox.exec()
@ -1461,6 +1456,7 @@ class PesterWindow(MovingWindow):
self.menu.setNativeMenuBar(False)
self.menu.setObjectName("mainmenu")
"""
if self.theme.has_key("main/menus/client/console"):
self.console = AttrDict(
dict(
@ -1498,6 +1494,7 @@ class PesterWindow(MovingWindow):
# ~self.connect(self.console.shortcuts.curwgt,
# ~ QtCore.SIGNAL('activate()'), self.console.
self.console.is_open = False
"""
filemenu = self.menu.addMenu(self.theme["main/menus/client/_name"])
self.filemenu = filemenu
@ -1915,7 +1912,7 @@ class PesterWindow(MovingWindow):
msg = addTimeInitial(msg, memo.times[handle].getGrammar())
if handle == "ChanServ":
systemColor = QtGui.QColor(self.theme["memos/systemMsgColor"])
msg = "<c=%s>%s</c>" % (systemColor.name(), msg)
msg = "<c={}>{}</c>".format(systemColor.name(), msg)
memo.addMessage(msg, handle)
mentioned = False
m = convertTags(msg, "text")
@ -2003,6 +2000,7 @@ class PesterWindow(MovingWindow):
self.tabmemo = MemoTabWindow(self)
self.tabmemo.windowClosed.connect(self.memoTabsClosed)
"""
@QtCore.pyqtSlot()
def toggleConsole(self):
if not _CONSOLE:
@ -2070,6 +2068,7 @@ class PesterWindow(MovingWindow):
self.console.is_open = False
self.console.window = None
PchumLog.info("Console closed.")
"""
def newMemo(self, channel, timestr, secret=False, invite=False):
if channel == "#pesterchum":
@ -2215,10 +2214,10 @@ class PesterWindow(MovingWindow):
## else:
## self.console.action.setText("Console")
# has_key doesn't work out here for some reason, possibly because of inherits?
try:
self.console.action.setText(self.theme["main/menus/client/console"])
except:
self.console.action.setText("Console")
# try:
# self.console.action.setText(self.theme["main/menus/client/console"])
# except:
# self.console.action.setText("Console")
try:
self.reportBugAction.setText(self.theme["main/menus/help/reportbug"])
@ -2238,7 +2237,7 @@ class PesterWindow(MovingWindow):
if hasattr(self, "moods"):
self.moods.removeButtons()
mood_list = theme["main/moods"]
mood_list = [dict([(str(k), v) for (k, v) in d.items()]) for d in mood_list]
mood_list = [{str(k): v for (k, v) in d.items()} for d in mood_list]
self.moods = PesterMoodHandler(
self, *[PesterMoodButton(self, **d) for d in mood_list]
)
@ -2387,7 +2386,7 @@ class PesterWindow(MovingWindow):
QtCore.QUrl.fromLocalFile("themes/honk.wav")
)
except Exception as err:
PchumLog.error("Warning: Error loading sounds! ({0!r})".format(err))
PchumLog.error(f"Warning: Error loading sounds! ({err!r})")
self.alarm = NoneSound()
self.memosound = NoneSound()
self.namesound = NoneSound()
@ -2415,7 +2414,7 @@ class PesterWindow(MovingWindow):
if self.sound_type == QtMultimedia.QSoundEffect:
sound.setVolume(vol)
except Exception as err:
PchumLog.warning("Couldn't set volume: {}".format(err))
PchumLog.warning(f"Couldn't set volume: {err}")
def canSetVolume(self):
"""Returns the state of volume setting capabilities."""
@ -2789,7 +2788,7 @@ class PesterWindow(MovingWindow):
errormsg.showMessage("THIS IS NOT A VALID CHUMTAG!")
self.addchumdialog = None
return
if re.search("[^A-Za-z0-9_\s]", group) is not None:
if re.search(r"[^A-Za-z0-9_\s]", group) is not None:
errormsg = QtWidgets.QErrorMessage(self)
errormsg.showMessage("THIS IS NOT A VALID GROUP NAME")
self.addchumdialog = None
@ -2813,7 +2812,7 @@ class PesterWindow(MovingWindow):
"Enter the reason you are reporting this user (optional):",
)
if ok:
self.sendMessage.emit("REPORT %s %s" % (handle, reason), "calSprite")
self.sendMessage.emit("REPORT {} {}".format(handle, reason), "calSprite")
@QtCore.pyqtSlot(QString)
def blockChum(self, handle):
@ -2942,7 +2941,7 @@ class PesterWindow(MovingWindow):
f = QtWidgets.QFileDialog.getOpenFileName(self)[0]
if f == "":
return
fp = open(f, "r")
fp = open(f)
regexp_state = None
for l in fp:
# import chumlist
@ -3135,7 +3134,7 @@ class PesterWindow(MovingWindow):
)
if ok:
gname = str(gname)
if re.search("[^A-Za-z0-9_\s]", gname) is not None:
if re.search(r"[^A-Za-z0-9_\s]", gname) is not None:
msgbox = QtWidgets.QMessageBox()
msgbox.setInformativeText("THIS IS NOT A VALID GROUP NAME")
msgbox.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
@ -3496,7 +3495,7 @@ class PesterWindow(MovingWindow):
"<br><br>"
"If you got this message at launch you may want to "
"change your default profile."
"<br><br>%s<\h3><\html>"
r"<br><br>%s<\h3><\html>"
% (self.profiledir, self.profiledir, handle, e)
)
@ -3508,7 +3507,7 @@ class PesterWindow(MovingWindow):
"file exists."
"<br><br>If you got this message at launch you may "
"want to change your default profile."
"<br><br>%s<\h3><\html>" % e
r"<br><br>%s<\h3><\html>" % e
)
PchumLog.critical(e)
msgBox.setText(msg)
@ -3765,7 +3764,7 @@ class PesterWindow(MovingWindow):
self.chooseServer()
return 1
with open(_datadir + "serverlist.json", "r") as server_file:
with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_list_obj = json.loads(read_file)
@ -3822,7 +3821,7 @@ class PesterWindow(MovingWindow):
def removeServer(self):
server_list_items = []
try:
with open(_datadir + "serverlist.json", "r") as server_file:
with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_list_obj = json.loads(read_file)
@ -3924,7 +3923,7 @@ class PesterWindow(MovingWindow):
# Read servers.
server_list_items = []
try:
with open(_datadir + "serverlist.json", "r") as server_file:
with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@ -3984,7 +3983,7 @@ class PesterWindow(MovingWindow):
else:
PchumLog.info(self.serverBox.currentText() + " chosen.")
with open(_datadir + "serverlist.json", "r") as server_file:
with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@ -4027,7 +4026,7 @@ class PesterWindow(MovingWindow):
# Read servers.
server_list_items = []
try:
with open(_datadir + "serverlist.json", "r") as server_file:
with open(_datadir + "serverlist.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@ -4099,7 +4098,7 @@ class PesterWindow(MovingWindow):
msgbox.setIcon(QtWidgets.QMessageBox.Icon.Warning)
msgbox.setText("Server certificate validation failed")
msgbox.setInformativeText(
'Reason: "%s (%s)"' % (e.verify_message, e.verify_code)
'Reason: "{} ({})"'.format(e.verify_message, e.verify_code)
+ "\n\nConnect anyway?"
)
msgbox.setStandardButtons(
@ -4150,7 +4149,7 @@ class PesterWindow(MovingWindow):
class PesterTray(QtWidgets.QSystemTrayIcon):
def __init__(self, icon, mainwindow, parent):
super(PesterTray, self).__init__(icon, parent)
super().__init__(icon, parent)
self.mainwindow = mainwindow
@QtCore.pyqtSlot(int)
@ -4167,7 +4166,7 @@ class PesterTray(QtWidgets.QSystemTrayIcon):
class MainProgram(QtCore.QObject):
def __init__(self):
super(MainProgram, self).__init__()
super().__init__()
_oldhook = sys.excepthook
sys.excepthook = self.uncaughtException
@ -4191,8 +4190,8 @@ class MainProgram(QtCore.QObject):
windll.shell32.SetCurrentProcessExplicitAppUserModelID(wid)
except Exception as err:
# Log, but otherwise ignore any exceptions.
PchumLog.error("Failed to set AppUserModel ID: {0}".format(err))
PchumLog.error("Attempted to set as {0!r}.".format(wid))
PchumLog.error(f"Failed to set AppUserModel ID: {err}")
PchumLog.error(f"Attempted to set as {wid!r}.")
# Back to our scheduled program.
self.app = QtWidgets.QApplication(sys.argv)
@ -4559,7 +4558,7 @@ class MainProgram(QtCore.QObject):
# Show error to end user and log.
try:
# Log to log file
PchumLog.error("%s, %s" % (exc, value))
PchumLog.error("{}, {}".format(exc, value))
# Try to write to separate logfile
try:

View file

@ -1,4 +1,3 @@
# -*- coding=UTF-8; tab-width: 4 -*-
# Heavily modified version of the code featured at the given link
## {{{ http://code.activestate.com/recipes/473786/ (r1)
class AttrDict(dict):
@ -11,7 +10,7 @@ class AttrDict(dict):
Overload _is_reserved if you want to change this."""
def __init__(self, init={}):
super(AttrDict, self).__init__(init)
super().__init__(init)
def __getstate__(self):
return list(self.__dict__.items())
@ -21,16 +20,16 @@ class AttrDict(dict):
self.__dict__[key] = val
def __repr__(self):
return "{0}({1})".format(type(self).__name__, super(AttrDict, self).__repr__())
return f"{type(self).__name__}({super().__repr__()})"
def __setitem__(self, name, value):
return super(AttrDict, self).__setitem__(name, value)
return super().__setitem__(name, value)
def __getitem__(self, name):
return super(AttrDict, self).__getitem__(name)
return super().__getitem__(name)
def __delitem__(self, name):
return super(AttrDict, self).__delitem__(name)
return super().__delitem__(name)
def __getattr__(self, name):
# NOTE: __getattr__ is called if the code has already failed to access
@ -50,7 +49,7 @@ class AttrDict(dict):
# Raising KeyError here will confuse __deepcopy__, so don't do
# that.
# Throw a custom error.
raise AttributeError("No key/attr {0!r}".format(name))
raise AttributeError(f"No key/attr {name!r}")
return result
def __setattr__(self, name, value):
@ -68,7 +67,7 @@ class AttrDict(dict):
# in this particular function?...
return object.__setattr__(self, name, value)
else:
return super(AttrDict, self).__setitem__(name, value)
return super().__setitem__(name, value)
def __delattr__(self, name):
# We very *specifically* use self.__dict__ here, because we couldn't
@ -106,10 +105,10 @@ class DefAttrDict(AttrDict):
def __init__(self, default_factory=None, *args, **kwargs):
self.default_factory = default_factory
super(DefAttrDict, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
def __repr__(self):
return "{0}({1!r}, {2})".format(
return "{}({!r}, {})".format(
type(self).__name__,
self.default_factory,
# We skip normal processing here, since AttrDict provides basic
@ -119,7 +118,7 @@ class DefAttrDict(AttrDict):
def __getitem__(self, name):
try:
result = super(DefAttrDict, self).__getitem__(name)
result = super().__getitem__(name)
except KeyError:
result = None
if self.default_factory is not None:
@ -129,7 +128,7 @@ class DefAttrDict(AttrDict):
def __getattr__(self, name):
try:
result = super(DefAttrDict, self).__getattr__(name)
result = super().__getattr__(name)
except AttributeError:
# Detect special/reserved names.
if self._is_reserved(name):

View file

@ -1,6 +1,3 @@
# -*- coding=UTF-8; tab-width: 4 -*-
from .unicolor import Color
import re
@ -20,7 +17,7 @@ except NameError:
# function appropriate to the given format - e.g. CTag.convert_pchum.
class Lexeme(object):
class Lexeme:
def __init__(self, string, origin):
# The 'string' property is just what it came from; the original
# representation. It doesn't have to be used, and honestly probably
@ -104,7 +101,7 @@ class CTag(Specifier):
sets_color = True
def __init__(self, string, origin, color):
super(CTag, self).__init__(string, origin)
super().__init__(string, origin)
# So we can also have None
if isinstance(color, tuple):
if len(color) < 2:
@ -256,7 +253,7 @@ class SpecifierEnd(CTagEnd, FTagEnd):
# .sets_color to False
class Lexer(object):
class Lexer:
# Subclasses need to supply a ref themselves
ref = None
compress_tags = False

View file

@ -1,6 +1,3 @@
# -*- coding=UTF-8; tab-width: 4 -*-
__all__ = ["Color"]
# karxi: Copied from my old Textsub script. Please forgive the mess, and keep
@ -26,7 +23,7 @@ else:
LabTuple = collections.namedtuple("LabTuple", ["L", "a", "b"])
class Color(object):
class Color:
# The threshold at which to consider two colors noticeably different, even
# if only barely
jnd = 2.3
@ -145,7 +142,7 @@ class Color(object):
def __repr__(self):
##return "%s(%r)" % (type(self).__name__, str(self))
return "%s(%r)" % (type(self).__name__, self.reduce_hexstr(self.hexstr))
return "{}({!r})".format(type(self).__name__, self.reduce_hexstr(self.hexstr))
def __str__(self):
##return self.reduce_hexstr(self.hexstr)
@ -158,8 +155,7 @@ class Color(object):
def __iter__(self):
targs = (self.red, self.green, self.blue)
for t in targs:
yield t
yield from targs
# If we got here, we're out of attributes to provide
raise StopIteration

View file

@ -25,7 +25,7 @@ _datadir = ostools.getDataDir()
PchumLog = logging.getLogger("pchumLogger")
class PesterLog(object):
class PesterLog:
def __init__(self, handle, parent=None):
global _datadir
self.parent = parent
@ -66,10 +66,12 @@ class PesterLog(object):
self.convos[handle] = {}
for (format, t) in modes.items():
if not os.path.exists(
"%s/%s/%s/%s" % (self.logpath, self.handle, handle, format)
"{}/{}/{}/{}".format(self.logpath, self.handle, handle, format)
):
os.makedirs(
"%s/%s/%s/%s" % (self.logpath, self.handle, handle, format)
"{}/{}/{}/{}".format(
self.logpath, self.handle, handle, format
)
)
fp = codecs.open(
"%s/%s/%s/%s/%s.%s.txt"
@ -94,7 +96,7 @@ class PesterLog(object):
# for (format, t) in modes.items():
# self.finish(handle)
except (IOError, OSError, KeyError, IndexError, ValueError) as e:
except (OSError, KeyError, IndexError, ValueError) as e:
# Catching this exception does not stop pchum from dying if we run out of file handles </3
PchumLog.critical(e)
errmsg = QtWidgets.QMessageBox()
@ -125,7 +127,7 @@ class PesterLog(object):
f.close()
class userConfig(object):
class userConfig:
def __init__(self, parent):
self.parent = parent
# Use for bit flag log setting
@ -184,9 +186,9 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
if not os.path.exists(self.logpath):
os.makedirs(self.logpath)
try:
with open("%s/groups.js" % (self.logpath), "r") as fp:
with open("%s/groups.js" % (self.logpath)) as fp:
self.groups = json.load(fp)
except (IOError, ValueError):
except (OSError, ValueError):
self.groups = {}
with open("%s/groups.js" % (self.logpath), "w") as fp:
json.dump(self.groups, fp)
@ -225,15 +227,12 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
pzip.writestr(x, f.read())
PchumLog.info("Updated backups-%s." % current_backup)
except OSError as e:
PchumLog.warning("Failed to make backup, no permission?")
PchumLog.warning(e)
except shutil.Error as e:
PchumLog.warning("Failed to make backup, shutil error?")
PchumLog.warning(e)
PchumLog.warning(f"Failed to make backup, shutil error?\n{e}")
except zipfile.BadZipFile as e:
PchumLog.warning("Failed to make backup, BadZipFile?")
PchumLog.warning(e)
PchumLog.warning(f"Failed to make backup, BadZipFile?\n{e}")
except OSError as e:
PchumLog.warning(f"Failed to make backup, no permission?\n{e}")
def chums(self):
if "chums" not in self.config:
@ -445,7 +444,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
if hasattr(self.parent, "serverOverride"):
return self.parent.serverOverride
try:
with open(_datadir + "server.json", "r") as server_file:
with open(_datadir + "server.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@ -468,7 +467,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
if hasattr(self.parent, "portOverride"):
return self.parent.portOverride
try:
with open(_datadir + "server.json", "r") as server_file:
with open(_datadir + "server.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@ -481,7 +480,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
# if hasattr(self.parent, 'tlsOverride'):
# return self.parent.tlsOverride
try:
with open(_datadir + "server.json", "r") as server_file:
with open(_datadir + "server.json") as server_file:
read_file = server_file.read()
server_file.close()
server_obj = json.loads(read_file)
@ -578,7 +577,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
+ "</a>"
+ "<br><br>"
+ str(e)
+ "<\h3><\html>"
+ r"<\h3><\html>"
)
# "\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \
# _datadir+"pesterchum.js" + \
@ -589,7 +588,7 @@ with a backup from: <a href='%s'>%s</a></h3></html>"
return [userProfile(p) for p in profs]
class userProfile(object):
class userProfile:
def __init__(self, user):
self.profiledir = _datadir + "profiles"
@ -610,8 +609,8 @@ class userProfile(object):
if len(initials) >= 2:
initials = (
initials,
"%s%s" % (initials[0].lower(), initials[1]),
"%s%s" % (initials[0], initials[1].lower()),
"{}{}".format(initials[0].lower(), initials[1]),
"{}{}".format(initials[0], initials[1].lower()),
)
self.mentions = [r"\b(%s)\b" % ("|".join(initials))]
else:
@ -624,7 +623,7 @@ class userProfile(object):
# u'XXX\\AppData\\Local\\pesterchum/profiles/XXX.js'
# Part 3 :(
try:
with open("%s/%s.js" % (self.profiledir, user)) as fp:
with open("{}/{}.js".format(self.profiledir, user)) as fp:
self.userprofile = json.load(fp)
except (json.JSONDecodeError, FileNotFoundError) as e:
msgBox = QtWidgets.QMessageBox()
@ -644,7 +643,7 @@ class userProfile(object):
+ "<br><br>If you got this message at launch you may want to change your default profile."
+ "<br><br>"
+ str(e)
+ "<\h3><\html>"
+ r"<\h3><\html>"
)
# "\" if pesterchum acts oddly you might want to try backing up and then deleting \"" + \
# _datadir+"pesterchum.js" + \
@ -674,8 +673,8 @@ class userProfile(object):
if len(initials) >= 2:
initials = (
initials,
"%s%s" % (initials[0].lower(), initials[1]),
"%s%s" % (initials[0], initials[1].lower()),
"{}{}".format(initials[0].lower(), initials[1]),
"{}{}".format(initials[0], initials[1].lower()),
)
self.userprofile["mentions"] = [r"\b(%s)\b" % ("|".join(initials))]
else:
@ -736,11 +735,12 @@ class userProfile(object):
return self.mentions
def setMentions(self, mentions):
i = None
try:
for (i, m) in enumerate(mentions):
re.compile(m)
except re.error as e:
PchumLog.error("#%s Not a valid regular expression: %s" % (i, e))
PchumLog.error("#{} Not a valid regular expression: {}".format(i, e))
else:
self.mentions = mentions
self.userprofile["mentions"] = mentions
@ -794,7 +794,7 @@ class userProfile(object):
jsonoutput = json.dumps(self.userprofile)
except ValueError as e:
raise e
with open("%s/%s.js" % (self.profiledir, handle), "w") as fp:
with open("{}/{}.js".format(self.profiledir, handle), "w") as fp:
fp.write(jsonoutput)
def saveNickServPass(self):
@ -811,7 +811,7 @@ class userProfile(object):
@staticmethod
def newUserProfile(chatprofile):
if os.path.exists("%s/%s.js" % (_datadir + "profiles", chatprofile.handle)):
if os.path.exists("{}/{}.js".format(_datadir + "profiles", chatprofile.handle)):
newprofile = userProfile(chatprofile.handle)
else:
newprofile = userProfile(chatprofile)
@ -826,9 +826,9 @@ class PesterProfileDB(dict):
if not os.path.exists(self.logpath):
os.makedirs(self.logpath)
try:
with open("%s/chums.js" % (self.logpath), "r") as fp:
with open("%s/chums.js" % (self.logpath)) as fp:
chumdict = json.load(fp)
except (IOError, ValueError):
except (OSError, ValueError):
# karxi: This code feels awfully familiar....
chumdict = {}
with open("%s/chums.js" % (self.logpath), "w") as fp:
@ -852,7 +852,7 @@ class PesterProfileDB(dict):
handle,
color=QtGui.QColor(c["color"]),
mood=Mood(c["mood"]),
**options
**options,
),
)
)
@ -928,7 +928,7 @@ class pesterTheme(dict):
try:
with open(self.path + "/style.js") as fp:
theme = json.load(fp, object_hook=self.pathHook)
except IOError:
except OSError:
theme = json.loads("{}")
self.update(theme)
if "inherits" in self:
@ -939,7 +939,7 @@ class pesterTheme(dict):
def __getitem__(self, key):
keys = key.split("/")
try:
v = super(pesterTheme, self).__getitem__(keys.pop(0))
v = super().__getitem__(keys.pop(0))
except KeyError as e:
if hasattr(self, "inheritedTheme"):
return self.inheritedTheme[key]
@ -969,7 +969,7 @@ class pesterTheme(dict):
def get(self, key, default):
keys = key.split("/")
try:
v = super(pesterTheme, self).__getitem__(keys.pop(0))
v = super().__getitem__(keys.pop(0))
for k in keys:
v = v[k]
return default if v is None else v
@ -982,7 +982,7 @@ class pesterTheme(dict):
def has_key(self, key):
keys = key.split("/")
try:
v = super(pesterTheme, self).__getitem__(keys.pop(0))
v = super().__getitem__(keys.pop(0))
for k in keys:
v = v[k]
return v is not None

View file

@ -7,7 +7,6 @@ except ImportError:
print("PyQt5 fallback (pyquirks.py)")
from PyQt5 import QtWidgets
import ostools
from quirks import ScriptQuirks
PchumLog = logging.getLogger("pchumLogger")

View file

@ -40,16 +40,16 @@ def init(host="127.0.0.1", port=None):
if line.startswith("port=") and line[5:-1].isdigit():
port = int(line[5:-1])
break
except IOError:
except OSError:
raise TwmnError(TwmnError.NO_CONF)
if type(port) == type(str()):
if type(port) == type(""):
port = int(port)
global s
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((host, port))
class Notification(object):
class Notification:
def __init__(self, title="", msg="", icon=""):
self.title = str(title)
self.msg = str(msg)

View file

@ -7,7 +7,7 @@ _datadir = ostools.getDataDir()
PchumLog = logging.getLogger("pchumLogger")
class ScriptQuirks(object):
class ScriptQuirks:
def __init__(self):
self._datadir = ostools.getDataDir()
self.home = os.getcwd()
@ -73,7 +73,9 @@ class ScriptQuirks(object):
continue
except Exception as e:
PchumLog.warning(
"Error loading %s: %s (in quirks.py)" % (os.path.basename(name), e)
"Error loading {}: {} (in quirks.py)".format(
os.path.basename(name), e
)
)
else:
if self.modHas(module, "setup"):

View file

@ -6,7 +6,6 @@ except ImportError:
print("PyQt5 fallback (randomer.py)")
from PyQt5 import QtCore, QtWidgets
import ostools
PchumLog = logging.getLogger("pchumLogger")

View file

@ -2,7 +2,6 @@
import sys
from cx_Freeze import setup, Executable
import pygame
from version import buildVersion

View file

@ -24,7 +24,7 @@ PchumLog = logging.getLogger("pchumLogger")
pynotify = None
class DefaultToast(object):
class DefaultToast:
def __init__(self, machine, title, msg, icon):
self.machine = machine
self.title = title
@ -43,8 +43,8 @@ class DefaultToast(object):
PchumLog.info("Done")
class ToastMachine(object):
class __Toast__(object):
class ToastMachine:
class __Toast__:
def __init__(self, machine, title, msg, time=3000, icon="", importance=0):
self.machine = machine
self.title = title