Skip to content

Commit

Permalink
Format files with black
Browse files Browse the repository at this point in the history
Format imports and lines with https://marketplace.visualstudio.com/items?itemName=ms-python.black-formatter

Add pragmas for new lines. Expected to **decrease coverage** by a few percent because of the better looking lines ;)
  • Loading branch information
VaeterchenFrost committed Dec 18, 2024
1 parent 2d3adc5 commit 4c7954a
Show file tree
Hide file tree
Showing 10 changed files with 741 additions and 587 deletions.
27 changes: 15 additions & 12 deletions scripts/build_directory_md.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,22 +32,24 @@

URL_BASE = "https://github.com/VaeterchenFrost/tdvisu/blob/master"

AFFECTED_EXT = ('.py', '.ipynb',)
AFFECTED_EXT = (
".py",
".ipynb",
)

EXCLUDED_FILENAMES = ('__init__.py',)
EXCLUDED_FILENAMES = ("__init__.py",)


def good_file_paths(top_dir: str = '.') -> Iterator[str]:
def good_file_paths(top_dir: str = ".") -> Iterator[str]:
"""Return relative path to files with extension in AFFECTED_EXT."""
for dir_path, dir_names, filenames in os.walk(top_dir):
dir_names[:] = [d for d in dir_names
if d != 'scripts' and d[0] not in '._']
dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"]
for filename in filenames:
if filename in EXCLUDED_FILENAMES:
continue
if os.path.splitext(filename)[1] in AFFECTED_EXT:
normalized_path = os.path.normpath(dir_path)
if normalized_path != '.':
if normalized_path != ".":
yield os.path.join(normalized_path, filename)
else:
yield filename
Expand All @@ -68,19 +70,20 @@ def print_path(old_path: str, new_path: str) -> str:
return new_path


def print_directory_md(top_dir: str = '.') -> None:
def print_directory_md(top_dir: str = ".") -> None:
"""Print the markdown for files with selected extensions recursing top_dir."""
old_path = ''
old_path = ""
for filepath in sorted(good_file_paths(top_dir)):
filepath, filename = os.path.split(filepath)
if filepath != old_path:
old_path = print_path(old_path, filepath)
indent = (filepath.count(os.sep) + 1) if filepath else 0
url = '/'.join((URL_BASE, *[quote(part)
for part in (filepath, filename) if part]))
filename = os.path.splitext(filename.replace('_', ' ').title())[0]
url = "/".join(
(URL_BASE, *[quote(part) for part in (filepath, filename) if part])
)
filename = os.path.splitext(filename.replace("_", " ").title())[0]
print(f"{md_prefix(indent)} [{filename}]({url})")


if __name__ == "__main__":
print_directory_md('.')
print_directory_md(".")
21 changes: 11 additions & 10 deletions tdvisu/dijkstra.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@
from itertools import count


def bidirectional_dijkstra(edges, source, target, weight='weight'):
def bidirectional_dijkstra(edges, source, target, weight="weight"):
r"""Dijkstra's algorithm for shortest paths using bidirectional search.
Parameters
Expand Down Expand Up @@ -127,7 +127,7 @@ def bidirectional_dijkstra(edges, source, target, weight='weight'):
push = heappush
pop = heappop
# Init: [Forward, Backward]
dists = [{}, {}] # dictionary of final distances
dists = [{}, {}] # dictionary of final distances
paths = [{source: [source]}, {target: [target]}] # dictionary of paths
fringe = [[], []] # heap of (distance, node) for choosing node to expand
seen = [{source: 0}, {target: 0}] # dict of distances to seen nodes
Expand Down Expand Up @@ -164,8 +164,7 @@ def bidirectional_dijkstra(edges, source, target, weight='weight'):
vw_length = dists[direction][v] + weight(w, v, d)
if w in dists[direction]:
if vw_length < dists[direction][w]:
raise ValueError(
"Contradictory paths found: negative weights?")
raise ValueError("Contradictory paths found: negative weights?")
elif w not in seen[direction] or vw_length < seen[direction][w]:
# relaxing
seen[direction][w] = vw_length
Expand Down Expand Up @@ -229,12 +228,14 @@ def _weight_function(weight, multigraph: bool = False):
return lambda u, v, data: data.get(weight, 1)


if __name__ == "__main__": # pragma: no cover
if __name__ == "__main__": # pragma: no cover
# Show one example and print to console
EDGES = {2: {1: {}, 3: {}, 4: {}},
1: {2: {}},
3: {2: {}},
4: {2: {}, 5: {}},
5: {4: {}}}
EDGES = {
2: {1: {}, 3: {}, 4: {}},
1: {2: {}},
3: {2: {}},
4: {2: {}, 5: {}},
5: {4: {}},
}
RESULT = bidirectional_dijkstra(EDGES, 3, 5)
print(RESULT)
30 changes: 13 additions & 17 deletions tdvisu/logging.yml
Original file line number Diff line number Diff line change
@@ -1,33 +1,29 @@
version: 1
---
formatters:
simple:
format: "%(asctime)s %(levelname)s %(message)s"
datefmt: "%H:%M:%S"
full:
format: "%(asctime)s,%(msecs)d %(levelname)s[%(filename)s:%(lineno)d] %(message)s"
datefmt: "%Y-%m-%d %H:%M:%S"
datefmt: '%Y-%m-%d %H:%M:%S'
format: '%(asctime)s,%(msecs)d %(levelname)s[%(filename)s:%(lineno)d] %(message)s'
simple:
datefmt: '%H:%M:%S'
format: '%(asctime)s %(levelname)s %(message)s'
handlers:
console:
class: logging.StreamHandler
level: WARNING
formatter: full
level: WARNING
stream: ext://sys.stdout
loggers:
visualization.py:
level: NOTSET

svgjoin.py:
construct_dpdb_visu.py:
level: NOTSET

reader.py:
level: NOTSET

construct_dpdb_visu.py:
svgjoin.py:
level: NOTSET

utilities.py:
level: NOTSET

visualization.py:
level: NOTSET
root:
level: WARNING
handlers: [console]
level: WARNING
version: 1
16 changes: 10 additions & 6 deletions tdvisu/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,12 @@ def main()

from tdvisu.utilities import add_edge_to

logger = logging.getLogger('reader.py')
logger = logging.getLogger("reader.py")


class Reader():
class Reader:
"""Base class for string-readers."""

@classmethod
def from_filename(cls, fname) -> Reader:
with open(fname, "r") as file:
Expand Down Expand Up @@ -150,7 +151,7 @@ def store_problem_vars(self):

def body(self, lines) -> None:
"""Store the content from the given lines in the edges and adjacency_dict."""
if self.format not in ('col', 'tw'):
if self.format not in ("col", "tw"):
logger.error("Not a tw file!")
sys.exit(1)

Expand All @@ -163,13 +164,16 @@ def body(self, lines) -> None:
logger.warning(
"Expected exactly 2 vertices at line %d, but %d found",
lineno,
len(line))
len(line),
)
vertex1 = int(line[0])
vertex2 = int(line[1])

add_edge_to(self.edges, self.adjacency_dict, vertex1, vertex2)

if len(self.edges) != self.num_edges:
logger.warning(
"Number of edges mismatch preamble (%d vs %d)", len(
self.edges), self.num_edges)
"Number of edges mismatch preamble (%d vs %d)",
len(self.edges),
self.num_edges,
)
Loading

0 comments on commit 4c7954a

Please sign in to comment.