Unverified Commit 132e6467 authored by David Hoese's avatar David Hoese Committed by GitHub
Browse files

Merge pull request #320 from djhoese/bugfix-style-bugbear

Fix all code style issues identified by flake8
parents 497efd31 b36be701
exclude: '^$'
fail_fast: false
repos:
#- repo: https://github.com/psf/black
# rev: 20.8b1 # Replace by any tag/version: https://github.com/psf/black/tags
# hooks:
# - id: black
# language_version: python3 # Should be a command that runs python3.6+
- repo: https://gitlab.com/pycqa/flake8
rev: 3.9.2
hooks:
- id: flake8
language_version: python3
additional_dependencies: [flake8-docstrings, flake8-debugger, flake8-bugbear]
#- repo: https://github.com/pycqa/isort
# rev: 5.8.0
# hooks:
# - id: isort
# language_version: python3
......@@ -3,7 +3,7 @@ universal=1
[flake8]
max-line-length = 120
ignore = E226,E241,E265,E266,W291,W293,W503,F999,E305,F405,W504
ignore = D,D107,D202,E226,E241,E265,E266,W291,W293,W503,F999,E305,F405,W503,W504
exclude =
uwsift/ui
uwsift/tests/timeline.py
......@@ -18,4 +18,4 @@ exclude =
;[coverage:run]
;omit =
; uwsift/version.py
; versioneer.py
\ No newline at end of file
; versioneer.py
......@@ -20,40 +20,6 @@ REQUIRES
__author__ = 'rayg'
__docformat__ = 'reStructuredText'
import argparse
import logging
import sys
import unittest
LOG = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(
description="PURPOSE",
epilog="",
fromfile_prefix_chars='@')
parser.add_argument('-v', '--verbose', dest='verbosity', action="count", default=0,
help='each occurrence increases verbosity 1 level through ERROR-WARNING-Info-DEBUG')
# http://docs.python.org/2.7/library/argparse.html#nargs
# parser.add_argument('--stuff', nargs='5', dest='my_stuff',
# help="one or more random things")
parser.add_argument('pos_args', nargs='*',
help="positional arguments don't have the '-' prefix")
args = parser.parse_args()
levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(3, args.verbosity)])
if not args.pos_args:
unittest.main()
return 0
for pn in args.pos_args:
pass
return 0
if __name__ == '__main__':
sys.exit(main())
......@@ -88,7 +88,7 @@ class SiftDocumentAsFramesInTracks(QFramesInTracksScene):
"""Remove QTrackItem and QFrameItem instances that no longer correspond to document content
"""
LOG.debug("purging {} orphan tracks and {} orphan frames from timeline scene".format(len(tracks), len(frames)))
for frid in frames:
for _ in frames:
self.removeItem()
self._frame_items = dict((k, v) for (k, v) in self._frame_items.items() if k not in frames)
self._track_items = dict((k, v) for (k, v) in self._track_items.items() if k not in tracks)
......
......@@ -20,16 +20,13 @@ REQUIRES
__author__ = 'rayg'
__docformat__ = 'reStructuredText'
import argparse
import logging
import sys
import unittest
from PyQt5.QtCore import QObject
# from PyQt4.QtGui import QAction
LOG = logging.getLogger(__name__)
FORMAT_GUIDEBOOK = {}
......@@ -68,37 +65,3 @@ class UserAddsFileToDoc(QObject):
:return:
"""
pass
LOG = logging.getLogger(__name__)
def main():
parser = argparse.ArgumentParser(
description="PURPOSE",
epilog="",
fromfile_prefix_chars='@')
parser.add_argument('-v', '--verbose', dest='verbosity', action="count", default=0,
help='each occurrence increases verbosity 1 level through ERROR-WARNING-Info-DEBUG')
# http://docs.python.org/2.7/library/argparse.html#nargs
# parser.add_argument('--stuff', nargs='5', dest='my_stuff',
# help="one or more random things")
parser.add_argument('pos_args', nargs='*',
help="positional arguments don't have the '-' prefix")
args = parser.parse_args()
levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(3, args.verbosity)])
if not args.pos_args:
unittest.main()
return 0
for pn in args.pos_args:
pass
return 0
if __name__ == '__main__':
sys.exit(main())
......@@ -712,12 +712,14 @@ class LayerStackTreeViewModel(QAbstractItemModel):
return True
elif role == Qt.DisplayRole:
if index.isValid():
LOG.debug("changing row {} name to {0!r:s}".format(index.row(), data))
LOG.debug("changing row {0} name to {1!r:s}".format(index.row(), data))
self.doc.change_layer_name(index.row(), data)
return True
return False
def insertRows(self, row, count, parent=QModelIndex()):
def insertRows(self, row, count, parent=None):
if parent is None:
parent = QModelIndex()
self.beginInsertRows(QModelIndex(), row, row + count - 1)
LOG.debug(">>>> INSERT {} rows".format(count))
# TODO: insert 'count' empty rows into document
......
......@@ -66,8 +66,8 @@ class UserModifiesRGBLayers(QObject):
families.append(None)
self.create_rgb(families=families)
def create_rgb(self, action=None, families=[]):
if len(families) == 0:
def create_rgb(self, action=None, families=None):
if families is None or len(families) == 0:
# get the layers to composite from current selection
uuids = [u for u in self.layer_list_model.current_selected_uuids() if
self.doc[u][Info.KIND] in [Kind.IMAGE, Kind.COMPOSITE]]
......
......@@ -60,10 +60,7 @@ from uwsift.model.layer import Mixing, DocLayer, DocBasicLayer, DocRGBLayer, Doc
__author__ = 'rayg'
__docformat__ = 'reStructuredText'
import sys
import logging
import unittest
import argparse
from collections import MutableSequence, OrderedDict, defaultdict
from itertools import groupby, chain
from uuid import UUID, uuid1 as uuidgen
......@@ -2149,8 +2146,8 @@ class Document(QObject): # base class is rightmost, mixins left of that
def _uuids_for_recipe(self, recipe, valid_only=True):
prez_uuids = self.current_layer_uuid_order
for inst_key, time_layers in self._recipe_layers[recipe.name].items():
for t, rgb_layer in time_layers.items():
for time_layers in self._recipe_layers[recipe.name].values():
for rgb_layer in time_layers.values():
u = rgb_layer[Info.UUID]
if not valid_only:
yield u
......@@ -2273,14 +2270,14 @@ class Document(QObject): # base class is rightmost, mixins left of that
# return empty `None` layers since we don't know what is wanted right now
# we look at all possible times
inst_layers = {
k: {l[Info.SCHED_TIME]: None for l in g}
k: {layer[Info.SCHED_TIME]: None for layer in g}
for k, g in groupby(sorted(layers, key=_key_func), _key_func)}
return inst_layers
else:
family_uuids = self._families[family]
family_layers = [self[u] for u in family_uuids]
# (sat, inst) -> {time -> layer}
inst_layers = {k: {l[Info.SCHED_TIME]: l for l in g} for k, g in
inst_layers = {k: {layer[Info.SCHED_TIME]: layer for layer in g} for k, g in
groupby(sorted(family_layers, key=_key_func), _key_func)}
return inst_layers
......@@ -2318,7 +2315,7 @@ class Document(QObject): # base class is rightmost, mixins left of that
# update the layer object with newly available layers if possible
# add the layer object to the document if it should be included with
# the rest of them
for recipe_name, inst_rgbs in self._recipe_layers.items():
for recipe_name in self._recipe_layers.keys():
recipe = self.recipe_manager[recipe_name]
self.update_rgb_composite_layers(recipe, times=new_times)
......@@ -2653,34 +2650,3 @@ class Document(QObject): # base class is rightmost, mixins left of that
#
# def
#
def main():
parser = argparse.ArgumentParser(
description="PURPOSE",
epilog="",
fromfile_prefix_chars='@')
parser.add_argument('-v', '--verbose', dest='verbosity', action="count", default=0,
help='each occurrence increases verbosity 1 level through ERROR-WARNING-Info-DEBUG')
# http://docs.python.org/2.7/library/argparse.html#nargs
# parser.add_argument('--stuff', nargs='5', dest='my_stuff',
# help="one or more random things")
parser.add_argument('pos_args', nargs='*',
help="positional arguments don't have the '-' prefix")
args = parser.parse_args()
levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(3, args.verbosity)])
if not args.pos_args:
unittest.main()
return 0
for pn in args.pos_args:
pass
return 0
if __name__ == '__main__':
sys.exit(main())
......@@ -26,11 +26,8 @@ from uwsift.common import Info, Kind
__author__ = 'rayg'
__docformat__ = 'reStructuredText'
import sys
import logging
import numpy as np
import unittest
import argparse
LOG = logging.getLogger(__name__)
......@@ -447,34 +444,3 @@ class DocAlgebraicLayer(DocCompositeLayer):
# """
# FUTURE: A shape layer which feeds probe values to another UI element or helper.
# """
def main():
parser = argparse.ArgumentParser(
description="PURPOSE",
epilog="",
fromfile_prefix_chars='@')
parser.add_argument('-v', '--verbose', dest='verbosity', action="count", default=0,
help='each occurrence increases verbosity 1 level through ERROR-WARNING-Info-DEBUG')
# http://docs.python.org/2.7/library/argparse.html#nargs
# parser.add_argument('--stuff', nargs='5', dest='my_stuff',
# help="one or more random things")
parser.add_argument('pos_args', nargs='*',
help="positional arguments don't have the '-' prefix")
args = parser.parse_args()
levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(3, args.verbosity)])
if not args.pos_args:
unittest.main()
return 0
for pn in args.pos_args:
pass
return 0
if __name__ == '__main__':
sys.exit(main())
......@@ -166,8 +166,8 @@ def ahi_dataset_metadata(input_filename, dataset_name):
metadata["valid_max"] = valid_max * scale_factor + add_offset
# mimic satpy metadata
metadata["start_time"] = getattr(nc, "Image_Date_Time")
metadata["end_time"] = getattr(nc, "Image_Date_Time")
metadata["start_time"] = nc.Image_Date_Time
metadata["end_time"] = nc.Image_Date_Time
if "standard_name" not in metadata:
for k, v in VAR_NAME_STANDARD_NAME.items():
if dataset_name.endswith(k):
......
......@@ -22,10 +22,7 @@ REQUIRES
__author__ = 'rayg'
__docformat__ = 'reStructuredText'
import argparse
import logging
import sys
import unittest
from collections import OrderedDict
from PyQt5.QtCore import QObject, pyqtSignal, QThread
......@@ -211,34 +208,3 @@ def test_task():
yield {TASK_DOING: 'test task', TASK_PROGRESS: float(dex) / 10.0}
TheQueue.sleep(1)
yield {TASK_DOING: 'test task', TASK_PROGRESS: 1.0}
def main():
parser = argparse.ArgumentParser(
description="PURPOSE",
epilog="",
fromfile_prefix_chars='@')
parser.add_argument('-v', '--verbose', dest='verbosity', action="count", default=0,
help='each occurrence increases verbosity 1 level through ERROR-WARNING-Info-DEBUG')
# http://docs.python.org/2.7/library/argparse.html#nargs
# parser.add_argument('--stuff', nargs='5', dest='my_stuff',
# help="one or more random things")
parser.add_argument('pos_args', nargs='*',
help="positional arguments don't have the '-' prefix")
args = parser.parse_args()
levels = [logging.ERROR, logging.WARN, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(3, args.verbosity)])
if not args.pos_args:
unittest.main()
return 0
for pn in args.pos_args:
pass
return 0
if __name__ == '__main__':
sys.exit(main())
......@@ -86,7 +86,7 @@ def test_wizard_abi_l1b(qtbot, monkeypatch):
# HACK: Bug in Windows, no enum's by name
assert wiz.button(getattr(QWizard.WizardButton, 'NextButton', 1)).isEnabled()
# Go to the next page
wiz.next()
wiz.next() # noqa: B305
## Page 2
# One product should be listed from our mocking above
......@@ -98,7 +98,7 @@ def test_wizard_abi_l1b(qtbot, monkeypatch):
# HACK: Bug in Windows, no enum's by name
assert wiz.button(getattr(QWizard.WizardButton, 'FinishButton', 3)).isEnabled()
# Go to the next page
wiz.next()
wiz.next() # noqa: B305
# Verify the wizard is left in a usable state for the MainWindow
assert len(wiz.scenes) == 1
......
......@@ -75,7 +75,6 @@ def test_get_reference_points_bad_points(ic, iv):
"""Test that error is thrown if given invalid mesh points."""
with pytest.raises(ValueError):
get_reference_points(np.array(ic), np.array(iv))
assert False
@pytest.mark.parametrize("cp,ip,num_p,mpp,exp", [
......@@ -114,7 +113,6 @@ def test_calc_view_extents_bad_box(iebox, cp, ip, cs, dx, dy):
"""Test that error is thrown given zero-sized box."""
with pytest.raises(ValueError):
calc_view_extents(iebox, np.array(cp), np.array(ip), cs, dx, dy)
assert False
@pytest.mark.parametrize("ims,ts,s,exp", [
......
......@@ -787,7 +787,7 @@ class ColormapManager(OrderedDict):
super(ColormapManager, self).__setitem__(k, v)
def __iter__(self):
for cat, cat_dict in self._category_dict.items():
for cat_dict in self._category_dict.values():
for cmap_name in cat_dict:
yield cmap_name
......@@ -797,7 +797,7 @@ class ColormapManager(OrderedDict):
def iter_colormaps(self, writeable_first=True):
all_cmaps = [(self.is_writeable_colormap(name), name) for name in self]
all_cmaps = sorted(all_cmaps, reverse=writeable_first) # writeable first
for editable, cmap in all_cmaps:
for _, cmap in all_cmaps:
try:
cmap_obj = self[cmap]
except KeyError:
......@@ -809,7 +809,7 @@ class ColormapManager(OrderedDict):
yield cmap
def _files_for_dir(self, base_dir, recursive=True):
for subdir, dirs, files in os.walk(base_dir):
for subdir, _, files in os.walk(base_dir):
for file_to_import in files:
nfp = os.path.join(subdir, file_to_import)
file_stem, file_ext = os.path.splitext(file_to_import)
......@@ -873,7 +873,7 @@ class ColormapManager(OrderedDict):
if category is not None:
return self[category][cmap_name]
for cat, cat_dict in self.items():
for cat_dict in self.values():
if cmap_name in cat_dict:
val = cat_dict[cmap_name]
self._cmap_cache[cmap_name] = val
......@@ -906,7 +906,7 @@ class ColormapManager(OrderedDict):
def __delitem__(self, key):
super(ColormapManager, self).__delitem__(key)
for cat_name, cat_list in self._category_dict.items():
for cat_list in self._category_dict.values():
try:
cat_list.remove(key)
except ValueError:
......
......@@ -31,7 +31,7 @@ class CreateAlgebraicDialog(QtWidgets.QDialog):
available_short_names = []
selected_short_names = []
# use DATASET_NAME as unique group identifier
for idx, prez, layer in self.doc.current_layers_where(kinds=(Kind.IMAGE, Kind.COMPOSITE)):
for _, _, layer in self.doc.current_layers_where(kinds=(Kind.IMAGE, Kind.COMPOSITE)):
# use the UUID as a representative when talking to the document
available_info.setdefault(layer[Info.SHORT_NAME],
layer[Info.UUID])
......
......@@ -419,7 +419,7 @@ class ExportImageHelper(QtCore.QObject):
for filename, file_images in filenames:
writer = imageio.get_writer(filename, format_name, **params)
for u, x in file_images:
for _, x in file_images:
writer.append_data(numpy.array(x))
writer.close()
......@@ -396,6 +396,6 @@ class RGBLayerConfigPane(QObject):
sbox.setDisabled(recipe.input_ids[idx] is None)
sbox.setValue(recipe.gammas[idx])
else:
for idx, sbox in enumerate(self.gamma_boxes):
for sbox in self.gamma_boxes:
sbox.setDisabled(True)
sbox.setValue(1.)
......@@ -169,7 +169,7 @@ class MultiChannelGPUScaledTexture2D:
@interpolation.setter
def interpolation(self, value):
for tex in self._textures:
for _ in self._textures:
self._texture.interpolation = value
def check_data_format(self, data_arrays):
......
......@@ -539,7 +539,7 @@ class TileCalculator(object):
# maximum stride that we shouldn't lower resolution beyond
self.overview_stride = self.calc_overview_stride()
def visible_tiles(self, visible_geom, stride=Point(1, 1), extra_tiles_box=Box(0, 0, 0, 0)) -> Box:
def visible_tiles(self, visible_geom, stride=None, extra_tiles_box=None) -> Box:
"""
given a visible world geometry and sampling, return (sampling-state, [Box-of-tiles-to-draw])
sampling state is WELLSAMPLED/OVERSAMPLED/UNDERSAMPLED
......@@ -547,6 +547,10 @@ class TileCalculator(object):
tiles are specified as (iy,ix) integer pairs
extra_box value says how many extra tiles to include around each edge
"""
if stride is None:
stride = Point(1, 1)
if extra_tiles_box is None:
extra_tiles_box = Box(0, 0, 0, 0)
v = visible_geom
e = extra_tiles_box
return visible_tiles(
......
......@@ -113,7 +113,7 @@ class CoordTransform(QObject):
self._time_base = new_settings.t
self._time_unit = new_settings.d
def __init__(self, time_base: datetime = None, time_unit: timedelta = timedelta(seconds=1), track_height=None):
def __init__(self, time_base: datetime = None, time_unit: timedelta = None, track_height=None):
"""
Args:
......@@ -121,6 +121,8 @@ class CoordTransform(QObject):
time_unit: time width corresponding to delta-X=1.0, defaults to 1.0s
track_height: pixels high to display individual ttracks
"""
if time_unit is None:
time_unit = timedelta(seconds=1)
super(CoordTransform, self).__init__()
self._time_base = time_base or datetime.utcnow()
self._time_unit = time_unit
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment