Bunch of pep8 and inspection cleanup

This commit is contained in:
Ebag333
2016-12-15 12:43:19 -08:00
parent 658a87cbc0
commit 4fb07cc1d0
24 changed files with 105 additions and 93 deletions

View File

@@ -44,11 +44,6 @@ class StreamToLogger(object):
From: http://www.electricmonk.nl/log/2011/08/14/redirect-stdout-and-stderr-to-a-logger-in-python/
"""
def __init__(self, logger, log_level=logging.INFO):
self.logger = logger
self.log_level = log_level
self.linebuf = ''
def write(self, buf):
for line in buf.rstrip().splitlines():
self.logger.log(self.log_level, line.rstrip())
@@ -61,7 +56,6 @@ def isFrozen():
return False
def __createDirs(path):
if not os.path.exists(path):
os.makedirs(path)
@@ -148,10 +142,12 @@ def getPyfaPath(append=None):
root = os.path.dirname(os.path.realpath(os.path.abspath(base)))
return _getPath(root, append)
def getSavePath(append=None):
root = os.path.expanduser(os.path.join("~", ".pyfa"))
return _getPath(root, append)
def _getPath(root, Append=None):
if type(root) == str: # leave unicode ones alone
try:

View File

@@ -208,6 +208,7 @@ def getFit(lookfor, eager=None):
return fit
def getFitsWithShip(shipID, ownerID=None, where=None, eager=None):
"""
Get all the fits using a certain ship.
@@ -284,6 +285,7 @@ def getFitList(eager=None):
return fits
@cachedQuery(Price, 1, "typeID")
def getPrice(typeID):
if isinstance(typeID, int):
@@ -407,6 +409,7 @@ def searchFits(nameLike, where=None, eager=None):
return fits
def getProjectedFits(fitID):
if isinstance(fitID, int):
with sd_lock:

View File

@@ -1,5 +1,7 @@
# Not used by any item
type = "passive"
def handler(fit, module, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("Information Command Specialist"),
"commandBonusHidden", module.getModifiedItemAttr("eliteBonusCommandShips3"), skill="Command Ships")

View File

@@ -5,8 +5,7 @@ type = "active", "projected"
def handler(fit, src, context):
if "projected" in context and (
(hasattr(src, "state") and src.state >= State.ACTIVE) or hasattr(src, "amountActive")):
if "projected" in context and ((hasattr(src, "state") and src.state >= State.ACTIVE) or hasattr(src, "amountActive")):
multiplier = src.amountActive if hasattr(src, "amountActive") else 1
amount = src.getModifiedItemAttr("energyNeutralizerAmount")
time = src.getModifiedItemAttr("duration")

View File

@@ -4,7 +4,8 @@ runTime = "late"
def handler(fit, module, context):
if "projected" not in context: return
if "projected" not in context:
return
bonus = module.getModifiedItemAttr("structureDamageAmount")
duration = module.getModifiedItemAttr("duration") / 1000.0
fit.extraAttributes.increase("hullRepair", bonus / duration)

View File

@@ -12,5 +12,5 @@ def handler(fit, module, context):
mod.charge.requiresSkill("Light Missiles"),
"{}Damage".format(type),
1 / module.getModifiedItemAttr("modeDamageBonusPostDiv"),
stackingPenalties = True,
stackingPenalties=True,
penaltyGroup="postDiv")

View File

@@ -6,8 +6,8 @@ type = "active", "projected"
def handler(fit, container, context):
amount = 0
if "projected" in context and ((hasattr(container, "state")
and container.state >= State.ACTIVE) or hasattr(container, "amountActive")):
amount = container.getModifiedItemAttr("energyNeutralizerAmount")
time = container.getModifiedItemAttr("duration")
fit.addDrain(container, time, amount, 0)
if "projected" in context:
if (hasattr(container, "state") and container.state >= State.ACTIVE) or hasattr(container, "amountActive"):
amount = container.getModifiedItemAttr("energyNeutralizerAmount")
time = container.getModifiedItemAttr("duration")
fit.addDrain(container, time, amount, 0)

View File

@@ -3,6 +3,7 @@ type = "active", "projected"
def handler(fit, module, context):
if "projected" not in context: return
if "projected" not in context:
return
fit.ship.boostItemAttr("maxVelocity", module.getModifiedItemAttr("speedFactor"),
stackingPenalties=True, remoteResists=True)

View File

@@ -1,5 +1,7 @@
# Not used by any item
type = "passive"
def handler(fit, module, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("Information Command Specialist"),
"commandBonusHidden", module.getModifiedItemAttr("subsystemBonusAmarrDefensive"), skill="Amarr Defensive Systems")

View File

@@ -1,5 +1,7 @@
# Not used by any item
type = "passive"
def handler(fit, module, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("Information Command Specialist"),
"commandBonusHidden", module.getModifiedItemAttr("subsystemBonusCaldariDefensive"), skill="Caldari Defensive Systems")

View File

@@ -1,5 +1,7 @@
# Not used by any item
type = "passive"
def handler(fit, module, context):
fit.modules.filteredItemBoost(lambda mod: mod.item.requiresSkill("Information Command Specialist"),
"commandBonusHidden", module.getModifiedItemAttr("subsystemBonusGallenteDefensive"), skill="Gallente Defensive Systems")

View File

@@ -2,6 +2,7 @@
type = "passive"
runTime = "late"
def handler(fit, module, context):
for x in xrange(1, 4):
module.boostChargeAttr("warfareBuff{}Multiplier".format(x), module.getModifiedItemAttr("commandBurstStrengthBonus"))

View File

@@ -502,7 +502,7 @@ class FittingView(d.Display):
itemContext = "Tactical Mode"
fullContext = (srcContext, itemContext)
if not srcContext in tuple(fCtxt[0] for fCtxt in contexts):
if srcContext not in tuple(fCtxt[0] for fCtxt in contexts):
contexts.append(fullContext)
selection.append(mod)
@@ -514,7 +514,6 @@ class FittingView(d.Display):
if srcContext not in tuple(fCtxt[0] for fCtxt in contexts):
contexts.append(fullContext)
if mod.charge is not None:
srcContext = "fittingCharge"
itemContext = sMkt.getCategoryByItem(mod.charge).name

View File

@@ -51,7 +51,7 @@ from gui.graphFrame import GraphFrame
from gui.copySelectDialog import CopySelectDialog
from gui.utils.clipboard import toClipboard, fromClipboard
from gui.updateDialog import UpdateDialog
from gui.builtinViews import * # TODO: unsure if this is needed here
from gui.builtinViews import * # TODO: unsure if this is needed here
from gui import graphFrame
from service.settings import SettingsProvider

View File

@@ -34,8 +34,8 @@ class Attribute():
if isinstance(identity, (int, basestring)):
info = eos.db.getAttributeInfo(identity, eager=("icon", "unit"))
elif isinstance(identity, (int, float)):
id = int(identity)
info = eos.db.getAttributeInfo(id, eager=("icon", "unit"))
id_ = int(identity)
info = eos.db.getAttributeInfo(id_, eager=("icon", "unit"))
else:
info = None
return info

View File

@@ -279,8 +279,8 @@ class Character(object):
return (char.apiID or "", char.apiKey or "", char.defaultChar or "", chars or [])
def apiEnabled(self, charID):
id, key, default, _ = self.getApiDetails(charID)
return id is not "" and key is not "" and default is not ""
id_, key, default, _ = self.getApiDetails(charID)
return id_ is not "" and key is not "" and default is not ""
def apiCharList(self, charID, userID, apiKey):
char = eos.db.getCharacter(charID)

View File

