Skip to content

Commit

Permalink
Use ruff to format strings to single quotes. (napari#6407)
Browse files Browse the repository at this point in the history
# Description

Based on a discussion from napari#6386 I updated the ruff configuration to
enable `Q000` https://docs.astral.sh/ruff/rules/#flake8-quotes-q rule
and configured it to use a single quotes string.

We have many double quotes string, but less than single quotes. 

This PR does not change the quotation of docstrings (`"""`) and
multiline strings (`"""`) as they are already enforced by ruff
configuration and could be easy changed.

to see configuration changes please use:
napari@a422ad7

cc @jni @brisvag

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
Czaki and pre-commit-ci[bot] authored Feb 17, 2024
1 parent bf12826 commit 0747da5
Show file tree
Hide file tree
Showing 403 changed files with 3,233 additions and 3,232 deletions.
46 changes: 23 additions & 23 deletions examples/3d_kymograph_.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@
try:
from omero.gateway import BlitzGateway
except ModuleNotFoundError:
print("Could not import BlitzGateway which is")
print("required to download the sample datasets.")
print("Please install omero-py:")
print("https://pypi.org/project/omero-py/")
print('Could not import BlitzGateway which is')
print('required to download the sample datasets.')
print('Please install omero-py:')
print('https://pypi.org/project/omero-py/')
exit(-1)
try:
from tqdm import tqdm
except ModuleNotFoundError:
print("Could not import tqdm which is")
print("required to show progress when downloading the sample datasets.")
print("Please install tqdm:")
print("https://pypi.org/project/tqdm/")
print('Could not import tqdm which is')
print('required to show progress when downloading the sample datasets.')
print('Please install tqdm:')
print('https://pypi.org/project/tqdm/')
exit(-1)

import napari
Expand All @@ -44,15 +44,15 @@ def IDR_fetch_image(image_id: int, progressbar: bool = True) -> np.ndarray:
"""

conn = BlitzGateway(
host="ws://idr.openmicroscopy.org/omero-ws",
username="public",
passwd="public",
host='ws://idr.openmicroscopy.org/omero-ws',
username='public',
passwd='public',
secure=True,
)
conn.connect()
conn.c.enableKeepAlive(60)

idr_img = conn.getObject("Image", image_id)
idr_img = conn.getObject('Image', image_id)
idr_pixels = idr_img.getPrimaryPixels()

_ = idr_img
Expand All @@ -73,7 +73,7 @@ def IDR_fetch_image(image_id: int, progressbar: bool = True) -> np.ndarray:
_tmp = np.asarray(list(idr_plane_iterator))
_tmp = _tmp.reshape((nz, nc, nt, ny, nx))
# the following line reorders the axes (no summing, despite the name)
return np.einsum("jmikl", _tmp)
return np.einsum('jmikl', _tmp)


description = """
Expand Down Expand Up @@ -133,29 +133,29 @@ def IDR_fetch_image(image_id: int, progressbar: bool = True) -> np.ndarray:
print(description)

samples = (
{"IDRid": 2864587, "description": "AURKB knockdown", "vol": None},
{"IDRid": 2862565, "description": "KIF11 knockdown", "vol": None},
{"IDRid": 2867896, "description": "INCENP knockdown", "vol": None},
{"IDRid": 1486532, "description": "TMPRSS11A knockdown", "vol": None},
{'IDRid': 2864587, 'description': 'AURKB knockdown', 'vol': None},
{'IDRid': 2862565, 'description': 'KIF11 knockdown', 'vol': None},
{'IDRid': 2867896, 'description': 'INCENP knockdown', 'vol': None},
{'IDRid': 1486532, 'description': 'TMPRSS11A knockdown', 'vol': None},
)

print("-------------------------------------------------------")
print("Sample datasets will require ~490 MB download from IDR.")
print('-------------------------------------------------------')
print('Sample datasets will require ~490 MB download from IDR.')
answer = input("Press Enter to proceed, 'n' to cancel: ")
if answer.lower().startswith('n'):
print("User cancelled download. Exiting.")
print('User cancelled download. Exiting.')
exit(0)
print("-------------------------------------------------------")
print('-------------------------------------------------------')
for s in samples:
print(f"Downloading sample {s['IDRid']}.")
print(f"Description: {s['description']}")
s["vol"] = np.squeeze(IDR_fetch_image(s["IDRid"]))
s['vol'] = np.squeeze(IDR_fetch_image(s['IDRid']))

v = napari.Viewer(ndisplay=3)
scale = (5, 1, 1) # "stretch" time domain
for s in samples:
v.add_image(
s["vol"], name=s['description'], scale=scale, blending="opaque"
s['vol'], name=s['description'], scale=scale, blending='opaque'
)

v.grid.enabled = True # show the volumes in grid mode
Expand Down
2 changes: 1 addition & 1 deletion examples/add_labels.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
cleared = remove_small_objects(clear_border(bw), 20)

# label image regions
label_image = label(cleared).astype("uint8")
label_image = label(cleared).astype('uint8')

# initialise viewer with coins image
viewer = napari.view_image(image, name='coins', rgb=False)
Expand Down
2 changes: 1 addition & 1 deletion examples/add_labels_with_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
'row': ['none']
+ ['top'] * 4
+ ['bottom'] * 4, # background is row: none
'size': ["none", *coin_sizes], # background is size: none
'size': ['none', *coin_sizes], # background is size: none
}