@@ -118,7 +118,6 @@ CONVERSIONS = {
"'Full Duplex' Ballistic Targeting System": "'Full Duplex' Ballistic Control System",
"'Kindred' Stabilization Actuator I": "'Kindred' Gyrostabilizer",
"Process-Interruptive Warp Disruptor": "'Interruptive' Warp Disruptor",
"Multi Sensor Firewall": "'Firewall' Signal Amplifier",
"'Inception' Target Painter I": "'Inception' Target Painter",
"Citadel Torpedoes": "XL Torpedoes",
"'Shady' ECCM - Gravimetric I": "'Shady' Sensor Booster",

View File

@@ -118,9 +118,9 @@ class Crest():
return chars2
def getCrestCharacter(self, charID):
'''
"""
Get character, and modify to include the eve connection
'''
"""
if self.settings.get('mode') == CrestModes.IMPLICIT:
if self.implicitCharacter.ID != charID:
raise ValueError("CharacterID does not match currently logged in character.")
@@ -141,7 +141,8 @@ class Crest():
return char.eve.get('%scharacters/%d/fittings/' % (char.eve._authed_endpoint, char.ID))
def postFitting(self, charID, json):
# @todo: new fitting ID can be recovered from Location header, ie: Location -> https://api-sisi.testeveonline.com/characters/1611853631/fittings/37486494/
# @todo: new fitting ID can be recovered from Location header,
# ie: Location -> https://api-sisi.testeveonline.com/characters/1611853631/fittings/37486494/
char = self.getCrestCharacter(charID)
return char.eve.post('%scharacters/%d/fittings/' % (char.eve._authed_endpoint, char.ID), data=json)

View File

@@ -949,28 +949,28 @@ class FilterRowset(object):
# - Each key maps to a Rowset, containing only the rows where the value
# of the column this FilterRowset was made on matches the key.
def __init__(self, cols=None, rows=None, key=None, key2=None, dict=None):
if dict is not None:
self._items = items = dict
def __init__(self, cols=None, rows=None, key=None, key2=None, dict_=None):
if dict_ is not None:
self._items = items = dict_
elif cols is not None:
self._items = items = {}
idfield = cols.index(key)
if not key2:
for row in rows:
id = row[idfield]
if id in items:
items[id].append(row)
id_ = row[idfield]
if id_ in items:
items[id_].append(row)
else:
items[id] = [row]
items[id_] = [row]
else:
idfield2 = cols.index(key2)
for row in rows:
id = row[idfield]
if id in items:
items[id][row[idfield2]] = row
id_ = row[idfield]
if id_ in items:
items[id_][row[idfield2]] = row
else:
items[id] = {row[idfield2]: row}
items[id_] = {row[idfield2]: row}
self._cols = cols
self.key = key
@@ -987,7 +987,7 @@ class FilterRowset(object):
self.__iter__ = items.__iter__
def copy(self):
return FilterRowset(self._cols[:], None, self.key, self.key2, dict=copy.deepcopy(self._items))
return FilterRowset(self._cols[:], None, self.key, self.key2, dict_=copy.deepcopy(self._items))
def get(self, key, default=_unspecified):
try:

View File

@@ -199,11 +199,12 @@ class Fit(object):
self.recalc(fit, withBoosters=True)
def getFit(self, fitID, projected=False, basic=False):
''' Gets fit from database
"""
Gets fit from database
Projected is a recursion flag that is set to reduce recursions into projected fits
Basic is a flag to simply return the fit without any other processing
'''
"""
if fitID is None:
return None
fit = eos.db.getFit(fitID)

View File

@@ -49,9 +49,9 @@ class ImplantSets(object):
return eos.db.getImplantSet(setID).implants
def addImplant(self, setID, itemID):
set = eos.db.getImplantSet(setID)
implant_set = eos.db.getImplantSet(setID)
implant = es_Implant(eos.db.getItem(itemID))
set.implants.append(implant)
implant_set.implants.append(implant)
eos.db.commit()
def removeImplant(self, setID, implant):

View File

@@ -60,13 +60,13 @@ class ShipBrowserWorkerThread(threading.Thread):
sMkt = Market.getInstance()
while True:
try:
id, callback = queue.get()
set = cache.get(id)
if set is None:
set = sMkt.getShipList(id)
cache[id] = set
id_, callback = queue.get()
set_ = cache.get(id_)
if set_ is None:
set_ = sMkt.getShipList(id_)
cache[id_] = set_
wx.CallAfter(callback, (id, set))
wx.CallAfter(callback, (id_, set_))
except:
pass
finally:
@@ -131,13 +131,13 @@ class SearchWorkerThread(threading.Thread):
sMkt = Market.getInstance()
if filterOn is True:
# Rely on category data provided by eos as we don't hardcode them much in service
filter = or_(e_Category.name.in_(sMkt.SEARCH_CATEGORIES), e_Group.name.in_(sMkt.SEARCH_GROUPS))
filter_ = or_(e_Category.name.in_(sMkt.SEARCH_CATEGORIES), e_Group.name.in_(sMkt.SEARCH_GROUPS))
elif filterOn: # filter by selected categories
filter = e_Category.name.in_(filterOn)
filter_ = e_Category.name.in_(filterOn)
else:
filter = None
filter_ = None
results = eos.db.searchItems(request, where=filter,
results = eos.db.searchItems(request, where=filter_,
join=(e_Item.group, e_Group.category),
eager=("icon", "group.category", "metaGroup", "metaGroup.parent"))
@@ -418,8 +418,8 @@ class Market():
item = eos.db.getItem(identity, *args, **kwargs)
elif isinstance(identity, float):
id = int(identity)
item = eos.db.getItem(id, *args, **kwargs)
id_ = int(identity)
item = eos.db.getItem(id_, *args, **kwargs)
else:
raise TypeError("Need Item object, integer, float or string as argument")
except:
@@ -453,8 +453,8 @@ class Market():
elif isinstance(identity, (int, basestring)):
category = eos.db.getCategory(identity, *args, **kwargs)
elif isinstance(identity, float):
id = int(identity)
category = eos.db.getCategory(id, *args, **kwargs)
id_ = int(identity)
category = eos.db.getCategory(id_, *args, **kwargs)
else:
raise TypeError("Need Category object, integer, float or string as argument")
return category
@@ -466,8 +466,8 @@ class Market():
elif isinstance(identity, (int, basestring)):
metaGroup = eos.db.getMetaGroup(identity, *args, **kwargs)
elif isinstance(identity, float):
id = int(identity)
metaGroup = eos.db.getMetaGroup(id, *args, **kwargs)
id_ = int(identity)
metaGroup = eos.db.getMetaGroup(id_, *args, **kwargs)
else:
raise TypeError("Need MetaGroup object, integer, float or string as argument")
return metaGroup
@@ -477,8 +477,8 @@ class Market():
if isinstance(identity, eos.types.MarketGroup):
marketGroup = identity
elif isinstance(identity, (int, float)):
id = int(identity)
marketGroup = eos.db.getMarketGroup(id, *args, **kwargs)
id_ = int(identity)
marketGroup = eos.db.getMarketGroup(id_, *args, **kwargs)
else:
raise TypeError("Need MarketGroup object, integer or float as argument")
return marketGroup
@@ -522,8 +522,8 @@ class Market():
def getMetaGroupIdByItem(self, item, fallback=0):
"""Get meta group ID by item"""
id = getattr(self.getMetaGroupByItem(item), "ID", fallback)
return id
id_ = getattr(self.getMetaGroupByItem(item), "ID", fallback)
return id_
def getMarketGroupByItem(self, item, parentcheck=True):
"""Get market group by item, its ID or name"""
@@ -607,7 +607,7 @@ class Market():
filter(lambda item: self.getPublicityByItem(item) and self.getGroupByItem(item) == group, groupItems))
return items
def getItemsByMarketGroup(self, mg, vars=True):
def getItemsByMarketGroup(self, mg, vars_=True):
"""Get items in the given market group"""
result = set()
# Get items from eos market group
@@ -616,7 +616,7 @@ class Market():
if mg.ID in self.ITEMS_FORCEDMARKETGROUP_R:
forceditms = set(self.getItem(itmn) for itmn in self.ITEMS_FORCEDMARKETGROUP_R[mg.ID])
baseitms.update(forceditms)
if vars:
if vars_:
parents = set()
for item in baseitms:
# Add one of the base market group items to result
@@ -634,7 +634,7 @@ class Market():
else:
result = baseitms
# Get rid of unpublished items
result = set(filter(lambda item: self.getPublicityByItem(item), result))
result = set(filter(lambda item_: self.getPublicityByItem(item_), result))
return result
def marketGroupHasTypesCheck(self, mg):
@@ -669,7 +669,7 @@ class Market():
elif self.marketGroupHasTypesCheck(mg):
# Do not request variations to make process faster
# Pick random item and use its icon
items = self.getItemsByMarketGroup(mg, vars=False)
items = self.getItemsByMarketGroup(mg, vars_=False)
try:
item = items.pop()
except KeyError:
@@ -707,8 +707,8 @@ class Market():
the ID, the name and the icon of the group
"""
root = set()
for id in self.ROOT_MARKET_GROUPS:
mg = self.getMarketGroup(id, eager="icon")
for id_ in self.ROOT_MARKET_GROUPS:
mg = self.getMarketGroup(id_, eager="icon")
root.add(mg)
return root
@@ -728,14 +728,14 @@ class Market():
ship.race
return ships
def getShipListDelayed(self, id, callback):
def getShipListDelayed(self, id_, callback):
"""Background version of getShipList"""
self.shipBrowserWorkerThread.queue.put((id, callback))
self.shipBrowserWorkerThread.queue.put((id_, callback))
def searchShips(self, name):
"""Find ships according to given text pattern"""
filter = e_Category.name.in_(["Ship", "Structure"])
results = eos.db.searchItems(name, where=filter,
filter_ = e_Category.name.in_(["Ship", "Structure"])
results = eos.db.searchItems(name, where=filter_,
join=(e_Item.group, e_Group.category),
eager=("icon", "group.category", "metaGroup", "metaGroup.parent"))
ships = set()

View File

@@ -35,7 +35,7 @@ from service.fit import Fit
import wx
from eos.types import State, Slot, Module, Cargo, Ship, Drone, Implant, Booster, Citadel
from eos.types import State, Slot, Module, Cargo, Ship, Drone, Implant, Booster, Citadel, Fighter
from service.crest import Crest
from service.market import Market
@@ -83,8 +83,8 @@ class Port(object):
if callback: # Pulse
wx.CallAfter(callback, 1, "Processing file:\n%s" % path)
file = open(path, "r")
srcString = file.read()
file_ = open(path, "r")
srcString = file_.read()
if len(srcString) == 0: # ignore blank files
continue
@@ -259,7 +259,7 @@ class Port(object):
item = nested_dict()
item['flag'] = INV_FLAG_FIGHTER
item['quantity'] = fighter.amountActive
item['type']['href'] = "%sinventory/types/%d/"%(eve._authed_endpoint, fighter.item.ID)
item['type']['href'] = "%sinventory/types/%d/" % (eve._authed_endpoint, fighter.item.ID)
item['type']['id'] = fighter.item.ID
item['type']['name'] = fighter.item.name
fit['items'].append(item)
@@ -299,8 +299,8 @@ class Port(object):
return "DNA", (cls.importDna(string),)
@staticmethod
def importCrest(str):
fit = json.loads(str)
def importCrest(str_):
fit = json.loads(str_)
sMkt = Market.getInstance()
f = Fit()
@@ -365,16 +365,16 @@ class Port(object):
sMkt = Market.getInstance()
ids = map(int, re.findall(r'\d+', string))
for id in ids:
for id_ in ids:
try:
try:
try:
Ship(sMkt.getItem(sMkt.getItem(id)))
Ship(sMkt.getItem(sMkt.getItem(id_)))
except ValueError:
Citadel(sMkt.getItem(sMkt.getItem(id)))
Citadel(sMkt.getItem(sMkt.getItem(id_)))
except ValueError:
Citadel(sMkt.getItem(id))
string = string[string.index(str(id)):]
Citadel(sMkt.getItem(id_))
string = string[string.index(str(id_)):]
break
except:
pass
@@ -389,10 +389,10 @@ class Port(object):
f.ship = Citadel(sMkt.getItem(int(info[0])))
f.name = "{0} - DNA Imported".format(f.ship.item.name)
except UnicodeEncodeError:
def logtransform(s):
if len(s) > 10:
return s[:10] + "..."
return s
def logtransform(s_):
if len(s_) > 10:
return s_[:10] + "..."
return s_
logger.exception("Couldn't import ship data %r", [logtransform(s) for s in info])
return None
@@ -519,7 +519,7 @@ class Port(object):
elif item.category.name == "Fighter":
extraAmount = int(extraAmount) if extraAmount is not None else 1
fighterItem = Fighter(item)
if (extraAmount > fighterItem.fighterSquadronMaxSize): #Amount bigger then max fightergroup size
if (extraAmount > fighterItem.fighterSquadronMaxSize): # Amount bigger then max fightergroup size
extraAmount = fighterItem.fighterSquadronMaxSize
if fighterItem.fits(fit):
fit.fighters.append(fighterItem)
@@ -666,9 +666,10 @@ class Port(object):
elif entityState == "Inactive":
d.amountActive = 0
f.drones.append(d)
elif droneItem.category.name == "Fighter": # EFT saves fighter as drones
elif droneItem.category.name == "Fighter": # EFT saves fighter as drones
ft = Fighter(droneItem)
ft.amount = int(droneAmount) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize
ft.amount = int(droneAmount) if ft.amount <= ft.fighterSquadronMaxSize \
else ft.fighterSquadronMaxSize
f.fighters.append(ft)
else:
continue
@@ -805,7 +806,8 @@ class Port(object):
f.drones.append(d)
elif item.category.name == "Fighter":
ft = Fighter(item)
ft.amount = int(hardware.getAttribute("qty")) if ft.amount <= ft.fighterSquadronMaxSize else ft.fighterSquadronMaxSize
ft.amount = int(hardware.getAttribute("qty")) if ft.amount <= ft.fighterSquadronMaxSize \
else ft.fighterSquadronMaxSize
f.fighters.append(ft)
elif hardware.getAttribute("slot").lower() == "cargo":
# although the eve client only support charges in cargo, third-party programs
@@ -946,7 +948,7 @@ class Port(object):
# `or 1` because some charges (ie scripts) are without qty
charges[mod.chargeID] += mod.numCharges or 1
for subsystem in sorted(subsystems, key=lambda mod: mod.getModifiedItemAttr("subSystemSlot")):
for subsystem in sorted(subsystems, key=lambda mod_: mod_.getModifiedItemAttr("subSystemSlot")):
dna += ":{0};1".format(subsystem.itemID)
for mod in mods:

View File

@@ -10,6 +10,7 @@ from service.settings import CRESTSettings
logger = logging.getLogger(__name__)
# noinspection PyPep8
HTML = '''
<!DOCTYPE html>
<html>