colors = {1: 'white', 2: 'blue', 3: 'green', 4: 'red', 5: 'yellow',
Expand Down
4 changes: 2 additions & 2 deletions examples/annotate-2d.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@

import napari

print("click to add points; close the window when finished.")
print('click to add points; close the window when finished.')

viewer = napari.view_image(data.astronaut(), rgb=True)
points = viewer.add_points(np.zeros((0, 2)))
Expand All @@ -22,5 +22,5 @@
if __name__ == '__main__':
napari.run()

print("you clicked on:")
print('you clicked on:')
print(points.data)
8 changes: 4 additions & 4 deletions examples/clipboard_.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ class Grabber(QWidget):
def __init__(self) -> None:
super().__init__()

self.copy_canvas_btn = QPushButton("Copy Canvas to Clipboard", self)
self.copy_canvas_btn.setToolTip("Copy screenshot of the canvas to clipboard.")
self.copy_viewer_btn = QPushButton("Copy Viewer to Clipboard", self)
self.copy_viewer_btn.setToolTip("Copy screenshot of the entire viewer to clipboard.")
self.copy_canvas_btn = QPushButton('Copy Canvas to Clipboard', self)
self.copy_canvas_btn.setToolTip('Copy screenshot of the canvas to clipboard.')
self.copy_viewer_btn = QPushButton('Copy Viewer to Clipboard', self)
self.copy_viewer_btn.setToolTip('Copy screenshot of the entire viewer to clipboard.')

layout = QVBoxLayout(self)
layout.addWidget(self.copy_canvas_btn)
Expand Down
10 changes: 5 additions & 5 deletions examples/clipping_planes_interactive_.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ def shift_plane_along_normal(viewer, event):
# Get transform which maps from data (vispy) to canvas
# note that we're using a private attribute here, which may not be present in future napari versions
visual2canvas = viewer.window._qt_viewer.canvas.layer_to_visual[volume_layer].node.get_transform(
map_from="visual", map_to="canvas"
map_from='visual', map_to='canvas'
)

# Find start and end positions of plane normal in canvas coordinates
Expand All @@ -148,7 +148,7 @@ def shift_plane_along_normal(viewer, event):
start_position_canv = event.pos

yield
while event.type == "mouse_move":
while event.type == 'mouse_move':
# Get end position in canvas coordinates
end_position_canv = event.pos

Expand Down Expand Up @@ -190,9 +190,9 @@ def shift_plane_along_normal(viewer, event):
viewer.camera.angles = (45, 45, 45)
viewer.camera.zoom = 5
viewer.text_overlay.update({
"text": 'Drag the clipping plane surface to move it along its normal.',
"font_size": 20,
"visible": True,
'text': 'Drag the clipping plane surface to move it along its normal.',
'font_size': 20,
'visible': True,
})

if __name__ == '__main__':
Expand Down
40 changes: 20 additions & 20 deletions examples/dev/demo_shape_creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,39 +30,39 @@ def time_me(label, func):
t = default_timer()
res = func()
t = default_timer() - t
print(f"{label}: {t:.4f} s")
print(f'{label}: {t:.4f} s')
return res


if __name__ == "__main__":
if __name__ == '__main__':

parser = argparse.ArgumentParser(description="")
parser = argparse.ArgumentParser(description='')

parser.add_argument(
"-n",
"--n_polys",
'-n',
'--n_polys',
type=int,
default=5000,
help='number of polygons to show',
)
parser.add_argument(
"-t",
"--type",
'-t',
'--type',
type=str,
default="path",
default='path',
choices=['path', 'path_concat', 'polygon', 'rectangle', 'ellipse'],
)
parser.add_argument(
"-c",
"--concat",
action="store_true",
'-c',
'--concat',
action='store_true',
help='concatenate all coordinates to a single mesh',
)
parser.add_argument(
"-v", "--view", action="store_true", help='show napari viewer'
'-v', '--view', action='store_true', help='show napari viewer'
)
parser.add_argument(
"--properties", action="store_true", help='add dummy shape properties'
'--properties', action='store_true', help='add dummy shape properties'
)

args = parser.parse_args()
Expand Down Expand Up @@ -90,16 +90,16 @@ def time_me(label, func):
color_cycle = ['blue', 'magenta', 'green']

kwargs = {
"shape_type": args.type,
"properties": properties if args.properties else None,
"face_color": 'class' if args.properties else [1,1,1,1],
"face_color_cycle": color_cycle,
"edge_color": 'class' if args.properties else [1,1,1,1],
"edge_color_cycle": color_cycle,
'shape_type': args.type,
'properties': properties if args.properties else None,
'face_color': 'class' if args.properties else [1,1,1,1],
'face_color_cycle': color_cycle,
'edge_color': 'class' if args.properties else [1,1,1,1],
'edge_color_cycle': color_cycle,
}

layer = time_me(
"time to create layer",
'time to create layer',
lambda: napari.layers.Shapes(coords, **kwargs),
)

Expand Down
2 changes: 1 addition & 1 deletion examples/dev/gui_notifications.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def raise_():


def warn_():
warnings.warn("warning!")
warnings.warn('warning!')


viewer = napari.Viewer()
Expand Down
2 changes: 1 addition & 1 deletion examples/dev/gui_notifications_threaded.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def make_warning(*_):
@thread_worker(start_thread=True)
def make_error(*_):
time.sleep(0.05)
raise ValueError("Error in another thread")
raise ValueError('Error in another thread')


viewer = napari.Viewer()
Expand Down
20 changes: 10 additions & 10 deletions examples/dev/leaking_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,33 +12,33 @@
process = psutil.Process(os.getpid())
viewer = napari.Viewer()

print("mem", process.memory_info().rss)
print('mem', process.memory_info().rss)

for _ in range(0):
print(viewer.add_image(np.random.random((60, 1000, 1000))).name)
for _ in range(2):
print(viewer.add_labels((np.random.random((2, 1000, 1000)) * 10).astype(np.uint8)).name)

print("mem", process.memory_info().rss)
print('mem', process.memory_info().rss)

# napari.run()

print("controls", viewer.window.qt_viewer.controls.widgets)
print('controls', viewer.window.qt_viewer.controls.widgets)
li = weakref.ref(viewer.layers[0])
data_li = weakref.ref(li()._data)
controls = weakref.ref(viewer.window.qt_viewer.controls.widgets[li()])
objgraph.show_backrefs(li(), filename="base.png")
objgraph.show_backrefs(li(), filename='base.png')
del viewer.layers[0]
qtpy.QtGui.QGuiApplication.processEvents()
gc.collect()
gc.collect()
print(li())
objgraph.show_backrefs(li(), max_depth=10, filename="test.png", refcounts=True)
objgraph.show_backrefs(controls(), max_depth=10, filename="controls.png", refcounts=True)
objgraph.show_backrefs(data_li(), max_depth=10, filename="test_data.png")
print("controls", viewer.window.qt_viewer.controls.widgets)
print("controls", gc.get_referrers(controls()))
print("controls", controls().parent())
objgraph.show_backrefs(li(), max_depth=10, filename='test.png', refcounts=True)
objgraph.show_backrefs(controls(), max_depth=10, filename='controls.png', refcounts=True)
objgraph.show_backrefs(data_li(), max_depth=10, filename='test_data.png')
print('controls', viewer.window.qt_viewer.controls.widgets)
print('controls', gc.get_referrers(controls()))
print('controls', controls().parent())
#print("controls", controls().parent().indexOf(controls()))
print(gc.get_referrers(li()))
print(gc.get_referrers(li())[1])
Expand Down
6 changes: 3 additions & 3 deletions examples/dev/q_list_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,14 @@ def __str__(self):


# spy on events
root.events.reordered.connect(lambda e: print("reordered to: ", e.value))
root.events.reordered.connect(lambda e: print('reordered to: ', e.value))
root.selection.events.changed.connect(
lambda e: print(
f"selection changed. added: {e.added}, removed: {e.removed}"
f'selection changed. added: {e.added}, removed: {e.removed}'
)
)
root.selection.events._current.connect(
lambda e: print(f"current item changed to: {e.value}")
lambda e: print(f'current item changed to: {e.value}')
)


Expand Down
12 changes: 6 additions & 6 deletions examples/dev/q_node_tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,18 @@
Group(
[
Node(name='1'),
Group([Node(name='2'), Node(name='3')], name="g2"),
Group([Node(name='2'), Node(name='3')], name='g2'),
Node(name='4'),
Node(name='5'),
Node(name='tip'),
],
name="g1",
name='g1',
),
Node(name='7'),
Node(name='8'),
Node(name='9'),
],
name="root",
name='root',
)
# create Qt view onto the Group
view = QtNodeTreeView(root)
Expand All @@ -65,14 +65,14 @@


# spy on events
root.events.reordered.connect(lambda e: print("reordered to: ", e.value))
root.events.reordered.connect(lambda e: print('reordered to: ', e.value))
root.selection.events.changed.connect(
lambda e: print(
f"selection changed. added: {e.added}, removed: {e.removed}"
f'selection changed. added: {e.added}, removed: {e.removed}'
)
)
root.selection.events._current.connect(
lambda e: print(f"current item changed to: {e.value}")
lambda e: print(f'current item changed to: {e.value}')
)

napari.run()
2 changes: 1 addition & 1 deletion examples/dev/slicing/random_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

parser = argparse.ArgumentParser()
parser.add_argument(
"n", type=int, nargs='?', default=10_000_000, help="(default: %(default)s)"
'n', type=int, nargs='?', default=10_000_000, help='(default: %(default)s)'
)
args = parser.parse_args()

Expand Down
2 changes: 1 addition & 1 deletion examples/fourier_transform_playground.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def combine_and_set_data(wave_args):
update_layer(f'wave {name}', data)


@thread_worker(connect={"yielded": combine_and_set_data})
@thread_worker(connect={'yielded': combine_and_set_data})
def update_viewer():
# keep track of each wave in a dictionary by id, this way we can modify/remove
# existing waves or add new ones
Expand Down
Loading

0 comments on commit 0747da5

Please sign in to comment.